root/trunk/src/game/Level3.cpp @ 229

Revision 229, 182.2 kB (checked in by yumileroy, 17 years ago)

[svn] *** Source: MaNGOS ***
* Fixed build extractor at Windows Vista. Author: Vladimir
* Fixed comment text and code indentifiers spelling. Author: Vladimir & Paradox.
* Access cached member lists in guild handlers instead of querying the DB. Author: Hunuza
* Small fixes in send/received packet and simple code cleanup also. Author: Vladimir
* Not output error at loading empty character_ticket table. Author: Vladimir
* Not reset display model at shapeshift aura remove if it not set at apply. Author: Arthorius
* Applied props to few files.

Original author: visagalis
Date: 2008-11-14 16:28:45-06:00

Line 
1/*
2* Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3*
4* Copyright (C) 2008 Trinity <http://www.trinitycore.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#include "Common.h"
22#include "Database/DatabaseEnv.h"
23#include "WorldPacket.h"
24#include "WorldSession.h"
25#include "World.h"
26#include "ObjectMgr.h"
27#include "AccountMgr.h"
28#include "PlayerDump.h"
29#include "SpellMgr.h"
30#include "Player.h"
31#include "Opcodes.h"
32#include "GameObject.h"
33#include "Chat.h"
34#include "Log.h"
35#include "Guild.h"
36#include "ObjectAccessor.h"
37#include "MapManager.h"
38#include "SpellAuras.h"
39#include "ScriptCalls.h"
40#include "Language.h"
41#include "GridNotifiersImpl.h"
42#include "CellImpl.h"
43#include "Weather.h"
44#include "PointMovementGenerator.h"
45#include "TargetedMovementGenerator.h"
46#include "SkillDiscovery.h"
47#include "SkillExtraItems.h"
48#include "SystemConfig.h"
49#include "Config/ConfigEnv.h"
50#include "Util.h"
51#include "ItemEnchantmentMgr.h"
52#include "BattleGroundMgr.h"
53#include "InstanceSaveMgr.h"
54#include "InstanceData.h"
55
56//reload commands
57bool ChatHandler::HandleReloadCommand(const char* arg)
58{
59    // this is error catcher for wrong table name in .reload commands
60    PSendSysMessage("Db table with name starting from '%s' not found and can't be reloaded.",arg);
61    SetSentErrorMessage(true);
62    return false;
63}
64
65bool ChatHandler::HandleReloadAllCommand(const char*)
66{
67    HandleReloadAreaTriggerTeleportCommand("");
68    HandleReloadSkillFishingBaseLevelCommand("");
69
70    HandleReloadAllAreaCommand("");
71    HandleReloadAllLootCommand("");
72    HandleReloadAllNpcCommand("");
73    HandleReloadAllQuestCommand("");
74    HandleReloadAllSpellCommand("");
75    HandleReloadAllItemCommand("");
76    HandleReloadAllLocalesCommand("");
77
78    HandleReloadCommandCommand("");
79    HandleReloadReservedNameCommand("");
80    HandleReloadTrinityStringCommand("");
81    HandleReloadGameTeleCommand("");
82    return true;
83}
84
85bool ChatHandler::HandleReloadAllAreaCommand(const char*)
86{
87    //HandleReloadQuestAreaTriggersCommand(""); -- reloaded in HandleReloadAllQuestCommand
88    HandleReloadAreaTriggerTeleportCommand("");
89    HandleReloadAreaTriggerTavernCommand("");
90    HandleReloadGameGraveyardZoneCommand("");
91    return true;
92}
93
94bool ChatHandler::HandleReloadAllLootCommand(const char*)
95{
96    sLog.outString( "Re-Loading Loot Tables..." );
97    LoadLootTables();
98    SendGlobalSysMessage("DB tables `*_loot_template` reloaded.");
99    return true;
100}
101
102bool ChatHandler::HandleReloadAllNpcCommand(const char* /*args*/)
103{
104    HandleReloadNpcGossipCommand("a");
105    HandleReloadNpcOptionCommand("a");
106    HandleReloadNpcTrainerCommand("a");
107    HandleReloadNpcVendorCommand("a");
108    return true;
109}
110
111bool ChatHandler::HandleReloadAllQuestCommand(const char* /*args*/)
112{
113    HandleReloadQuestAreaTriggersCommand("a");
114    HandleReloadQuestTemplateCommand("a");
115
116    sLog.outString( "Re-Loading Quests Relations..." );
117    objmgr.LoadQuestRelations();
118    SendGlobalSysMessage("DB tables `*_questrelation` and `*_involvedrelation` reloaded.");
119    return true;
120}
121
122bool ChatHandler::HandleReloadAllScriptsCommand(const char*)
123{
124    if(sWorld.IsScriptScheduled())
125    {
126        PSendSysMessage("DB scripts used currently, please attempt reload later.");
127        SetSentErrorMessage(true);
128        return false;
129    }
130
131    sLog.outString( "Re-Loading Scripts..." );
132    HandleReloadGameObjectScriptsCommand("a");
133    HandleReloadEventScriptsCommand("a");
134    HandleReloadQuestEndScriptsCommand("a");
135    HandleReloadQuestStartScriptsCommand("a");
136    HandleReloadSpellScriptsCommand("a");
137    SendGlobalSysMessage("DB tables `*_scripts` reloaded.");
138    return true;
139}
140
141bool ChatHandler::HandleReloadAllSpellCommand(const char*)
142{
143    HandleReloadSkillDiscoveryTemplateCommand("a");
144    HandleReloadSkillExtraItemTemplateCommand("a");
145    HandleReloadSpellAffectCommand("a");
146    HandleReloadSpellChainCommand("a");
147    HandleReloadSpellElixirCommand("a");
148    HandleReloadSpellLearnSpellCommand("a");
149    HandleReloadSpellProcEventCommand("a");
150    HandleReloadSpellScriptTargetCommand("a");
151    HandleReloadSpellTargetPositionCommand("a");
152    HandleReloadSpellThreatsCommand("a");
153    HandleReloadSpellPetAurasCommand("a");
154    HandleReloadSpellDisabledCommand("a");
155    return true;
156}
157
158bool ChatHandler::HandleReloadAllItemCommand(const char*)
159{
160    HandleReloadPageTextsCommand("a");
161    HandleReloadItemEnchantementsCommand("a");
162    return true;
163}
164
165bool ChatHandler::HandleReloadAllLocalesCommand(const char* /*args*/)
166{
167    HandleReloadLocalesCreatureCommand("a");
168    HandleReloadLocalesGameobjectCommand("a");
169    HandleReloadLocalesItemCommand("a");
170    HandleReloadLocalesNpcTextCommand("a");
171    HandleReloadLocalesPageTextCommand("a");
172    HandleReloadLocalesQuestCommand("a");
173    return true;
174}
175
176bool ChatHandler::HandleReloadConfigCommand(const char* /*args*/)
177{
178    sLog.outString( "Re-Loading config settings..." );
179    sWorld.LoadConfigSettings(true);
180    SendGlobalSysMessage("World config settings reloaded.");
181    return true;
182}
183
184bool ChatHandler::HandleReloadAreaTriggerTavernCommand(const char*)
185{
186    sLog.outString( "Re-Loading Tavern Area Triggers..." );
187    objmgr.LoadTavernAreaTriggers();
188    SendGlobalSysMessage("DB table `areatrigger_tavern` reloaded.");
189    return true;
190}
191
192bool ChatHandler::HandleReloadAreaTriggerTeleportCommand(const char*)
193{
194    sLog.outString( "Re-Loading AreaTrigger teleport definitions..." );
195    objmgr.LoadAreaTriggerTeleports();
196    SendGlobalSysMessage("DB table `areatrigger_teleport` reloaded.");
197    return true;
198}
199
200bool ChatHandler::HandleReloadCommandCommand(const char*)
201{
202    load_command_table = true;
203    SendGlobalSysMessage("DB table `command` will be reloaded at next chat command use.");
204    return true;
205}
206
207bool ChatHandler::HandleReloadCreatureQuestRelationsCommand(const char*)
208{
209    sLog.outString( "Loading Quests Relations... (`creature_questrelation`)" );
210    objmgr.LoadCreatureQuestRelations();
211    SendGlobalSysMessage("DB table `creature_questrelation` (creature quest givers) reloaded.");
212    return true;
213}
214
215bool ChatHandler::HandleReloadCreatureQuestInvRelationsCommand(const char*)
216{
217    sLog.outString( "Loading Quests Relations... (`creature_involvedrelation`)" );
218    objmgr.LoadCreatureInvolvedRelations();
219    SendGlobalSysMessage("DB table `creature_involvedrelation` (creature quest takers) reloaded.");
220    return true;
221}
222
223bool ChatHandler::HandleReloadGOQuestRelationsCommand(const char*)
224{
225    sLog.outString( "Loading Quests Relations... (`gameobject_questrelation`)" );
226    objmgr.LoadGameobjectQuestRelations();
227    SendGlobalSysMessage("DB table `gameobject_questrelation` (gameobject quest givers) reloaded.");
228    return true;
229}
230
231bool ChatHandler::HandleReloadGOQuestInvRelationsCommand(const char*)
232{
233    sLog.outString( "Loading Quests Relations... (`gameobject_involvedrelation`)" );
234    objmgr.LoadGameobjectInvolvedRelations();
235    SendGlobalSysMessage("DB table `gameobject_involvedrelation` (gameobject quest takers) reloaded.");
236    return true;
237}
238
239bool ChatHandler::HandleReloadQuestAreaTriggersCommand(const char*)
240{
241    sLog.outString( "Re-Loading Quest Area Triggers..." );
242    objmgr.LoadQuestAreaTriggers();
243    SendGlobalSysMessage("DB table `areatrigger_involvedrelation` (quest area triggers) reloaded.");
244    return true;
245}
246
247bool ChatHandler::HandleReloadQuestTemplateCommand(const char*)
248{
249    sLog.outString( "Re-Loading Quest Templates..." );
250    objmgr.LoadQuests();
251    SendGlobalSysMessage("DB table `quest_template` (quest definitions) reloaded.");
252    return true;
253}
254
255bool ChatHandler::HandleReloadLootTemplatesCreatureCommand(const char*)
256{
257    sLog.outString( "Re-Loading Loot Tables... (`creature_loot_template`)" );
258    LoadLootTemplates_Creature();
259    LootTemplates_Creature.CheckLootRefs();
260    SendGlobalSysMessage("DB table `creature_loot_template` reloaded.");
261    return true;
262}
263
264bool ChatHandler::HandleReloadLootTemplatesDisenchantCommand(const char*)
265{
266    sLog.outString( "Re-Loading Loot Tables... (`disenchant_loot_template`)" );
267    LoadLootTemplates_Disenchant();
268    LootTemplates_Disenchant.CheckLootRefs();
269    SendGlobalSysMessage("DB table `disenchant_loot_template` reloaded.");
270    return true;
271}
272
273bool ChatHandler::HandleReloadLootTemplatesFishingCommand(const char*)
274{
275    sLog.outString( "Re-Loading Loot Tables... (`fishing_loot_template`)" );
276    LoadLootTemplates_Fishing();
277    LootTemplates_Fishing.CheckLootRefs();
278    SendGlobalSysMessage("DB table `fishing_loot_template` reloaded.");
279    return true;
280}
281
282bool ChatHandler::HandleReloadLootTemplatesGameobjectCommand(const char*)
283{
284    sLog.outString( "Re-Loading Loot Tables... (`gameobject_loot_template`)" );
285    LoadLootTemplates_Gameobject();
286    LootTemplates_Gameobject.CheckLootRefs();
287    SendGlobalSysMessage("DB table `gameobject_loot_template` reloaded.");
288    return true;
289}
290
291bool ChatHandler::HandleReloadLootTemplatesItemCommand(const char*)
292{
293    sLog.outString( "Re-Loading Loot Tables... (`item_loot_template`)" );
294    LoadLootTemplates_Item();
295    LootTemplates_Item.CheckLootRefs();
296    SendGlobalSysMessage("DB table `item_loot_template` reloaded.");
297    return true;
298}
299
300bool ChatHandler::HandleReloadLootTemplatesPickpocketingCommand(const char*)
301{
302    sLog.outString( "Re-Loading Loot Tables... (`pickpocketing_loot_template`)" );
303    LoadLootTemplates_Pickpocketing();
304    LootTemplates_Pickpocketing.CheckLootRefs();
305    SendGlobalSysMessage("DB table `pickpocketing_loot_template` reloaded.");
306    return true;
307}
308
309bool ChatHandler::HandleReloadLootTemplatesProspectingCommand(const char*)
310{
311    sLog.outString( "Re-Loading Loot Tables... (`prospecting_loot_template`)" );
312    LoadLootTemplates_Prospecting();
313    LootTemplates_Prospecting.CheckLootRefs();
314    SendGlobalSysMessage("DB table `prospecting_loot_template` reloaded.");
315    return true;
316}
317
318bool ChatHandler::HandleReloadLootTemplatesQuestMailCommand(const char*)
319{
320    sLog.outString( "Re-Loading Loot Tables... (`quest_mail_loot_template`)" );
321    LoadLootTemplates_QuestMail();
322    LootTemplates_QuestMail.CheckLootRefs();
323    SendGlobalSysMessage("DB table `quest_mail_loot_template` reloaded.");
324    return true;
325}
326
327bool ChatHandler::HandleReloadLootTemplatesReferenceCommand(const char*)
328{
329    sLog.outString( "Re-Loading Loot Tables... (`reference_loot_template`)" );
330    LoadLootTemplates_Reference();
331    SendGlobalSysMessage("DB table `reference_loot_template` reloaded.");
332    return true;
333}
334
335bool ChatHandler::HandleReloadLootTemplatesSkinningCommand(const char*)
336{
337    sLog.outString( "Re-Loading Loot Tables... (`skinning_loot_template`)" );
338    LoadLootTemplates_Skinning();
339    LootTemplates_Skinning.CheckLootRefs();
340    SendGlobalSysMessage("DB table `skinning_loot_template` reloaded.");
341    return true;
342}
343
344bool ChatHandler::HandleReloadTrinityStringCommand(const char*)
345{
346    sLog.outString( "Re-Loading trinity_string Table!" );
347    objmgr.LoadTrinityStrings();
348    SendGlobalSysMessage("DB table `trinity_string` reloaded.");
349    return true;
350}
351
352bool ChatHandler::HandleReloadNpcOptionCommand(const char*)
353{
354    sLog.outString( "Re-Loading `npc_option` Table!" );
355    objmgr.LoadNpcOptions();
356    SendGlobalSysMessage("DB table `npc_option` reloaded.");
357    return true;
358}
359
360bool ChatHandler::HandleReloadNpcGossipCommand(const char*)
361{
362    sLog.outString( "Re-Loading `npc_gossip` Table!" );
363    objmgr.LoadNpcTextId();
364    SendGlobalSysMessage("DB table `npc_gossip` reloaded.");
365    return true;
366}
367
368bool ChatHandler::HandleReloadNpcTrainerCommand(const char*)
369{
370    sLog.outString( "Re-Loading `npc_trainer` Table!" );
371    objmgr.LoadTrainerSpell();
372    SendGlobalSysMessage("DB table `npc_trainer` reloaded.");
373    return true;
374}
375
376bool ChatHandler::HandleReloadNpcVendorCommand(const char*)
377{
378    sLog.outString( "Re-Loading `npc_vendor` Table!" );
379    objmgr.LoadVendors();
380    SendGlobalSysMessage("DB table `npc_vendor` reloaded.");
381    return true;
382}
383
384bool ChatHandler::HandleReloadReservedNameCommand(const char*)
385{
386    sLog.outString( "Loading ReservedNames... (`reserved_name`)" );
387    objmgr.LoadReservedPlayersNames();
388    SendGlobalSysMessage("DB table `reserved_name` (player reserved names) reloaded.");
389    return true;
390}
391
392bool ChatHandler::HandleReloadSkillDiscoveryTemplateCommand(const char* /*args*/)
393{
394    sLog.outString( "Re-Loading Skill Discovery Table..." );
395    LoadSkillDiscoveryTable();
396    SendGlobalSysMessage("DB table `skill_discovery_template` (recipes discovered at crafting) reloaded.");
397    return true;
398}
399
400bool ChatHandler::HandleReloadSkillExtraItemTemplateCommand(const char* /*args*/)
401{
402    sLog.outString( "Re-Loading Skill Extra Item Table..." );
403    LoadSkillExtraItemTable();
404    SendGlobalSysMessage("DB table `skill_extra_item_template` (extra item creation when crafting) reloaded.");
405    return true;
406}
407
408bool ChatHandler::HandleReloadSkillFishingBaseLevelCommand(const char* /*args*/)
409{
410    sLog.outString( "Re-Loading Skill Fishing base level requirements..." );
411    objmgr.LoadFishingBaseSkillLevel();
412    SendGlobalSysMessage("DB table `skill_fishing_base_level` (fishing base level for zone/subzone) reloaded.");
413    return true;
414}
415
416bool ChatHandler::HandleReloadSpellAffectCommand(const char*)
417{
418    sLog.outString( "Re-Loading SpellAffect definitions..." );
419    spellmgr.LoadSpellAffects();
420    SendGlobalSysMessage("DB table `spell_affect` (spell mods apply requirements) reloaded.");
421    return true;
422}
423
424bool ChatHandler::HandleReloadSpellChainCommand(const char*)
425{
426    sLog.outString( "Re-Loading Spell Chain Data... " );
427    spellmgr.LoadSpellChains();
428    SendGlobalSysMessage("DB table `spell_chain` (spell ranks) reloaded.");
429    return true;
430}
431
432bool ChatHandler::HandleReloadSpellElixirCommand(const char*)
433{
434    sLog.outString( "Re-Loading Spell Elixir types..." );
435    spellmgr.LoadSpellElixirs();
436    SendGlobalSysMessage("DB table `spell_elixir` (spell elixir types) reloaded.");
437    return true;
438}
439
440bool ChatHandler::HandleReloadSpellLearnSpellCommand(const char*)
441{
442    sLog.outString( "Re-Loading Spell Learn Spells..." );
443    spellmgr.LoadSpellLearnSpells();
444    SendGlobalSysMessage("DB table `spell_learn_spell` reloaded.");
445    return true;
446}
447
448bool ChatHandler::HandleReloadSpellProcEventCommand(const char*)
449{
450    sLog.outString( "Re-Loading Spell Proc Event conditions..." );
451    spellmgr.LoadSpellProcEvents();
452    SendGlobalSysMessage("DB table `spell_proc_event` (spell proc trigger requirements) reloaded.");
453    return true;
454}
455
456bool ChatHandler::HandleReloadSpellScriptTargetCommand(const char*)
457{
458    sLog.outString( "Re-Loading SpellsScriptTarget..." );
459    spellmgr.LoadSpellScriptTarget();
460    SendGlobalSysMessage("DB table `spell_script_target` (spell targets selection in case specific creature/GO requirements) reloaded.");
461    return true;
462}
463
464bool ChatHandler::HandleReloadSpellTargetPositionCommand(const char*)
465{
466    sLog.outString( "Re-Loading Spell target coordinates..." );
467    spellmgr.LoadSpellTargetPositions();
468    SendGlobalSysMessage("DB table `spell_target_position` (destination coordinates for spell targets) reloaded.");
469    return true;
470}
471
472bool ChatHandler::HandleReloadSpellThreatsCommand(const char*)
473{
474    sLog.outString( "Re-Loading Aggro Spells Definitions...");
475    spellmgr.LoadSpellThreats();
476    SendGlobalSysMessage("DB table `spell_threat` (spell aggro definitions) reloaded.");
477    return true;
478}
479
480bool ChatHandler::HandleReloadSpellPetAurasCommand(const char*)
481{
482    sLog.outString( "Re-Loading Spell pet auras...");
483    spellmgr.LoadSpellPetAuras();
484    SendGlobalSysMessage("DB table `spell_pet_auras` reloaded.");
485    return true;
486}
487
488bool ChatHandler::HandleReloadPageTextsCommand(const char*)
489{
490    sLog.outString( "Re-Loading Page Texts..." );
491    objmgr.LoadPageTexts();
492    SendGlobalSysMessage("DB table `page_texts` reloaded.");
493    return true;
494}
495
496bool ChatHandler::HandleReloadItemEnchantementsCommand(const char*)
497{
498    sLog.outString( "Re-Loading Item Random Enchantments Table..." );
499    LoadRandomEnchantmentsTable();
500    SendGlobalSysMessage("DB table `item_enchantment_template` reloaded.");
501    return true;
502}
503
504bool ChatHandler::HandleReloadGameObjectScriptsCommand(const char* arg)
505{
506    if(sWorld.IsScriptScheduled())
507    {
508        SendSysMessage("DB scripts used currently, please attempt reload later.");
509        SetSentErrorMessage(true);
510        return false;
511    }
512
513    if(*arg!='a')
514        sLog.outString( "Re-Loading Scripts from `gameobject_scripts`...");
515
516    objmgr.LoadGameObjectScripts();
517
518    if(*arg!='a')
519        SendGlobalSysMessage("DB table `gameobject_scripts` reloaded.");
520
521    return true;
522}
523
524bool ChatHandler::HandleReloadEventScriptsCommand(const char* arg)
525{
526    if(sWorld.IsScriptScheduled())
527    {
528        SendSysMessage("DB scripts used currently, please attempt reload later.");
529        SetSentErrorMessage(true);
530        return false;
531    }
532
533    if(*arg!='a')
534        sLog.outString( "Re-Loading Scripts from `event_scripts`...");
535
536    objmgr.LoadEventScripts();
537
538    if(*arg!='a')
539        SendGlobalSysMessage("DB table `event_scripts` reloaded.");
540
541    return true;
542}
543
544bool ChatHandler::HandleReloadQuestEndScriptsCommand(const char* arg)
545{
546    if(sWorld.IsScriptScheduled())
547    {
548        SendSysMessage("DB scripts used currently, please attempt reload later.");
549        SetSentErrorMessage(true);
550        return false;
551    }
552
553    if(*arg!='a')
554        sLog.outString( "Re-Loading Scripts from `quest_end_scripts`...");
555
556    objmgr.LoadQuestEndScripts();
557
558    if(*arg!='a')
559        SendGlobalSysMessage("DB table `quest_end_scripts` reloaded.");
560
561    return true;
562}
563
564bool ChatHandler::HandleReloadQuestStartScriptsCommand(const char* arg)
565{
566    if(sWorld.IsScriptScheduled())
567    {
568        SendSysMessage("DB scripts used currently, please attempt reload later.");
569        SetSentErrorMessage(true);
570        return false;
571    }
572
573    if(*arg!='a')
574        sLog.outString( "Re-Loading Scripts from `quest_start_scripts`...");
575
576    objmgr.LoadQuestStartScripts();
577
578    if(*arg!='a')
579        SendGlobalSysMessage("DB table `quest_start_scripts` reloaded.");
580
581    return true;
582}
583
584bool ChatHandler::HandleReloadSpellScriptsCommand(const char* arg)
585{
586    if(sWorld.IsScriptScheduled())
587    {
588        SendSysMessage("DB scripts used currently, please attempt reload later.");
589        SetSentErrorMessage(true);
590        return false;
591    }
592
593    if(*arg!='a')
594        sLog.outString( "Re-Loading Scripts from `spell_scripts`...");
595
596    objmgr.LoadSpellScripts();
597
598    if(*arg!='a')
599        SendGlobalSysMessage("DB table `spell_scripts` reloaded.");
600
601    return true;
602}
603
604bool ChatHandler::HandleReloadGameGraveyardZoneCommand(const char* /*arg*/)
605{
606    sLog.outString( "Re-Loading Graveyard-zone links...");
607
608    objmgr.LoadGraveyardZones();
609
610    SendGlobalSysMessage("DB table `game_graveyard_zone` reloaded.");
611
612    return true;
613}
614
615bool ChatHandler::HandleReloadGameTeleCommand(const char* /*arg*/)
616{
617    sLog.outString( "Re-Loading Game Tele coordinates...");
618
619    objmgr.LoadGameTele();
620
621    SendGlobalSysMessage("DB table `game_tele` reloaded.");
622
623    return true;
624}
625
626bool ChatHandler::HandleReloadSpellDisabledCommand(const char* /*arg*/)
627{
628    sLog.outString( "Re-Loading spell disabled table...");
629
630    objmgr.LoadSpellDisabledEntrys();
631
632    SendGlobalSysMessage("DB table `spell_disabled` reloaded.");
633
634    return true;
635}
636
637bool ChatHandler::HandleReloadLocalesCreatureCommand(const char* /*arg*/)
638{
639    sLog.outString( "Re-Loading Locales Creature ...");
640    objmgr.LoadCreatureLocales();
641    SendGlobalSysMessage("DB table `locales_creature` reloaded.");
642    return true;
643}
644
645bool ChatHandler::HandleReloadLocalesGameobjectCommand(const char* /*arg*/)
646{
647    sLog.outString( "Re-Loading Locales Gameobject ... ");
648    objmgr.LoadGameObjectLocales();
649    SendGlobalSysMessage("DB table `locales_gameobject` reloaded.");
650    return true;
651}
652
653bool ChatHandler::HandleReloadLocalesItemCommand(const char* /*arg*/)
654{
655    sLog.outString( "Re-Loading Locales Item ... ");
656    objmgr.LoadItemLocales();
657    SendGlobalSysMessage("DB table `locales_item` reloaded.");
658    return true;
659}
660
661bool ChatHandler::HandleReloadLocalesNpcTextCommand(const char* /*arg*/)
662{
663    sLog.outString( "Re-Loading Locales NPC Text ... ");
664    objmgr.LoadNpcTextLocales();
665    SendGlobalSysMessage("DB table `locales_npc_text` reloaded.");
666    return true;
667}
668
669bool ChatHandler::HandleReloadLocalesPageTextCommand(const char* /*arg*/)
670{
671    sLog.outString( "Re-Loading Locales Page Text ... ");
672    objmgr.LoadPageTextLocales();
673    SendGlobalSysMessage("DB table `locales_page_text` reloaded.");
674    return true;
675}
676
677bool ChatHandler::HandleReloadLocalesQuestCommand(const char* /*arg*/)
678{
679    sLog.outString( "Re-Loading Locales Quest ... ");
680    objmgr.LoadQuestLocales();
681    SendGlobalSysMessage("DB table `locales_quest` reloaded.");
682    return true;
683}
684
685bool ChatHandler::HandleLoadScriptsCommand(const char* args)
686{
687    if(!LoadScriptingModule(args)) return true;
688
689    sWorld.SendWorldText(LANG_SCRIPTS_RELOADED);
690    return true;
691}
692
693bool ChatHandler::HandleAccountSetGmLevelCommand(const char* args)
694{
695    char* arg1 = strtok((char*)args, " ");
696    if( !arg1 )
697        return false;
698
699    /// must be NULL if targeted syntax and must be not nULL if not targeted
700    char* arg2 = strtok(NULL, " ");
701
702    std::string targetAccountName;
703    uint32 targetAccountId = 0;
704    uint32 targetSecurity = 0;
705
706    /// only target player different from self allowed (if targetPlayer!=NULL then not console)
707    Player* targetPlayer = getSelectedPlayer();
708    if(targetPlayer && m_session->GetPlayer()!=targetPlayer)
709    {
710        /// wrong command syntax or unexpected targeting
711        if(arg2)
712            return false;
713
714        /// security level expected in arg2 after this if.
715        arg2 = arg1;
716
717        targetAccountId = targetPlayer->GetSession()->GetAccountId();
718        targetSecurity = targetPlayer->GetSession()->GetSecurity();
719        if(!accmgr.GetName(targetAccountId,targetAccountName))
720        {
721            PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,targetAccountName.c_str());
722            SetSentErrorMessage(true);
723            return false;
724        }
725    }
726    else
727    {
728        /// wrong command syntax (second arg expected)
729        if(!arg2)
730            return false;
731
732        targetAccountName = arg1;
733        if(!AccountMgr::normilizeString(targetAccountName))
734        {
735            PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,targetAccountName.c_str());
736            SetSentErrorMessage(true);
737            return false;
738        }
739
740        targetAccountId = accmgr.GetId(targetAccountName);
741        targetSecurity = accmgr.GetSecurity(targetAccountId);
742    }
743
744    int32 gm = (int32)atoi(arg2);
745    if ( gm < SEC_PLAYER || gm > SEC_ADMINISTRATOR )
746    {
747        SendSysMessage(LANG_BAD_VALUE);
748        SetSentErrorMessage(true);
749        return false;
750    }
751
752    /// m_session==NULL only for console
753    uint32 plSecurity = m_session ? m_session->GetSecurity() : SEC_CONSOLE;
754
755    /// can set security level only for target with less security and to less security that we have
756    /// This is also reject self apply in fact
757    if(targetSecurity >= plSecurity || uint32(gm) >= plSecurity )
758    {
759        SendSysMessage(LANG_YOURS_SECURITY_IS_LOW);
760        SetSentErrorMessage(true);
761        return false;
762    }
763
764    if(targetPlayer)
765    {
766        ChatHandler(targetPlayer).PSendSysMessage(LANG_YOURS_SECURITY_CHANGED,GetName(), gm);
767        targetPlayer->GetSession()->SetSecurity(gm);
768    }
769
770    PSendSysMessage(LANG_YOU_CHANGE_SECURITY, targetAccountName.c_str(), gm);
771    loginDatabase.PExecute("UPDATE account SET gmlevel = '%i' WHERE id = '%u'", gm, targetAccountId);
772
773    return true;
774}
775
776/// Set password for account
777bool ChatHandler::HandleAccountSetPasswordCommand(const char* args)
778{
779    if(!*args)
780        return false;
781
782    ///- Get the command line arguments
783    char *szAccount = strtok ((char*)args," ");
784    char *szPassword1 =  strtok (NULL," ");
785    char *szPassword2 =  strtok (NULL," ");
786
787    if (!szAccount||!szPassword1 || !szPassword2)
788        return false;
789
790    std::string account_name = szAccount;
791    if(!AccountMgr::normilizeString(account_name))
792    {
793        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
794        SetSentErrorMessage(true);
795        return false;
796    }
797
798    uint32 targetAccountId = accmgr.GetId(account_name);
799    if (!targetAccountId)
800    {
801        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
802        SetSentErrorMessage(true);
803        return false;
804    }
805
806    uint32 targetSecurity = accmgr.GetSecurity(targetAccountId);
807
808    /// m_session==NULL only for console
809    uint32 plSecurity = m_session ? m_session->GetSecurity() : SEC_CONSOLE;
810
811    /// can set password only for target with less security
812    /// This is also reject self apply in fact
813    if (targetSecurity >= plSecurity)
814    {
815        SendSysMessage (LANG_YOURS_SECURITY_IS_LOW);
816        SetSentErrorMessage (true);
817        return false;
818    }
819
820    if (strcmp(szPassword1,szPassword2))
821    {
822        SendSysMessage (LANG_NEW_PASSWORDS_NOT_MATCH);
823        SetSentErrorMessage (true);
824        return false;
825    }
826
827    AccountOpResult result = accmgr.ChangePassword(targetAccountId, szPassword1);
828
829    switch(result)
830    {
831        case AOR_OK:
832            SendSysMessage(LANG_COMMAND_PASSWORD);
833            break;
834        case AOR_NAME_NOT_EXIST:
835            PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
836            SetSentErrorMessage(true);
837            return false;
838        case AOR_PASS_TOO_LONG:
839            SendSysMessage(LANG_PASSWORD_TOO_LONG);
840            SetSentErrorMessage(true);
841            return false;
842        default:
843            SendSysMessage(LANG_COMMAND_NOTCHANGEPASSWORD);
844            SetSentErrorMessage(true);
845            return false;
846    }
847
848    return true;
849}
850
851bool ChatHandler::HandleAllowMovementCommand(const char* /*args*/)
852{
853    if(sWorld.getAllowMovement())
854    {
855        sWorld.SetAllowMovement(false);
856        SendSysMessage(LANG_CREATURE_MOVE_DISABLED);
857    }
858    else
859    {
860        sWorld.SetAllowMovement(true);
861        SendSysMessage(LANG_CREATURE_MOVE_ENABLED);
862    }
863    return true;
864}
865
866bool ChatHandler::HandleMaxSkillCommand(const char* /*args*/)
867{
868    Player* SelectedPlayer = getSelectedPlayer();
869    if(!SelectedPlayer)
870    {
871        SendSysMessage(LANG_NO_CHAR_SELECTED);
872        SetSentErrorMessage(true);
873        return false;
874    }
875
876    // each skills that have max skill value dependent from level seted to current level max skill value
877    SelectedPlayer->UpdateSkillsToMaxSkillsForLevel();
878    return true;
879}
880
881bool ChatHandler::HandleSetSkillCommand(const char* args)
882{
883    // number or [name] Shift-click form |color|Hskill:skill_id|h[name]|h|r
884    char* skill_p = extractKeyFromLink((char*)args,"Hskill");
885    if(!skill_p)
886        return false;
887
888    char *level_p = strtok (NULL, " ");
889
890    if( !level_p)
891        return false;
892
893    char *max_p   = strtok (NULL, " ");
894
895    int32 skill = atoi(skill_p);
896
897    if (skill <= 0)
898    {
899        PSendSysMessage(LANG_INVALID_SKILL_ID, skill);
900        SetSentErrorMessage(true);
901        return false;
902    }
903
904    int32 level = atol (level_p);
905
906    Player * target = getSelectedPlayer();
907    if(!target)
908    {
909        SendSysMessage(LANG_NO_CHAR_SELECTED);
910        SetSentErrorMessage(true);
911        return false;
912    }
913
914    SkillLineEntry const* sl = sSkillLineStore.LookupEntry(skill);
915    if(!sl)
916    {
917        PSendSysMessage(LANG_INVALID_SKILL_ID, skill);
918        SetSentErrorMessage(true);
919        return false;
920    }
921
922    if(!target->GetSkillValue(skill))
923    {
924        PSendSysMessage(LANG_SET_SKILL_ERROR, target->GetName(), skill, sl->name[0]);
925        SetSentErrorMessage(true);
926        return false;
927    }
928
929    int32 max   = max_p ? atol (max_p) : target->GetPureMaxSkillValue(skill);
930
931    if( level <= 0 || level > max || max <= 0 )
932        return false;
933
934    target->SetSkill(skill, level, max);
935    PSendSysMessage(LANG_SET_SKILL, skill, sl->name[0], target->GetName(), level, max);
936
937    return true;
938}
939
940bool ChatHandler::HandleUnLearnCommand(const char* args)
941{
942    if (!*args)
943        return false;
944
945    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r
946    uint32 min_id = extractSpellIdFromLink((char*)args);
947    if(!min_id)
948        return false;
949
950    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r
951    char* tail = strtok(NULL,"");
952
953    uint32 max_id = extractSpellIdFromLink(tail);
954
955    if (!max_id)
956    {
957        // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r
958        max_id =  min_id+1;
959    }
960    else
961    {
962        if (max_id < min_id)
963            std::swap(min_id,max_id);
964
965        max_id=max_id+1;
966    }
967
968    Player* target = getSelectedPlayer();
969    if(!target)
970    {
971        SendSysMessage(LANG_NO_CHAR_SELECTED);
972        SetSentErrorMessage(true);
973        return false;
974    }
975
976    for(uint32 spell=min_id;spell<max_id;spell++)
977    {
978        if (target->HasSpell(spell))
979            target->removeSpell(spell);
980        else
981            SendSysMessage(LANG_FORGET_SPELL);
982    }
983
984    return true;
985}
986
987bool ChatHandler::HandleCooldownCommand(const char* args)
988{
989    Player* target = getSelectedPlayer();
990    if(!target)
991    {
992        SendSysMessage(LANG_PLAYER_NOT_FOUND);
993        SetSentErrorMessage(true);
994        return false;
995    }
996
997    if (!*args)
998    {
999        target->RemoveAllSpellCooldown();
1000        PSendSysMessage(LANG_REMOVEALL_COOLDOWN, target->GetName());
1001    }
1002    else
1003    {
1004        // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
1005        uint32 spell_id = extractSpellIdFromLink((char*)args);
1006        if(!spell_id)
1007            return false;
1008
1009        if(!sSpellStore.LookupEntry(spell_id))
1010        {
1011            PSendSysMessage(LANG_UNKNOWN_SPELL, target==m_session->GetPlayer() ? GetTrinityString(LANG_YOU) : target->GetName());
1012            SetSentErrorMessage(true);
1013            return false;
1014        }
1015
1016        WorldPacket data( SMSG_CLEAR_COOLDOWN, (4+8) );
1017        data << uint32(spell_id);
1018        data << uint64(target->GetGUID());
1019        target->GetSession()->SendPacket(&data);
1020        target->RemoveSpellCooldown(spell_id);
1021        PSendSysMessage(LANG_REMOVE_COOLDOWN, spell_id, target==m_session->GetPlayer() ? GetTrinityString(LANG_YOU) : target->GetName());
1022    }
1023    return true;
1024}
1025
1026bool ChatHandler::HandleLearnAllCommand(const char* /*args*/)
1027{
1028    static const char *allSpellList[] =
1029    {
1030        "3365",
1031        "6233",
1032        "6247",
1033        "6246",
1034        "6477",
1035        "6478",
1036        "22810",
1037        "8386",
1038        "21651",
1039        "21652",
1040        "522",
1041        "7266",
1042        "8597",
1043        "2479",
1044        "22027",
1045        "6603",
1046        "5019",
1047        "133",
1048        "168",
1049        "227",
1050        "5009",
1051        "9078",
1052        "668",
1053        "203",
1054        "20599",
1055        "20600",
1056        "81",
1057        "20597",
1058        "20598",
1059        "20864",
1060        "1459",
1061        "5504",
1062        "587",
1063        "5143",
1064        "118",
1065        "5505",
1066        "597",
1067        "604",
1068        "1449",
1069        "1460",
1070        "2855",
1071        "1008",
1072        "475",
1073        "5506",
1074        "1463",
1075        "12824",
1076        "8437",
1077        "990",
1078        "5145",
1079        "8450",
1080        "1461",
1081        "759",
1082        "8494",
1083        "8455",
1084        "8438",
1085        "6127",
1086        "8416",
1087        "6129",
1088        "8451",
1089        "8495",
1090        "8439",
1091        "3552",
1092        "8417",
1093        "10138",
1094        "12825",
1095        "10169",
1096        "10156",
1097        "10144",
1098        "10191",
1099        "10201",
1100        "10211",
1101        "10053",
1102        "10173",
1103        "10139",
1104        "10145",
1105        "10192",
1106        "10170",
1107        "10202",
1108        "10054",
1109        "10174",
1110        "10193",
1111        "12826",
1112        "2136",
1113        "143",
1114        "145",
1115        "2137",
1116        "2120",
1117        "3140",
1118        "543",
1119        "2138",
1120        "2948",
1121        "8400",
1122        "2121",
1123        "8444",
1124        "8412",
1125        "8457",
1126        "8401",
1127        "8422",
1128        "8445",
1129        "8402",
1130        "8413",
1131        "8458",
1132        "8423",
1133        "8446",
1134        "10148",
1135        "10197",
1136        "10205",
1137        "10149",
1138        "10215",
1139        "10223",
1140        "10206",
1141        "10199",
1142        "10150",
1143        "10216",
1144        "10207",
1145        "10225",
1146        "10151",
1147        "116",
1148        "205",
1149        "7300",
1150        "122",
1151        "837",
1152        "10",
1153        "7301",
1154        "7322",
1155        "6143",
1156        "120",
1157        "865",
1158        "8406",
1159        "6141",
1160        "7302",
1161        "8461",
1162        "8407",
1163        "8492",
1164        "8427",
1165        "8408",
1166        "6131",
1167        "7320",
1168        "10159",
1169        "8462",
1170        "10185",
1171        "10179",
1172        "10160",
1173        "10180",
1174        "10219",
1175        "10186",
1176        "10177",
1177        "10230",
1178        "10181",
1179        "10161",
1180        "10187",
1181        "10220",
1182        "2018",
1183        "2663",
1184        "12260",
1185        "2660",
1186        "3115",
1187        "3326",
1188        "2665",
1189        "3116",
1190        "2738",
1191        "3293",
1192        "2661",
1193        "3319",
1194        "2662",
1195        "9983",
1196        "8880",
1197        "2737",
1198        "2739",
1199        "7408",
1200        "3320",
1201        "2666",
1202        "3323",
1203        "3324",
1204        "3294",
1205        "22723",
1206        "23219",
1207        "23220",
1208        "23221",
1209        "23228",
1210        "23338",
1211        "10788",
1212        "10790",
1213        "5611",
1214        "5016",
1215        "5609",
1216        "2060",
1217        "10963",
1218        "10964",
1219        "10965",
1220        "22593",
1221        "22594",
1222        "596",
1223        "996",
1224        "499",
1225        "768",
1226        "17002",
1227        "1448",
1228        "1082",
1229        "16979",
1230        "1079",
1231        "5215",
1232        "20484",
1233        "5221",
1234        "15590",
1235        "17007",
1236        "6795",
1237        "6807",
1238        "5487",
1239        "1446",
1240        "1066",
1241        "5421",
1242        "3139",
1243        "779",
1244        "6811",
1245        "6808",
1246        "1445",
1247        "5216",
1248        "1737",
1249        "5222",
1250        "5217",
1251        "1432",
1252        "6812",
1253        "9492",
1254        "5210",
1255        "3030",
1256        "1441",
1257        "783",
1258        "6801",
1259        "20739",
1260        "8944",
1261        "9491",
1262        "22569",
1263        "5226",
1264        "6786",
1265        "1433",
1266        "8973",
1267        "1828",
1268        "9495",
1269        "9006",
1270        "6794",
1271        "8993",
1272        "5203",
1273        "16914",
1274        "6784",
1275        "9635",
1276        "22830",
1277        "20722",
1278        "9748",
1279        "6790",
1280        "9753",
1281        "9493",
1282        "9752",
1283        "9831",
1284        "9825",
1285        "9822",
1286        "5204",
1287        "5401",
1288        "22831",
1289        "6793",
1290        "9845",
1291        "17401",
1292        "9882",
1293        "9868",
1294        "20749",
1295        "9893",
1296        "9899",
1297        "9895",
1298        "9832",
1299        "9902",
1300        "9909",
1301        "22832",
1302        "9828",
1303        "9851",
1304        "9883",
1305        "9869",
1306        "17406",
1307        "17402",
1308        "9914",
1309        "20750",
1310        "9897",
1311        "9848",
1312        "3127",
1313        "107",
1314        "204",
1315        "9116",
1316        "2457",
1317        "78",
1318        "18848",
1319        "331",
1320        "403",
1321        "2098",
1322        "1752",
1323        "11278",
1324        "11288",
1325        "11284",
1326        "6461",
1327        "2344",
1328        "2345",
1329        "6463",
1330        "2346",
1331        "2352",
1332        "775",
1333        "1434",
1334        "1612",
1335        "71",
1336        "2468",
1337        "2458",
1338        "2467",
1339        "7164",
1340        "7178",
1341        "7367",
1342        "7376",
1343        "7381",
1344        "21156",
1345        "5209",
1346        "3029",
1347        "5201",
1348        "9849",
1349        "9850",
1350        "20719",
1351        "22568",
1352        "22827",
1353        "22828",
1354        "22829",
1355        "6809",
1356        "8972",
1357        "9005",
1358        "9823",
1359        "9827",
1360        "6783",
1361        "9913",
1362        "6785",
1363        "6787",
1364        "9866",
1365        "9867",
1366        "9894",
1367        "9896",
1368        "6800",
1369        "8992",
1370        "9829",
1371        "9830",
1372        "780",
1373        "769",
1374        "6749",
1375        "6750",
1376        "9755",
1377        "9754",
1378        "9908",
1379        "20745",
1380        "20742",
1381        "20747",
1382        "20748",
1383        "9746",
1384        "9745",
1385        "9880",
1386        "9881",
1387        "5391",
1388        "842",
1389        "3025",
1390        "3031",
1391        "3287",
1392        "3329",
1393        "1945",
1394        "3559",
1395        "4933",
1396        "4934",
1397        "4935",
1398        "4936",
1399        "5142",
1400        "5390",
1401        "5392",
1402        "5404",
1403        "5420",
1404        "6405",
1405        "7293",
1406        "7965",
1407        "8041",
1408        "8153",
1409        "9033",
1410        "9034",
1411        //"9036", problems with ghost state
1412        "16421",
1413        "21653",
1414        "22660",
1415        "5225",
1416        "9846",
1417        "2426",
1418        "5916",
1419        "6634",
1420        //"6718", phasing stealth, annoying for learn all case.
1421        "6719",
1422        "8822",
1423        "9591",
1424        "9590",
1425        "10032",
1426        "17746",
1427        "17747",
1428        "8203",
1429        "11392",
1430        "12495",
1431        "16380",
1432        "23452",
1433        "4079",
1434        "4996",
1435        "4997",
1436        "4998",
1437        "4999",
1438        "5000",
1439        "6348",
1440        "6349",
1441        "6481",
1442        "6482",
1443        "6483",
1444        "6484",
1445        "11362",
1446        "11410",
1447        "11409",
1448        "12510",
1449        "12509",
1450        "12885",
1451        "13142",
1452        "21463",
1453        "23460",
1454        "11421",
1455        "11416",
1456        "11418",
1457        "1851",
1458        "10059",
1459        "11423",
1460        "11417",
1461        "11422",
1462        "11419",
1463        "11424",
1464        "11420",
1465        "27",
1466        "31",
1467        "33",
1468        "34",
1469        "35",
1470        "15125",
1471        "21127",
1472        "22950",
1473        "1180",
1474        "201",
1475        "12593",
1476        "12842",
1477        "16770",
1478        "6057",
1479        "12051",
1480        "18468",
1481        "12606",
1482        "12605",
1483        "18466",
1484        "12502",
1485        "12043",
1486        "15060",
1487        "12042",
1488        "12341",
1489        "12848",
1490        "12344",
1491        "12353",
1492        "18460",
1493        "11366",
1494        "12350",
1495        "12352",
1496        "13043",
1497        "11368",
1498        "11113",
1499        "12400",
1500        "11129",
1501        "16766",
1502        "12573",
1503        "15053",
1504        "12580",
1505        "12475",
1506        "12472",
1507        "12953",
1508        "12488",
1509        "11189",
1510        "12985",
1511        "12519",
1512        "16758",
1513        "11958",
1514        "12490",
1515        "11426",
1516        "3565",
1517        "3562",
1518        "18960",
1519        "3567",
1520        "3561",
1521        "3566",
1522        "3563",
1523        "1953",
1524        "2139",
1525        "12505",
1526        "13018",
1527        "12522",
1528        "12523",
1529        "5146",
1530        "5144",
1531        "5148",
1532        "8419",
1533        "8418",
1534        "10213",
1535        "10212",
1536        "10157",
1537        "12524",
1538        "13019",
1539        "12525",
1540        "13020",
1541        "12526",
1542        "13021",
1543        "18809",
1544        "13031",
1545        "13032",
1546        "13033",
1547        "4036",
1548        "3920",
1549        "3919",
1550        "3918",
1551        "7430",
1552        "3922",
1553        "3923",
1554        "7411",
1555        "7418",
1556        "7421",
1557        "13262",
1558        "7412",
1559        "7415",
1560        "7413",
1561        "7416",
1562        "13920",
1563        "13921",
1564        "7745",
1565        "7779",
1566        "7428",
1567        "7457",
1568        "7857",
1569        "7748",
1570        "7426",
1571        "13421",
1572        "7454",
1573        "13378",
1574        "7788",
1575        "14807",
1576        "14293",
1577        "7795",
1578        "6296",
1579        "20608",
1580        "755",
1581        "444",
1582        "427",
1583        "428",
1584        "442",
1585        "447",
1586        "3578",
1587        "3581",
1588        "19027",
1589        "3580",
1590        "665",
1591        "3579",
1592        "3577",
1593        "6755",
1594        "3576",
1595        "2575",
1596        "2577",
1597        "2578",
1598        "2579",
1599        "2580",
1600        "2656",
1601        "2657",
1602        "2576",
1603        "3564",
1604        "10248",
1605        "8388",
1606        "2659",
1607        "14891",
1608        "3308",
1609        "3307",
1610        "10097",
1611        "2658",
1612        "3569",
1613        "16153",
1614        "3304",
1615        "10098",
1616        "4037",
1617        "3929",
1618        "3931",
1619        "3926",
1620        "3924",
1621        "3930",
1622        "3977",
1623        "3925",
1624        "136",
1625        "228",
1626        "5487",
1627        "43",
1628        "202",
1629        "0"
1630    };
1631
1632    int loop = 0;
1633    while(strcmp(allSpellList[loop], "0"))
1634    {
1635        uint32 spell = atol((char*)allSpellList[loop++]);
1636
1637        if (m_session->GetPlayer()->HasSpell(spell))
1638            continue;
1639
1640        SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
1641        if(!spellInfo || !SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
1642        {
1643            PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
1644            continue;
1645        }
1646
1647        m_session->GetPlayer()->learnSpell(spell);
1648    }
1649
1650    SendSysMessage(LANG_COMMAND_LEARN_MANY_SPELLS);
1651
1652    return true;
1653}
1654
1655bool ChatHandler::HandleLearnAllGMCommand(const char* /*args*/)
1656{
1657    static const char *gmSpellList[] =
1658    {
1659        "24347",                                            // Become A Fish, No Breath Bar
1660        "35132",                                            // Visual Boom
1661        "38488",                                            // Attack 4000-8000 AOE
1662        "38795",                                            // Attack 2000 AOE + Slow Down 90%
1663        "15712",                                            // Attack 200
1664        "1852",                                             // GM Spell Silence
1665        "31899",                                            // Kill
1666        "31924",                                            // Kill
1667        "29878",                                            // Kill My Self
1668        "26644",                                            // More Kill
1669
1670        "28550",                                            //Invisible 24
1671        "23452",                                            //Invisible + Target
1672        "0"
1673    };
1674
1675    uint16 gmSpellIter = 0;
1676    while( strcmp(gmSpellList[gmSpellIter], "0") )
1677    {
1678        uint32 spell = atol((char*)gmSpellList[gmSpellIter++]);
1679
1680        SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
1681        if(!spellInfo || !SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
1682        {
1683            PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
1684            continue;
1685        }
1686
1687        m_session->GetPlayer()->learnSpell(spell);
1688    }
1689
1690    SendSysMessage(LANG_LEARNING_GM_SKILLS);
1691    return true;
1692}
1693
1694bool ChatHandler::HandleLearnAllMyClassCommand(const char* /*args*/)
1695{
1696    HandleLearnAllMySpellsCommand("");
1697    HandleLearnAllMyTalentsCommand("");
1698    return true;
1699}
1700
1701bool ChatHandler::HandleLearnAllMySpellsCommand(const char* /*args*/)
1702{
1703    ChrClassesEntry const* clsEntry = sChrClassesStore.LookupEntry(m_session->GetPlayer()->getClass());
1704    if(!clsEntry)
1705        return true;
1706    uint32 family = clsEntry->spellfamily;
1707
1708    for (uint32 i = 0; i < sSpellStore.GetNumRows(); i++)
1709    {
1710        SpellEntry const *spellInfo = sSpellStore.LookupEntry(i);
1711        if(!spellInfo)
1712            continue;
1713
1714        // skip wrong class/race skills
1715        if(!m_session->GetPlayer()->IsSpellFitByClassAndRace(spellInfo->Id))
1716            continue;
1717
1718        // skip other spell families
1719        if( spellInfo->SpellFamilyName != family)
1720            continue;
1721
1722        //TODO: skip triggered spells
1723
1724        // skip spells with first rank learned as talent (and all talents then also)
1725        uint32 first_rank = spellmgr.GetFirstSpellInChain(spellInfo->Id);
1726        if(GetTalentSpellCost(first_rank) > 0 )
1727            continue;
1728
1729        // skip broken spells
1730        if(!SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer(),false))
1731            continue;
1732
1733        m_session->GetPlayer()->learnSpell(i);
1734    }
1735
1736    SendSysMessage(LANG_COMMAND_LEARN_CLASS_SPELLS);
1737    return true;
1738}
1739
1740static void learnAllHighRanks(Player* player, uint32 spellid)
1741{
1742    SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
1743    for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
1744    {
1745        player->learnSpell(itr->second);
1746        learnAllHighRanks(player,itr->second);
1747    }
1748}
1749
1750bool ChatHandler::HandleLearnAllMyTalentsCommand(const char* /*args*/)
1751{
1752    Player* player = m_session->GetPlayer();
1753    uint32 classMask = player->getClassMask();
1754
1755    for (uint32 i = 0; i < sTalentStore.GetNumRows(); i++)
1756    {
1757        TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
1758        if(!talentInfo)
1759            continue;
1760
1761        TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
1762        if(!talentTabInfo)
1763            continue;
1764
1765        if( (classMask & talentTabInfo->ClassMask) == 0 )
1766            continue;
1767
1768        // search highest talent rank
1769        uint32 spellid = 0;
1770        int rank = 4;
1771        for(; rank >= 0; --rank)
1772        {
1773            if(talentInfo->RankID[rank]!=0)
1774            {
1775                spellid = talentInfo->RankID[rank];
1776                break;
1777            }
1778        }
1779
1780        if(!spellid)                                        // ??? none spells in talent
1781            continue;
1782
1783        SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellid);
1784        if(!spellInfo || !SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer(),false))
1785            continue;
1786
1787        // learn highest rank of talent
1788        player->learnSpell(spellid);
1789
1790        // and learn all non-talent spell ranks (recursive by tree)
1791        learnAllHighRanks(player,spellid);
1792    }
1793
1794    SendSysMessage(LANG_COMMAND_LEARN_CLASS_TALENTS);
1795    return true;
1796}
1797
1798bool ChatHandler::HandleLearnAllLangCommand(const char* /*args*/)
1799{
1800    // skipping UNIVERSAL language (0)
1801    for(int i = 1; i < LANGUAGES_COUNT; ++i)
1802        m_session->GetPlayer()->learnSpell(lang_description[i].spell_id);
1803
1804    SendSysMessage(LANG_COMMAND_LEARN_ALL_LANG);
1805    return true;
1806}
1807
1808bool ChatHandler::HandleLearnAllDefaultCommand(const char* args)
1809{
1810    char* pName = strtok((char*)args, "");
1811    Player *player = NULL;
1812    if (pName)
1813    {
1814        std::string name = pName;
1815
1816        if(!normalizePlayerName(name))
1817        {
1818            SendSysMessage(LANG_PLAYER_NOT_FOUND);
1819            SetSentErrorMessage(true);
1820            return false;
1821        }
1822
1823        player = objmgr.GetPlayer(name.c_str());
1824    }
1825    else
1826        player = getSelectedPlayer();
1827
1828    if(!player)
1829    {
1830        SendSysMessage(LANG_NO_CHAR_SELECTED);
1831        SetSentErrorMessage(true);
1832        return false;
1833    }
1834
1835    player->learnDefaultSpells();
1836    player->learnQuestRewardedSpells();
1837
1838    PSendSysMessage(LANG_COMMAND_LEARN_ALL_DEFAULT_AND_QUEST,player->GetName());
1839    return true;
1840}
1841
1842bool ChatHandler::HandleLearnCommand(const char* args)
1843{
1844    Player* targetPlayer = getSelectedPlayer();
1845
1846    if(!targetPlayer)
1847    {
1848        SendSysMessage(LANG_PLAYER_NOT_FOUND);
1849        SetSentErrorMessage(true);
1850        return false;
1851    }
1852
1853    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
1854    uint32 spell = extractSpellIdFromLink((char*)args);
1855    if(!spell || !sSpellStore.LookupEntry(spell))
1856        return false;
1857
1858    if (targetPlayer->HasSpell(spell))
1859    {
1860        if(targetPlayer == m_session->GetPlayer())
1861            SendSysMessage(LANG_YOU_KNOWN_SPELL);
1862        else
1863            PSendSysMessage(LANG_TARGET_KNOWN_SPELL,targetPlayer->GetName());
1864        SetSentErrorMessage(true);
1865        return false;
1866    }
1867
1868    SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
1869    if(!spellInfo || !SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
1870    {
1871        PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
1872        SetSentErrorMessage(true);
1873        return false;
1874    }
1875
1876    targetPlayer->learnSpell(spell);
1877
1878    return true;
1879}
1880
1881bool ChatHandler::HandleAddItemCommand(const char* args)
1882{
1883    if (!*args)
1884        return false;
1885
1886    uint32 itemId = 0;
1887
1888    if(args[0]=='[')                                        // [name] manual form
1889    {
1890        char* citemName = citemName = strtok((char*)args, "]");
1891
1892        if(citemName && citemName[0])
1893        {
1894            std::string itemName = citemName+1;
1895            WorldDatabase.escape_string(itemName);
1896            QueryResult *result = WorldDatabase.PQuery("SELECT entry FROM item_template WHERE name = '%s'", itemName.c_str());
1897            if (!result)
1898            {
1899                PSendSysMessage(LANG_COMMAND_COULDNOTFIND, citemName+1);
1900                SetSentErrorMessage(true);
1901                return false;
1902            }
1903            itemId = result->Fetch()->GetUInt16();
1904            delete result;
1905        }
1906        else
1907            return false;
1908    }
1909    else                                                    // item_id or [name] Shift-click form |color|Hitem:item_id:0:0:0|h[name]|h|r
1910    {
1911        char* cId = extractKeyFromLink((char*)args,"Hitem");
1912        if(!cId)
1913            return false;
1914        itemId = atol(cId);
1915    }
1916
1917    char* ccount = strtok(NULL, " ");
1918
1919    int32 count = 1;
1920
1921    if (ccount)
1922        count = strtol(ccount, NULL, 10);
1923
1924    if (count == 0)
1925        count = 1;
1926
1927    Player* pl = m_session->GetPlayer();
1928    Player* plTarget = getSelectedPlayer();
1929    if(!plTarget)
1930        plTarget = pl;
1931
1932    sLog.outDetail(GetTrinityString(LANG_ADDITEM), itemId, count);
1933
1934    ItemPrototype const *pProto = objmgr.GetItemPrototype(itemId);
1935    if(!pProto)
1936    {
1937        PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, itemId);
1938        SetSentErrorMessage(true);
1939        return false;
1940    }
1941
1942    //Subtract
1943    if (count < 0)
1944    {
1945        plTarget->DestroyItemCount(itemId, -count, true, false);
1946        PSendSysMessage(LANG_REMOVEITEM, itemId, -count, plTarget->GetName());
1947        return true;
1948    }
1949
1950    //Adding items
1951    uint32 noSpaceForCount = 0;
1952
1953    // check space and find places
1954    ItemPosCountVec dest;
1955    uint8 msg = plTarget->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, count, &noSpaceForCount );
1956    if( msg != EQUIP_ERR_OK )                               // convert to possible store amount
1957        count -= noSpaceForCount;
1958
1959    if( count == 0 || dest.empty())                         // can't add any
1960    {
1961        PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itemId, noSpaceForCount );
1962        SetSentErrorMessage(true);
1963        return false;
1964    }
1965
1966    Item* item = plTarget->StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
1967
1968    // remove binding (let GM give it to another player later)
1969    if(pl==plTarget)
1970        for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
1971            if(Item* item1 = pl->GetItemByPos(itr->pos))
1972                item1->SetBinding( false );
1973
1974    if(count > 0 && item)
1975    {
1976        pl->SendNewItem(item,count,false,true);
1977        if(pl!=plTarget)
1978            plTarget->SendNewItem(item,count,true,false);
1979    }
1980
1981    if(noSpaceForCount > 0)
1982        PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itemId, noSpaceForCount);
1983
1984    return true;
1985}
1986
1987bool ChatHandler::HandleAddItemSetCommand(const char* args)
1988{
1989    if (!*args)
1990        return false;
1991
1992    char* cId = extractKeyFromLink((char*)args,"Hitemset"); // number or [name] Shift-click form |color|Hitemset:itemset_id|h[name]|h|r
1993    if (!cId)
1994        return false;
1995
1996    uint32 itemsetId = atol(cId);
1997
1998    // prevent generation all items with itemset field value '0'
1999    if (itemsetId == 0)
2000    {
2001        PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND,itemsetId);
2002        SetSentErrorMessage(true);
2003        return false;
2004    }
2005
2006    Player* pl = m_session->GetPlayer();
2007    Player* plTarget = getSelectedPlayer();
2008    if(!plTarget)
2009        plTarget = pl;
2010
2011    sLog.outDetail(GetTrinityString(LANG_ADDITEMSET), itemsetId);
2012
2013    bool found = false;
2014    for (uint32 id = 0; id < sItemStorage.MaxEntry; id++)
2015    {
2016        ItemPrototype const *pProto = sItemStorage.LookupEntry<ItemPrototype>(id);
2017        if (!pProto)
2018            continue;
2019
2020        if (pProto->ItemSet == itemsetId)
2021        {
2022            found = true;
2023            ItemPosCountVec dest;
2024            uint8 msg = plTarget->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pProto->ItemId, 1 );
2025            if (msg == EQUIP_ERR_OK)
2026            {
2027                Item* item = plTarget->StoreNewItem( dest, pProto->ItemId, true);
2028
2029                // remove binding (let GM give it to another player later)
2030                if (pl==plTarget)
2031                    item->SetBinding( false );
2032
2033                pl->SendNewItem(item,1,false,true);
2034                if (pl!=plTarget)
2035                    plTarget->SendNewItem(item,1,true,false);
2036            }
2037            else
2038            {
2039                pl->SendEquipError( msg, NULL, NULL );
2040                PSendSysMessage(LANG_ITEM_CANNOT_CREATE, pProto->ItemId, 1);
2041            }
2042        }
2043    }
2044
2045    if (!found)
2046    {
2047        PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND,itemsetId);
2048
2049        SetSentErrorMessage(true);
2050        return false;
2051    }
2052
2053    return true;
2054}
2055
2056bool ChatHandler::HandleListItemCommand(const char* args)
2057{
2058    if(!*args)
2059        return false;
2060
2061    char* cId = extractKeyFromLink((char*)args,"Hitem");
2062    if(!cId)
2063        return false;
2064
2065    uint32 item_id = atol(cId);
2066    if(!item_id)
2067    {
2068        PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id);
2069        SetSentErrorMessage(true);
2070        return false;
2071    }
2072
2073    ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_id);
2074    if(!itemProto)
2075    {
2076        PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id);
2077        SetSentErrorMessage(true);
2078        return false;
2079    }
2080
2081    char* c_count = strtok(NULL, " ");
2082    int count = c_count ? atol(c_count) : 10;
2083
2084    if(count < 0)
2085        return false;
2086
2087    QueryResult *result;
2088
2089    // inventory case
2090    uint32 inv_count = 0;
2091    result=CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM character_inventory WHERE item_template='%u'",item_id);
2092    if(result)
2093    {
2094        inv_count = (*result)[0].GetUInt32();
2095        delete result;
2096    }
2097
2098    result=CharacterDatabase.PQuery(
2099    //          0        1             2             3        4                  5
2100        "SELECT ci.item, cibag.slot AS bag, ci.slot, ci.guid, characters.account,characters.name "
2101        "FROM character_inventory AS ci LEFT JOIN character_inventory AS cibag ON (cibag.item=ci.bag),characters "
2102        "WHERE ci.item_template='%u' AND ci.guid = characters.guid LIMIT %u ",
2103        item_id,uint32(count));
2104
2105    if(result)
2106    {
2107        do
2108        {
2109            Field *fields = result->Fetch();
2110            uint32 item_guid = fields[0].GetUInt32();
2111            uint32 item_bag = fields[1].GetUInt32();
2112            uint32 item_slot = fields[2].GetUInt32();
2113            uint32 owner_guid = fields[3].GetUInt32();
2114            uint32 owner_acc = fields[4].GetUInt32();
2115            std::string owner_name = fields[5].GetCppString();
2116
2117            char const* item_pos = 0;
2118            if(Player::IsEquipmentPos(item_bag,item_slot))
2119                item_pos = "[equipped]";
2120            else if(Player::IsInventoryPos(item_bag,item_slot))
2121                item_pos = "[in inventory]";
2122            else if(Player::IsBankPos(item_bag,item_slot))
2123                item_pos = "[in bank]";
2124            else
2125                item_pos = "";
2126
2127            PSendSysMessage(LANG_ITEMLIST_SLOT,
2128                item_guid,owner_name.c_str(),owner_guid,owner_acc,item_pos);
2129        } while (result->NextRow());
2130
2131        int64 res_count = result->GetRowCount();
2132
2133        delete result;
2134
2135        if(count > res_count)
2136            count-=res_count;
2137        else if(count)
2138            count = 0;
2139    }
2140
2141    // mail case
2142    uint32 mail_count = 0;
2143    result=CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM mail_items WHERE item_template='%u'", item_id);
2144    if(result)
2145    {
2146        mail_count = (*result)[0].GetUInt32();
2147        delete result;
2148    }
2149
2150    if(count > 0)
2151    {
2152        result=CharacterDatabase.PQuery(
2153        //          0                     1            2              3               4            5               6
2154            "SELECT mail_items.item_guid, mail.sender, mail.receiver, char_s.account, char_s.name, char_r.account, char_r.name "
2155            "FROM mail,mail_items,characters as char_s,characters as char_r "
2156            "WHERE mail_items.item_template='%u' AND char_s.guid = mail.sender AND char_r.guid = mail.receiver AND mail.id=mail_items.mail_id LIMIT %u",
2157            item_id,uint32(count));
2158    }
2159    else
2160        result = NULL;
2161
2162    if(result)
2163    {
2164        do
2165        {
2166            Field *fields = result->Fetch();
2167            uint32 item_guid        = fields[0].GetUInt32();
2168            uint32 item_s           = fields[1].GetUInt32();
2169            uint32 item_r           = fields[2].GetUInt32();
2170            uint32 item_s_acc       = fields[3].GetUInt32();
2171            std::string item_s_name = fields[4].GetCppString();
2172            uint32 item_r_acc       = fields[5].GetUInt32();
2173            std::string item_r_name = fields[6].GetCppString();
2174
2175            char const* item_pos = "[in mail]";
2176
2177            PSendSysMessage(LANG_ITEMLIST_MAIL,
2178                item_guid,item_s_name.c_str(),item_s,item_s_acc,item_r_name.c_str(),item_r,item_r_acc,item_pos);
2179        } while (result->NextRow());
2180
2181        int64 res_count = result->GetRowCount();
2182
2183        delete result;
2184
2185        if(count > res_count)
2186            count-=res_count;
2187        else if(count)
2188            count = 0;
2189    }
2190
2191    // auction case
2192    uint32 auc_count = 0;
2193    result=CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM auctionhouse WHERE item_template='%u'",item_id);
2194    if(result)
2195    {
2196        auc_count = (*result)[0].GetUInt32();
2197        delete result;
2198    }
2199
2200    if(count > 0)
2201    {
2202        result=CharacterDatabase.PQuery(
2203        //           0                      1                       2                   3
2204            "SELECT  auctionhouse.itemguid, auctionhouse.itemowner, characters.account, characters.name "
2205            "FROM auctionhouse,characters WHERE auctionhouse.item_template='%u' AND characters.guid = auctionhouse.itemowner LIMIT %u",
2206            item_id,uint32(count));
2207    }
2208    else
2209        result = NULL;
2210
2211    if(result)
2212    {
2213        do
2214        {
2215            Field *fields = result->Fetch();
2216            uint32 item_guid       = fields[0].GetUInt32();
2217            uint32 owner           = fields[1].GetUInt32();
2218            uint32 owner_acc       = fields[2].GetUInt32();
2219            std::string owner_name = fields[3].GetCppString();
2220
2221            char const* item_pos = "[in auction]";
2222
2223            PSendSysMessage(LANG_ITEMLIST_AUCTION, item_guid, owner_name.c_str(), owner, owner_acc,item_pos);
2224        } while (result->NextRow());
2225
2226        delete result;
2227    }
2228
2229    // guild bank case
2230    uint32 guild_count = 0;
2231    result=CharacterDatabase.PQuery("SELECT COUNT(item_entry) FROM guild_bank_item WHERE item_entry='%u'",item_id);
2232    if(result)
2233    {
2234        guild_count = (*result)[0].GetUInt32();
2235        delete result;
2236    }
2237
2238    result=CharacterDatabase.PQuery(
2239        //      0             1           2
2240        "SELECT gi.item_guid, gi.guildid, guild.name "
2241        "FROM guild_bank_item AS gi, guild WHERE gi.item_entry='%u' AND gi.guildid = guild.guildid LIMIT %u ",
2242        item_id,uint32(count));
2243
2244    if(result)
2245    {
2246        do
2247        {
2248            Field *fields = result->Fetch();
2249            uint32 item_guid = fields[0].GetUInt32();
2250            uint32 guild_guid = fields[1].GetUInt32();
2251            std::string guild_name = fields[2].GetCppString();
2252
2253            char const* item_pos = "[in guild bank]";
2254
2255            PSendSysMessage(LANG_ITEMLIST_GUILD,item_guid,guild_name.c_str(),guild_guid,item_pos);
2256        } while (result->NextRow());
2257
2258        int64 res_count = result->GetRowCount();
2259
2260        delete result;
2261
2262        if(count > res_count)
2263            count-=res_count;
2264        else if(count)
2265            count = 0;
2266    }
2267
2268    if(inv_count+mail_count+auc_count+guild_count == 0)
2269    {
2270        SendSysMessage(LANG_COMMAND_NOITEMFOUND);
2271        SetSentErrorMessage(true);
2272        return false;
2273    }
2274
2275    PSendSysMessage(LANG_COMMAND_LISTITEMMESSAGE,item_id,inv_count+mail_count+auc_count+guild_count,inv_count,mail_count,auc_count,guild_count);
2276
2277    return true;
2278}
2279
2280bool ChatHandler::HandleListObjectCommand(const char* args)
2281{
2282    if(!*args)
2283        return false;
2284
2285    // number or [name] Shift-click form |color|Hgameobject_entry:go_id|h[name]|h|r
2286    char* cId = extractKeyFromLink((char*)args,"Hgameobject_entry");
2287    if(!cId)
2288        return false;
2289
2290    uint32 go_id = atol(cId);
2291    if(!go_id)
2292    {
2293        PSendSysMessage(LANG_COMMAND_LISTOBJINVALIDID, go_id);
2294        SetSentErrorMessage(true);
2295        return false;
2296    }
2297
2298    GameObjectInfo const * gInfo = objmgr.GetGameObjectInfo(go_id);
2299    if(!gInfo)
2300    {
2301        PSendSysMessage(LANG_COMMAND_LISTOBJINVALIDID, go_id);
2302        SetSentErrorMessage(true);
2303        return false;
2304    }
2305
2306    char* c_count = strtok(NULL, " ");
2307    int count = c_count ? atol(c_count) : 10;
2308
2309    if(count < 0)
2310        return false;
2311
2312    QueryResult *result;
2313
2314    uint32 obj_count = 0;
2315    result=WorldDatabase.PQuery("SELECT COUNT(guid) FROM gameobject WHERE id='%u'",go_id);
2316    if(result)
2317    {
2318        obj_count = (*result)[0].GetUInt32();
2319        delete result;
2320    }
2321
2322    if(m_session)
2323    {
2324        Player* pl = m_session->GetPlayer();
2325        result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map, (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ FROM gameobject WHERE id = '%u' ORDER BY order_ ASC LIMIT %u",
2326            pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(),go_id,uint32(count));
2327    }
2328    else
2329        result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map FROM gameobject WHERE id = '%u' LIMIT %u",
2330            go_id,uint32(count));
2331
2332    if (result)
2333    {
2334        do
2335        {
2336            Field *fields = result->Fetch();
2337            uint32 guid = fields[0].GetUInt32();
2338            float x = fields[1].GetFloat();
2339            float y = fields[2].GetFloat();
2340            float z = fields[3].GetFloat();
2341            int mapid = fields[4].GetUInt16();
2342
2343            if (m_session)
2344                PSendSysMessage(LANG_GO_LIST_CHAT, guid, guid, gInfo->name, x, y, z, mapid);
2345            else
2346                PSendSysMessage(LANG_GO_LIST_CONSOLE, guid, gInfo->name, x, y, z, mapid);
2347        } while (result->NextRow());
2348
2349        delete result;
2350    }
2351
2352    PSendSysMessage(LANG_COMMAND_LISTOBJMESSAGE,go_id,obj_count);
2353    return true;
2354}
2355
2356bool ChatHandler::HandleNearObjectCommand(const char* args)
2357{
2358    float distance = (!*args) ? 10 : atol(args);
2359    uint32 count = 0;
2360
2361    Player* pl = m_session->GetPlayer();
2362    QueryResult *result = WorldDatabase.PQuery("SELECT guid, id, position_x, position_y, position_z, map, "
2363        "(POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ "
2364        "FROM gameobject WHERE map='%u' AND (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) <= '%f' ORDER BY order_",
2365        pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(),
2366        pl->GetMapId(),pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(),distance*distance);
2367
2368    if (result)
2369    {
2370        do
2371        {
2372            Field *fields = result->Fetch();
2373            uint32 guid = fields[0].GetUInt32();
2374            uint32 entry = fields[1].GetUInt32();
2375            float x = fields[2].GetFloat();
2376            float y = fields[3].GetFloat();
2377            float z = fields[4].GetFloat();
2378            int mapid = fields[5].GetUInt16();
2379
2380            GameObjectInfo const * gInfo = objmgr.GetGameObjectInfo(entry);
2381
2382            if(!gInfo)
2383                continue;
2384
2385            PSendSysMessage(LANG_GO_LIST_CHAT, guid, guid, gInfo->name, x, y, z, mapid);
2386
2387            ++count;
2388        } while (result->NextRow());
2389
2390        delete result;
2391    }
2392
2393    PSendSysMessage(LANG_COMMAND_NEAROBJMESSAGE,distance,count);
2394    return true;
2395}
2396
2397bool ChatHandler::HandleObjectStateCommand(const char* args)
2398{
2399    // number or [name] Shift-click form |color|Hgameobject:go_id|h[name]|h|r
2400    char* cId = extractKeyFromLink((char*)args, "Hgameobject");
2401    if(!cId)
2402        return false;
2403
2404    uint32 lowguid = atoi(cId);
2405    if(!lowguid)
2406        return false;
2407
2408    GameObject* gobj = NULL;
2409
2410    if(GameObjectData const* goData = objmgr.GetGOData(lowguid))
2411        gobj = GetObjectGlobalyWithGuidOrNearWithDbGuid(lowguid, goData->id);
2412
2413    if(!gobj)
2414    {
2415        PSendSysMessage(LANG_COMMAND_OBJNOTFOUND, lowguid);
2416        SetSentErrorMessage(true);
2417        return false;
2418    }
2419
2420    char* cstate = strtok(NULL, " ");
2421    if(!cstate)
2422        return false;
2423
2424    int32 state = atoi(cstate);
2425    if(state < 0)
2426        gobj->SendObjectDeSpawnAnim(gobj->GetGUID());
2427    else
2428        gobj->SetGoState(state);
2429
2430    return true;
2431
2432    return true;
2433}
2434
2435bool ChatHandler::HandleListCreatureCommand(const char* args)
2436{
2437    if(!*args)
2438        return false;
2439
2440    // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
2441    char* cId = extractKeyFromLink((char*)args,"Hcreature_entry");
2442    if(!cId)
2443        return false;
2444
2445    uint32 cr_id = atol(cId);
2446    if(!cr_id)
2447    {
2448        PSendSysMessage(LANG_COMMAND_INVALIDCREATUREID, cr_id);
2449        SetSentErrorMessage(true);
2450        return false;
2451    }
2452
2453    CreatureInfo const* cInfo = objmgr.GetCreatureTemplate(cr_id);
2454    if(!cInfo)
2455    {
2456        PSendSysMessage(LANG_COMMAND_INVALIDCREATUREID, cr_id);
2457        SetSentErrorMessage(true);
2458        return false;
2459    }
2460
2461    char* c_count = strtok(NULL, " ");
2462    int count = c_count ? atol(c_count) : 10;
2463
2464    if(count < 0)
2465        return false;
2466
2467    QueryResult *result;
2468
2469    uint32 cr_count = 0;
2470    result=WorldDatabase.PQuery("SELECT COUNT(guid) FROM creature WHERE id='%u'",cr_id);
2471    if(result)
2472    {
2473        cr_count = (*result)[0].GetUInt32();
2474        delete result;
2475    }
2476
2477    if(m_session)
2478    {
2479        Player* pl = m_session->GetPlayer();
2480        result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map, (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ FROM creature WHERE id = '%u' ORDER BY order_ ASC LIMIT %u",
2481            pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), cr_id,uint32(count));
2482    }
2483    else
2484        result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map FROM creature WHERE id = '%u' LIMIT %u",
2485            cr_id,uint32(count));
2486
2487    if (result)
2488    {
2489        do
2490        {
2491            Field *fields = result->Fetch();
2492            uint32 guid = fields[0].GetUInt32();
2493            float x = fields[1].GetFloat();
2494            float y = fields[2].GetFloat();
2495            float z = fields[3].GetFloat();
2496            int mapid = fields[4].GetUInt16();
2497
2498            if  (m_session)
2499                PSendSysMessage(LANG_CREATURE_LIST_CHAT, guid, guid, cInfo->Name, x, y, z, mapid);
2500            else
2501                PSendSysMessage(LANG_CREATURE_LIST_CONSOLE, guid, cInfo->Name, x, y, z, mapid);
2502        } while (result->NextRow());
2503
2504        delete result;
2505    }
2506
2507    PSendSysMessage(LANG_COMMAND_LISTCREATUREMESSAGE,cr_id,cr_count);
2508    return true;
2509}
2510
2511bool ChatHandler::HandleLookupItemCommand(const char* args)
2512{
2513    if(!*args)
2514        return false;
2515
2516    std::string namepart = args;
2517    std::wstring wnamepart;
2518
2519    // converting string that we try to find to lower case
2520    if(!Utf8toWStr(namepart,wnamepart))
2521        return false;
2522
2523    wstrToLower(wnamepart);
2524
2525    uint32 counter = 0;
2526
2527    // Search in `item_template`
2528    for (uint32 id = 0; id < sItemStorage.MaxEntry; id++)
2529    {
2530        ItemPrototype const *pProto = sItemStorage.LookupEntry<ItemPrototype >(id);
2531        if(!pProto)
2532            continue;
2533
2534        int loc_idx = m_session ? m_session->GetSessionDbLocaleIndex() : objmgr.GetDBCLocaleIndex();
2535        if ( loc_idx >= 0 )
2536        {
2537            ItemLocale const *il = objmgr.GetItemLocale(pProto->ItemId);
2538            if (il)
2539            {
2540                if (il->Name.size() > loc_idx && !il->Name[loc_idx].empty())
2541                {
2542                    std::string name = il->Name[loc_idx];
2543
2544                    if (Utf8FitTo(name, wnamepart))
2545                    {
2546                        if (m_session)
2547                            PSendSysMessage(LANG_ITEM_LIST_CHAT, id, id, name.c_str());
2548                        else
2549                            PSendSysMessage(LANG_ITEM_LIST_CONSOLE, id, name.c_str());
2550                        ++counter;
2551                        continue;
2552                    }
2553                }
2554            }
2555        }
2556
2557        std::string name = pProto->Name1;
2558        if(name.empty())
2559            continue;
2560
2561        if (Utf8FitTo(name, wnamepart))
2562        {
2563            if (m_session)
2564                PSendSysMessage(LANG_ITEM_LIST_CHAT, id, id, name.c_str());
2565            else
2566                PSendSysMessage(LANG_ITEM_LIST_CONSOLE, id, name.c_str());
2567            ++counter;
2568        }
2569    }
2570
2571    if (counter==0)
2572        SendSysMessage(LANG_COMMAND_NOITEMFOUND);
2573
2574    return true;
2575}
2576
2577bool ChatHandler::HandleLookupItemSetCommand(const char* args)
2578{
2579    if(!*args)
2580        return false;
2581
2582    std::string namepart = args;
2583    std::wstring wnamepart;
2584
2585    if(!Utf8toWStr(namepart,wnamepart))
2586        return false;
2587
2588    // converting string that we try to find to lower case
2589    wstrToLower( wnamepart );
2590
2591    uint32 counter = 0;                                     // Counter for figure out that we found smth.
2592
2593    // Search in ItemSet.dbc
2594    for (uint32 id = 0; id < sItemSetStore.GetNumRows(); id++)
2595    {
2596        ItemSetEntry const *set = sItemSetStore.LookupEntry(id);
2597        if(set)
2598        {
2599            int loc = m_session ? m_session->GetSessionDbcLocale() : sWorld.GetDefaultDbcLocale();
2600            std::string name = set->name[loc];
2601            if(name.empty())
2602                continue;
2603
2604            if (!Utf8FitTo(name, wnamepart))
2605            {
2606                loc = 0;
2607                for(; loc < MAX_LOCALE; ++loc)
2608                {
2609                    if(m_session && loc==m_session->GetSessionDbcLocale())
2610                        continue;
2611
2612                    name = set->name[loc];
2613                    if(name.empty())
2614                        continue;
2615
2616                    if (Utf8FitTo(name, wnamepart))
2617                        break;
2618                }
2619            }
2620
2621            if(loc < MAX_LOCALE)
2622            {
2623                // send item set in "id - [namedlink locale]" format
2624                if (m_session)
2625                    PSendSysMessage(LANG_ITEMSET_LIST_CHAT,id,id,name.c_str(),localeNames[loc]);
2626                else
2627                    PSendSysMessage(LANG_ITEMSET_LIST_CONSOLE,id,name.c_str(),localeNames[loc]);
2628                ++counter;
2629            }
2630        }
2631    }
2632    if (counter == 0)                                       // if counter == 0 then we found nth
2633        SendSysMessage(LANG_COMMAND_NOITEMSETFOUND);
2634    return true;
2635}
2636
2637bool ChatHandler::HandleLookupSkillCommand(const char* args)
2638{
2639    if(!*args)
2640        return false;
2641
2642    // can be NULL in console call
2643    Player* target = getSelectedPlayer();
2644
2645    std::string namepart = args;
2646    std::wstring wnamepart;
2647
2648    if(!Utf8toWStr(namepart,wnamepart))
2649        return false;
2650
2651    // converting string that we try to find to lower case
2652    wstrToLower( wnamepart );
2653
2654    uint32 counter = 0;                                     // Counter for figure out that we found smth.
2655
2656    // Search in SkillLine.dbc
2657    for (uint32 id = 0; id < sSkillLineStore.GetNumRows(); id++)
2658    {
2659        SkillLineEntry const *skillInfo = sSkillLineStore.LookupEntry(id);
2660        if(skillInfo)
2661        {
2662            int loc = m_session ? m_session->GetSessionDbcLocale() : sWorld.GetDefaultDbcLocale();
2663            std::string name = skillInfo->name[loc];
2664            if(name.empty())
2665                continue;
2666
2667            if (!Utf8FitTo(name, wnamepart))
2668            {
2669                loc = 0;
2670                for(; loc < MAX_LOCALE; ++loc)
2671                {
2672                    if(m_session && loc==m_session->GetSessionDbcLocale())
2673                        continue;
2674
2675                    name = skillInfo->name[loc];
2676                    if(name.empty())
2677                        continue;
2678
2679                    if (Utf8FitTo(name, wnamepart))
2680                        break;
2681                }
2682            }
2683
2684            if(loc < MAX_LOCALE)
2685            {
2686                char const* knownStr = "";
2687                if(target && target->HasSkill(id))
2688                    knownStr = GetTrinityString(LANG_KNOWN);
2689
2690                // send skill in "id - [namedlink locale]" format
2691                if (m_session)
2692                    PSendSysMessage(LANG_SKILL_LIST_CHAT,id,id,name.c_str(),localeNames[loc],knownStr);
2693                else
2694                    PSendSysMessage(LANG_SKILL_LIST_CONSOLE,id,name.c_str(),localeNames[loc],knownStr);
2695
2696                ++counter;
2697            }
2698        }
2699    }
2700    if (counter == 0)                                       // if counter == 0 then we found nth
2701        SendSysMessage(LANG_COMMAND_NOSKILLFOUND);
2702    return true;
2703}
2704
2705bool ChatHandler::HandleLookupSpellCommand(const char* args)
2706{
2707    if(!*args)
2708        return false;
2709
2710    // can be NULL at console call
2711    Player* target = getSelectedPlayer();
2712
2713    std::string namepart = args;
2714    std::wstring wnamepart;
2715
2716    if(!Utf8toWStr(namepart,wnamepart))
2717        return false;
2718
2719    // converting string that we try to find to lower case
2720    wstrToLower( wnamepart );
2721
2722    uint32 counter = 0;                                     // Counter for figure out that we found smth.
2723
2724    // Search in Spell.dbc
2725    for (uint32 id = 0; id < sSpellStore.GetNumRows(); id++)
2726    {
2727        SpellEntry const *spellInfo = sSpellStore.LookupEntry(id);
2728        if(spellInfo)
2729        {
2730            int loc = m_session ? m_session->GetSessionDbcLocale() : sWorld.GetDefaultDbcLocale();
2731            std::string name = spellInfo->SpellName[loc];
2732            if(name.empty())
2733                continue;
2734
2735            if (!Utf8FitTo(name, wnamepart))
2736            {
2737                loc = 0;
2738                for(; loc < MAX_LOCALE; ++loc)
2739                {
2740                    if(m_session && loc==m_session->GetSessionDbcLocale())
2741                        continue;
2742
2743                    name = spellInfo->SpellName[loc];
2744                    if(name.empty())
2745                        continue;
2746
2747                    if (Utf8FitTo(name, wnamepart))
2748                        break;
2749                }
2750            }
2751
2752            if(loc < MAX_LOCALE)
2753            {
2754                bool known = target && target->HasSpell(id);
2755                bool learn = (spellInfo->Effect[0] == SPELL_EFFECT_LEARN_SPELL);
2756
2757                uint32 talentCost = GetTalentSpellCost(id);
2758
2759                bool talent = (talentCost > 0);
2760                bool passive = IsPassiveSpell(id);
2761                bool active = target && (target->HasAura(id,0) || target->HasAura(id,1) || target->HasAura(id,2));
2762
2763                // unit32 used to prevent interpreting uint8 as char at output
2764                // find rank of learned spell for learning spell, or talent rank
2765                uint32 rank = talentCost ? talentCost : spellmgr.GetSpellRank(learn ? spellInfo->EffectTriggerSpell[0] : id);
2766
2767                // send spell in "id - [name, rank N] [talent] [passive] [learn] [known]" format
2768                std::ostringstream ss;
2769                if (m_session)
2770                    ss << id << " - |cffffffff|Hspell:" << id << "|h[" << name;
2771                else
2772                    ss << id << " - " << name;
2773
2774                // include rank in link name
2775                if(rank)
2776                    ss << GetTrinityString(LANG_SPELL_RANK) << rank;
2777
2778                if (m_session)
2779                    ss << " " << localeNames[loc] << "]|h|r";
2780                else
2781                    ss << " " << localeNames[loc];
2782
2783                if(talent)
2784                    ss << GetTrinityString(LANG_TALENT);
2785                if(passive)
2786                    ss << GetTrinityString(LANG_PASSIVE);
2787                if(learn)
2788                    ss << GetTrinityString(LANG_LEARN);
2789                if(known)
2790                    ss << GetTrinityString(LANG_KNOWN);
2791                if(active)
2792                    ss << GetTrinityString(LANG_ACTIVE);
2793
2794                SendSysMessage(ss.str().c_str());
2795
2796                ++counter;
2797            }
2798        }
2799    }
2800    if (counter == 0)                                       // if counter == 0 then we found nth
2801        SendSysMessage(LANG_COMMAND_NOSPELLFOUND);
2802    return true;
2803}
2804
2805bool ChatHandler::HandleLookupQuestCommand(const char* args)
2806{
2807    if(!*args)
2808        return false;
2809
2810    // can be NULL at console call
2811    Player* target = getSelectedPlayer();
2812
2813    std::string namepart = args;
2814    std::wstring wnamepart;
2815
2816    // converting string that we try to find to lower case
2817    if(!Utf8toWStr(namepart,wnamepart))
2818        return false;
2819
2820    wstrToLower(wnamepart);
2821
2822    uint32 counter = 0 ;
2823
2824    ObjectMgr::QuestMap const& qTemplates = objmgr.GetQuestTemplates();
2825    for (ObjectMgr::QuestMap::const_iterator iter = qTemplates.begin(); iter != qTemplates.end(); ++iter)
2826    {
2827        Quest * qinfo = iter->second;
2828
2829        int loc_idx = m_session ? m_session->GetSessionDbLocaleIndex() : objmgr.GetDBCLocaleIndex();
2830        if ( loc_idx >= 0 )
2831        {
2832            QuestLocale const *il = objmgr.GetQuestLocale(qinfo->GetQuestId());
2833            if (il)
2834            {
2835                if (il->Title.size() > loc_idx && !il->Title[loc_idx].empty())
2836                {
2837                    std::string title = il->Title[loc_idx];
2838
2839                    if (Utf8FitTo(title, wnamepart))
2840                    {
2841                        char const* statusStr = "";
2842
2843                        if(target)
2844                        {
2845                            QuestStatus status = target->GetQuestStatus(qinfo->GetQuestId());
2846
2847                            if(status == QUEST_STATUS_COMPLETE)
2848                            {
2849                                if(target->GetQuestRewardStatus(qinfo->GetQuestId()))
2850                                    statusStr = GetTrinityString(LANG_COMMAND_QUEST_REWARDED);
2851                                else
2852                                    statusStr = GetTrinityString(LANG_COMMAND_QUEST_COMPLETE);
2853                            }
2854                            else if(status == QUEST_STATUS_INCOMPLETE)
2855                                statusStr = GetTrinityString(LANG_COMMAND_QUEST_ACTIVE);
2856                        }
2857
2858                        if (m_session)
2859                            PSendSysMessage(LANG_QUEST_LIST_CHAT,qinfo->GetQuestId(),qinfo->GetQuestId(),title.c_str(),statusStr);
2860                        else
2861                            PSendSysMessage(LANG_QUEST_LIST_CONSOLE,qinfo->GetQuestId(),title.c_str(),statusStr);
2862                        ++counter;
2863                        continue;
2864                    }
2865                }
2866            }
2867        }
2868
2869        std::string title = qinfo->GetTitle();
2870        if(title.empty())
2871            continue;
2872
2873        if (Utf8FitTo(title, wnamepart))
2874        {
2875            char const* statusStr = "";
2876
2877            if(target)
2878            {
2879                QuestStatus status = target->GetQuestStatus(qinfo->GetQuestId());
2880
2881                if(status == QUEST_STATUS_COMPLETE)
2882                {
2883                    if(target->GetQuestRewardStatus(qinfo->GetQuestId()))
2884                        statusStr = GetTrinityString(LANG_COMMAND_QUEST_REWARDED);
2885                    else
2886                        statusStr = GetTrinityString(LANG_COMMAND_QUEST_COMPLETE);
2887                }
2888                else if(status == QUEST_STATUS_INCOMPLETE)
2889                    statusStr = GetTrinityString(LANG_COMMAND_QUEST_ACTIVE);
2890            }
2891
2892            if (m_session)
2893                PSendSysMessage(LANG_QUEST_LIST_CHAT,qinfo->GetQuestId(),qinfo->GetQuestId(),title.c_str(),statusStr);
2894            else
2895                PSendSysMessage(LANG_QUEST_LIST_CONSOLE,qinfo->GetQuestId(),title.c_str(),statusStr);
2896
2897            ++counter;
2898        }
2899    }
2900
2901    if (counter==0)
2902        SendSysMessage(LANG_COMMAND_NOQUESTFOUND);
2903
2904    return true;
2905}
2906
2907bool ChatHandler::HandleLookupCreatureCommand(const char* args)
2908{
2909    if (!*args)
2910        return false;
2911
2912    std::string namepart = args;
2913    std::wstring wnamepart;
2914
2915    // converting string that we try to find to lower case
2916    if (!Utf8toWStr (namepart,wnamepart))
2917        return false;
2918
2919    wstrToLower (wnamepart);
2920
2921    uint32 counter = 0;
2922
2923    for (uint32 id = 0; id< sCreatureStorage.MaxEntry; ++id)
2924    {
2925        CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo> (id);
2926        if(!cInfo)
2927            continue;
2928
2929        int loc_idx = m_session ? m_session->GetSessionDbLocaleIndex() : objmgr.GetDBCLocaleIndex();
2930        if (loc_idx >= 0)
2931        {
2932            CreatureLocale const *cl = objmgr.GetCreatureLocale (id);
2933            if (cl)
2934            {
2935                if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty ())
2936                {
2937                    std::string name = cl->Name[loc_idx];
2938
2939                    if (Utf8FitTo (name, wnamepart))
2940                    {
2941                        if (m_session)
2942                            PSendSysMessage (LANG_CREATURE_ENTRY_LIST_CHAT, id, id, name.c_str ());
2943                        else
2944                            PSendSysMessage (LANG_CREATURE_ENTRY_LIST_CONSOLE, id, name.c_str ());
2945                        ++counter;
2946                        continue;
2947                    }
2948                }
2949            }
2950        }
2951
2952        std::string name = cInfo->Name;
2953        if (name.empty ())
2954            continue;
2955
2956        if (Utf8FitTo(name, wnamepart))
2957        {
2958            if (m_session)
2959                PSendSysMessage (LANG_CREATURE_ENTRY_LIST_CHAT, id, id, name.c_str ());
2960            else
2961                PSendSysMessage (LANG_CREATURE_ENTRY_LIST_CONSOLE, id, name.c_str ());
2962            ++counter;
2963        }
2964    }
2965
2966    if (counter==0)
2967        SendSysMessage (LANG_COMMAND_NOCREATUREFOUND);
2968
2969    return true;
2970}
2971
2972bool ChatHandler::HandleLookupObjectCommand(const char* args)
2973{
2974    if(!*args)
2975        return false;
2976
2977    std::string namepart = args;
2978    std::wstring wnamepart;
2979
2980    // converting string that we try to find to lower case
2981    if(!Utf8toWStr(namepart,wnamepart))
2982        return false;
2983
2984    wstrToLower(wnamepart);
2985
2986    uint32 counter = 0;
2987
2988    for (uint32 id = 0; id< sGOStorage.MaxEntry; id++ )
2989    {
2990        GameObjectInfo const* gInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
2991        if(!gInfo)
2992            continue;
2993
2994        int loc_idx = m_session ? m_session->GetSessionDbLocaleIndex() : objmgr.GetDBCLocaleIndex();
2995        if ( loc_idx >= 0 )
2996        {
2997            GameObjectLocale const *gl = objmgr.GetGameObjectLocale(id);
2998            if (gl)
2999            {
3000                if (gl->Name.size() > loc_idx && !gl->Name[loc_idx].empty())
3001                {
3002                    std::string name = gl->Name[loc_idx];
3003
3004                    if (Utf8FitTo(name, wnamepart))
3005                    {
3006                        if (m_session)
3007                            PSendSysMessage(LANG_GO_ENTRY_LIST_CHAT, id, id, name.c_str());
3008                        else
3009                            PSendSysMessage(LANG_GO_ENTRY_LIST_CONSOLE, id, name.c_str());
3010                        ++counter;
3011                        continue;
3012                    }
3013                }
3014            }
3015        }
3016
3017        std::string name = gInfo->name;
3018        if(name.empty())
3019            continue;
3020
3021        if(Utf8FitTo(name, wnamepart))
3022        {
3023            if (m_session)
3024                PSendSysMessage(LANG_GO_ENTRY_LIST_CHAT, id, id, name.c_str());
3025            else
3026                PSendSysMessage(LANG_GO_ENTRY_LIST_CONSOLE, id, name.c_str());
3027            ++counter;
3028        }
3029    }
3030
3031    if(counter==0)
3032        SendSysMessage(LANG_COMMAND_NOGAMEOBJECTFOUND);
3033
3034    return true;
3035}
3036
3037/** \brief GM command level 3 - Create a guild.
3038 *
3039 * This command allows a GM (level 3) to create a guild.
3040 *
3041 * The "args" parameter contains the name of the guild leader
3042 * and then the name of the guild.
3043 *
3044 */
3045bool ChatHandler::HandleGuildCreateCommand(const char* args)
3046{
3047
3048    if (!*args)
3049        return false;
3050
3051    char *lname = strtok ((char*)args, " ");
3052    char *gname = strtok (NULL, "");
3053
3054    if (!lname)
3055        return false;
3056
3057    if (!gname)
3058    {
3059        SendSysMessage (LANG_INSERT_GUILD_NAME);
3060        SetSentErrorMessage (true);
3061        return false;
3062    }
3063
3064    std::string guildname = gname;
3065
3066    Player* player = ObjectAccessor::Instance ().FindPlayerByName (lname);
3067    if (!player)
3068    {
3069        SendSysMessage (LANG_PLAYER_NOT_FOUND);
3070        SetSentErrorMessage (true);
3071        return false;
3072    }
3073
3074    if (player->GetGuildId())
3075    {
3076        SendSysMessage (LANG_PLAYER_IN_GUILD);
3077        return true;
3078    }
3079
3080    Guild *guild = new Guild;
3081    if (!guild->create (player->GetGUID (),guildname))
3082    {
3083        delete guild;
3084        SendSysMessage (LANG_GUILD_NOT_CREATED);
3085        SetSentErrorMessage (true);
3086        return false;
3087    }
3088
3089    objmgr.AddGuild (guild);
3090    return true;
3091}
3092
3093bool ChatHandler::HandleGuildInviteCommand(const char *args)
3094{
3095    if (!*args)
3096        return false;
3097
3098    char* par1 = strtok ((char*)args, " ");
3099    char* par2 = strtok (NULL, "");
3100    if(!par1 || !par2)
3101        return false;
3102
3103    std::string glName = par2;
3104    Guild* targetGuild = objmgr.GetGuildByName (glName);
3105    if (!targetGuild)
3106        return false;
3107
3108    std::string plName = par1;
3109    if (!normalizePlayerName (plName))
3110    {
3111        SendSysMessage (LANG_PLAYER_NOT_FOUND);
3112        SetSentErrorMessage (true);
3113        return false;
3114    }
3115
3116    uint64 plGuid = 0;
3117    if (Player* targetPlayer = ObjectAccessor::Instance ().FindPlayerByName (plName.c_str ()))
3118        plGuid = targetPlayer->GetGUID ();
3119    else
3120        plGuid = objmgr.GetPlayerGUIDByName (plName.c_str ());
3121
3122    if (!plGuid)
3123        false;
3124
3125    // player's guild membership checked in AddMember before add
3126    if (!targetGuild->AddMember (plGuid,targetGuild->GetLowestRank ()))
3127        return false;
3128
3129    return true;
3130}
3131
3132bool ChatHandler::HandleGuildUninviteCommand(const char *args)
3133{
3134    if (!*args)
3135        return false;
3136
3137    char* par1 = strtok ((char*)args, " ");
3138    if(!par1)
3139        return false;
3140
3141    std::string plName = par1;
3142    if (!normalizePlayerName (plName))
3143    {
3144        SendSysMessage (LANG_PLAYER_NOT_FOUND);
3145        SetSentErrorMessage (true);
3146        return false;
3147    }
3148
3149    uint64 plGuid = 0;
3150    uint32 glId   = 0;
3151    if (Player* targetPlayer = ObjectAccessor::Instance ().FindPlayerByName (plName.c_str ()))
3152    {
3153        plGuid = targetPlayer->GetGUID ();
3154        glId   = targetPlayer->GetGuildId ();
3155    }
3156    else
3157    {
3158        plGuid = objmgr.GetPlayerGUIDByName (plName.c_str ());
3159        glId = Player::GetGuildIdFromDB (plGuid);
3160    }
3161
3162    if (!plGuid || !glId)
3163        return false;
3164
3165    Guild* targetGuild = objmgr.GetGuildById (glId);
3166    if (!targetGuild)
3167        return false;
3168
3169    targetGuild->DelMember (plGuid);
3170
3171    return true;
3172}
3173
3174bool ChatHandler::HandleGuildRankCommand(const char *args)
3175{
3176    if (!*args)
3177        return false;
3178
3179    char* par1 = strtok ((char*)args, " ");
3180    char* par2 = strtok (NULL, " ");
3181    if (!par1 || !par2)
3182        return false;
3183    std::string plName = par1;
3184    if (!normalizePlayerName (plName))
3185    {
3186        SendSysMessage (LANG_PLAYER_NOT_FOUND);
3187        SetSentErrorMessage (true);
3188        return false;
3189    }
3190
3191    uint64 plGuid = 0;
3192    uint32 glId   = 0;
3193    if (Player* targetPlayer = ObjectAccessor::Instance ().FindPlayerByName (plName.c_str ()))
3194    {
3195        plGuid = targetPlayer->GetGUID ();
3196        glId   = targetPlayer->GetGuildId ();
3197    }
3198    else
3199    {
3200        plGuid = objmgr.GetPlayerGUIDByName (plName.c_str ());
3201        glId = Player::GetGuildIdFromDB (plGuid);
3202    }
3203
3204    if (!plGuid || !glId)
3205        return false;
3206
3207    Guild* targetGuild = objmgr.GetGuildById (glId);
3208    if (!targetGuild)
3209        return false;
3210
3211    uint32 newrank = uint32 (atoi (par2));
3212    if (newrank > targetGuild->GetLowestRank ())
3213        return false;
3214
3215    targetGuild->ChangeRank (plGuid,newrank);
3216
3217    return true;
3218}
3219
3220bool ChatHandler::HandleGuildDeleteCommand(const char* args)
3221{
3222    if (!*args)
3223        return false;
3224
3225    char* par1 = strtok ((char*)args, " ");
3226    if (!par1)
3227        return false;
3228
3229    std::string gld = par1;
3230
3231    Guild* targetGuild = objmgr.GetGuildByName (gld);
3232    if (!targetGuild)
3233        return false;
3234
3235    targetGuild->Disband ();
3236
3237    return true;
3238}
3239
3240bool ChatHandler::HandleGetDistanceCommand(const char* /*args*/)
3241{
3242    Unit* pUnit = getSelectedUnit();
3243
3244    if(!pUnit)
3245    {
3246        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3247        SetSentErrorMessage(true);
3248        return false;
3249    }
3250
3251    PSendSysMessage(LANG_DISTANCE, m_session->GetPlayer()->GetDistance(pUnit),m_session->GetPlayer()->GetDistance2d(pUnit));
3252
3253    return true;
3254}
3255
3256// FIX-ME!!!
3257
3258bool ChatHandler::HandleAddWeaponCommand(const char* /*args*/)
3259{
3260    /*if (!*args)
3261        return false;
3262
3263    uint64 guid = m_session->GetPlayer()->GetSelection();
3264    if (guid == 0)
3265    {
3266        SendSysMessage(LANG_NO_SELECTION);
3267        return true;
3268    }
3269
3270    Creature *pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), guid);
3271
3272    if(!pCreature)
3273    {
3274        SendSysMessage(LANG_SELECT_CREATURE);
3275        return true;
3276    }
3277
3278    char* pSlotID = strtok((char*)args, " ");
3279    if (!pSlotID)
3280        return false;
3281
3282    char* pItemID = strtok(NULL, " ");
3283    if (!pItemID)
3284        return false;
3285
3286    uint32 ItemID = atoi(pItemID);
3287    uint32 SlotID = atoi(pSlotID);
3288
3289    ItemPrototype* tmpItem = objmgr.GetItemPrototype(ItemID);
3290
3291    bool added = false;
3292    if(tmpItem)
3293    {
3294        switch(SlotID)
3295        {
3296            case 1:
3297                pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY, ItemID);
3298                added = true;
3299                break;
3300            case 2:
3301                pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_01, ItemID);
3302                added = true;
3303                break;
3304            case 3:
3305                pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_02, ItemID);
3306                added = true;
3307                break;
3308            default:
3309                PSendSysMessage(LANG_ITEM_SLOT_NOT_EXIST,SlotID);
3310                added = false;
3311                break;
3312        }
3313        if(added)
3314        {
3315            PSendSysMessage(LANG_ITEM_ADDED_TO_SLOT,ItemID,tmpItem->Name1,SlotID);
3316        }
3317    }
3318    else
3319    {
3320        PSendSysMessage(LANG_ITEM_NOT_FOUND,ItemID);
3321        return true;
3322    }
3323    */
3324    return true;
3325}
3326
3327bool ChatHandler::HandleDieCommand(const char* /*args*/)
3328{
3329    Unit* target = getSelectedUnit();
3330
3331    if(!target || !m_session->GetPlayer()->GetSelection())
3332    {
3333        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3334        SetSentErrorMessage(true);
3335        return false;
3336    }
3337
3338    if( target->isAlive() )
3339    {
3340        m_session->GetPlayer()->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
3341    }
3342
3343    return true;
3344}
3345
3346bool ChatHandler::HandleDamageCommand(const char * args)
3347{
3348    if (!*args)
3349        return false;
3350
3351    Unit* target = getSelectedUnit();
3352
3353    if(!target || !m_session->GetPlayer()->GetSelection())
3354    {
3355        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3356        SetSentErrorMessage(true);
3357        return false;
3358    }
3359
3360    if( !target->isAlive() )
3361        return true;
3362
3363    char* damageStr = strtok((char*)args, " ");
3364    if(!damageStr)
3365        return false;
3366
3367    int32 damage = atoi((char*)damageStr);
3368    if(damage <=0)
3369        return true;
3370
3371    char* schoolStr = strtok((char*)NULL, " ");
3372
3373    // flat melee damage without resistence/etc reduction
3374    if(!schoolStr)
3375    {
3376        m_session->GetPlayer()->DealDamage(target, damage, NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
3377        m_session->GetPlayer()->SendAttackStateUpdate (HITINFO_NORMALSWING2, target, 1, SPELL_SCHOOL_MASK_NORMAL, damage, 0, 0, VICTIMSTATE_NORMAL, 0);
3378        return true;
3379    }
3380
3381    uint32 school = schoolStr ? atoi((char*)schoolStr) : SPELL_SCHOOL_NORMAL;
3382    if(school >= MAX_SPELL_SCHOOL)
3383        return false;
3384
3385    SpellSchoolMask schoolmask = SpellSchoolMask(1 << school);
3386
3387    if ( schoolmask & SPELL_SCHOOL_MASK_NORMAL )
3388        damage = m_session->GetPlayer()->CalcArmorReducedDamage(target, damage);
3389
3390    char* spellStr = strtok((char*)NULL, " ");
3391
3392    // melee damage by specific school
3393    if(!spellStr)
3394    {
3395        uint32 absorb = 0;
3396        uint32 resist = 0;
3397
3398        m_session->GetPlayer()->CalcAbsorbResist(target,schoolmask, SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
3399
3400        if (damage <= absorb + resist)
3401            return true;
3402
3403        damage -= absorb + resist;
3404
3405        m_session->GetPlayer()->DealDamage(target, damage, NULL, DIRECT_DAMAGE, schoolmask, NULL, false);
3406        m_session->GetPlayer()->SendAttackStateUpdate (HITINFO_NORMALSWING2, target, 1, schoolmask, damage, absorb, resist, VICTIMSTATE_NORMAL, 0);
3407        return true;
3408    }
3409
3410    // non-melee damage
3411
3412    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
3413    uint32 spellid = extractSpellIdFromLink((char*)args);
3414    if(!spellid || !sSpellStore.LookupEntry(spellid))
3415        return false;
3416
3417    m_session->GetPlayer()->SpellNonMeleeDamageLog(target, spellid, damage, false);
3418    return true;
3419}
3420
3421bool ChatHandler::HandleModifyArenaCommand(const char * args)
3422{
3423    if (!*args)
3424        return false;
3425
3426    Player *target = getSelectedPlayer();
3427    if(!target)
3428    {
3429        SendSysMessage(LANG_PLAYER_NOT_FOUND);
3430        SetSentErrorMessage(true);
3431        return false;
3432    }
3433
3434    int32 amount = (uint32)atoi(args);
3435
3436    target->ModifyArenaPoints(amount);
3437
3438    PSendSysMessage(LANG_COMMAND_MODIFY_ARENA, target->GetName(), target->GetArenaPoints());
3439
3440    return true;
3441}
3442
3443bool ChatHandler::HandleReviveCommand(const char* args)
3444{
3445    Player* SelectedPlayer = NULL;
3446
3447    if (*args)
3448    {
3449        std::string name = args;
3450        if(!normalizePlayerName(name))
3451        {
3452            SendSysMessage(LANG_PLAYER_NOT_FOUND);
3453            SetSentErrorMessage(true);
3454            return false;
3455        }
3456
3457        SelectedPlayer = objmgr.GetPlayer(name.c_str());
3458    }
3459    else
3460        SelectedPlayer = getSelectedPlayer();
3461
3462    if(!SelectedPlayer)
3463    {
3464        SendSysMessage(LANG_NO_CHAR_SELECTED);
3465        SetSentErrorMessage(true);
3466        return false;
3467    }
3468
3469    SelectedPlayer->ResurrectPlayer(0.5f);
3470    SelectedPlayer->SpawnCorpseBones();
3471    SelectedPlayer->SaveToDB();
3472    return true;
3473}
3474
3475bool ChatHandler::HandleAuraCommand(const char* args)
3476{
3477    char* px = strtok((char*)args, " ");
3478    if (!px)
3479        return false;
3480
3481    Unit *target = getSelectedUnit();
3482    if(!target)
3483    {
3484        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3485        SetSentErrorMessage(true);
3486        return false;
3487    }
3488
3489    uint32 spellID = (uint32)atoi(px);
3490    SpellEntry const *spellInfo = sSpellStore.LookupEntry( spellID );
3491    if(spellInfo)
3492    {
3493        for(uint32 i = 0;i<3;i++)
3494        {
3495            uint8 eff = spellInfo->Effect[i];
3496            if (eff>=TOTAL_SPELL_EFFECTS)
3497                continue;
3498            if( IsAreaAuraEffect(eff)           ||
3499                eff == SPELL_EFFECT_APPLY_AURA  ||
3500                eff == SPELL_EFFECT_PERSISTENT_AREA_AURA )
3501            {
3502                Aura *Aur = CreateAura(spellInfo, i, NULL, target);
3503                target->AddAura(Aur);
3504            }
3505        }
3506    }
3507
3508    return true;
3509}
3510
3511bool ChatHandler::HandleUnAuraCommand(const char* args)
3512{
3513    char* px = strtok((char*)args, " ");
3514    if (!px)
3515        return false;
3516
3517    Unit *target = getSelectedUnit();
3518    if(!target)
3519    {
3520        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3521        SetSentErrorMessage(true);
3522        return false;
3523    }
3524
3525    std::string argstr = args;
3526    if (argstr == "all")
3527    {
3528        target->RemoveAllAuras();
3529        return true;
3530    }
3531
3532    uint32 spellID = (uint32)atoi(px);
3533    target->RemoveAurasDueToSpell(spellID);
3534
3535    return true;
3536}
3537
3538bool ChatHandler::HandleLinkGraveCommand(const char* args)
3539{
3540    if(!*args)
3541        return false;
3542
3543    char* px = strtok((char*)args, " ");
3544    if (!px)
3545        return false;
3546
3547    uint32 g_id = (uint32)atoi(px);
3548
3549    uint32 g_team;
3550
3551    char* px2 = strtok(NULL, " ");
3552
3553    if (!px2)
3554        g_team = 0;
3555    else if (strncmp(px2,"horde",6)==0)
3556        g_team = HORDE;
3557    else if (strncmp(px2,"alliance",9)==0)
3558        g_team = ALLIANCE;
3559    else
3560        return false;
3561
3562    WorldSafeLocsEntry const* graveyard =  sWorldSafeLocsStore.LookupEntry(g_id);
3563
3564    if(!graveyard )
3565    {
3566        PSendSysMessage(LANG_COMMAND_GRAVEYARDNOEXIST, g_id);
3567        SetSentErrorMessage(true);
3568        return false;
3569    }
3570
3571    Player* player = m_session->GetPlayer();
3572
3573    uint32 zoneId = player->GetZoneId();
3574
3575    AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
3576    if(!areaEntry || areaEntry->zone !=0 )
3577    {
3578        PSendSysMessage(LANG_COMMAND_GRAVEYARDWRONGZONE, g_id,zoneId);
3579        SetSentErrorMessage(true);
3580        return false;
3581    }
3582
3583    if(graveyard->map_id != areaEntry->mapid && g_team != 0)
3584    {
3585        SendSysMessage(LANG_COMMAND_GRAVEYARDWRONGTEAM);
3586        SetSentErrorMessage(true);
3587        return false;
3588    }
3589
3590    if(objmgr.AddGraveYardLink(g_id,player->GetZoneId(),g_team))
3591        PSendSysMessage(LANG_COMMAND_GRAVEYARDLINKED, g_id,zoneId);
3592    else
3593        PSendSysMessage(LANG_COMMAND_GRAVEYARDALRLINKED, g_id,zoneId);
3594
3595    return true;
3596}
3597
3598bool ChatHandler::HandleNearGraveCommand(const char* args)
3599{
3600    uint32 g_team;
3601
3602    size_t argslen = strlen(args);
3603
3604    if(!*args)
3605        g_team = 0;
3606    else if (strncmp((char*)args,"horde",argslen)==0)
3607        g_team = HORDE;
3608    else if (strncmp((char*)args,"alliance",argslen)==0)
3609        g_team = ALLIANCE;
3610    else
3611        return false;
3612
3613    Player* player = m_session->GetPlayer();
3614
3615    WorldSafeLocsEntry const* graveyard = objmgr.GetClosestGraveYard(
3616        player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(),player->GetMapId(),g_team);
3617
3618    if(graveyard)
3619    {
3620        uint32 g_id = graveyard->ID;
3621
3622        GraveYardData const* data = objmgr.FindGraveYardData(g_id,player->GetZoneId());
3623        if (!data)
3624        {
3625            PSendSysMessage(LANG_COMMAND_GRAVEYARDERROR,g_id);
3626            SetSentErrorMessage(true);
3627            return false;
3628        }
3629
3630        g_team = data->team;
3631
3632        std::string team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_NOTEAM);
3633
3634        if(g_team == 0)
3635            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_ANY);
3636        else if(g_team == HORDE)
3637            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_HORDE);
3638        else if(g_team == ALLIANCE)
3639            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_ALLIANCE);
3640
3641        PSendSysMessage(LANG_COMMAND_GRAVEYARDNEAREST, g_id,team_name.c_str(),player->GetZoneId());
3642    }
3643    else
3644    {
3645        std::string team_name;
3646
3647        if(g_team == 0)
3648            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_ANY);
3649        else if(g_team == HORDE)
3650            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_HORDE);
3651        else if(g_team == ALLIANCE)
3652            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_ALLIANCE);
3653
3654        if(g_team == ~uint32(0))
3655            PSendSysMessage(LANG_COMMAND_ZONENOGRAVEYARDS, player->GetZoneId());
3656        else
3657            PSendSysMessage(LANG_COMMAND_ZONENOGRAFACTION, player->GetZoneId(),team_name.c_str());
3658    }
3659
3660    return true;
3661}
3662
3663//play npc emote
3664bool ChatHandler::HandleNpcPlayEmoteCommand(const char* args)
3665{
3666    uint32 emote = atoi((char*)args);
3667
3668    Creature* target = getSelectedCreature();
3669    if(!target)
3670    {
3671        SendSysMessage(LANG_SELECT_CREATURE);
3672        SetSentErrorMessage(true);
3673        return false;
3674    }
3675
3676    target->SetUInt32Value(UNIT_NPC_EMOTESTATE,emote);
3677
3678    return true;
3679}
3680
3681bool ChatHandler::HandleNpcInfoCommand(const char* /*args*/)
3682{
3683    Creature* target = getSelectedCreature();
3684
3685    if(!target)
3686    {
3687        SendSysMessage(LANG_SELECT_CREATURE);
3688        SetSentErrorMessage(true);
3689        return false;
3690    }
3691
3692    uint32 faction = target->getFaction();
3693    uint32 npcflags = target->GetUInt32Value(UNIT_NPC_FLAGS);
3694    uint32 displayid = target->GetDisplayId();
3695    uint32 nativeid = target->GetNativeDisplayId();
3696    uint32 Entry = target->GetEntry();
3697    CreatureInfo const* cInfo = target->GetCreatureInfo();
3698
3699    int32 curRespawnDelay = target->GetRespawnTimeEx()-time(NULL);
3700    if(curRespawnDelay < 0)
3701        curRespawnDelay = 0;
3702    std::string curRespawnDelayStr = secsToTimeString(curRespawnDelay,true);
3703    std::string defRespawnDelayStr = secsToTimeString(target->GetRespawnDelay(),true);
3704
3705    PSendSysMessage(LANG_NPCINFO_CHAR,  target->GetDBTableGUIDLow(), faction, npcflags, Entry, displayid, nativeid);
3706    PSendSysMessage(LANG_NPCINFO_LEVEL, target->getLevel());
3707    PSendSysMessage(LANG_NPCINFO_HEALTH,target->GetCreateHealth(), target->GetMaxHealth(), target->GetHealth());
3708    PSendSysMessage(LANG_NPCINFO_FLAGS, target->GetUInt32Value(UNIT_FIELD_FLAGS), target->GetUInt32Value(UNIT_DYNAMIC_FLAGS), target->getFaction());
3709    PSendSysMessage(LANG_COMMAND_RAWPAWNTIMES, defRespawnDelayStr.c_str(),curRespawnDelayStr.c_str());
3710    PSendSysMessage(LANG_NPCINFO_LOOT,  cInfo->lootid,cInfo->pickpocketLootId,cInfo->SkinLootId);
3711    PSendSysMessage(LANG_NPCINFO_DUNGEON_ID, target->GetInstanceId());
3712    PSendSysMessage(LANG_NPCINFO_POSITION,float(target->GetPositionX()), float(target->GetPositionY()), float(target->GetPositionZ()));
3713
3714    if ((npcflags & UNIT_NPC_FLAG_VENDOR) )
3715    {
3716        SendSysMessage(LANG_NPCINFO_VENDOR);
3717    }
3718    if ((npcflags & UNIT_NPC_FLAG_TRAINER) )
3719    {
3720        SendSysMessage(LANG_NPCINFO_TRAINER);
3721    }
3722
3723    return true;
3724}
3725
3726bool ChatHandler::HandleExploreCheatCommand(const char* args)
3727{
3728    if (!*args)
3729        return false;
3730
3731    int flag = atoi((char*)args);
3732
3733    Player *chr = getSelectedPlayer();
3734    if (chr == NULL)
3735    {
3736        SendSysMessage(LANG_NO_CHAR_SELECTED);
3737        SetSentErrorMessage(true);
3738        return false;
3739    }
3740
3741    if (flag != 0)
3742    {
3743        PSendSysMessage(LANG_YOU_SET_EXPLORE_ALL, chr->GetName());
3744        if (needReportToTarget(chr))
3745            ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_ALL,GetName());
3746    }
3747    else
3748    {
3749        PSendSysMessage(LANG_YOU_SET_EXPLORE_NOTHING, chr->GetName());
3750        if (needReportToTarget(chr))
3751            ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_NOTHING,GetName());
3752    }
3753
3754    for (uint8 i=0; i<128; i++)
3755    {
3756        if (flag != 0)
3757        {
3758            m_session->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1+i,0xFFFFFFFF);
3759        }
3760        else
3761        {
3762            m_session->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1+i,0);
3763        }
3764    }
3765
3766    return true;
3767}
3768
3769bool ChatHandler::HandleHoverCommand(const char* args)
3770{
3771    char* px = strtok((char*)args, " ");
3772    uint32 flag;
3773    if (!px)
3774        flag = 1;
3775    else
3776        flag = atoi(px);
3777
3778    m_session->GetPlayer()->SetHover(flag);
3779
3780    if (flag)
3781        SendSysMessage(LANG_HOVER_ENABLED);
3782    else
3783        SendSysMessage(LANG_HOVER_DISABLED);
3784
3785    return true;
3786}
3787
3788bool ChatHandler::HandleWaterwalkCommand(const char* args)
3789{
3790    if(!args)
3791        return false;
3792
3793    Player *player = getSelectedPlayer();
3794    if(!player)
3795    {
3796        PSendSysMessage(LANG_NO_CHAR_SELECTED);
3797        SetSentErrorMessage(true);
3798        return false;
3799    }
3800
3801    if (strncmp(args, "on", 3) == 0)
3802        player->SetMovement(MOVE_WATER_WALK);               // ON
3803    else if (strncmp(args, "off", 4) == 0)
3804        player->SetMovement(MOVE_LAND_WALK);                // OFF
3805    else
3806    {
3807        SendSysMessage(LANG_USE_BOL);
3808        return false;
3809    }
3810
3811    PSendSysMessage(LANG_YOU_SET_WATERWALK, args, player->GetName());
3812    if(needReportToTarget(player))
3813        ChatHandler(player).PSendSysMessage(LANG_YOUR_WATERWALK_SET, args, GetName());
3814    return true;
3815
3816}
3817
3818bool ChatHandler::HandleLevelUpCommand(const char* args)
3819{
3820    char* px = strtok((char*)args, " ");
3821    char* py = strtok((char*)NULL, " ");
3822
3823    // command format parsing
3824    char* pname = (char*)NULL;
3825    int addlevel = 1;
3826
3827    if(px && py)                                            // .levelup name level
3828    {
3829        addlevel = atoi(py);
3830        pname = px;
3831    }
3832    else if(px && !py)                                      // .levelup name OR .levelup level
3833    {
3834        if(isalpha(px[0]))                                  // .levelup name
3835            pname = px;
3836        else                                                // .levelup level
3837            addlevel = atoi(px);
3838    }
3839    // else .levelup - nothing do for preparing
3840
3841    // player
3842    Player *chr = NULL;
3843    uint64 chr_guid = 0;
3844
3845    std::string name;
3846
3847    if(pname)                                               // player by name
3848    {
3849        name = pname;
3850        if(!normalizePlayerName(name))
3851        {
3852            SendSysMessage(LANG_PLAYER_NOT_FOUND);
3853            SetSentErrorMessage(true);
3854            return false;
3855        }
3856
3857        chr = objmgr.GetPlayer(name.c_str());
3858        if(!chr)                                            // not in game
3859        {
3860            chr_guid = objmgr.GetPlayerGUIDByName(name);
3861            if (chr_guid == 0)
3862            {
3863                SendSysMessage(LANG_PLAYER_NOT_FOUND);
3864                SetSentErrorMessage(true);
3865                return false;
3866            }
3867        }
3868    }
3869    else                                                    // player by selection
3870    {
3871        chr = getSelectedPlayer();
3872
3873        if (chr == NULL)
3874        {
3875            SendSysMessage(LANG_NO_CHAR_SELECTED);
3876            SetSentErrorMessage(true);
3877            return false;
3878        }
3879
3880        name = chr->GetName();
3881    }
3882
3883    assert(chr || chr_guid);
3884
3885    int32 oldlevel = chr ? chr->getLevel() : Player::GetUInt32ValueFromDB(UNIT_FIELD_LEVEL,chr_guid);
3886    int32 newlevel = oldlevel + addlevel;
3887    if(newlevel < 1)
3888        newlevel = 1;
3889    if(newlevel > 255)                                      // hardcoded maximum level
3890        newlevel = 255;
3891
3892    if(chr)
3893    {
3894        chr->GiveLevel(newlevel);
3895        chr->InitTalentForLevel();
3896        chr->SetUInt32Value(PLAYER_XP,0);
3897
3898        if(oldlevel == newlevel)
3899            ChatHandler(chr).SendSysMessage(LANG_YOURS_LEVEL_PROGRESS_RESET);
3900        else
3901        if(oldlevel < newlevel)
3902            ChatHandler(chr).PSendSysMessage(LANG_YOURS_LEVEL_UP,newlevel-oldlevel);
3903        else
3904        if(oldlevel > newlevel)
3905            ChatHandler(chr).PSendSysMessage(LANG_YOURS_LEVEL_DOWN,newlevel-oldlevel);
3906    }
3907    else
3908    {
3909        // update level and XP at level, all other will be updated at loading
3910        Tokens values;
3911        Player::LoadValuesArrayFromDB(values,chr_guid);
3912        Player::SetUInt32ValueInArray(values,UNIT_FIELD_LEVEL,newlevel);
3913        Player::SetUInt32ValueInArray(values,PLAYER_XP,0);
3914        Player::SaveValuesArrayInDB(values,chr_guid);
3915    }
3916
3917    if(m_session->GetPlayer() != chr)                       // including chr==NULL
3918        PSendSysMessage(LANG_YOU_CHANGE_LVL,name.c_str(),newlevel);
3919    return true;
3920}
3921
3922bool ChatHandler::HandleShowAreaCommand(const char* args)
3923{
3924    if (!*args)
3925        return false;
3926
3927    int area = atoi((char*)args);
3928
3929    Player *chr = getSelectedPlayer();
3930    if (chr == NULL)
3931    {
3932        SendSysMessage(LANG_NO_CHAR_SELECTED);
3933        SetSentErrorMessage(true);
3934        return false;
3935    }
3936
3937    int offset = area / 32;
3938    uint32 val = (uint32)(1 << (area % 32));
3939
3940    if(offset >= 128)
3941    {
3942        SendSysMessage(LANG_BAD_VALUE);
3943        SetSentErrorMessage(true);
3944        return false;
3945    }
3946
3947    uint32 currFields = chr->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
3948    chr->SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
3949
3950    SendSysMessage(LANG_EXPLORE_AREA);
3951    return true;
3952}
3953
3954bool ChatHandler::HandleHideAreaCommand(const char* args)
3955{
3956    if (!*args)
3957        return false;
3958
3959    int area = atoi((char*)args);
3960
3961    Player *chr = getSelectedPlayer();
3962    if (chr == NULL)
3963    {
3964        SendSysMessage(LANG_NO_CHAR_SELECTED);
3965        SetSentErrorMessage(true);
3966        return false;
3967    }
3968
3969    int offset = area / 32;
3970    uint32 val = (uint32)(1 << (area % 32));
3971
3972    if(offset >= 128)
3973    {
3974        SendSysMessage(LANG_BAD_VALUE);
3975        SetSentErrorMessage(true);
3976        return false;
3977    }
3978
3979    uint32 currFields = chr->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
3980    chr->SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields ^ val));
3981
3982    SendSysMessage(LANG_UNEXPLORE_AREA);
3983    return true;
3984}
3985
3986bool ChatHandler::HandleUpdate(const char* args)
3987{
3988    if(!*args)
3989        return false;
3990
3991    uint32 updateIndex;
3992    uint32 value;
3993
3994    char* pUpdateIndex = strtok((char*)args, " ");
3995
3996    Unit* chr = getSelectedUnit();
3997    if (chr == NULL)
3998    {
3999        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
4000        SetSentErrorMessage(true);
4001        return false;
4002    }
4003
4004    if(!pUpdateIndex)
4005    {
4006        return true;
4007    }
4008    updateIndex = atoi(pUpdateIndex);
4009    //check updateIndex
4010    if(chr->GetTypeId() == TYPEID_PLAYER)
4011    {
4012        if (updateIndex>=PLAYER_END) return true;
4013    }
4014    else
4015    {
4016        if (updateIndex>=UNIT_END) return true;
4017    }
4018
4019    char*  pvalue = strtok(NULL, " ");
4020    if (!pvalue)
4021    {
4022        value=chr->GetUInt32Value(updateIndex);
4023
4024        PSendSysMessage(LANG_UPDATE, chr->GetGUIDLow(),updateIndex,value);
4025        return true;
4026    }
4027
4028    value=atoi(pvalue);
4029
4030    PSendSysMessage(LANG_UPDATE_CHANGE, chr->GetGUIDLow(),updateIndex,value);
4031
4032    chr->SetUInt32Value(updateIndex,value);
4033
4034    return true;
4035}
4036
4037bool ChatHandler::HandleBankCommand(const char* /*args*/)
4038{
4039    m_session->SendShowBank( m_session->GetPlayer()->GetGUID() );
4040
4041    return true;
4042}
4043
4044bool ChatHandler::HandleChangeWeather(const char* args)
4045{
4046    if(!*args)
4047        return false;
4048
4049    //Weather is OFF
4050    if (!sWorld.getConfig(CONFIG_WEATHER))
4051    {
4052        SendSysMessage(LANG_WEATHER_DISABLED);
4053        SetSentErrorMessage(true);
4054        return false;
4055    }
4056
4057    //*Change the weather of a cell
4058    char* px = strtok((char*)args, " ");
4059    char* py = strtok(NULL, " ");
4060
4061    if (!px || !py)
4062        return false;
4063
4064    uint32 type = (uint32)atoi(px);                         //0 to 3, 0: fine, 1: rain, 2: snow, 3: sand
4065    float grade = (float)atof(py);                          //0 to 1, sending -1 is instand good weather
4066
4067    Player *player = m_session->GetPlayer();
4068    uint32 zoneid = player->GetZoneId();
4069
4070    Weather* wth = sWorld.FindWeather(zoneid);
4071
4072    if(!wth)
4073        wth = sWorld.AddWeather(zoneid);
4074    if(!wth)
4075    {
4076        SendSysMessage(LANG_NO_WEATHER);
4077        SetSentErrorMessage(true);
4078        return false;
4079    }
4080
4081    wth->SetWeather(WeatherType(type), grade);
4082
4083    return true;
4084}
4085
4086bool ChatHandler::HandleSetValue(const char* args)
4087{
4088    if(!*args)
4089        return false;
4090
4091    char* px = strtok((char*)args, " ");
4092    char* py = strtok(NULL, " ");
4093    char* pz = strtok(NULL, " ");
4094
4095    if (!px || !py)
4096        return false;
4097
4098    Unit* target = getSelectedUnit();
4099    if(!target)
4100    {
4101        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
4102        SetSentErrorMessage(true);
4103        return false;
4104    }
4105
4106    uint64 guid = target->GetGUID();
4107
4108    uint32 Opcode = (uint32)atoi(px);
4109    if(Opcode >= target->GetValuesCount())
4110    {
4111        PSendSysMessage(LANG_TOO_BIG_INDEX, Opcode, GUID_LOPART(guid), target->GetValuesCount());
4112        return false;
4113    }
4114    uint32 iValue;
4115    float fValue;
4116    bool isint32 = true;
4117    if(pz)
4118        isint32 = (bool)atoi(pz);
4119    if(isint32)
4120    {
4121        iValue = (uint32)atoi(py);
4122        sLog.outDebug(GetTrinityString(LANG_SET_UINT), GUID_LOPART(guid), Opcode, iValue);
4123        target->SetUInt32Value( Opcode , iValue );
4124        PSendSysMessage(LANG_SET_UINT_FIELD, GUID_LOPART(guid), Opcode,iValue);
4125    }
4126    else
4127    {
4128        fValue = (float)atof(py);
4129        sLog.outDebug(GetTrinityString(LANG_SET_FLOAT), GUID_LOPART(guid), Opcode, fValue);
4130        target->SetFloatValue( Opcode , fValue );
4131        PSendSysMessage(LANG_SET_FLOAT_FIELD, GUID_LOPART(guid), Opcode,fValue);
4132    }
4133
4134    return true;
4135}
4136
4137bool ChatHandler::HandleGetValue(const char* args)
4138{
4139    if(!*args)
4140        return false;
4141
4142    char* px = strtok((char*)args, " ");
4143    char* pz = strtok(NULL, " ");
4144
4145    if (!px)
4146        return false;
4147
4148    Unit* target = getSelectedUnit();
4149    if(!target)
4150    {
4151        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
4152        SetSentErrorMessage(true);
4153        return false;
4154    }
4155
4156    uint64 guid = target->GetGUID();
4157
4158    uint32 Opcode = (uint32)atoi(px);
4159    if(Opcode >= target->GetValuesCount())
4160    {
4161        PSendSysMessage(LANG_TOO_BIG_INDEX, Opcode, GUID_LOPART(guid), target->GetValuesCount());
4162        return false;
4163    }
4164    uint32 iValue;
4165    float fValue;
4166    bool isint32 = true;
4167    if(pz)
4168        isint32 = (bool)atoi(pz);
4169
4170    if(isint32)
4171    {
4172        iValue = target->GetUInt32Value( Opcode );
4173        sLog.outDebug(GetTrinityString(LANG_GET_UINT), GUID_LOPART(guid), Opcode, iValue);
4174        PSendSysMessage(LANG_GET_UINT_FIELD, GUID_LOPART(guid), Opcode,    iValue);
4175    }
4176    else
4177    {
4178        fValue = target->GetFloatValue( Opcode );
4179        sLog.outDebug(GetTrinityString(LANG_GET_FLOAT), GUID_LOPART(guid), Opcode, fValue);
4180        PSendSysMessage(LANG_GET_FLOAT_FIELD, GUID_LOPART(guid), Opcode, fValue);
4181    }
4182
4183    return true;
4184}
4185
4186bool ChatHandler::HandleSet32Bit(const char* args)
4187{
4188    if(!*args)
4189        return false;
4190
4191    char* px = strtok((char*)args, " ");
4192    char* py = strtok(NULL, " ");
4193
4194    if (!px || !py)
4195        return false;
4196
4197    uint32 Opcode = (uint32)atoi(px);
4198    uint32 Value = (uint32)atoi(py);
4199    if (Value > 32)                                         //uint32 = 32 bits
4200        return false;
4201
4202    sLog.outDebug(GetTrinityString(LANG_SET_32BIT), Opcode, Value);
4203
4204    m_session->GetPlayer( )->SetUInt32Value( Opcode , 2^Value );
4205
4206    PSendSysMessage(LANG_SET_32BIT_FIELD, Opcode,1);
4207    return true;
4208}
4209
4210bool ChatHandler::HandleMod32Value(const char* args)
4211{
4212    if(!*args)
4213        return false;
4214
4215    char* px = strtok((char*)args, " ");
4216    char* py = strtok(NULL, " ");
4217
4218    if (!px || !py)
4219        return false;
4220
4221    uint32 Opcode = (uint32)atoi(px);
4222    int Value = atoi(py);
4223
4224    if(Opcode >= m_session->GetPlayer()->GetValuesCount())
4225    {
4226        PSendSysMessage(LANG_TOO_BIG_INDEX, Opcode, m_session->GetPlayer()->GetGUIDLow(), m_session->GetPlayer( )->GetValuesCount());
4227        return false;
4228    }
4229
4230    sLog.outDebug(GetTrinityString(LANG_CHANGE_32BIT), Opcode, Value);
4231
4232    int CurrentValue = (int)m_session->GetPlayer( )->GetUInt32Value( Opcode );
4233
4234    CurrentValue += Value;
4235    m_session->GetPlayer( )->SetUInt32Value( Opcode , (uint32)CurrentValue );
4236
4237    PSendSysMessage(LANG_CHANGE_32BIT_FIELD, Opcode,CurrentValue);
4238
4239    return true;
4240}
4241
4242bool ChatHandler::HandleAddTeleCommand(const char * args)
4243{
4244    if(!*args)
4245        return false;
4246
4247    Player *player=m_session->GetPlayer();
4248    if (!player)
4249        return false;
4250
4251    std::string name = args;
4252
4253    if(objmgr.GetGameTele(name))
4254    {
4255        SendSysMessage(LANG_COMMAND_TP_ALREADYEXIST);
4256        SetSentErrorMessage(true);
4257        return false;
4258    }
4259
4260    GameTele tele;
4261    tele.position_x  = player->GetPositionX();
4262    tele.position_y  = player->GetPositionY();
4263    tele.position_z  = player->GetPositionZ();
4264    tele.orientation = player->GetOrientation();
4265    tele.mapId       = player->GetMapId();
4266    tele.name        = name;
4267
4268    if(objmgr.AddGameTele(tele))
4269    {
4270        SendSysMessage(LANG_COMMAND_TP_ADDED);
4271    }
4272    else
4273    {
4274        SendSysMessage(LANG_COMMAND_TP_ADDEDERR);
4275        SetSentErrorMessage(true);
4276        return false;
4277    }
4278
4279    return true;
4280}
4281
4282bool ChatHandler::HandleDelTeleCommand(const char * args)
4283{
4284    if(!*args)
4285        return false;
4286
4287    std::string name = args;
4288
4289    if(!objmgr.DeleteGameTele(name))
4290    {
4291        SendSysMessage(LANG_COMMAND_TELE_NOTFOUND);
4292        SetSentErrorMessage(true);
4293        return false;
4294    }
4295
4296    SendSysMessage(LANG_COMMAND_TP_DELETED);
4297    return true;
4298}
4299
4300bool ChatHandler::HandleListAurasCommand (const char * /*args*/)
4301{
4302    Unit *unit = getSelectedUnit();
4303    if(!unit)
4304    {
4305        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
4306        SetSentErrorMessage(true);
4307        return false;
4308    }
4309
4310    char const* talentStr = GetTrinityString(LANG_TALENT);
4311    char const* passiveStr = GetTrinityString(LANG_PASSIVE);
4312
4313    Unit::AuraMap const& uAuras = unit->GetAuras();
4314    PSendSysMessage(LANG_COMMAND_TARGET_LISTAURAS, uAuras.size());
4315    for (Unit::AuraMap::const_iterator itr = uAuras.begin(); itr != uAuras.end(); ++itr)
4316    {
4317        bool talent = GetTalentSpellCost(itr->second->GetId()) > 0;
4318        PSendSysMessage(LANG_COMMAND_TARGET_AURADETAIL, itr->second->GetId(), itr->second->GetEffIndex(),
4319            itr->second->GetModifier()->m_auraname, itr->second->GetAuraDuration(), itr->second->GetAuraMaxDuration(),
4320            itr->second->GetSpellProto()->SpellName[m_session->GetSessionDbcLocale()],
4321            (itr->second->IsPassive() ? passiveStr : ""),(talent ? talentStr : ""),
4322            IS_PLAYER_GUID(itr->second->GetCasterGUID()) ? "player" : "creature",GUID_LOPART(itr->second->GetCasterGUID()));
4323    }
4324    for (int i = 0; i < TOTAL_AURAS; i++)
4325    {
4326        Unit::AuraList const& uAuraList = unit->GetAurasByType(AuraType(i));
4327        if (uAuraList.empty()) continue;
4328        PSendSysMessage(LANG_COMMAND_TARGET_LISTAURATYPE, uAuraList.size(), i);
4329        for (Unit::AuraList::const_iterator itr = uAuraList.begin(); itr != uAuraList.end(); ++itr)
4330        {
4331            bool talent = GetTalentSpellCost((*itr)->GetId()) > 0;
4332            PSendSysMessage(LANG_COMMAND_TARGET_AURASIMPLE, (*itr)->GetId(), (*itr)->GetEffIndex(),
4333                (*itr)->GetSpellProto()->SpellName[m_session->GetSessionDbcLocale()],((*itr)->IsPassive() ? passiveStr : ""),(talent ? talentStr : ""),
4334                IS_PLAYER_GUID((*itr)->GetCasterGUID()) ? "player" : "creature",GUID_LOPART((*itr)->GetCasterGUID()));
4335        }
4336    }
4337    return true;
4338}
4339
4340bool ChatHandler::HandleResetHonorCommand (const char * args)
4341{
4342    char* pName = strtok((char*)args, "");
4343    Player *player = NULL;
4344    if (pName)
4345    {
4346        std::string name = pName;
4347        if(!normalizePlayerName(name))
4348        {
4349            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4350            SetSentErrorMessage(true);
4351            return false;
4352        }
4353
4354        uint64 guid = objmgr.GetPlayerGUIDByName(name.c_str());
4355        player = objmgr.GetPlayer(guid);
4356    }
4357    else
4358        player = getSelectedPlayer();
4359
4360    if(!player)
4361    {
4362        SendSysMessage(LANG_NO_CHAR_SELECTED);
4363        return true;
4364    }
4365
4366    player->SetUInt32Value(PLAYER_FIELD_KILLS, 0);
4367    player->SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0);
4368    player->SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, 0);
4369    player->SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
4370    player->SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
4371
4372    return true;
4373}
4374
4375static bool HandleResetStatsOrLevelHelper(Player* player)
4376{
4377    PlayerInfo const *info = objmgr.GetPlayerInfo(player->getRace(), player->getClass());
4378    if(!info) return false;
4379
4380    ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(player->getClass());
4381    if(!cEntry)
4382    {
4383        sLog.outError("Class %u not found in DBC (Wrong DBC files?)",player->getClass());
4384        return false;
4385    }
4386
4387    uint8 powertype = cEntry->powerType;
4388
4389    uint32 unitfield;
4390    if(powertype == POWER_RAGE)
4391        unitfield = 0x1100EE00;
4392    else if(powertype == POWER_ENERGY)
4393        unitfield = 0x00000000;
4394    else if(powertype == POWER_MANA)
4395        unitfield = 0x0000EE00;
4396    else
4397    {
4398        sLog.outError("Invalid default powertype %u for player (class %u)",powertype,player->getClass());
4399        return false;
4400    }
4401
4402    // reset m_form if no aura
4403    if(!player->HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
4404        player->m_form = FORM_NONE;
4405
4406    player->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE );
4407    player->SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f   );
4408
4409    player->setFactionForRace(player->getRace());
4410
4411    player->SetUInt32Value(UNIT_FIELD_BYTES_0, ( ( player->getRace() ) | ( player->getClass() << 8 ) | ( player->getGender() << 16 ) | ( powertype << 24 ) ) );
4412
4413    // reset only if player not in some form;
4414    if(player->m_form==FORM_NONE)
4415    {
4416        switch(player->getGender())
4417        {
4418            case GENDER_FEMALE:
4419                player->SetDisplayId(info->displayId_f);
4420                player->SetNativeDisplayId(info->displayId_f);
4421                break;
4422            case GENDER_MALE:
4423                player->SetDisplayId(info->displayId_m);
4424                player->SetNativeDisplayId(info->displayId_m);
4425                break;
4426            default:
4427                break;
4428        }
4429    }
4430
4431    // set UNIT_FIELD_BYTES_1 to init state but preserve m_form value
4432    player->SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
4433    player->SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_UNK5 );
4434    player->SetByteValue(UNIT_FIELD_BYTES_2, 3, player->m_form);
4435
4436    player->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
4437
4438    //-1 is default value
4439    player->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
4440
4441    //player->SetUInt32Value(PLAYER_FIELD_BYTES, 0xEEE00000 );
4442    return true;
4443}
4444
4445bool ChatHandler::HandleResetLevelCommand(const char * args)
4446{
4447    char* pName = strtok((char*)args, "");
4448    Player *player = NULL;
4449    if (pName)
4450    {
4451        std::string name = pName;
4452        if(!normalizePlayerName(name))
4453        {
4454            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4455            SetSentErrorMessage(true);
4456            return false;
4457        }
4458
4459        uint64 guid = objmgr.GetPlayerGUIDByName(name.c_str());
4460        player = objmgr.GetPlayer(guid);
4461    }
4462    else
4463        player = getSelectedPlayer();
4464
4465    if(!player)
4466    {
4467        SendSysMessage(LANG_NO_CHAR_SELECTED);
4468        SetSentErrorMessage(true);
4469        return false;
4470    }
4471
4472    if(!HandleResetStatsOrLevelHelper(player))
4473        return false;
4474
4475    player->SetLevel(1);
4476    player->InitStatsForLevel(true);
4477    player->InitTaxiNodesForLevel();
4478    player->InitTalentForLevel();
4479    player->SetUInt32Value(PLAYER_XP,0);
4480
4481    // reset level to summoned pet
4482    Pet* pet = player->GetPet();
4483    if(pet && pet->getPetType()==SUMMON_PET)
4484        pet->InitStatsForLevel(1);
4485
4486    return true;
4487}
4488
4489bool ChatHandler::HandleResetStatsCommand(const char * args)
4490{
4491    char* pName = strtok((char*)args, "");
4492    Player *player = NULL;
4493    if (pName)
4494    {
4495        std::string name = pName;
4496        if(!normalizePlayerName(name))
4497        {
4498            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4499            SetSentErrorMessage(true);
4500            return false;
4501        }
4502
4503        uint64 guid = objmgr.GetPlayerGUIDByName(name.c_str());
4504        player = objmgr.GetPlayer(guid);
4505    }
4506    else
4507        player = getSelectedPlayer();
4508
4509    if(!player)
4510    {
4511        SendSysMessage(LANG_NO_CHAR_SELECTED);
4512        SetSentErrorMessage(true);
4513        return false;
4514    }
4515
4516    if(!HandleResetStatsOrLevelHelper(player))
4517        return false;
4518
4519    player->InitStatsForLevel(true);
4520    player->InitTaxiNodesForLevel();
4521    player->InitTalentForLevel();
4522
4523    return true;
4524}
4525
4526bool ChatHandler::HandleResetSpellsCommand(const char * args)
4527{
4528    char* pName = strtok((char*)args, "");
4529    Player *player = NULL;
4530    uint64 playerGUID = 0;
4531    if (pName)
4532    {
4533        std::string name = pName;
4534
4535        if(!normalizePlayerName(name))
4536        {
4537            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4538            SetSentErrorMessage(true);
4539            return false;
4540        }
4541
4542        player = objmgr.GetPlayer(name.c_str());
4543        if(!player)
4544            playerGUID = objmgr.GetPlayerGUIDByName(name.c_str());
4545    }
4546    else
4547        player = getSelectedPlayer();
4548
4549    if(!player && !playerGUID)
4550    {
4551        SendSysMessage(LANG_NO_CHAR_SELECTED);
4552        SetSentErrorMessage(true);
4553        return false;
4554    }
4555
4556    if(player)
4557    {
4558        player->resetSpells();
4559
4560        ChatHandler(player).SendSysMessage(LANG_RESET_SPELLS);
4561
4562        if(m_session->GetPlayer()!=player)
4563            PSendSysMessage(LANG_RESET_SPELLS_ONLINE,player->GetName());
4564    }
4565    else
4566    {
4567        CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid = '%u'",uint32(AT_LOGIN_RESET_SPELLS), GUID_LOPART(playerGUID));
4568        PSendSysMessage(LANG_RESET_SPELLS_OFFLINE,pName);
4569    }
4570
4571    return true;
4572}
4573
4574bool ChatHandler::HandleResetTalentsCommand(const char * args)
4575{
4576    char* pName = strtok((char*)args, "");
4577    Player *player = NULL;
4578    uint64 playerGUID = 0;
4579    if (pName)
4580    {
4581        std::string name = pName;
4582        if(!normalizePlayerName(name))
4583        {
4584            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4585            SetSentErrorMessage(true);
4586            return false;
4587        }
4588
4589        player = objmgr.GetPlayer(name.c_str());
4590        if(!player)
4591            playerGUID = objmgr.GetPlayerGUIDByName(name.c_str());
4592    }
4593    else
4594        player = getSelectedPlayer();
4595
4596    if(!player && !playerGUID)
4597    {
4598        SendSysMessage(LANG_NO_CHAR_SELECTED);
4599        SetSentErrorMessage(true);
4600        return false;
4601    }
4602
4603    if(player)
4604    {
4605        player->resetTalents(true);
4606
4607        ChatHandler(player).SendSysMessage(LANG_RESET_TALENTS);
4608
4609        if(m_session->GetPlayer()!=player)
4610            PSendSysMessage(LANG_RESET_TALENTS_ONLINE,player->GetName());
4611    }
4612    else
4613    {
4614        CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid = '%u'",uint32(AT_LOGIN_RESET_TALENTS), GUID_LOPART(playerGUID) );
4615        PSendSysMessage(LANG_RESET_TALENTS_OFFLINE,pName);
4616    }
4617
4618    return true;
4619}
4620
4621bool ChatHandler::HandleResetAllCommand(const char * args)
4622{
4623    if(!*args)
4624        return false;
4625
4626    std::string casename = args;
4627
4628    AtLoginFlags atLogin;
4629
4630    // Command specially created as single command to prevent using short case names
4631    if(casename=="spells")
4632    {
4633        atLogin = AT_LOGIN_RESET_SPELLS;
4634        sWorld.SendWorldText(LANG_RESETALL_SPELLS);
4635    }
4636    else if(casename=="talents")
4637    {
4638        atLogin = AT_LOGIN_RESET_TALENTS;
4639        sWorld.SendWorldText(LANG_RESETALL_TALENTS);
4640    }
4641    else
4642    {
4643        PSendSysMessage(LANG_RESETALL_UNKNOWN_CASE,args);
4644        SetSentErrorMessage(true);
4645        return false;
4646    }
4647
4648    CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u'",atLogin);
4649    HashMapHolder<Player>::MapType const& plist = ObjectAccessor::Instance().GetPlayers();
4650    for(HashMapHolder<Player>::MapType::const_iterator itr = plist.begin(); itr != plist.end(); ++itr)
4651        itr->second->SetAtLoginFlag(atLogin);
4652
4653    return true;
4654}
4655
4656bool ChatHandler::HandleShutDownCommand(const char* args)
4657{
4658    if(!*args)
4659        return false;
4660
4661    if(std::string(args)=="cancel")
4662    {
4663        sWorld.ShutdownCancel();
4664    }
4665    else
4666    {
4667        int32 time = atoi(args);
4668
4669        ///- Prevent interpret wrong arg value as 0 secs shutdown time
4670        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
4671            return false;
4672
4673        sWorld.ShutdownServ(time);
4674    }
4675    return true;
4676}
4677
4678bool ChatHandler::HandleRestartCommand(const char* args)
4679{
4680    if(!*args)
4681        return false;
4682
4683    if(std::string(args)=="cancel")
4684    {
4685        sWorld.ShutdownCancel();
4686    }
4687    else
4688    {
4689        int32 time = atoi(args);
4690
4691        ///- Prevent interpret wrong arg value as 0 secs shutdown time
4692        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
4693            return false;
4694
4695        sWorld.ShutdownServ(time, SHUTDOWN_MASK_RESTART);
4696    }
4697    return true;
4698}
4699
4700bool ChatHandler::HandleIdleRestartCommand(const char* args)
4701{
4702    if(!*args)
4703        return false;
4704
4705    if(std::string(args)=="cancel")
4706    {
4707        sWorld.ShutdownCancel();
4708    }
4709    else
4710    {
4711        int32 time = atoi(args);
4712
4713        ///- Prevent interpret wrong arg value as 0 secs shutdown time
4714        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
4715            return false;
4716
4717        sWorld.ShutdownServ(time,SHUTDOWN_MASK_RESTART+SHUTDOWN_MASK_IDLE);
4718    }
4719    return true;
4720}
4721
4722bool ChatHandler::HandleIdleShutDownCommand(const char* args)
4723{
4724    if(!*args)
4725        return false;
4726
4727    if(std::string(args)=="cancel")
4728    {
4729        sWorld.ShutdownCancel();
4730    }
4731    else
4732    {
4733        int32 time = atoi(args);
4734
4735        ///- Prevent interpret wrong arg value as 0 secs shutdown time
4736        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
4737            return false;
4738
4739        sWorld.ShutdownServ(time,SHUTDOWN_MASK_IDLE);
4740    }
4741    return true;
4742}
4743
4744bool ChatHandler::HandleAddQuest(const char* args)
4745{
4746    Player* player = getSelectedPlayer();
4747    if(!player)
4748    {
4749        SendSysMessage(LANG_NO_CHAR_SELECTED);
4750        SetSentErrorMessage(true);
4751        return false;
4752    }
4753
4754    // .addquest #entry'
4755    // number or [name] Shift-click form |color|Hquest:quest_id|h[name]|h|r
4756    char* cId = extractKeyFromLink((char*)args,"Hquest");
4757    if(!cId)
4758        return false;
4759
4760    uint32 entry = atol(cId);
4761
4762    Quest const* pQuest = objmgr.GetQuestTemplate(entry);
4763
4764    if(!pQuest)
4765    {
4766        PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND,entry);
4767        SetSentErrorMessage(true);
4768        return false;
4769    }
4770
4771    // check item starting quest (it can work incorrectly if added without item in inventory)
4772    for (uint32 id = 0; id < sItemStorage.MaxEntry; id++)
4773    {
4774        ItemPrototype const *pProto = sItemStorage.LookupEntry<ItemPrototype>(id);
4775        if (!pProto)
4776            continue;
4777
4778        if (pProto->StartQuest == entry)
4779        {
4780            PSendSysMessage(LANG_COMMAND_QUEST_STARTFROMITEM, entry, pProto->ItemId);
4781            SetSentErrorMessage(true);
4782            return false;
4783        }
4784    }
4785
4786    // ok, normal (creature/GO starting) quest
4787    if( player->CanAddQuest( pQuest, true ) )
4788    {
4789        player->AddQuest( pQuest, NULL );
4790
4791        if ( player->CanCompleteQuest( entry ) )
4792            player->CompleteQuest( entry );
4793    }
4794
4795    return true;
4796}
4797
4798bool ChatHandler::HandleRemoveQuest(const char* args)
4799{
4800    Player* player = getSelectedPlayer();
4801    if(!player)
4802    {
4803        SendSysMessage(LANG_NO_CHAR_SELECTED);
4804        SetSentErrorMessage(true);
4805        return false;
4806    }
4807
4808    // .removequest #entry'
4809    // number or [name] Shift-click form |color|Hquest:quest_id|h[name]|h|r
4810    char* cId = extractKeyFromLink((char*)args,"Hquest");
4811    if(!cId)
4812        return false;
4813
4814    uint32 entry = atol(cId);
4815
4816    Quest const* pQuest = objmgr.GetQuestTemplate(entry);
4817
4818    if(!pQuest)
4819    {
4820        PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry);
4821        SetSentErrorMessage(true);
4822        return false;
4823    }
4824
4825    // remove all quest entries for 'entry' from quest log
4826    for(uint8 slot = 0; slot < MAX_QUEST_LOG_SIZE; ++slot )
4827    {
4828        uint32 quest = player->GetQuestSlotQuestId(slot);
4829        if(quest==entry)
4830        {
4831            player->SetQuestSlot(slot,0);
4832
4833            // we ignore unequippable quest items in this case, its' still be equipped
4834            player->TakeQuestSourceItem( quest, false );
4835        }
4836    }
4837
4838    // set quest status to not started (will updated in DB at next save)
4839    player->SetQuestStatus( entry, QUEST_STATUS_NONE);
4840
4841    // reset rewarded for restart repeatable quest
4842    player->getQuestStatusMap()[entry].m_rewarded = false;
4843
4844    SendSysMessage(LANG_COMMAND_QUEST_REMOVED);
4845    return true;
4846}
4847
4848bool ChatHandler::HandleCompleteQuest(const char* args)
4849{
4850    Player* player = getSelectedPlayer();
4851    if(!player)
4852    {
4853        SendSysMessage(LANG_NO_CHAR_SELECTED);
4854        SetSentErrorMessage(true);
4855        return false;
4856    }
4857
4858    // .quest complete #entry
4859    // number or [name] Shift-click form |color|Hquest:quest_id|h[name]|h|r
4860    char* cId = extractKeyFromLink((char*)args,"Hquest");
4861    if(!cId)
4862        return false;
4863
4864    uint32 entry = atol(cId);
4865
4866    Quest const* pQuest = objmgr.GetQuestTemplate(entry);
4867
4868    // If player doesn't have the quest
4869    if(!pQuest || player->GetQuestStatus(entry) == QUEST_STATUS_NONE)
4870    {
4871        PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry);
4872        SetSentErrorMessage(true);
4873        return false;
4874    }
4875
4876    // Add quest items for quests that require items
4877    for(uint8 x = 0; x < QUEST_OBJECTIVES_COUNT; ++x)
4878    {
4879        uint32 id = pQuest->ReqItemId[x];
4880        uint32 count = pQuest->ReqItemCount[x];
4881        if(!id || !count)
4882            continue;
4883
4884        uint32 curItemCount = player->GetItemCount(id,true);
4885
4886        ItemPosCountVec dest;
4887        uint8 msg = player->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, id, count-curItemCount );
4888        if( msg == EQUIP_ERR_OK )
4889        {
4890            Item* item = player->StoreNewItem( dest, id, true);
4891            player->SendNewItem(item,count-curItemCount,true,false);
4892        }
4893    }
4894
4895    // All creature/GO slain/casted (not required, but otherwise it will display "Creature slain 0/10")
4896    for(uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
4897    {
4898        uint32 creature = pQuest->ReqCreatureOrGOId[i];
4899        uint32 creaturecount = pQuest->ReqCreatureOrGOCount[i];
4900
4901        if(uint32 spell_id = pQuest->ReqSpell[i])
4902        {
4903            for(uint16 z = 0; z < creaturecount; ++z)
4904                player->CastedCreatureOrGO(creature,0,spell_id);
4905        }
4906        else if(creature > 0)
4907        {
4908            for(uint16 z = 0; z < creaturecount; ++z)
4909                player->KilledMonster(creature,0);
4910        }
4911        else if(creature < 0)
4912        {
4913            for(uint16 z = 0; z < creaturecount; ++z)
4914                player->CastedCreatureOrGO(creature,0,0);
4915        }
4916    }
4917
4918    // If the quest requires reputation to complete
4919    if(uint32 repFaction = pQuest->GetRepObjectiveFaction())
4920    {
4921        uint32 repValue = pQuest->GetRepObjectiveValue();
4922        uint32 curRep = player->GetReputation(repFaction);
4923        if(curRep < repValue)
4924        {
4925            FactionEntry const *factionEntry = sFactionStore.LookupEntry(repFaction);
4926            player->SetFactionReputation(factionEntry,repValue);
4927        }
4928    }
4929
4930    // If the quest requires money
4931    int32 ReqOrRewMoney = pQuest->GetRewOrReqMoney();
4932    if(ReqOrRewMoney < 0)
4933        player->ModifyMoney(-ReqOrRewMoney);
4934
4935    player->CompleteQuest(entry);
4936    return true;
4937}
4938
4939bool ChatHandler::HandleBanAccountCommand(const char* args)
4940{
4941    return HandleBanHelper(BAN_ACCOUNT,args);
4942}
4943
4944bool ChatHandler::HandleBanCharacterCommand(const char* args)
4945{
4946    return HandleBanHelper(BAN_CHARACTER,args);
4947}
4948
4949bool ChatHandler::HandleBanIPCommand(const char* args)
4950{
4951    return HandleBanHelper(BAN_IP,args);
4952}
4953
4954bool ChatHandler::HandleBanHelper(BanMode mode, const char* args)
4955{
4956    if(!args)
4957        return false;
4958
4959    char* cnameOrIP = strtok ((char*)args, " ");
4960    if (!cnameOrIP)
4961        return false;
4962
4963    std::string nameOrIP = cnameOrIP;
4964
4965    char* duration = strtok (NULL," ");
4966    if(!duration || !atoi(duration))
4967        return false;
4968
4969    char* reason = strtok (NULL,"");
4970    if(!reason)
4971        return false;
4972
4973    switch(mode)
4974    {
4975        case BAN_ACCOUNT:
4976            if(!AccountMgr::normilizeString(nameOrIP))
4977            {
4978                PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,nameOrIP.c_str());
4979                SetSentErrorMessage(true);
4980                return false;
4981            }
4982            break;
4983        case BAN_CHARACTER:
4984            if(!normalizePlayerName(nameOrIP))
4985            {
4986                SendSysMessage(LANG_PLAYER_NOT_FOUND);
4987                SetSentErrorMessage(true);
4988                return false;
4989            }
4990            break;
4991        case BAN_IP:
4992            if(!IsIPAddress(nameOrIP.c_str()))
4993                return false;
4994            break;
4995    }
4996
4997    switch(sWorld.BanAccount(mode, nameOrIP, duration, reason,m_session ? m_session->GetPlayerName() : ""))
4998    {
4999        case BAN_SUCCESS:
5000            if(atoi(duration)>0)
5001                PSendSysMessage(LANG_BAN_YOUBANNED,nameOrIP.c_str(),secsToTimeString(TimeStringToSecs(duration),true).c_str(),reason);
5002            else
5003                PSendSysMessage(LANG_BAN_YOUPERMBANNED,nameOrIP.c_str(),reason);
5004            break;
5005        case BAN_SYNTAX_ERROR:
5006            return false;
5007        case BAN_NOTFOUND:
5008            switch(mode)
5009            {
5010                default:
5011                    PSendSysMessage(LANG_BAN_NOTFOUND,"account",nameOrIP.c_str());
5012                    break;
5013                case BAN_CHARACTER:
5014                    PSendSysMessage(LANG_BAN_NOTFOUND,"character",nameOrIP.c_str());
5015                    break;
5016                case BAN_IP:
5017                    PSendSysMessage(LANG_BAN_NOTFOUND,"ip",nameOrIP.c_str());
5018                    break;
5019            }
5020            SetSentErrorMessage(true);
5021            return false;
5022    }
5023
5024    return true;
5025}
5026
5027bool ChatHandler::HandleUnBanAccountCommand(const char* args)
5028{
5029    return HandleUnBanHelper(BAN_ACCOUNT,args);
5030}
5031
5032bool ChatHandler::HandleUnBanCharacterCommand(const char* args)
5033{
5034    return HandleUnBanHelper(BAN_CHARACTER,args);
5035}
5036
5037bool ChatHandler::HandleUnBanIPCommand(const char* args)
5038{
5039    return HandleUnBanHelper(BAN_IP,args);
5040}
5041
5042bool ChatHandler::HandleUnBanHelper(BanMode mode, const char* args)
5043{
5044    if(!args)
5045        return false;
5046
5047    char* cnameOrIP = strtok ((char*)args, " ");
5048    if(!cnameOrIP)
5049        return false;
5050
5051    std::string nameOrIP = cnameOrIP;
5052
5053    switch(mode)
5054    {
5055        case BAN_ACCOUNT:
5056            if(!AccountMgr::normilizeString(nameOrIP))
5057            {
5058                PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,nameOrIP.c_str());
5059                SetSentErrorMessage(true);
5060                return false;
5061            }
5062            break;
5063        case BAN_CHARACTER:
5064            if(!normalizePlayerName(nameOrIP))
5065            {
5066                SendSysMessage(LANG_PLAYER_NOT_FOUND);
5067                SetSentErrorMessage(true);
5068                return false;
5069            }
5070            break;
5071        case BAN_IP:
5072            if(!IsIPAddress(nameOrIP.c_str()))
5073                return false;
5074            break;
5075    }
5076
5077    if(sWorld.RemoveBanAccount(mode,nameOrIP))
5078        PSendSysMessage(LANG_UNBAN_UNBANNED,nameOrIP.c_str());
5079    else
5080        PSendSysMessage(LANG_UNBAN_ERROR,nameOrIP.c_str());
5081
5082    return true;
5083}
5084
5085bool ChatHandler::HandleBanInfoAccountCommand(const char* args)
5086{
5087    if(!args)
5088        return false;
5089
5090    char* cname = strtok((char*)args, "");
5091    if(!cname)
5092        return false;
5093
5094    std::string account_name = cname;
5095    if(!AccountMgr::normilizeString(account_name))
5096    {
5097        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5098        SetSentErrorMessage(true);
5099        return false;
5100    }
5101
5102    uint32 accountid = accmgr.GetId(account_name);
5103    if(!accountid)
5104    {
5105        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5106        return true;
5107    }
5108
5109    return HandleBanInfoHelper(accountid,account_name.c_str());
5110}
5111
5112bool ChatHandler::HandleBanInfoCharacterCommand(const char* args)
5113{
5114    if(!args)
5115        return false;
5116
5117    char* cname = strtok ((char*)args, "");
5118    if(!cname)
5119        return false;
5120
5121    std::string name = cname;
5122    if(!normalizePlayerName(name))
5123    {
5124        SendSysMessage(LANG_PLAYER_NOT_FOUND);
5125        SetSentErrorMessage(true);
5126        return false;
5127    }
5128
5129    uint32 accountid = objmgr.GetPlayerAccountIdByPlayerName(name);
5130    if(!accountid)
5131    {
5132        SendSysMessage(LANG_PLAYER_NOT_FOUND);
5133        SetSentErrorMessage(true);
5134        return false;
5135    }
5136
5137    std::string accountname;
5138    if(!accmgr.GetName(accountid,accountname))
5139    {
5140        PSendSysMessage(LANG_BANINFO_NOCHARACTER);
5141        return true;
5142    }
5143
5144    return HandleBanInfoHelper(accountid,accountname.c_str());
5145}
5146
5147bool ChatHandler::HandleBanInfoHelper(uint32 accountid, char const* accountname)
5148{
5149    QueryResult *result = loginDatabase.PQuery("SELECT FROM_UNIXTIME(bandate), unbandate-bandate, active, unbandate,banreason,bannedby FROM account_banned WHERE id = '%u' ORDER BY bandate ASC",accountid);
5150    if(!result)
5151    {
5152        PSendSysMessage(LANG_BANINFO_NOACCOUNTBAN, accountname);
5153        return true;
5154    }
5155
5156    PSendSysMessage(LANG_BANINFO_BANHISTORY,accountname);
5157    do
5158    {
5159        Field* fields = result->Fetch();
5160
5161        time_t unbandate = time_t(fields[3].GetUInt64());
5162        bool active = false;
5163        if(fields[2].GetBool() && (fields[1].GetUInt64() == (uint64)0 ||unbandate >= time(NULL)) )
5164            active = true;
5165        bool permanent = (fields[1].GetUInt64() == (uint64)0);
5166        std::string bantime = permanent?GetTrinityString(LANG_BANINFO_INFINITE):secsToTimeString(fields[1].GetUInt64(), true);
5167        PSendSysMessage(LANG_BANINFO_HISTORYENTRY,
5168            fields[0].GetString(), bantime.c_str(), active ? GetTrinityString(LANG_BANINFO_YES):GetTrinityString(LANG_BANINFO_NO), fields[4].GetString(), fields[5].GetString());
5169    }while (result->NextRow());
5170
5171    delete result;
5172    return true;
5173}
5174
5175bool ChatHandler::HandleBanInfoIPCommand(const char* args)
5176{
5177    if(!args)
5178        return false;
5179
5180    char* cIP = strtok ((char*)args, "");
5181    if(!cIP)
5182        return false;
5183
5184    if (!IsIPAddress(cIP))
5185        return false;
5186
5187    std::string IP = cIP;
5188
5189    loginDatabase.escape_string(IP);
5190    QueryResult *result = loginDatabase.PQuery("SELECT ip, FROM_UNIXTIME(bandate), FROM_UNIXTIME(unbandate), unbandate-UNIX_TIMESTAMP(), banreason,bannedby,unbandate-bandate FROM ip_banned WHERE ip = '%s'",IP.c_str());
5191    if(!result)
5192    {
5193        PSendSysMessage(LANG_BANINFO_NOIP);
5194        return true;
5195    }
5196
5197    Field *fields = result->Fetch();
5198    bool permanent = !fields[6].GetUInt64();
5199    PSendSysMessage(LANG_BANINFO_IPENTRY,
5200        fields[0].GetString(), fields[1].GetString(), permanent ? GetTrinityString(LANG_BANINFO_NEVER):fields[2].GetString(),
5201        permanent ? GetTrinityString(LANG_BANINFO_INFINITE):secsToTimeString(fields[3].GetUInt64(), true).c_str(), fields[4].GetString(), fields[5].GetString());
5202    delete result;
5203    return true;
5204}
5205
5206bool ChatHandler::HandleBanListCharacterCommand(const char* args)
5207{
5208    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
5209
5210    char* cFilter = strtok ((char*)args, " ");
5211    if(!cFilter)
5212        return false;
5213
5214    std::string filter = cFilter;
5215    loginDatabase.escape_string(filter);
5216    QueryResult* result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'"),filter.c_str());
5217    if (!result)
5218    {
5219        PSendSysMessage(LANG_BANLIST_NOCHARACTER);
5220        return true;
5221    }
5222
5223    return HandleBanListHelper(result);
5224}
5225
5226bool ChatHandler::HandleBanListAccountCommand(const char* args)
5227{
5228    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
5229
5230    char* cFilter = strtok((char*)args, " ");
5231    std::string filter = cFilter ? cFilter : "";
5232    loginDatabase.escape_string(filter);
5233
5234    QueryResult* result;
5235
5236    if(filter.empty())
5237    {
5238        result = loginDatabase.Query("SELECT account.id, username FROM account, account_banned"
5239            " WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id");
5240    }
5241    else
5242    {
5243        result = loginDatabase.PQuery("SELECT account.id, username FROM account, account_banned"
5244            " WHERE account.id = account_banned.id AND active = 1 AND username "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'")" GROUP BY account.id",
5245            filter.c_str());
5246    }
5247
5248    if (!result)
5249    {
5250        PSendSysMessage(LANG_BANLIST_NOACCOUNT);
5251        return true;
5252    }
5253
5254    return HandleBanListHelper(result);
5255}
5256
5257bool ChatHandler::HandleBanListHelper(QueryResult* result)
5258{
5259    PSendSysMessage(LANG_BANLIST_MATCHINGACCOUNT);
5260
5261    // Chat short output
5262    if(m_session)
5263    {
5264        do
5265        {
5266            Field* fields = result->Fetch();
5267            uint32 accountid = fields[0].GetUInt32();
5268
5269            QueryResult* banresult = loginDatabase.PQuery("SELECT account.username FROM account,account_banned WHERE account_banned.id='%u' AND account_banned.id=account.id",accountid);
5270            if(banresult)
5271            {
5272                Field* fields2 = banresult->Fetch();
5273                PSendSysMessage("%s",fields2[0].GetString());
5274                delete banresult;
5275            }
5276        } while (result->NextRow());
5277    }
5278    // Console wide output
5279    else
5280    {
5281        SendSysMessage(LANG_BANLIST_ACCOUNTS);
5282        SendSysMessage("===============================================================================");
5283        SendSysMessage(LANG_BANLIST_ACCOUNTS_HEADER);
5284        do
5285        {
5286            SendSysMessage("-------------------------------------------------------------------------------");
5287            Field *fields = result->Fetch();
5288            uint32 account_id = fields[0].GetUInt32 ();
5289
5290            std::string account_name;
5291
5292            // "account" case, name can be get in same query
5293            if(result->GetFieldCount() > 1)
5294                account_name = fields[1].GetCppString();
5295            // "character" case, name need extract from another DB
5296            else
5297                accmgr.GetName (account_id,account_name);
5298
5299            // No SQL injection. id is uint32.
5300            QueryResult *banInfo = loginDatabase.PQuery("SELECT bandate,unbandate,bannedby,banreason FROM account_banned WHERE id = %u ORDER BY unbandate", account_id);
5301            if (banInfo)
5302            {
5303                Field *fields2 = banInfo->Fetch();
5304                do
5305                {
5306                    time_t t_ban = fields2[0].GetUInt64();
5307                    tm* aTm_ban = localtime(&t_ban);
5308
5309                    if (fields2[0].GetUInt64() == fields2[1].GetUInt64())
5310                    {
5311                        PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|   permanent  |%-15.15s|%-15.15s|",
5312                            account_name.c_str(),aTm_ban->tm_year%100, aTm_ban->tm_mon+1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min,
5313                            fields2[2].GetString(),fields2[3].GetString());
5314                    }
5315                    else
5316                    {
5317                        time_t t_unban = fields2[1].GetUInt64();
5318                        tm* aTm_unban = localtime(&t_unban);
5319                        PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|",
5320                            account_name.c_str(),aTm_ban->tm_year%100, aTm_ban->tm_mon+1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min,
5321                            aTm_unban->tm_year%100, aTm_unban->tm_mon+1, aTm_unban->tm_mday, aTm_unban->tm_hour, aTm_unban->tm_min,
5322                            fields2[2].GetString(),fields2[3].GetString());
5323                    }
5324                }while ( banInfo->NextRow() );
5325                delete banInfo;
5326            }
5327        }while( result->NextRow() );
5328        SendSysMessage("===============================================================================");
5329    }
5330
5331    delete result;
5332    return true;
5333}
5334
5335bool ChatHandler::HandleBanListIPCommand(const char* args)
5336{
5337    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
5338
5339    char* cFilter = strtok((char*)args, " ");
5340    std::string filter = cFilter ? cFilter : "";
5341    loginDatabase.escape_string(filter);
5342
5343    QueryResult* result;
5344
5345    if(filter.empty())
5346    {
5347        result = loginDatabase.Query ("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned"
5348            " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP())"
5349            " ORDER BY unbandate" );
5350    }
5351    else
5352    {
5353        result = loginDatabase.PQuery( "SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned"
5354            " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP()) AND ip "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'")
5355            " ORDER BY unbandate",filter.c_str() );
5356    }
5357
5358    if(!result)
5359    {
5360        PSendSysMessage(LANG_BANLIST_NOIP);
5361        return true;
5362    }
5363
5364    PSendSysMessage(LANG_BANLIST_MATCHINGIP);
5365    // Chat short output
5366    if(m_session)
5367    {
5368        do
5369        {
5370            Field* fields = result->Fetch();
5371            PSendSysMessage("%s",fields[0].GetString());
5372        } while (result->NextRow());
5373    }
5374    // Console wide output
5375    else
5376    {
5377        SendSysMessage(LANG_BANLIST_IPS);
5378        SendSysMessage("===============================================================================");
5379        SendSysMessage(LANG_BANLIST_IPS_HEADER);
5380        do
5381        {
5382            SendSysMessage("-------------------------------------------------------------------------------");
5383            Field *fields = result->Fetch();
5384            time_t t_ban = fields[1].GetUInt64();
5385            tm* aTm_ban = localtime(&t_ban);
5386            if ( fields[1].GetUInt64() == fields[2].GetUInt64() )
5387            {
5388                PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|   permanent  |%-15.15s|%-15.15s|",
5389                    fields[0].GetString(), aTm_ban->tm_year%100, aTm_ban->tm_mon+1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min,
5390                    fields[3].GetString(), fields[4].GetString());
5391            }
5392            else
5393            {
5394                time_t t_unban = fields[2].GetUInt64();
5395                tm* aTm_unban = localtime(&t_unban);
5396                PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|",
5397                    fields[0].GetString(), aTm_ban->tm_year%100, aTm_ban->tm_mon+1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min,
5398                    aTm_unban->tm_year%100, aTm_unban->tm_mon+1, aTm_unban->tm_mday, aTm_unban->tm_hour, aTm_unban->tm_min,
5399                    fields[3].GetString(), fields[4].GetString());
5400            }
5401        }while( result->NextRow() );
5402        SendSysMessage("===============================================================================");
5403    }
5404
5405    delete result;
5406    return true;
5407}
5408
5409bool ChatHandler::HandleRespawnCommand(const char* /*args*/)
5410{
5411    Player* pl = m_session->GetPlayer();
5412
5413    // accept only explicitly selected target (not implicitly self targeting case)
5414    Unit* target = getSelectedUnit();
5415    if(pl->GetSelection() && target)
5416    {
5417        if(target->GetTypeId()!=TYPEID_UNIT)
5418        {
5419            SendSysMessage(LANG_SELECT_CREATURE);
5420            SetSentErrorMessage(true);
5421            return false;
5422        }
5423
5424        if(target->isDead())
5425            ((Creature*)target)->Respawn();
5426        return true;
5427    }
5428
5429    CellPair p(Trinity::ComputeCellPair(pl->GetPositionX(), pl->GetPositionY()));
5430    Cell cell(p);
5431    cell.data.Part.reserved = ALL_DISTRICT;
5432    cell.SetNoCreate();
5433
5434    Trinity::RespawnDo u_do;
5435    Trinity::WorldObjectWorker<Trinity::RespawnDo> worker(u_do);
5436
5437    TypeContainerVisitor<Trinity::WorldObjectWorker<Trinity::RespawnDo>, GridTypeMapContainer > obj_worker(worker);
5438    CellLock<GridReadGuard> cell_lock(cell, p);
5439    cell_lock->Visit(cell_lock, obj_worker, *MapManager::Instance().GetMap(pl->GetMapId(), pl));
5440
5441    return true;
5442}
5443
5444bool ChatHandler::HandleFlyModeCommand(const char* args)
5445{
5446    if(!args)
5447        return false;
5448
5449    Unit *unit = getSelectedUnit();
5450    if (!unit || (unit->GetTypeId() != TYPEID_PLAYER))
5451        unit = m_session->GetPlayer();
5452
5453    WorldPacket data(12);
5454    if (strncmp(args, "on", 3) == 0)
5455        data.SetOpcode(SMSG_MOVE_SET_CAN_FLY);
5456    else if (strncmp(args, "off", 4) == 0)
5457        data.SetOpcode(SMSG_MOVE_UNSET_CAN_FLY);
5458    else
5459    {
5460        SendSysMessage(LANG_USE_BOL);
5461        return false;
5462    }
5463    data.append(unit->GetPackGUID());
5464    data << uint32(0);                                      // unknown
5465    unit->SendMessageToSet(&data, true);
5466    PSendSysMessage(LANG_COMMAND_FLYMODE_STATUS, unit->GetName(), args);
5467    return true;
5468}
5469
5470bool ChatHandler::HandleLoadPDumpCommand(const char *args)
5471{
5472    if(!args)
5473        return false;
5474
5475    char * file = strtok((char*)args, " ");
5476    if(!file)
5477        return false;
5478
5479    char * account = strtok(NULL, " ");
5480    if(!account)
5481        return false;
5482
5483    std::string account_name = account;
5484    if(!AccountMgr::normilizeString(account_name))
5485    {
5486        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5487        SetSentErrorMessage(true);
5488        return false;
5489    }
5490
5491    uint32 account_id = accmgr.GetId(account_name);
5492    if(!account_id)
5493    {
5494        account_id = atoi(account);                             // use original string
5495        if(!account_id)
5496        {
5497            PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5498            SetSentErrorMessage(true);
5499            return false;
5500        }
5501    }
5502
5503    if(!accmgr.GetName(account_id,account_name))
5504    {
5505        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5506        SetSentErrorMessage(true);
5507        return false;
5508    }
5509
5510    char* guid_str = NULL;
5511    char* name_str = strtok(NULL, " ");
5512
5513    std::string name;
5514    if(name_str)
5515    {
5516        name = name_str;
5517        // normalize the name if specified and check if it exists
5518        if(!normalizePlayerName(name))
5519        {
5520            PSendSysMessage(LANG_INVALID_CHARACTER_NAME);
5521            SetSentErrorMessage(true);
5522            return false;
5523        }
5524
5525        if(!ObjectMgr::IsValidName(name,true))
5526        {
5527            PSendSysMessage(LANG_INVALID_CHARACTER_NAME);
5528            SetSentErrorMessage(true);
5529            return false;
5530        }
5531
5532        guid_str = strtok(NULL, " ");
5533    }
5534
5535    uint32 guid = 0;
5536
5537    if(guid_str)
5538    {
5539        guid = atoi(guid_str);
5540        if(!guid)
5541        {
5542            PSendSysMessage(LANG_INVALID_CHARACTER_GUID);
5543            SetSentErrorMessage(true);
5544            return false;
5545        }
5546
5547        if(objmgr.GetPlayerAccountIdByGUID(guid))
5548        {
5549            PSendSysMessage(LANG_CHARACTER_GUID_IN_USE,guid);
5550            SetSentErrorMessage(true);
5551            return false;
5552        }
5553    }
5554
5555    switch(PlayerDumpReader().LoadDump(file, account_id, name, guid))
5556    {
5557        case DUMP_SUCCESS:
5558            PSendSysMessage(LANG_COMMAND_IMPORT_SUCCESS);
5559            break;
5560        case DUMP_FILE_OPEN_ERROR:
5561            PSendSysMessage(LANG_FILE_OPEN_FAIL,file);
5562            SetSentErrorMessage(true);
5563            return false;
5564        case DUMP_FILE_BROKEN:
5565            PSendSysMessage(LANG_DUMP_BROKEN,file);
5566            SetSentErrorMessage(true);
5567            return false;
5568        case DUMP_TOO_MANY_CHARS:
5569            PSendSysMessage(LANG_ACCOUNT_CHARACTER_LIST_FULL,account_name.c_str(),account_id);
5570            SetSentErrorMessage(true);
5571            return false;
5572        default:
5573            PSendSysMessage(LANG_COMMAND_IMPORT_FAILED);
5574            SetSentErrorMessage(true);
5575            return false;
5576    }
5577
5578    return true;
5579}
5580
5581bool ChatHandler::HandleNpcChangeEntryCommand(const char *args)
5582{
5583    if(!args)
5584        return false;
5585
5586    uint32 newEntryNum = atoi(args);
5587    if(!newEntryNum)
5588        return false;
5589
5590    Unit* unit = getSelectedUnit();
5591    if(!unit || unit->GetTypeId() != TYPEID_UNIT)
5592    {
5593        SendSysMessage(LANG_SELECT_CREATURE);
5594        SetSentErrorMessage(true);
5595        return false;
5596    }
5597    Creature* creature = (Creature*)unit;
5598    if(creature->UpdateEntry(newEntryNum))
5599        SendSysMessage(LANG_DONE);
5600    else
5601        SendSysMessage(LANG_ERROR);
5602    return true;
5603}
5604
5605bool ChatHandler::HandleWritePDumpCommand(const char *args)
5606{
5607    if(!args)
5608        return false;
5609
5610    char* file = strtok((char*)args, " ");
5611    char* p2 = strtok(NULL, " ");
5612
5613    if(!file || !p2)
5614        return false;
5615
5616    uint32 guid = objmgr.GetPlayerGUIDByName(p2);
5617    if(!guid)
5618        guid = atoi(p2);
5619
5620    if(!objmgr.GetPlayerAccountIdByGUID(guid))
5621    {
5622        PSendSysMessage(LANG_PLAYER_NOT_FOUND);
5623        SetSentErrorMessage(true);
5624        return false;
5625    }
5626
5627    switch(PlayerDumpWriter().WriteDump(file, guid))
5628    {
5629        case DUMP_SUCCESS:
5630            PSendSysMessage(LANG_COMMAND_EXPORT_SUCCESS);
5631            break;
5632        case DUMP_FILE_OPEN_ERROR:
5633            PSendSysMessage(LANG_FILE_OPEN_FAIL,file);
5634            SetSentErrorMessage(true);
5635            return false;
5636        default:
5637            PSendSysMessage(LANG_COMMAND_EXPORT_FAILED);
5638            SetSentErrorMessage(true);
5639            return false;
5640    }
5641
5642    return true;
5643}
5644
5645bool ChatHandler::HandleMovegensCommand(const char* /*args*/)
5646{
5647    Unit* unit = getSelectedUnit();
5648    if(!unit)
5649    {
5650        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5651        SetSentErrorMessage(true);
5652        return false;
5653    }
5654
5655    PSendSysMessage(LANG_MOVEGENS_LIST,(unit->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature" ),unit->GetGUIDLow());
5656
5657    MotionMaster* mm = unit->GetMotionMaster();
5658    for(MotionMaster::const_iterator itr = mm->begin(); itr != mm->end(); ++itr)
5659    {
5660        switch((*itr)->GetMovementGeneratorType())
5661        {
5662            case IDLE_MOTION_TYPE:          SendSysMessage(LANG_MOVEGENS_IDLE);          break;
5663            case RANDOM_MOTION_TYPE:        SendSysMessage(LANG_MOVEGENS_RANDOM);        break;
5664            case WAYPOINT_MOTION_TYPE:      SendSysMessage(LANG_MOVEGENS_WAYPOINT);      break;
5665            case ANIMAL_RANDOM_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_ANIMAL_RANDOM); break;
5666            case CONFUSED_MOTION_TYPE:      SendSysMessage(LANG_MOVEGENS_CONFUSED);      break;
5667            case TARGETED_MOTION_TYPE:
5668            {
5669                if(unit->GetTypeId()==TYPEID_PLAYER)
5670                {
5671                    TargetedMovementGenerator<Player> const* mgen = static_cast<TargetedMovementGenerator<Player> const*>(*itr);
5672                    Unit* target = mgen->GetTarget();
5673                    if(target)
5674                        PSendSysMessage(LANG_MOVEGENS_TARGETED_PLAYER,target->GetName(),target->GetGUIDLow());
5675                    else
5676                        SendSysMessage(LANG_MOVEGENS_TARGETED_NULL);
5677                }
5678                else
5679                {
5680                    TargetedMovementGenerator<Creature> const* mgen = static_cast<TargetedMovementGenerator<Creature> const*>(*itr);
5681                    Unit* target = mgen->GetTarget();
5682                    if(target)
5683                        PSendSysMessage(LANG_MOVEGENS_TARGETED_CREATURE,target->GetName(),target->GetGUIDLow());
5684                    else
5685                        SendSysMessage(LANG_MOVEGENS_TARGETED_NULL);
5686                }
5687                break;
5688            }
5689            case HOME_MOTION_TYPE:
5690                if(unit->GetTypeId()==TYPEID_UNIT)
5691                {
5692                    float x,y,z;
5693                    (*itr)->GetDestination(x,y,z);
5694                    PSendSysMessage(LANG_MOVEGENS_HOME_CREATURE,x,y,z);
5695                }
5696                else
5697                    SendSysMessage(LANG_MOVEGENS_HOME_PLAYER);
5698                break;
5699            case FLIGHT_MOTION_TYPE:   SendSysMessage(LANG_MOVEGENS_FLIGHT);  break;
5700            case POINT_MOTION_TYPE:
5701            {
5702                float x,y,z;
5703                (*itr)->GetDestination(x,y,z);
5704                PSendSysMessage(LANG_MOVEGENS_POINT,x,y,z);
5705                break;
5706            }
5707            case FLEEING_MOTION_TYPE:  SendSysMessage(LANG_MOVEGENS_FEAR);    break;
5708            case DISTRACT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_DISTRACT);  break;
5709            default:
5710                PSendSysMessage(LANG_MOVEGENS_UNKNOWN,(*itr)->GetMovementGeneratorType());
5711                break;
5712        }
5713    }
5714    return true;
5715}
5716
5717bool ChatHandler::HandlePLimitCommand(const char *args)
5718{
5719    if(*args)
5720    {
5721        char* param = strtok((char*)args, " ");
5722        if(!param)
5723            return false;
5724
5725        int l = strlen(param);
5726
5727        if(     strncmp(param,"player",l) == 0 )
5728            sWorld.SetPlayerLimit(-SEC_PLAYER);
5729        else if(strncmp(param,"moderator",l) == 0 )
5730            sWorld.SetPlayerLimit(-SEC_MODERATOR);
5731        else if(strncmp(param,"gamemaster",l) == 0 )
5732            sWorld.SetPlayerLimit(-SEC_GAMEMASTER);
5733        else if(strncmp(param,"administrator",l) == 0 )
5734            sWorld.SetPlayerLimit(-SEC_ADMINISTRATOR);
5735        else if(strncmp(param,"reset",l) == 0 )
5736            sWorld.SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT) );
5737        else
5738        {
5739            int val = atoi(param);
5740            if(val < -SEC_ADMINISTRATOR) val = -SEC_ADMINISTRATOR;
5741
5742            sWorld.SetPlayerLimit(val);
5743        }
5744
5745        // kick all low security level players
5746        if(sWorld.GetPlayerAmountLimit() > SEC_PLAYER)
5747            sWorld.KickAllLess(sWorld.GetPlayerSecurityLimit());
5748    }
5749
5750    uint32 pLimit = sWorld.GetPlayerAmountLimit();
5751    AccountTypes allowedAccountType = sWorld.GetPlayerSecurityLimit();
5752    char const* secName = "";
5753    switch(allowedAccountType)
5754    {
5755        case SEC_PLAYER:        secName = "Player";        break;
5756        case SEC_MODERATOR:     secName = "Moderator";     break;
5757        case SEC_GAMEMASTER:    secName = "Gamemaster";    break;
5758        case SEC_ADMINISTRATOR: secName = "Administrator"; break;
5759        default:                secName = "<unknown>";     break;
5760    }
5761
5762    PSendSysMessage("Player limits: amount %u, min. security level %s.",pLimit,secName);
5763
5764    return true;
5765}
5766
5767bool ChatHandler::HandleCastCommand(const char* args)
5768{
5769    if(!*args)
5770        return false;
5771
5772    Unit* target = getSelectedUnit();
5773
5774    if(!target)
5775    {
5776        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5777        SetSentErrorMessage(true);
5778        return false;
5779    }
5780
5781    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5782    uint32 spell = extractSpellIdFromLink((char*)args);
5783    if(!spell)
5784        return false;
5785
5786    SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
5787    if(!spellInfo)
5788        return false;
5789
5790    if(!SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
5791    {
5792        PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
5793        SetSentErrorMessage(true);
5794        return false;
5795    }
5796
5797    char* trig_str = strtok(NULL, " ");
5798    if(trig_str)
5799    {
5800        int l = strlen(trig_str);
5801        if(strncmp(trig_str,"triggered",l) != 0 )
5802            return false;
5803    }
5804
5805    bool triggered = (trig_str != NULL);
5806
5807    m_session->GetPlayer()->CastSpell(target,spell,triggered);
5808
5809    return true;
5810}
5811
5812bool ChatHandler::HandleCastBackCommand(const char* args)
5813{
5814    Creature* caster = getSelectedCreature();
5815
5816    if(!caster)
5817    {
5818        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5819        SetSentErrorMessage(true);
5820        return false;
5821    }
5822
5823    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r
5824    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5825    uint32 spell = extractSpellIdFromLink((char*)args);
5826    if(!spell || !sSpellStore.LookupEntry(spell))
5827        return false;
5828
5829    char* trig_str = strtok(NULL, " ");
5830    if(trig_str)
5831    {
5832        int l = strlen(trig_str);
5833        if(strncmp(trig_str,"triggered",l) != 0 )
5834            return false;
5835    }
5836
5837    bool triggered = (trig_str != NULL);
5838
5839    // update orientation at server
5840    caster->SetOrientation(caster->GetAngle(m_session->GetPlayer()));
5841
5842    // and client
5843    WorldPacket data;
5844    caster->BuildHeartBeatMsg(&data);
5845    caster->SendMessageToSet(&data,true);
5846
5847    caster->CastSpell(m_session->GetPlayer(),spell,triggered);
5848
5849    return true;
5850}
5851
5852bool ChatHandler::HandleCastDistCommand(const char* args)
5853{
5854    if(!*args)
5855        return false;
5856
5857    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5858    uint32 spell = extractSpellIdFromLink((char*)args);
5859    if(!spell)
5860        return false;
5861
5862    SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
5863    if(!spellInfo)
5864        return false;
5865
5866    if(!SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
5867    {
5868        PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
5869        SetSentErrorMessage(true);
5870        return false;
5871    }
5872
5873    char *distStr = strtok(NULL, " ");
5874
5875    float dist = 0;
5876
5877    if(distStr)
5878        sscanf(distStr, "%f", &dist);
5879
5880    char* trig_str = strtok(NULL, " ");
5881    if(trig_str)
5882    {
5883        int l = strlen(trig_str);
5884        if(strncmp(trig_str,"triggered",l) != 0 )
5885            return false;
5886    }
5887
5888    bool triggered = (trig_str != NULL);
5889
5890    float x,y,z;
5891    m_session->GetPlayer()->GetClosePoint(x,y,z,dist);
5892
5893    m_session->GetPlayer()->CastSpell(x,y,z,spell,triggered);
5894    return true;
5895}
5896
5897bool ChatHandler::HandleCastTargetCommand(const char* args)
5898{
5899    Creature* caster = getSelectedCreature();
5900
5901    if(!caster)
5902    {
5903        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5904        SetSentErrorMessage(true);
5905        return false;
5906    }
5907
5908    if(!caster->getVictim())
5909    {
5910        SendSysMessage(LANG_SELECTED_TARGET_NOT_HAVE_VICTIM);
5911        SetSentErrorMessage(true);
5912        return false;
5913    }
5914
5915    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5916    uint32 spell = extractSpellIdFromLink((char*)args);
5917    if(!spell || !sSpellStore.LookupEntry(spell))
5918        return false;
5919
5920    char* trig_str = strtok(NULL, " ");
5921    if(trig_str)
5922    {
5923        int l = strlen(trig_str);
5924        if(strncmp(trig_str,"triggered",l) != 0 )
5925            return false;
5926    }
5927
5928    bool triggered = (trig_str != NULL);
5929
5930    // update orientation at server
5931    caster->SetOrientation(caster->GetAngle(m_session->GetPlayer()));
5932
5933    // and client
5934    WorldPacket data;
5935    caster->BuildHeartBeatMsg(&data);
5936    caster->SendMessageToSet(&data,true);
5937
5938    caster->CastSpell(caster->getVictim(),spell,triggered);
5939
5940    return true;
5941}
5942
5943/*
5944ComeToMe command REQUIRED for 3rd party scripting library to have access to PointMovementGenerator
5945Without this function 3rd party scripting library will get linking errors (unresolved external)
5946when attempting to use the PointMovementGenerator
5947*/
5948bool ChatHandler::HandleComeToMeCommand(const char *args)
5949{
5950    Creature* caster = getSelectedCreature();
5951
5952    if(!caster)
5953    {
5954        SendSysMessage(LANG_SELECT_CREATURE);
5955        SetSentErrorMessage(true);
5956        return false;
5957    }
5958
5959    char* newFlagStr = strtok((char*)args, " ");
5960
5961    if(!newFlagStr)
5962        return false;
5963
5964    uint32 newFlags = atoi(newFlagStr);
5965
5966    caster->SetUnitMovementFlags(newFlags);
5967
5968    Player* pl = m_session->GetPlayer();
5969
5970    caster->GetMotionMaster()->MovePoint(0, pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ());
5971    return true;
5972}
5973
5974bool ChatHandler::HandleCastSelfCommand(const char* args)
5975{
5976    if(!*args)
5977        return false;
5978
5979    Unit* target = getSelectedUnit();
5980
5981    if(!target)
5982    {
5983        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5984        SetSentErrorMessage(true);
5985        return false;
5986    }
5987
5988    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5989    uint32 spell = extractSpellIdFromLink((char*)args);
5990    if(!spell)
5991        return false;
5992
5993    SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
5994    if(!spellInfo)
5995        return false;
5996
5997    if(!SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
5998    {
5999        PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
6000        SetSentErrorMessage(true);
6001        return false;
6002    }
6003
6004    target->CastSpell(target,spell,false);
6005
6006    return true;
6007}
6008
6009std::string GetTimeString(uint32 time)
6010{
6011    uint16 days = time / DAY, hours = (time % DAY) / HOUR, minute = (time % HOUR) / MINUTE;
6012    std::ostringstream ss;
6013    if(days) ss << days << "d ";
6014    if(hours) ss << hours << "h ";
6015    ss << minute << "m";
6016    return ss.str();
6017}
6018
6019bool ChatHandler::HandleInstanceListBindsCommand(const char* /*args*/)
6020{
6021    Player* player = getSelectedPlayer();
6022    if (!player) player = m_session->GetPlayer();
6023    uint32 counter = 0;
6024    for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
6025    {
6026        Player::BoundInstancesMap &binds = player->GetBoundInstances(i);
6027        for(Player::BoundInstancesMap::iterator itr = binds.begin(); itr != binds.end(); ++itr)
6028        {
6029            InstanceSave *save = itr->second.save;
6030            std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL));
6031            PSendSysMessage("map: %d inst: %d perm: %s diff: %s canReset: %s TTR: %s", itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no",  save->GetDifficulty() == DIFFICULTY_NORMAL ? "normal" : "heroic", save->CanReset() ? "yes" : "no", timeleft.c_str());
6032            counter++;
6033        }
6034    }
6035    PSendSysMessage("player binds: %d", counter);
6036    counter = 0;
6037    Group *group = player->GetGroup();
6038    if(group)
6039    {
6040        for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
6041        {
6042            Group::BoundInstancesMap &binds = group->GetBoundInstances(i);
6043            for(Group::BoundInstancesMap::iterator itr = binds.begin(); itr != binds.end(); ++itr)
6044            {
6045                InstanceSave *save = itr->second.save;
6046                std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL));
6047                PSendSysMessage("map: %d inst: %d perm: %s diff: %s canReset: %s TTR: %s", itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no",  save->GetDifficulty() == DIFFICULTY_NORMAL ? "normal" : "heroic", save->CanReset() ? "yes" : "no", timeleft.c_str());
6048                counter++;
6049            }
6050        }
6051    }
6052    PSendSysMessage("group binds: %d", counter);
6053
6054    return true;
6055}
6056
6057bool ChatHandler::HandleInstanceUnbindCommand(const char* args)
6058{
6059    if(!*args)
6060        return false;
6061
6062    std::string cmd = args;
6063    if(cmd == "all")
6064    {
6065        Player* player = getSelectedPlayer();
6066        if (!player) player = m_session->GetPlayer();
6067        uint32 counter = 0;
6068        for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
6069        {
6070            Player::BoundInstancesMap &binds = player->GetBoundInstances(i);
6071            for(Player::BoundInstancesMap::iterator itr = binds.begin(); itr != binds.end();)
6072            {
6073                if(itr->first != player->GetMapId())
6074                {
6075                    InstanceSave *save = itr->second.save;
6076                    std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL));
6077                    PSendSysMessage("unbinding map: %d inst: %d perm: %s diff: %s canReset: %s TTR: %s", itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no",  save->GetDifficulty() == DIFFICULTY_NORMAL ? "normal" : "heroic", save->CanReset() ? "yes" : "no", timeleft.c_str());
6078                    player->UnbindInstance(itr, i);
6079                    counter++;
6080                }
6081                else
6082                    ++itr;
6083            }
6084        }
6085        PSendSysMessage("instances unbound: %d", counter);
6086    }
6087    return true;
6088}
6089
6090bool ChatHandler::HandleInstanceStatsCommand(const char* /*args*/)
6091{
6092    PSendSysMessage("instances loaded: %d", MapManager::Instance().GetNumInstances());
6093    PSendSysMessage("players in instances: %d", MapManager::Instance().GetNumPlayersInInstances());
6094    PSendSysMessage("instance saves: %d", sInstanceSaveManager.GetNumInstanceSaves());
6095    PSendSysMessage("players bound: %d", sInstanceSaveManager.GetNumBoundPlayersTotal());
6096    PSendSysMessage("groups bound: %d", sInstanceSaveManager.GetNumBoundGroupsTotal());
6097    return true;
6098}
6099
6100bool ChatHandler::HandleInstanceSaveDataCommand(const char * /*args*/)
6101{
6102    Player* pl = m_session->GetPlayer();
6103
6104    Map* map = pl->GetMap();
6105    if (!map->IsDungeon())
6106    {
6107        PSendSysMessage("Map is not a dungeon.");
6108        SetSentErrorMessage(true);
6109        return false;
6110    }
6111
6112    if (!((InstanceMap*)map)->GetInstanceData())
6113    {
6114        PSendSysMessage("Map has no instance data.");
6115        SetSentErrorMessage(true);
6116        return false;
6117    }
6118
6119    ((InstanceMap*)map)->GetInstanceData()->SaveToDB();
6120    return true;
6121}
6122
6123/// Display the list of GMs
6124bool ChatHandler::HandleGMListFullCommand(const char* /*args*/)
6125{
6126    ///- Get the accounts with GM Level >0
6127    QueryResult *result = loginDatabase.Query( "SELECT username,gmlevel FROM account WHERE gmlevel > 0" );
6128    if(result)
6129    {
6130        SendSysMessage(LANG_GMLIST);
6131        SendSysMessage("========================");
6132        SendSysMessage(LANG_GMLIST_HEADER);
6133        SendSysMessage("========================");
6134
6135        ///- Circle through them. Display username and GM level
6136        do
6137        {
6138            Field *fields = result->Fetch();
6139            PSendSysMessage("|%15s|%6s|", fields[0].GetString(),fields[1].GetString());
6140        }while( result->NextRow() );
6141
6142        PSendSysMessage("========================");
6143        delete result;
6144    }
6145    else
6146        PSendSysMessage(LANG_GMLIST_EMPTY);
6147    return true;
6148}
6149
6150/// Define the 'Message of the day' for the realm
6151bool ChatHandler::HandleServerSetMotdCommand(const char* args)
6152{
6153    sWorld.SetMotd(args);
6154    PSendSysMessage(LANG_MOTD_NEW, args);
6155    return true;
6156}
6157
6158/// Set/Unset the expansion level for an account
6159bool ChatHandler::HandleAccountSetAddonCommand(const char* args)
6160{
6161    ///- Get the command line arguments
6162    char *szAcc = strtok((char*)args," ");
6163    char *szExp = strtok(NULL," ");
6164
6165    if(!szAcc)
6166        return false;
6167
6168    std::string account_name;
6169    uint32 account_id;
6170
6171    if(!szExp)
6172    {
6173        Player* player = getSelectedPlayer();
6174        if(!player)
6175            return false;
6176
6177        account_id = player->GetSession()->GetAccountId();
6178        accmgr.GetName(account_id,account_name);
6179        szExp = szAcc;
6180    }
6181    else
6182    {
6183        ///- Convert Account name to Upper Format
6184        account_name = szAcc;
6185        if(!AccountMgr::normilizeString(account_name))
6186        {
6187            PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
6188            SetSentErrorMessage(true);
6189            return false;
6190        }
6191
6192        account_id = accmgr.GetId(account_name);
6193        if(!account_id)
6194        {
6195            PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
6196            SetSentErrorMessage(true);
6197            return false;
6198        }
6199    }
6200
6201    int lev=atoi(szExp);                                    //get int anyway (0 if error)
6202    if(lev < 0)
6203        return false;
6204
6205    // No SQL injection
6206    loginDatabase.PExecute("UPDATE account SET expansion = '%d' WHERE id = '%u'",lev,account_id);
6207    PSendSysMessage(LANG_ACCOUNT_SETADDON,account_name.c_str(),account_id,lev);
6208    return true;
6209}
6210
6211/// Send a message to a player in game
6212bool ChatHandler::HandleSendMessageCommand(const char* args)
6213{
6214    ///- Get the command line arguments
6215    char* name_str = strtok((char*)args, " ");
6216    char* msg_str = strtok(NULL, "");
6217
6218    if(!name_str || !msg_str)
6219        return false;
6220
6221    std::string name = name_str;
6222
6223    if(!normalizePlayerName(name))
6224        return false;
6225
6226    ///- Find the player and check that he is not logging out.
6227    Player *rPlayer = objmgr.GetPlayer(name.c_str());
6228    if(!rPlayer)
6229    {
6230        SendSysMessage(LANG_PLAYER_NOT_FOUND);
6231        SetSentErrorMessage(true);
6232        return false;
6233    }
6234
6235    if(rPlayer->GetSession()->isLogingOut())
6236    {
6237        SendSysMessage(LANG_PLAYER_NOT_FOUND);
6238        SetSentErrorMessage(true);
6239        return false;
6240    }
6241
6242    ///- Send the message
6243    //Use SendAreaTriggerMessage for fastest delivery.
6244    rPlayer->GetSession()->SendAreaTriggerMessage("%s", msg_str);
6245    rPlayer->GetSession()->SendAreaTriggerMessage("|cffff0000[Message from administrator]:|r");
6246
6247    //Confirmation message
6248    PSendSysMessage(LANG_SENDMESSAGE,name.c_str(),msg_str);
6249    return true;
6250}
6251
6252bool ChatHandler::HandlePlayAllCommand(const char* args)
6253{
6254    if(!*args)
6255        return false;
6256
6257    uint32 soundId = atoi((char*)args);
6258
6259    if(!sSoundEntriesStore.LookupEntry(soundId))
6260    {
6261        PSendSysMessage(LANG_SOUND_NOT_EXIST, soundId);
6262        SetSentErrorMessage(true);
6263        return false;
6264    }
6265
6266    WorldPacket data(SMSG_PLAY_SOUND, 4);
6267    data << uint32(soundId) << m_session->GetPlayer()->GetGUID();
6268    sWorld.SendGlobalMessage(&data);
6269
6270    PSendSysMessage(LANG_COMMAND_PLAYED_TO_ALL, soundId);
6271    return true;
6272}
6273
6274bool ChatHandler::HandleModifyGenderCommand(const char *args)
6275{
6276    if(!*args)  return false;
6277    Player *player = getSelectedPlayer();
6278
6279    if(!player)
6280    {
6281        PSendSysMessage(LANG_NO_PLAYER);
6282        SetSentErrorMessage(true);
6283        return false;
6284    }
6285
6286    std::string gender = (char*)args;
6287    uint32 displayId = player->GetNativeDisplayId();
6288
6289    if(gender == "male") // MALE
6290    {
6291        if(player->getGender() == GENDER_MALE)
6292        {
6293            PSendSysMessage("%s is already male", player->GetName());
6294            SetSentErrorMessage(true);
6295            return false;
6296        }
6297
6298        // Set gender
6299        player->SetByteValue(UNIT_FIELD_BYTES_0, 2, GENDER_MALE);
6300        // Change display ID
6301        player->SetDisplayId(player->getRace() == RACE_BLOODELF ? displayId+1 : displayId-1);
6302        player->SetNativeDisplayId(player->getRace() == RACE_BLOODELF ? displayId+1 : displayId-1);
6303
6304        ChatHandler(player).PSendSysMessage("Gender changed. You are now a man!");
6305        PSendSysMessage("Gender changed for %s", player->GetName());
6306        return true;
6307    }
6308    else if(gender == "female") // FEMALE
6309    {
6310        if(player->getGender() == GENDER_FEMALE)
6311        {
6312            PSendSysMessage("%s is already female", player->GetName());
6313            SetSentErrorMessage(true);
6314            return false;
6315        }
6316
6317        // Set gender
6318        player->SetByteValue(UNIT_FIELD_BYTES_0, 2, GENDER_FEMALE);
6319        // Change display ID
6320        player->SetDisplayId(player->getRace() == RACE_BLOODELF ? displayId-1 : displayId+1);
6321        player->SetNativeDisplayId(player->getRace() == RACE_BLOODELF ? displayId-1 : displayId+1);
6322
6323        ChatHandler(player).PSendSysMessage("Gender changed. You are now a woman!");
6324        PSendSysMessage("Gender changed for %s", player->GetName());
6325        return true;
6326    }
6327    else
6328    {
6329        PSendSysMessage("You must use male or female as gender.");
6330        SetSentErrorMessage(true);
6331        return false;
6332    }
6333
6334    return true;
6335}
6336
6337bool ChatHandler::HandleFreezeCommand(const char *args)
6338{
6339    std::string name;
6340    Player* player;
6341    char* TargetName = strtok((char*)args, " "); //get entered name
6342    if (!TargetName) //if no name entered use target
6343    {
6344        player = getSelectedPlayer();
6345        if (player) //prevent crash with creature as target
6346        {   
6347            name = player->GetName();
6348            normalizePlayerName(name);
6349        }
6350    }
6351    else // if name entered
6352    {
6353        name = TargetName;
6354        normalizePlayerName(name);
6355        player = objmgr.GetPlayer(name.c_str()); //get player by name
6356    }
6357
6358    if (!player)
6359    {
6360        SendSysMessage(LANG_COMMAND_FREEZE_WRONG);
6361        return true;
6362    }
6363
6364    if (player==m_session->GetPlayer())
6365    {
6366        SendSysMessage(LANG_COMMAND_FREEZE_ERROR);
6367        return true;
6368    }
6369
6370    //effect
6371    if ((player) && (!(player==m_session->GetPlayer())))
6372    {
6373        PSendSysMessage(LANG_COMMAND_FREEZE,name.c_str());
6374
6375        //stop combat + make player unattackable + duel stop + stop some spells
6376        player->setFaction(35);
6377        player->CombatStop();
6378        if(player->IsNonMeleeSpellCasted(true))
6379            player->InterruptNonMeleeSpells(true);
6380        player->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
6381        player->SetUInt32Value(PLAYER_DUEL_TEAM, 1);
6382
6383        //if player class = hunter || warlock remove pet if alive
6384        if((player->getClass() == CLASS_HUNTER) || (player->getClass() == CLASS_WARLOCK))
6385        {
6386            if(Pet* pet = player->GetPet())
6387            {
6388                pet->SavePetToDB(PET_SAVE_AS_CURRENT);
6389                // not let dismiss dead pet
6390                if(pet && pet->isAlive())
6391                    player->RemovePet(pet,PET_SAVE_NOT_IN_SLOT);
6392            }
6393        }
6394
6395        //stop movement and disable spells
6396        uint32 spellID = 9454;
6397        //m_session->GetPlayer()->CastSpell(player,spellID,false);
6398        SpellEntry const *spellInfo = sSpellStore.LookupEntry( spellID );
6399        if(spellInfo) //TODO: Change the duration of the aura to -1 instead of 5000000
6400        {
6401            for(uint32 i = 0;i<3;i++)
6402            {
6403                uint8 eff = spellInfo->Effect[i];
6404                if (eff>=TOTAL_SPELL_EFFECTS)
6405                    continue;
6406                if( eff == SPELL_EFFECT_APPLY_AREA_AURA_PARTY || eff == SPELL_EFFECT_APPLY_AURA ||
6407                    eff == SPELL_EFFECT_PERSISTENT_AREA_AURA || eff == SPELL_EFFECT_APPLY_AREA_AURA_FRIEND || 
6408                    eff == SPELL_EFFECT_APPLY_AREA_AURA_ENEMY)
6409                {
6410                    Aura *Aur = CreateAura(spellInfo, i, NULL, player);
6411                    player->AddAura(Aur);
6412                }
6413            }
6414        }
6415
6416        //save player
6417        player->SaveToDB();
6418    }
6419    return true;
6420}
6421
6422bool ChatHandler::HandleUnFreezeCommand(const char *args)
6423{
6424    std::string name;
6425    Player* player;
6426    char* TargetName = strtok((char*)args, " "); //get entered name
6427    if (!TargetName) //if no name entered use target
6428    {
6429        player = getSelectedPlayer();
6430        if (player) //prevent crash with creature as target
6431        {   
6432            name = player->GetName();
6433        }
6434    }
6435
6436    else // if name entered
6437    {
6438        name = TargetName;
6439        normalizePlayerName(name);
6440        player = objmgr.GetPlayer(name.c_str()); //get player by name
6441    }
6442
6443    //effect
6444    if (player)
6445    {
6446        PSendSysMessage(LANG_COMMAND_UNFREEZE,name.c_str());
6447
6448        //Reset player faction + allow combat + allow duels
6449        player->setFactionForRace(player->getRace());
6450        player->RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
6451
6452        //allow movement and spells
6453        uint32 spellID = 9454;
6454        player->RemoveAurasDueToSpell(spellID);
6455
6456        //save player
6457        player->SaveToDB();
6458    }
6459
6460    if (!player)
6461    {
6462        if (TargetName)
6463        {       
6464            //check for offline players
6465            QueryResult *result = CharacterDatabase.PQuery("SELECT characters.guid FROM `characters` WHERE characters.name = '%s'",name.c_str());
6466            if(!result)
6467            {
6468                SendSysMessage(LANG_COMMAND_FREEZE_WRONG);
6469                return true;
6470            }
6471            //if player found: delete his freeze aura
6472            Field *fields=result->Fetch();
6473            uint64 pguid = fields[0].GetUInt64();
6474            delete result;
6475            CharacterDatabase.PQuery("DELETE FROM `character_aura` WHERE character_aura.spell = 9454 AND character_aura.guid = '%u'",pguid);
6476            PSendSysMessage(LANG_COMMAND_UNFREEZE,name.c_str());
6477            return true;
6478        }
6479        else
6480        {
6481            SendSysMessage(LANG_COMMAND_FREEZE_WRONG);
6482            return true;
6483        }
6484    }
6485
6486    return true;
6487}
6488
6489bool ChatHandler::HandleListFreezeCommand(const char* args)
6490{
6491    //Get names from DB
6492    QueryResult *result = CharacterDatabase.PQuery("SELECT characters.name FROM `characters` LEFT JOIN `character_aura` ON (characters.guid = character_aura.guid) WHERE character_aura.spell = 9454");
6493    if(!result)
6494    {
6495        SendSysMessage(LANG_COMMAND_NO_FROZEN_PLAYERS);
6496        return true;
6497    }
6498    //Header of the names
6499    PSendSysMessage(LANG_COMMAND_LIST_FREEZE);
6500
6501    //Output of the results
6502    do
6503    {
6504        Field *fields = result->Fetch();
6505        std::string fplayers = fields[0].GetCppString();
6506        PSendSysMessage(LANG_COMMAND_FROZEN_PLAYERS,fplayers.c_str());
6507    } while (result->NextRow());
6508
6509    delete result;
6510    return true;
6511}
6512
6513bool ChatHandler::HandleFlushArenaPointsCommand(const char * /*args*/)
6514{
6515    sBattleGroundMgr.DistributeArenaPoints();
6516    return true;
6517}
6518
6519bool ChatHandler::HandleGroupLeaderCommand(const char* args)
6520{
6521    Player* plr  = NULL;
6522    Group* group = NULL;
6523    uint64 guid  = 0;
6524    char* cname  = strtok((char*)args, " ");
6525
6526    if(GetPlayerGroupAndGUIDByName(cname, plr, group, guid))
6527        if(group && group->GetLeaderGUID() != guid)
6528            group->ChangeLeader(guid);
6529
6530    return true;
6531}
6532
6533bool ChatHandler::HandleGroupDisbandCommand(const char* args)
6534{
6535    Player* plr  = NULL;
6536    Group* group = NULL;
6537    uint64 guid  = 0;
6538    char* cname  = strtok((char*)args, " ");
6539
6540    if(GetPlayerGroupAndGUIDByName(cname, plr, group, guid))
6541        if(group)
6542            group->Disband();
6543
6544    return true;
6545}
6546
6547bool ChatHandler::HandleGroupRemoveCommand(const char* args)
6548{
6549    Player* plr  = NULL;
6550    Group* group = NULL;
6551    uint64 guid  = 0;
6552    char* cname  = strtok((char*)args, " ");
6553
6554    if(GetPlayerGroupAndGUIDByName(cname, plr, group, guid, true))
6555        if(group)
6556            group->RemoveMember(guid, 0);
6557
6558    return true;
6559}
6560
6561bool ChatHandler::HandlePossessCommand(const char* args)
6562{
6563    Unit* pUnit = getSelectedUnit();
6564    if(!pUnit)
6565        return false;
6566
6567    // Don't allow unlimited possession of players
6568    if (pUnit->GetTypeId() == TYPEID_PLAYER)
6569        return false;
6570
6571    m_session->GetPlayer()->Possess(pUnit);
6572
6573    return true;
6574}
6575
6576bool ChatHandler::HandleUnPossessCommand(const char* args)
6577{
6578    // Use this command to also unpossess ourselves
6579    if (m_session->GetPlayer()->isPossessed())
6580        m_session->GetPlayer()->UnpossessSelf(false);
6581    else
6582        m_session->GetPlayer()->RemovePossess(false);
6583
6584    return true;
6585}
Note: See TracBrowser for help on using the browser.