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

Revision 235, 188.8 kB (checked in by yumileroy, 17 years ago)

[svn] * Partly reverted 242 changes. To fix compile error.

Original author: visagalis
Date: 2008-11-15 07:37:41-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        for(int rank = 4; rank >= 0; --rank)
1771        {
1772            if(talentInfo->RankID[rank]!=0)
1773            {
1774                spellid = talentInfo->RankID[rank];
1775                break;
1776            }
1777        }
1778
1779        if(!spellid)                                        // ??? none spells in talent
1780            continue;
1781
1782        SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellid);
1783        if(!spellInfo || !SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer(),false))
1784            continue;
1785
1786        // learn highest rank of talent
1787        player->learnSpell(spellid);
1788
1789        // and learn all non-talent spell ranks (recursive by tree)
1790        learnAllHighRanks(player,spellid);
1791    }
1792
1793    SendSysMessage(LANG_COMMAND_LEARN_CLASS_TALENTS);
1794    return true;
1795}
1796
1797bool ChatHandler::HandleLearnAllLangCommand(const char* /*args*/)
1798{
1799    // skipping UNIVERSAL language (0)
1800    for(int i = 1; i < LANGUAGES_COUNT; ++i)
1801        m_session->GetPlayer()->learnSpell(lang_description[i].spell_id);
1802
1803    SendSysMessage(LANG_COMMAND_LEARN_ALL_LANG);
1804    return true;
1805}
1806
1807bool ChatHandler::HandleLearnAllDefaultCommand(const char* args)
1808{
1809    char* pName = strtok((char*)args, "");
1810    Player *player = NULL;
1811    if (pName)
1812    {
1813        std::string name = pName;
1814
1815        if(!normalizePlayerName(name))
1816        {
1817            SendSysMessage(LANG_PLAYER_NOT_FOUND);
1818            SetSentErrorMessage(true);
1819            return false;
1820        }
1821
1822        player = objmgr.GetPlayer(name.c_str());
1823    }
1824    else
1825        player = getSelectedPlayer();
1826
1827    if(!player)
1828    {
1829        SendSysMessage(LANG_NO_CHAR_SELECTED);
1830        SetSentErrorMessage(true);
1831        return false;
1832    }
1833
1834    player->learnDefaultSpells();
1835    player->learnQuestRewardedSpells();
1836
1837    PSendSysMessage(LANG_COMMAND_LEARN_ALL_DEFAULT_AND_QUEST,player->GetName());
1838    return true;
1839}
1840
1841bool ChatHandler::HandleLearnCommand(const char* args)
1842{
1843    Player* targetPlayer = getSelectedPlayer();
1844
1845    if(!targetPlayer)
1846    {
1847        SendSysMessage(LANG_PLAYER_NOT_FOUND);
1848        SetSentErrorMessage(true);
1849        return false;
1850    }
1851
1852    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
1853    uint32 spell = extractSpellIdFromLink((char*)args);
1854    if(!spell || !sSpellStore.LookupEntry(spell))
1855        return false;
1856
1857    if (targetPlayer->HasSpell(spell))
1858    {
1859        if(targetPlayer == m_session->GetPlayer())
1860            SendSysMessage(LANG_YOU_KNOWN_SPELL);
1861        else
1862            PSendSysMessage(LANG_TARGET_KNOWN_SPELL,targetPlayer->GetName());
1863        SetSentErrorMessage(true);
1864        return false;
1865    }
1866
1867    SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
1868    if(!spellInfo || !SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
1869    {
1870        PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
1871        SetSentErrorMessage(true);
1872        return false;
1873    }
1874
1875    targetPlayer->learnSpell(spell);
1876
1877    return true;
1878}
1879
1880bool ChatHandler::HandleAddItemCommand(const char* args)
1881{
1882    if (!*args)
1883        return false;
1884
1885    uint32 itemId = 0;
1886
1887    if(args[0]=='[')                                        // [name] manual form
1888    {
1889        char* citemName = citemName = strtok((char*)args, "]");
1890
1891        if(citemName && citemName[0])
1892        {
1893            std::string itemName = citemName+1;
1894            WorldDatabase.escape_string(itemName);
1895            QueryResult *result = WorldDatabase.PQuery("SELECT entry FROM item_template WHERE name = '%s'", itemName.c_str());
1896            if (!result)
1897            {
1898                PSendSysMessage(LANG_COMMAND_COULDNOTFIND, citemName+1);
1899                SetSentErrorMessage(true);
1900                return false;
1901            }
1902            itemId = result->Fetch()->GetUInt16();
1903            delete result;
1904        }
1905        else
1906            return false;
1907    }
1908    else                                                    // item_id or [name] Shift-click form |color|Hitem:item_id:0:0:0|h[name]|h|r
1909    {
1910        char* cId = extractKeyFromLink((char*)args,"Hitem");
1911        if(!cId)
1912            return false;
1913        itemId = atol(cId);
1914    }
1915
1916    char* ccount = strtok(NULL, " ");
1917
1918    int32 count = 1;
1919
1920    if (ccount)
1921        count = strtol(ccount, NULL, 10);
1922
1923    if (count == 0)
1924        count = 1;
1925
1926    Player* pl = m_session->GetPlayer();
1927    Player* plTarget = getSelectedPlayer();
1928    if(!plTarget)
1929        plTarget = pl;
1930
1931    sLog.outDetail(GetTrinityString(LANG_ADDITEM), itemId, count);
1932
1933    ItemPrototype const *pProto = objmgr.GetItemPrototype(itemId);
1934    if(!pProto)
1935    {
1936        PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, itemId);
1937        SetSentErrorMessage(true);
1938        return false;
1939    }
1940
1941    //Subtract
1942    if (count < 0)
1943    {
1944        plTarget->DestroyItemCount(itemId, -count, true, false);
1945        PSendSysMessage(LANG_REMOVEITEM, itemId, -count, plTarget->GetName());
1946        return true;
1947    }
1948
1949    //Adding items
1950    uint32 noSpaceForCount = 0;
1951
1952    // check space and find places
1953    ItemPosCountVec dest;
1954    uint8 msg = plTarget->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, count, &noSpaceForCount );
1955    if( msg != EQUIP_ERR_OK )                               // convert to possible store amount
1956        count -= noSpaceForCount;
1957
1958    if( count == 0 || dest.empty())                         // can't add any
1959    {
1960        PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itemId, noSpaceForCount );
1961        SetSentErrorMessage(true);
1962        return false;
1963    }
1964
1965    Item* item = plTarget->StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
1966
1967    // remove binding (let GM give it to another player later)
1968    if(pl==plTarget)
1969        for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
1970            if(Item* item1 = pl->GetItemByPos(itr->pos))
1971                item1->SetBinding( false );
1972
1973    if(count > 0 && item)
1974    {
1975        pl->SendNewItem(item,count,false,true);
1976        if(pl!=plTarget)
1977            plTarget->SendNewItem(item,count,true,false);
1978    }
1979
1980    if(noSpaceForCount > 0)
1981        PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itemId, noSpaceForCount);
1982
1983    return true;
1984}
1985
1986bool ChatHandler::HandleAddItemSetCommand(const char* args)
1987{
1988    if (!*args)
1989        return false;
1990
1991    char* cId = extractKeyFromLink((char*)args,"Hitemset"); // number or [name] Shift-click form |color|Hitemset:itemset_id|h[name]|h|r
1992    if (!cId)
1993        return false;
1994
1995    uint32 itemsetId = atol(cId);
1996
1997    // prevent generation all items with itemset field value '0'
1998    if (itemsetId == 0)
1999    {
2000        PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND,itemsetId);
2001        SetSentErrorMessage(true);
2002        return false;
2003    }
2004
2005    Player* pl = m_session->GetPlayer();
2006    Player* plTarget = getSelectedPlayer();
2007    if(!plTarget)
2008        plTarget = pl;
2009
2010    sLog.outDetail(GetTrinityString(LANG_ADDITEMSET), itemsetId);
2011
2012    bool found = false;
2013    for (uint32 id = 0; id < sItemStorage.MaxEntry; id++)
2014    {
2015        ItemPrototype const *pProto = sItemStorage.LookupEntry<ItemPrototype>(id);
2016        if (!pProto)
2017            continue;
2018
2019        if (pProto->ItemSet == itemsetId)
2020        {
2021            found = true;
2022            ItemPosCountVec dest;
2023            uint8 msg = plTarget->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pProto->ItemId, 1 );
2024            if (msg == EQUIP_ERR_OK)
2025            {
2026                Item* item = plTarget->StoreNewItem( dest, pProto->ItemId, true);
2027
2028                // remove binding (let GM give it to another player later)
2029                if (pl==plTarget)
2030                    item->SetBinding( false );
2031
2032                pl->SendNewItem(item,1,false,true);
2033                if (pl!=plTarget)
2034                    plTarget->SendNewItem(item,1,true,false);
2035            }
2036            else
2037            {
2038                pl->SendEquipError( msg, NULL, NULL );
2039                PSendSysMessage(LANG_ITEM_CANNOT_CREATE, pProto->ItemId, 1);
2040            }
2041        }
2042    }
2043
2044    if (!found)
2045    {
2046        PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND,itemsetId);
2047
2048        SetSentErrorMessage(true);
2049        return false;
2050    }
2051
2052    return true;
2053}
2054
2055bool ChatHandler::HandleListItemCommand(const char* args)
2056{
2057    if(!*args)
2058        return false;
2059
2060    char* cId = extractKeyFromLink((char*)args,"Hitem");
2061    if(!cId)
2062        return false;
2063
2064    uint32 item_id = atol(cId);
2065    if(!item_id)
2066    {
2067        PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id);
2068        SetSentErrorMessage(true);
2069        return false;
2070    }
2071
2072    ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_id);
2073    if(!itemProto)
2074    {
2075        PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id);
2076        SetSentErrorMessage(true);
2077        return false;
2078    }
2079
2080    char* c_count = strtok(NULL, " ");
2081    int count = c_count ? atol(c_count) : 10;
2082
2083    if(count < 0)
2084        return false;
2085
2086    QueryResult *result;
2087
2088    // inventory case
2089    uint32 inv_count = 0;
2090    result=CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM character_inventory WHERE item_template='%u'",item_id);
2091    if(result)
2092    {
2093        inv_count = (*result)[0].GetUInt32();
2094        delete result;
2095    }
2096
2097    result=CharacterDatabase.PQuery(
2098    //          0        1             2             3        4                  5
2099        "SELECT ci.item, cibag.slot AS bag, ci.slot, ci.guid, characters.account,characters.name "
2100        "FROM character_inventory AS ci LEFT JOIN character_inventory AS cibag ON (cibag.item=ci.bag),characters "
2101        "WHERE ci.item_template='%u' AND ci.guid = characters.guid LIMIT %u ",
2102        item_id,uint32(count));
2103
2104    if(result)
2105    {
2106        do
2107        {
2108            Field *fields = result->Fetch();
2109            uint32 item_guid = fields[0].GetUInt32();
2110            uint32 item_bag = fields[1].GetUInt32();
2111            uint32 item_slot = fields[2].GetUInt32();
2112            uint32 owner_guid = fields[3].GetUInt32();
2113            uint32 owner_acc = fields[4].GetUInt32();
2114            std::string owner_name = fields[5].GetCppString();
2115
2116            char const* item_pos = 0;
2117            if(Player::IsEquipmentPos(item_bag,item_slot))
2118                item_pos = "[equipped]";
2119            else if(Player::IsInventoryPos(item_bag,item_slot))
2120                item_pos = "[in inventory]";
2121            else if(Player::IsBankPos(item_bag,item_slot))
2122                item_pos = "[in bank]";
2123            else
2124                item_pos = "";
2125
2126            PSendSysMessage(LANG_ITEMLIST_SLOT,
2127                item_guid,owner_name.c_str(),owner_guid,owner_acc,item_pos);
2128        } while (result->NextRow());
2129
2130        int64 res_count = result->GetRowCount();
2131
2132        delete result;
2133
2134        if(count > res_count)
2135            count-=res_count;
2136        else if(count)
2137            count = 0;
2138    }
2139
2140    // mail case
2141    uint32 mail_count = 0;
2142    result=CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM mail_items WHERE item_template='%u'", item_id);
2143    if(result)
2144    {
2145        mail_count = (*result)[0].GetUInt32();
2146        delete result;
2147    }
2148
2149    if(count > 0)
2150    {
2151        result=CharacterDatabase.PQuery(
2152        //          0                     1            2              3               4            5               6
2153            "SELECT mail_items.item_guid, mail.sender, mail.receiver, char_s.account, char_s.name, char_r.account, char_r.name "
2154            "FROM mail,mail_items,characters as char_s,characters as char_r "
2155            "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",
2156            item_id,uint32(count));
2157    }
2158    else
2159        result = NULL;
2160
2161    if(result)
2162    {
2163        do
2164        {
2165            Field *fields = result->Fetch();
2166            uint32 item_guid        = fields[0].GetUInt32();
2167            uint32 item_s           = fields[1].GetUInt32();
2168            uint32 item_r           = fields[2].GetUInt32();
2169            uint32 item_s_acc       = fields[3].GetUInt32();
2170            std::string item_s_name = fields[4].GetCppString();
2171            uint32 item_r_acc       = fields[5].GetUInt32();
2172            std::string item_r_name = fields[6].GetCppString();
2173
2174            char const* item_pos = "[in mail]";
2175
2176            PSendSysMessage(LANG_ITEMLIST_MAIL,
2177                item_guid,item_s_name.c_str(),item_s,item_s_acc,item_r_name.c_str(),item_r,item_r_acc,item_pos);
2178        } while (result->NextRow());
2179
2180        int64 res_count = result->GetRowCount();
2181
2182        delete result;
2183
2184        if(count > res_count)
2185            count-=res_count;
2186        else if(count)
2187            count = 0;
2188    }
2189
2190    // auction case
2191    uint32 auc_count = 0;
2192    result=CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM auctionhouse WHERE item_template='%u'",item_id);
2193    if(result)
2194    {
2195        auc_count = (*result)[0].GetUInt32();
2196        delete result;
2197    }
2198
2199    if(count > 0)
2200    {
2201        result=CharacterDatabase.PQuery(
2202        //           0                      1                       2                   3
2203            "SELECT  auctionhouse.itemguid, auctionhouse.itemowner, characters.account, characters.name "
2204            "FROM auctionhouse,characters WHERE auctionhouse.item_template='%u' AND characters.guid = auctionhouse.itemowner LIMIT %u",
2205            item_id,uint32(count));
2206    }
2207    else
2208        result = NULL;
2209
2210    if(result)
2211    {
2212        do
2213        {
2214            Field *fields = result->Fetch();
2215            uint32 item_guid       = fields[0].GetUInt32();
2216            uint32 owner           = fields[1].GetUInt32();
2217            uint32 owner_acc       = fields[2].GetUInt32();
2218            std::string owner_name = fields[3].GetCppString();
2219
2220            char const* item_pos = "[in auction]";
2221
2222            PSendSysMessage(LANG_ITEMLIST_AUCTION, item_guid, owner_name.c_str(), owner, owner_acc,item_pos);
2223        } while (result->NextRow());
2224
2225        delete result;
2226    }
2227
2228    // guild bank case
2229    uint32 guild_count = 0;
2230    result=CharacterDatabase.PQuery("SELECT COUNT(item_entry) FROM guild_bank_item WHERE item_entry='%u'",item_id);
2231    if(result)
2232    {
2233        guild_count = (*result)[0].GetUInt32();
2234        delete result;
2235    }
2236
2237    result=CharacterDatabase.PQuery(
2238        //      0             1           2
2239        "SELECT gi.item_guid, gi.guildid, guild.name "
2240        "FROM guild_bank_item AS gi, guild WHERE gi.item_entry='%u' AND gi.guildid = guild.guildid LIMIT %u ",
2241        item_id,uint32(count));
2242
2243    if(result)
2244    {
2245        do
2246        {
2247            Field *fields = result->Fetch();
2248            uint32 item_guid = fields[0].GetUInt32();
2249            uint32 guild_guid = fields[1].GetUInt32();
2250            std::string guild_name = fields[2].GetCppString();
2251
2252            char const* item_pos = "[in guild bank]";
2253
2254            PSendSysMessage(LANG_ITEMLIST_GUILD,item_guid,guild_name.c_str(),guild_guid,item_pos);
2255        } while (result->NextRow());
2256
2257        int64 res_count = result->GetRowCount();
2258
2259        delete result;
2260
2261        if(count > res_count)
2262            count-=res_count;
2263        else if(count)
2264            count = 0;
2265    }
2266
2267    if(inv_count+mail_count+auc_count+guild_count == 0)
2268    {
2269        SendSysMessage(LANG_COMMAND_NOITEMFOUND);
2270        SetSentErrorMessage(true);
2271        return false;
2272    }
2273
2274    PSendSysMessage(LANG_COMMAND_LISTITEMMESSAGE,item_id,inv_count+mail_count+auc_count+guild_count,inv_count,mail_count,auc_count,guild_count);
2275
2276    return true;
2277}
2278
2279bool ChatHandler::HandleListObjectCommand(const char* args)
2280{
2281    if(!*args)
2282        return false;
2283
2284    // number or [name] Shift-click form |color|Hgameobject_entry:go_id|h[name]|h|r
2285    char* cId = extractKeyFromLink((char*)args,"Hgameobject_entry");
2286    if(!cId)
2287        return false;
2288
2289    uint32 go_id = atol(cId);
2290    if(!go_id)
2291    {
2292        PSendSysMessage(LANG_COMMAND_LISTOBJINVALIDID, go_id);
2293        SetSentErrorMessage(true);
2294        return false;
2295    }
2296
2297    GameObjectInfo const * gInfo = objmgr.GetGameObjectInfo(go_id);
2298    if(!gInfo)
2299    {
2300        PSendSysMessage(LANG_COMMAND_LISTOBJINVALIDID, go_id);
2301        SetSentErrorMessage(true);
2302        return false;
2303    }
2304
2305    char* c_count = strtok(NULL, " ");
2306    int count = c_count ? atol(c_count) : 10;
2307
2308    if(count < 0)
2309        return false;
2310
2311    QueryResult *result;
2312
2313    uint32 obj_count = 0;
2314    result=WorldDatabase.PQuery("SELECT COUNT(guid) FROM gameobject WHERE id='%u'",go_id);
2315    if(result)
2316    {
2317        obj_count = (*result)[0].GetUInt32();
2318        delete result;
2319    }
2320
2321    if(m_session)
2322    {
2323        Player* pl = m_session->GetPlayer();
2324        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",
2325            pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(),go_id,uint32(count));
2326    }
2327    else
2328        result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map FROM gameobject WHERE id = '%u' LIMIT %u",
2329            go_id,uint32(count));
2330
2331    if (result)
2332    {
2333        do
2334        {
2335            Field *fields = result->Fetch();
2336            uint32 guid = fields[0].GetUInt32();
2337            float x = fields[1].GetFloat();
2338            float y = fields[2].GetFloat();
2339            float z = fields[3].GetFloat();
2340            int mapid = fields[4].GetUInt16();
2341
2342            if (m_session)
2343                PSendSysMessage(LANG_GO_LIST_CHAT, guid, guid, gInfo->name, x, y, z, mapid);
2344            else
2345                PSendSysMessage(LANG_GO_LIST_CONSOLE, guid, gInfo->name, x, y, z, mapid);
2346        } while (result->NextRow());
2347
2348        delete result;
2349    }
2350
2351    PSendSysMessage(LANG_COMMAND_LISTOBJMESSAGE,go_id,obj_count);
2352    return true;
2353}
2354
2355bool ChatHandler::HandleNearObjectCommand(const char* args)
2356{
2357    float distance = (!*args) ? 10 : atol(args);
2358    uint32 count = 0;
2359
2360    Player* pl = m_session->GetPlayer();
2361    QueryResult *result = WorldDatabase.PQuery("SELECT guid, id, position_x, position_y, position_z, map, "
2362        "(POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ "
2363        "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_",
2364        pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(),
2365        pl->GetMapId(),pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(),distance*distance);
2366
2367    if (result)
2368    {
2369        do
2370        {
2371            Field *fields = result->Fetch();
2372            uint32 guid = fields[0].GetUInt32();
2373            uint32 entry = fields[1].GetUInt32();
2374            float x = fields[2].GetFloat();
2375            float y = fields[3].GetFloat();
2376            float z = fields[4].GetFloat();
2377            int mapid = fields[5].GetUInt16();
2378
2379            GameObjectInfo const * gInfo = objmgr.GetGameObjectInfo(entry);
2380
2381            if(!gInfo)
2382                continue;
2383
2384            PSendSysMessage(LANG_GO_LIST_CHAT, guid, guid, gInfo->name, x, y, z, mapid);
2385
2386            ++count;
2387        } while (result->NextRow());
2388
2389        delete result;
2390    }
2391
2392    PSendSysMessage(LANG_COMMAND_NEAROBJMESSAGE,distance,count);
2393    return true;
2394}
2395
2396bool ChatHandler::HandleObjectStateCommand(const char* args)
2397{
2398    // number or [name] Shift-click form |color|Hgameobject:go_id|h[name]|h|r
2399    char* cId = extractKeyFromLink((char*)args, "Hgameobject");
2400    if(!cId)
2401        return false;
2402
2403    uint32 lowguid = atoi(cId);
2404    if(!lowguid)
2405        return false;
2406
2407    GameObject* gobj = NULL;
2408
2409    if(GameObjectData const* goData = objmgr.GetGOData(lowguid))
2410        gobj = GetObjectGlobalyWithGuidOrNearWithDbGuid(lowguid, goData->id);
2411
2412    if(!gobj)
2413    {
2414        PSendSysMessage(LANG_COMMAND_OBJNOTFOUND, lowguid);
2415        SetSentErrorMessage(true);
2416        return false;
2417    }
2418
2419    char* cstate = strtok(NULL, " ");
2420    if(!cstate)
2421        return false;
2422
2423    int32 state = atoi(cstate);
2424    if(state < 0)
2425        gobj->SendObjectDeSpawnAnim(gobj->GetGUID());
2426    else
2427        gobj->SetGoState(state);
2428
2429    return true;
2430
2431    return true;
2432}
2433
2434bool ChatHandler::HandleListCreatureCommand(const char* args)
2435{
2436    if(!*args)
2437        return false;
2438
2439    // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
2440    char* cId = extractKeyFromLink((char*)args,"Hcreature_entry");
2441    if(!cId)
2442        return false;
2443
2444    uint32 cr_id = atol(cId);
2445    if(!cr_id)
2446    {
2447        PSendSysMessage(LANG_COMMAND_INVALIDCREATUREID, cr_id);
2448        SetSentErrorMessage(true);
2449        return false;
2450    }
2451
2452    CreatureInfo const* cInfo = objmgr.GetCreatureTemplate(cr_id);
2453    if(!cInfo)
2454    {
2455        PSendSysMessage(LANG_COMMAND_INVALIDCREATUREID, cr_id);
2456        SetSentErrorMessage(true);
2457        return false;
2458    }
2459
2460    char* c_count = strtok(NULL, " ");
2461    int count = c_count ? atol(c_count) : 10;
2462
2463    if(count < 0)
2464        return false;
2465
2466    QueryResult *result;
2467
2468    uint32 cr_count = 0;
2469    result=WorldDatabase.PQuery("SELECT COUNT(guid) FROM creature WHERE id='%u'",cr_id);
2470    if(result)
2471    {
2472        cr_count = (*result)[0].GetUInt32();
2473        delete result;
2474    }
2475
2476    if(m_session)
2477    {
2478        Player* pl = m_session->GetPlayer();
2479        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",
2480            pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), cr_id,uint32(count));
2481    }
2482    else
2483        result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map FROM creature WHERE id = '%u' LIMIT %u",
2484            cr_id,uint32(count));
2485
2486    if (result)
2487    {
2488        do
2489        {
2490            Field *fields = result->Fetch();
2491            uint32 guid = fields[0].GetUInt32();
2492            float x = fields[1].GetFloat();
2493            float y = fields[2].GetFloat();
2494            float z = fields[3].GetFloat();
2495            int mapid = fields[4].GetUInt16();
2496
2497            if  (m_session)
2498                PSendSysMessage(LANG_CREATURE_LIST_CHAT, guid, guid, cInfo->Name, x, y, z, mapid);
2499            else
2500                PSendSysMessage(LANG_CREATURE_LIST_CONSOLE, guid, cInfo->Name, x, y, z, mapid);
2501        } while (result->NextRow());
2502
2503        delete result;
2504    }
2505
2506    PSendSysMessage(LANG_COMMAND_LISTCREATUREMESSAGE,cr_id,cr_count);
2507    return true;
2508}
2509
2510bool ChatHandler::HandleLookupItemCommand(const char* args)
2511{
2512    if(!*args)
2513        return false;
2514
2515    std::string namepart = args;
2516    std::wstring wnamepart;
2517
2518    // converting string that we try to find to lower case
2519    if(!Utf8toWStr(namepart,wnamepart))
2520        return false;
2521
2522    wstrToLower(wnamepart);
2523
2524    uint32 counter = 0;
2525
2526    // Search in `item_template`
2527    for (uint32 id = 0; id < sItemStorage.MaxEntry; id++)
2528    {
2529        ItemPrototype const *pProto = sItemStorage.LookupEntry<ItemPrototype >(id);
2530        if(!pProto)
2531            continue;
2532
2533        int loc_idx = m_session ? m_session->GetSessionDbLocaleIndex() : objmgr.GetDBCLocaleIndex();
2534        if ( loc_idx >= 0 )
2535        {
2536            ItemLocale const *il = objmgr.GetItemLocale(pProto->ItemId);
2537            if (il)
2538            {
2539                if (il->Name.size() > loc_idx && !il->Name[loc_idx].empty())
2540                {
2541                    std::string name = il->Name[loc_idx];
2542
2543                    if (Utf8FitTo(name, wnamepart))
2544                    {
2545                        if (m_session)
2546                            PSendSysMessage(LANG_ITEM_LIST_CHAT, id, id, name.c_str());
2547                        else
2548                            PSendSysMessage(LANG_ITEM_LIST_CONSOLE, id, name.c_str());
2549                        ++counter;
2550                        continue;
2551                    }
2552                }
2553            }
2554        }
2555
2556        std::string name = pProto->Name1;
2557        if(name.empty())
2558            continue;
2559
2560        if (Utf8FitTo(name, wnamepart))
2561        {
2562            if (m_session)
2563                PSendSysMessage(LANG_ITEM_LIST_CHAT, id, id, name.c_str());
2564            else
2565                PSendSysMessage(LANG_ITEM_LIST_CONSOLE, id, name.c_str());
2566            ++counter;
2567        }
2568    }
2569
2570    if (counter==0)
2571        SendSysMessage(LANG_COMMAND_NOITEMFOUND);
2572
2573    return true;
2574}
2575
2576bool ChatHandler::HandleLookupItemSetCommand(const char* args)
2577{
2578    if(!*args)
2579        return false;
2580
2581    std::string namepart = args;
2582    std::wstring wnamepart;
2583
2584    if(!Utf8toWStr(namepart,wnamepart))
2585        return false;
2586
2587    // converting string that we try to find to lower case
2588    wstrToLower( wnamepart );
2589
2590    uint32 counter = 0;                                     // Counter for figure out that we found smth.
2591
2592    // Search in ItemSet.dbc
2593    for (uint32 id = 0; id < sItemSetStore.GetNumRows(); id++)
2594    {
2595        ItemSetEntry const *set = sItemSetStore.LookupEntry(id);
2596        if(set)
2597        {
2598            int loc = m_session ? m_session->GetSessionDbcLocale() : sWorld.GetDefaultDbcLocale();
2599            std::string name = set->name[loc];
2600            if(name.empty())
2601                continue;
2602
2603            if (!Utf8FitTo(name, wnamepart))
2604            {
2605                loc = 0;
2606                for(; loc < MAX_LOCALE; ++loc)
2607                {
2608                    if(m_session && loc==m_session->GetSessionDbcLocale())
2609                        continue;
2610
2611                    name = set->name[loc];
2612                    if(name.empty())
2613                        continue;
2614
2615                    if (Utf8FitTo(name, wnamepart))
2616                        break;
2617                }
2618            }
2619
2620            if(loc < MAX_LOCALE)
2621            {
2622                // send item set in "id - [namedlink locale]" format
2623                if (m_session)
2624                    PSendSysMessage(LANG_ITEMSET_LIST_CHAT,id,id,name.c_str(),localeNames[loc]);
2625                else
2626                    PSendSysMessage(LANG_ITEMSET_LIST_CONSOLE,id,name.c_str(),localeNames[loc]);
2627                ++counter;
2628            }
2629        }
2630    }
2631    if (counter == 0)                                       // if counter == 0 then we found nth
2632        SendSysMessage(LANG_COMMAND_NOITEMSETFOUND);
2633    return true;
2634}
2635
2636bool ChatHandler::HandleLookupSkillCommand(const char* args)
2637{
2638    if(!*args)
2639        return false;
2640
2641    // can be NULL in console call
2642    Player* target = getSelectedPlayer();
2643
2644    std::string namepart = args;
2645    std::wstring wnamepart;
2646
2647    if(!Utf8toWStr(namepart,wnamepart))
2648        return false;
2649
2650    // converting string that we try to find to lower case
2651    wstrToLower( wnamepart );
2652
2653    uint32 counter = 0;                                     // Counter for figure out that we found smth.
2654
2655    // Search in SkillLine.dbc
2656    for (uint32 id = 0; id < sSkillLineStore.GetNumRows(); id++)
2657    {
2658        SkillLineEntry const *skillInfo = sSkillLineStore.LookupEntry(id);
2659        if(skillInfo)
2660        {
2661            int loc = m_session ? m_session->GetSessionDbcLocale() : sWorld.GetDefaultDbcLocale();
2662            std::string name = skillInfo->name[loc];
2663            if(name.empty())
2664                continue;
2665
2666            if (!Utf8FitTo(name, wnamepart))
2667            {
2668                loc = 0;
2669                for(; loc < MAX_LOCALE; ++loc)
2670                {
2671                    if(m_session && loc==m_session->GetSessionDbcLocale())
2672                        continue;
2673
2674                    name = skillInfo->name[loc];
2675                    if(name.empty())
2676                        continue;
2677
2678                    if (Utf8FitTo(name, wnamepart))
2679                        break;
2680                }
2681            }
2682
2683            if(loc < MAX_LOCALE)
2684            {
2685                char const* knownStr = "";
2686                if(target && target->HasSkill(id))
2687                    knownStr = GetTrinityString(LANG_KNOWN);
2688
2689                // send skill in "id - [namedlink locale]" format
2690                if (m_session)
2691                    PSendSysMessage(LANG_SKILL_LIST_CHAT,id,id,name.c_str(),localeNames[loc],knownStr);
2692                else
2693                    PSendSysMessage(LANG_SKILL_LIST_CONSOLE,id,name.c_str(),localeNames[loc],knownStr);
2694
2695                ++counter;
2696            }
2697        }
2698    }
2699    if (counter == 0)                                       // if counter == 0 then we found nth
2700        SendSysMessage(LANG_COMMAND_NOSKILLFOUND);
2701    return true;
2702}
2703
2704bool ChatHandler::HandleLookupSpellCommand(const char* args)
2705{
2706    if(!*args)
2707        return false;
2708
2709    // can be NULL at console call
2710    Player* target = getSelectedPlayer();
2711
2712    std::string namepart = args;
2713    std::wstring wnamepart;
2714
2715    if(!Utf8toWStr(namepart,wnamepart))
2716        return false;
2717
2718    // converting string that we try to find to lower case
2719    wstrToLower( wnamepart );
2720
2721    uint32 counter = 0;                                     // Counter for figure out that we found smth.
2722
2723    // Search in Spell.dbc
2724    for (uint32 id = 0; id < sSpellStore.GetNumRows(); id++)
2725    {
2726        SpellEntry const *spellInfo = sSpellStore.LookupEntry(id);
2727        if(spellInfo)
2728        {
2729            int loc = m_session ? m_session->GetSessionDbcLocale() : sWorld.GetDefaultDbcLocale();
2730            std::string name = spellInfo->SpellName[loc];
2731            if(name.empty())
2732                continue;
2733
2734            if (!Utf8FitTo(name, wnamepart))
2735            {
2736                loc = 0;
2737                for(; loc < MAX_LOCALE; ++loc)
2738                {
2739                    if(m_session && loc==m_session->GetSessionDbcLocale())
2740                        continue;
2741
2742                    name = spellInfo->SpellName[loc];
2743                    if(name.empty())
2744                        continue;
2745
2746                    if (Utf8FitTo(name, wnamepart))
2747                        break;
2748                }
2749            }
2750
2751            if(loc < MAX_LOCALE)
2752            {
2753                bool known = target && target->HasSpell(id);
2754                bool learn = (spellInfo->Effect[0] == SPELL_EFFECT_LEARN_SPELL);
2755
2756                uint32 talentCost = GetTalentSpellCost(id);
2757
2758                bool talent = (talentCost > 0);
2759                bool passive = IsPassiveSpell(id);
2760                bool active = target && (target->HasAura(id,0) || target->HasAura(id,1) || target->HasAura(id,2));
2761
2762                // unit32 used to prevent interpreting uint8 as char at output
2763                // find rank of learned spell for learning spell, or talent rank
2764                uint32 rank = talentCost ? talentCost : spellmgr.GetSpellRank(learn ? spellInfo->EffectTriggerSpell[0] : id);
2765
2766                // send spell in "id - [name, rank N] [talent] [passive] [learn] [known]" format
2767                std::ostringstream ss;
2768                if (m_session)
2769                    ss << id << " - |cffffffff|Hspell:" << id << "|h[" << name;
2770                else
2771                    ss << id << " - " << name;
2772
2773                // include rank in link name
2774                if(rank)
2775                    ss << GetTrinityString(LANG_SPELL_RANK) << rank;
2776
2777                if (m_session)
2778                    ss << " " << localeNames[loc] << "]|h|r";
2779                else
2780                    ss << " " << localeNames[loc];
2781
2782                if(talent)
2783                    ss << GetTrinityString(LANG_TALENT);
2784                if(passive)
2785                    ss << GetTrinityString(LANG_PASSIVE);
2786                if(learn)
2787                    ss << GetTrinityString(LANG_LEARN);
2788                if(known)
2789                    ss << GetTrinityString(LANG_KNOWN);
2790                if(active)
2791                    ss << GetTrinityString(LANG_ACTIVE);
2792
2793                SendSysMessage(ss.str().c_str());
2794
2795                ++counter;
2796            }
2797        }
2798    }
2799    if (counter == 0)                                       // if counter == 0 then we found nth
2800        SendSysMessage(LANG_COMMAND_NOSPELLFOUND);
2801    return true;
2802}
2803
2804bool ChatHandler::HandleLookupQuestCommand(const char* args)
2805{
2806    if(!*args)
2807        return false;
2808
2809    // can be NULL at console call
2810    Player* target = getSelectedPlayer();
2811
2812    std::string namepart = args;
2813    std::wstring wnamepart;
2814
2815    // converting string that we try to find to lower case
2816    if(!Utf8toWStr(namepart,wnamepart))
2817        return false;
2818
2819    wstrToLower(wnamepart);
2820
2821    uint32 counter = 0 ;
2822
2823    ObjectMgr::QuestMap const& qTemplates = objmgr.GetQuestTemplates();
2824    for (ObjectMgr::QuestMap::const_iterator iter = qTemplates.begin(); iter != qTemplates.end(); ++iter)
2825    {
2826        Quest * qinfo = iter->second;
2827
2828        int loc_idx = m_session ? m_session->GetSessionDbLocaleIndex() : objmgr.GetDBCLocaleIndex();
2829        if ( loc_idx >= 0 )
2830        {
2831            QuestLocale const *il = objmgr.GetQuestLocale(qinfo->GetQuestId());
2832            if (il)
2833            {
2834                if (il->Title.size() > loc_idx && !il->Title[loc_idx].empty())
2835                {
2836                    std::string title = il->Title[loc_idx];
2837
2838                    if (Utf8FitTo(title, wnamepart))
2839                    {
2840                        char const* statusStr = "";
2841
2842                        if(target)
2843                        {
2844                            QuestStatus status = target->GetQuestStatus(qinfo->GetQuestId());
2845
2846                            if(status == QUEST_STATUS_COMPLETE)
2847                            {
2848                                if(target->GetQuestRewardStatus(qinfo->GetQuestId()))
2849                                    statusStr = GetTrinityString(LANG_COMMAND_QUEST_REWARDED);
2850                                else
2851                                    statusStr = GetTrinityString(LANG_COMMAND_QUEST_COMPLETE);
2852                            }
2853                            else if(status == QUEST_STATUS_INCOMPLETE)
2854                                statusStr = GetTrinityString(LANG_COMMAND_QUEST_ACTIVE);
2855                        }
2856
2857                        if (m_session)
2858                            PSendSysMessage(LANG_QUEST_LIST_CHAT,qinfo->GetQuestId(),qinfo->GetQuestId(),title.c_str(),statusStr);
2859                        else
2860                            PSendSysMessage(LANG_QUEST_LIST_CONSOLE,qinfo->GetQuestId(),title.c_str(),statusStr);
2861                        ++counter;
2862                        continue;
2863                    }
2864                }
2865            }
2866        }
2867
2868        std::string title = qinfo->GetTitle();
2869        if(title.empty())
2870            continue;
2871
2872        if (Utf8FitTo(title, wnamepart))
2873        {
2874            char const* statusStr = "";
2875
2876            if(target)
2877            {
2878                QuestStatus status = target->GetQuestStatus(qinfo->GetQuestId());
2879
2880                if(status == QUEST_STATUS_COMPLETE)
2881                {
2882                    if(target->GetQuestRewardStatus(qinfo->GetQuestId()))
2883                        statusStr = GetTrinityString(LANG_COMMAND_QUEST_REWARDED);
2884                    else
2885                        statusStr = GetTrinityString(LANG_COMMAND_QUEST_COMPLETE);
2886                }
2887                else if(status == QUEST_STATUS_INCOMPLETE)
2888                    statusStr = GetTrinityString(LANG_COMMAND_QUEST_ACTIVE);
2889            }
2890
2891            if (m_session)
2892                PSendSysMessage(LANG_QUEST_LIST_CHAT,qinfo->GetQuestId(),qinfo->GetQuestId(),title.c_str(),statusStr);
2893            else
2894                PSendSysMessage(LANG_QUEST_LIST_CONSOLE,qinfo->GetQuestId(),title.c_str(),statusStr);
2895
2896            ++counter;
2897        }
2898    }
2899
2900    if (counter==0)
2901        SendSysMessage(LANG_COMMAND_NOQUESTFOUND);
2902
2903    return true;
2904}
2905
2906bool ChatHandler::HandleLookupCreatureCommand(const char* args)
2907{
2908    if (!*args)
2909        return false;
2910
2911    std::string namepart = args;
2912    std::wstring wnamepart;
2913
2914    // converting string that we try to find to lower case
2915    if (!Utf8toWStr (namepart,wnamepart))
2916        return false;
2917
2918    wstrToLower (wnamepart);
2919
2920    uint32 counter = 0;
2921
2922    for (uint32 id = 0; id< sCreatureStorage.MaxEntry; ++id)
2923    {
2924        CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo> (id);
2925        if(!cInfo)
2926            continue;
2927
2928        int loc_idx = m_session ? m_session->GetSessionDbLocaleIndex() : objmgr.GetDBCLocaleIndex();
2929        if (loc_idx >= 0)
2930        {
2931            CreatureLocale const *cl = objmgr.GetCreatureLocale (id);
2932            if (cl)
2933            {
2934                if (cl->Name.size() > loc_idx && !cl->Name[loc_idx].empty ())
2935                {
2936                    std::string name = cl->Name[loc_idx];
2937
2938                    if (Utf8FitTo (name, wnamepart))
2939                    {
2940                        if (m_session)
2941                            PSendSysMessage (LANG_CREATURE_ENTRY_LIST_CHAT, id, id, name.c_str ());
2942                        else
2943                            PSendSysMessage (LANG_CREATURE_ENTRY_LIST_CONSOLE, id, name.c_str ());
2944                        ++counter;
2945                        continue;
2946                    }
2947                }
2948            }
2949        }
2950
2951        std::string name = cInfo->Name;
2952        if (name.empty ())
2953            continue;
2954
2955        if (Utf8FitTo(name, wnamepart))
2956        {
2957            if (m_session)
2958                PSendSysMessage (LANG_CREATURE_ENTRY_LIST_CHAT, id, id, name.c_str ());
2959            else
2960                PSendSysMessage (LANG_CREATURE_ENTRY_LIST_CONSOLE, id, name.c_str ());
2961            ++counter;
2962        }
2963    }
2964
2965    if (counter==0)
2966        SendSysMessage (LANG_COMMAND_NOCREATUREFOUND);
2967
2968    return true;
2969}
2970
2971bool ChatHandler::HandleLookupObjectCommand(const char* args)
2972{
2973    if(!*args)
2974        return false;
2975
2976    std::string namepart = args;
2977    std::wstring wnamepart;
2978
2979    // converting string that we try to find to lower case
2980    if(!Utf8toWStr(namepart,wnamepart))
2981        return false;
2982
2983    wstrToLower(wnamepart);
2984
2985    uint32 counter = 0;
2986
2987    for (uint32 id = 0; id< sGOStorage.MaxEntry; id++ )
2988    {
2989        GameObjectInfo const* gInfo = sGOStorage.LookupEntry<GameObjectInfo>(id);
2990        if(!gInfo)
2991            continue;
2992
2993        int loc_idx = m_session ? m_session->GetSessionDbLocaleIndex() : objmgr.GetDBCLocaleIndex();
2994        if ( loc_idx >= 0 )
2995        {
2996            GameObjectLocale const *gl = objmgr.GetGameObjectLocale(id);
2997            if (gl)
2998            {
2999                if (gl->Name.size() > loc_idx && !gl->Name[loc_idx].empty())
3000                {
3001                    std::string name = gl->Name[loc_idx];
3002
3003                    if (Utf8FitTo(name, wnamepart))
3004                    {
3005                        if (m_session)
3006                            PSendSysMessage(LANG_GO_ENTRY_LIST_CHAT, id, id, name.c_str());
3007                        else
3008                            PSendSysMessage(LANG_GO_ENTRY_LIST_CONSOLE, id, name.c_str());
3009                        ++counter;
3010                        continue;
3011                    }
3012                }
3013            }
3014        }
3015
3016        std::string name = gInfo->name;
3017        if(name.empty())
3018            continue;
3019
3020        if(Utf8FitTo(name, wnamepart))
3021        {
3022            if (m_session)
3023                PSendSysMessage(LANG_GO_ENTRY_LIST_CHAT, id, id, name.c_str());
3024            else
3025                PSendSysMessage(LANG_GO_ENTRY_LIST_CONSOLE, id, name.c_str());
3026            ++counter;
3027        }
3028    }
3029
3030    if(counter==0)
3031        SendSysMessage(LANG_COMMAND_NOGAMEOBJECTFOUND);
3032
3033    return true;
3034}
3035
3036/** \brief GM command level 3 - Create a guild.
3037 *
3038 * This command allows a GM (level 3) to create a guild.
3039 *
3040 * The "args" parameter contains the name of the guild leader
3041 * and then the name of the guild.
3042 *
3043 */
3044bool ChatHandler::HandleGuildCreateCommand(const char* args)
3045{
3046
3047    if (!*args)
3048        return false;
3049
3050    char *lname = strtok ((char*)args, " ");
3051    char *gname = strtok (NULL, "");
3052
3053    if (!lname)
3054        return false;
3055
3056    if (!gname)
3057    {
3058        SendSysMessage (LANG_INSERT_GUILD_NAME);
3059        SetSentErrorMessage (true);
3060        return false;
3061    }
3062
3063    std::string guildname = gname;
3064
3065    Player* player = ObjectAccessor::Instance ().FindPlayerByName (lname);
3066    if (!player)
3067    {
3068        SendSysMessage (LANG_PLAYER_NOT_FOUND);
3069        SetSentErrorMessage (true);
3070        return false;
3071    }
3072
3073    if (player->GetGuildId())
3074    {
3075        SendSysMessage (LANG_PLAYER_IN_GUILD);
3076        return true;
3077    }
3078
3079    Guild *guild = new Guild;
3080    if (!guild->create (player->GetGUID (),guildname))
3081    {
3082        delete guild;
3083        SendSysMessage (LANG_GUILD_NOT_CREATED);
3084        SetSentErrorMessage (true);
3085        return false;
3086    }
3087
3088    objmgr.AddGuild (guild);
3089    return true;
3090}
3091
3092bool ChatHandler::HandleGuildInviteCommand(const char *args)
3093{
3094    if (!*args)
3095        return false;
3096
3097    char* par1 = strtok ((char*)args, " ");
3098    char* par2 = strtok (NULL, "");
3099    if(!par1 || !par2)
3100        return false;
3101
3102    std::string glName = par2;
3103    Guild* targetGuild = objmgr.GetGuildByName (glName);
3104    if (!targetGuild)
3105        return false;
3106
3107    std::string plName = par1;
3108    if (!normalizePlayerName (plName))
3109    {
3110        SendSysMessage (LANG_PLAYER_NOT_FOUND);
3111        SetSentErrorMessage (true);
3112        return false;
3113    }
3114
3115    uint64 plGuid = 0;
3116    if (Player* targetPlayer = ObjectAccessor::Instance ().FindPlayerByName (plName.c_str ()))
3117        plGuid = targetPlayer->GetGUID ();
3118    else
3119        plGuid = objmgr.GetPlayerGUIDByName (plName.c_str ());
3120
3121    if (!plGuid)
3122        false;
3123
3124    // player's guild membership checked in AddMember before add
3125    if (!targetGuild->AddMember (plGuid,targetGuild->GetLowestRank ()))
3126        return false;
3127
3128    return true;
3129}
3130
3131bool ChatHandler::HandleGuildUninviteCommand(const char *args)
3132{
3133    if (!*args)
3134        return false;
3135
3136    char* par1 = strtok ((char*)args, " ");
3137    if(!par1)
3138        return false;
3139
3140    std::string plName = par1;
3141    if (!normalizePlayerName (plName))
3142    {
3143        SendSysMessage (LANG_PLAYER_NOT_FOUND);
3144        SetSentErrorMessage (true);
3145        return false;
3146    }
3147
3148    uint64 plGuid = 0;
3149    uint32 glId   = 0;
3150    if (Player* targetPlayer = ObjectAccessor::Instance ().FindPlayerByName (plName.c_str ()))
3151    {
3152        plGuid = targetPlayer->GetGUID ();
3153        glId   = targetPlayer->GetGuildId ();
3154    }
3155    else
3156    {
3157        plGuid = objmgr.GetPlayerGUIDByName (plName.c_str ());
3158        glId = Player::GetGuildIdFromDB (plGuid);
3159    }
3160
3161    if (!plGuid || !glId)
3162        return false;
3163
3164    Guild* targetGuild = objmgr.GetGuildById (glId);
3165    if (!targetGuild)
3166        return false;
3167
3168    targetGuild->DelMember (plGuid);
3169
3170    return true;
3171}
3172
3173bool ChatHandler::HandleGuildRankCommand(const char *args)
3174{
3175    if (!*args)
3176        return false;
3177
3178    char* par1 = strtok ((char*)args, " ");
3179    char* par2 = strtok (NULL, " ");
3180    if (!par1 || !par2)
3181        return false;
3182    std::string plName = par1;
3183    if (!normalizePlayerName (plName))
3184    {
3185        SendSysMessage (LANG_PLAYER_NOT_FOUND);
3186        SetSentErrorMessage (true);
3187        return false;
3188    }
3189
3190    uint64 plGuid = 0;
3191    uint32 glId   = 0;
3192    if (Player* targetPlayer = ObjectAccessor::Instance ().FindPlayerByName (plName.c_str ()))
3193    {
3194        plGuid = targetPlayer->GetGUID ();
3195        glId   = targetPlayer->GetGuildId ();
3196    }
3197    else
3198    {
3199        plGuid = objmgr.GetPlayerGUIDByName (plName.c_str ());
3200        glId = Player::GetGuildIdFromDB (plGuid);
3201    }
3202
3203    if (!plGuid || !glId)
3204        return false;
3205
3206    Guild* targetGuild = objmgr.GetGuildById (glId);
3207    if (!targetGuild)
3208        return false;
3209
3210    uint32 newrank = uint32 (atoi (par2));
3211    if (newrank > targetGuild->GetLowestRank ())
3212        return false;
3213
3214    targetGuild->ChangeRank (plGuid,newrank);
3215
3216    return true;
3217}
3218
3219bool ChatHandler::HandleGuildDeleteCommand(const char* args)
3220{
3221    if (!*args)
3222        return false;
3223
3224    char* par1 = strtok ((char*)args, " ");
3225    if (!par1)
3226        return false;
3227
3228    std::string gld = par1;
3229
3230    Guild* targetGuild = objmgr.GetGuildByName (gld);
3231    if (!targetGuild)
3232        return false;
3233
3234    targetGuild->Disband ();
3235
3236    return true;
3237}
3238
3239bool ChatHandler::HandleGetDistanceCommand(const char* /*args*/)
3240{
3241    Unit* pUnit = getSelectedUnit();
3242
3243    if(!pUnit)
3244    {
3245        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3246        SetSentErrorMessage(true);
3247        return false;
3248    }
3249
3250    PSendSysMessage(LANG_DISTANCE, m_session->GetPlayer()->GetDistance(pUnit),m_session->GetPlayer()->GetDistance2d(pUnit));
3251
3252    return true;
3253}
3254
3255// FIX-ME!!!
3256
3257bool ChatHandler::HandleAddWeaponCommand(const char* /*args*/)
3258{
3259    /*if (!*args)
3260        return false;
3261
3262    uint64 guid = m_session->GetPlayer()->GetSelection();
3263    if (guid == 0)
3264    {
3265        SendSysMessage(LANG_NO_SELECTION);
3266        return true;
3267    }
3268
3269    Creature *pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), guid);
3270
3271    if(!pCreature)
3272    {
3273        SendSysMessage(LANG_SELECT_CREATURE);
3274        return true;
3275    }
3276
3277    char* pSlotID = strtok((char*)args, " ");
3278    if (!pSlotID)
3279        return false;
3280
3281    char* pItemID = strtok(NULL, " ");
3282    if (!pItemID)
3283        return false;
3284
3285    uint32 ItemID = atoi(pItemID);
3286    uint32 SlotID = atoi(pSlotID);
3287
3288    ItemPrototype* tmpItem = objmgr.GetItemPrototype(ItemID);
3289
3290    bool added = false;
3291    if(tmpItem)
3292    {
3293        switch(SlotID)
3294        {
3295            case 1:
3296                pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY, ItemID);
3297                added = true;
3298                break;
3299            case 2:
3300                pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_01, ItemID);
3301                added = true;
3302                break;
3303            case 3:
3304                pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_02, ItemID);
3305                added = true;
3306                break;
3307            default:
3308                PSendSysMessage(LANG_ITEM_SLOT_NOT_EXIST,SlotID);
3309                added = false;
3310                break;
3311        }
3312        if(added)
3313        {
3314            PSendSysMessage(LANG_ITEM_ADDED_TO_SLOT,ItemID,tmpItem->Name1,SlotID);
3315        }
3316    }
3317    else
3318    {
3319        PSendSysMessage(LANG_ITEM_NOT_FOUND,ItemID);
3320        return true;
3321    }
3322    */
3323    return true;
3324}
3325
3326bool ChatHandler::HandleDieCommand(const char* /*args*/)
3327{
3328    Unit* target = getSelectedUnit();
3329
3330    if(!target || !m_session->GetPlayer()->GetSelection())
3331    {
3332        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3333        SetSentErrorMessage(true);
3334        return false;
3335    }
3336
3337    if( target->isAlive() )
3338    {
3339        m_session->GetPlayer()->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
3340    }
3341
3342    return true;
3343}
3344
3345bool ChatHandler::HandleDamageCommand(const char * args)
3346{
3347    if (!*args)
3348        return false;
3349
3350    Unit* target = getSelectedUnit();
3351
3352    if(!target || !m_session->GetPlayer()->GetSelection())
3353    {
3354        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3355        SetSentErrorMessage(true);
3356        return false;
3357    }
3358
3359    if( !target->isAlive() )
3360        return true;
3361
3362    char* damageStr = strtok((char*)args, " ");
3363    if(!damageStr)
3364        return false;
3365
3366    int32 damage = atoi((char*)damageStr);
3367    if(damage <=0)
3368        return true;
3369
3370    char* schoolStr = strtok((char*)NULL, " ");
3371
3372    // flat melee damage without resistence/etc reduction
3373    if(!schoolStr)
3374    {
3375        m_session->GetPlayer()->DealDamage(target, damage, NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
3376        m_session->GetPlayer()->SendAttackStateUpdate (HITINFO_NORMALSWING2, target, 1, SPELL_SCHOOL_MASK_NORMAL, damage, 0, 0, VICTIMSTATE_NORMAL, 0);
3377        return true;
3378    }
3379
3380    uint32 school = schoolStr ? atoi((char*)schoolStr) : SPELL_SCHOOL_NORMAL;
3381    if(school >= MAX_SPELL_SCHOOL)
3382        return false;
3383
3384    SpellSchoolMask schoolmask = SpellSchoolMask(1 << school);
3385
3386    if ( schoolmask & SPELL_SCHOOL_MASK_NORMAL )
3387        damage = m_session->GetPlayer()->CalcArmorReducedDamage(target, damage);
3388
3389    char* spellStr = strtok((char*)NULL, " ");
3390
3391    // melee damage by specific school
3392    if(!spellStr)
3393    {
3394        uint32 absorb = 0;
3395        uint32 resist = 0;
3396
3397        m_session->GetPlayer()->CalcAbsorbResist(target,schoolmask, SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
3398
3399        if (damage <= absorb + resist)
3400            return true;
3401
3402        damage -= absorb + resist;
3403
3404        m_session->GetPlayer()->DealDamage(target, damage, NULL, DIRECT_DAMAGE, schoolmask, NULL, false);
3405        m_session->GetPlayer()->SendAttackStateUpdate (HITINFO_NORMALSWING2, target, 1, schoolmask, damage, absorb, resist, VICTIMSTATE_NORMAL, 0);
3406        return true;
3407    }
3408
3409    // non-melee damage
3410
3411    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
3412    uint32 spellid = extractSpellIdFromLink((char*)args);
3413    if(!spellid || !sSpellStore.LookupEntry(spellid))
3414        return false;
3415
3416    m_session->GetPlayer()->SpellNonMeleeDamageLog(target, spellid, damage, false);
3417    return true;
3418}
3419
3420bool ChatHandler::HandleModifyArenaCommand(const char * args)
3421{
3422    if (!*args)
3423        return false;
3424
3425    Player *target = getSelectedPlayer();
3426    if(!target)
3427    {
3428        SendSysMessage(LANG_PLAYER_NOT_FOUND);
3429        SetSentErrorMessage(true);
3430        return false;
3431    }
3432
3433    int32 amount = (uint32)atoi(args);
3434
3435    target->ModifyArenaPoints(amount);
3436
3437    PSendSysMessage(LANG_COMMAND_MODIFY_ARENA, target->GetName(), target->GetArenaPoints());
3438
3439    return true;
3440}
3441
3442bool ChatHandler::HandleReviveCommand(const char* args)
3443{
3444    Player* SelectedPlayer = NULL;
3445
3446    if (*args)
3447    {
3448        std::string name = args;
3449        if(!normalizePlayerName(name))
3450        {
3451            SendSysMessage(LANG_PLAYER_NOT_FOUND);
3452            SetSentErrorMessage(true);
3453            return false;
3454        }
3455
3456        SelectedPlayer = objmgr.GetPlayer(name.c_str());
3457    }
3458    else
3459        SelectedPlayer = getSelectedPlayer();
3460
3461    if(!SelectedPlayer)
3462    {
3463        SendSysMessage(LANG_NO_CHAR_SELECTED);
3464        SetSentErrorMessage(true);
3465        return false;
3466    }
3467
3468    SelectedPlayer->ResurrectPlayer(0.5f);
3469    SelectedPlayer->SpawnCorpseBones();
3470    SelectedPlayer->SaveToDB();
3471    return true;
3472}
3473
3474bool ChatHandler::HandleAuraCommand(const char* args)
3475{
3476    char* px = strtok((char*)args, " ");
3477    if (!px)
3478        return false;
3479
3480    Unit *target = getSelectedUnit();
3481    if(!target)
3482    {
3483        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3484        SetSentErrorMessage(true);
3485        return false;
3486    }
3487
3488    uint32 spellID = (uint32)atoi(px);
3489    SpellEntry const *spellInfo = sSpellStore.LookupEntry( spellID );
3490    if(spellInfo)
3491    {
3492        for(uint32 i = 0;i<3;i++)
3493        {
3494            uint8 eff = spellInfo->Effect[i];
3495            if (eff>=TOTAL_SPELL_EFFECTS)
3496                continue;
3497            if( IsAreaAuraEffect(eff)           ||
3498                eff == SPELL_EFFECT_APPLY_AURA  ||
3499                eff == SPELL_EFFECT_PERSISTENT_AREA_AURA )
3500            {
3501                Aura *Aur = CreateAura(spellInfo, i, NULL, target);
3502                target->AddAura(Aur);
3503            }
3504        }
3505    }
3506
3507    return true;
3508}
3509
3510bool ChatHandler::HandleUnAuraCommand(const char* args)
3511{
3512    char* px = strtok((char*)args, " ");
3513    if (!px)
3514        return false;
3515
3516    Unit *target = getSelectedUnit();
3517    if(!target)
3518    {
3519        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3520        SetSentErrorMessage(true);
3521        return false;
3522    }
3523
3524    std::string argstr = args;
3525    if (argstr == "all")
3526    {
3527        target->RemoveAllAuras();
3528        return true;
3529    }
3530
3531    uint32 spellID = (uint32)atoi(px);
3532    target->RemoveAurasDueToSpell(spellID);
3533
3534    return true;
3535}
3536
3537bool ChatHandler::HandleLinkGraveCommand(const char* args)
3538{
3539    if(!*args)
3540        return false;
3541
3542    char* px = strtok((char*)args, " ");
3543    if (!px)
3544        return false;
3545
3546    uint32 g_id = (uint32)atoi(px);
3547
3548    uint32 g_team;
3549
3550    char* px2 = strtok(NULL, " ");
3551
3552    if (!px2)
3553        g_team = 0;
3554    else if (strncmp(px2,"horde",6)==0)
3555        g_team = HORDE;
3556    else if (strncmp(px2,"alliance",9)==0)
3557        g_team = ALLIANCE;
3558    else
3559        return false;
3560
3561    WorldSafeLocsEntry const* graveyard =  sWorldSafeLocsStore.LookupEntry(g_id);
3562
3563    if(!graveyard )
3564    {
3565        PSendSysMessage(LANG_COMMAND_GRAVEYARDNOEXIST, g_id);
3566        SetSentErrorMessage(true);
3567        return false;
3568    }
3569
3570    Player* player = m_session->GetPlayer();
3571
3572    uint32 zoneId = player->GetZoneId();
3573
3574    AreaTableEntry const *areaEntry = GetAreaEntryByAreaID(zoneId);
3575    if(!areaEntry || areaEntry->zone !=0 )
3576    {
3577        PSendSysMessage(LANG_COMMAND_GRAVEYARDWRONGZONE, g_id,zoneId);
3578        SetSentErrorMessage(true);
3579        return false;
3580    }
3581
3582    if(objmgr.AddGraveYardLink(g_id,player->GetZoneId(),g_team))
3583        PSendSysMessage(LANG_COMMAND_GRAVEYARDLINKED, g_id,zoneId);
3584    else
3585        PSendSysMessage(LANG_COMMAND_GRAVEYARDALRLINKED, g_id,zoneId);
3586
3587    return true;
3588}
3589
3590bool ChatHandler::HandleNearGraveCommand(const char* args)
3591{
3592    uint32 g_team;
3593
3594    size_t argslen = strlen(args);
3595
3596    if(!*args)
3597        g_team = 0;
3598    else if (strncmp((char*)args,"horde",argslen)==0)
3599        g_team = HORDE;
3600    else if (strncmp((char*)args,"alliance",argslen)==0)
3601        g_team = ALLIANCE;
3602    else
3603        return false;
3604
3605    Player* player = m_session->GetPlayer();
3606
3607    WorldSafeLocsEntry const* graveyard = objmgr.GetClosestGraveYard(
3608        player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(),player->GetMapId(),g_team);
3609
3610    if(graveyard)
3611    {
3612        uint32 g_id = graveyard->ID;
3613
3614        GraveYardData const* data = objmgr.FindGraveYardData(g_id,player->GetZoneId());
3615        if (!data)
3616        {
3617            PSendSysMessage(LANG_COMMAND_GRAVEYARDERROR,g_id);
3618            SetSentErrorMessage(true);
3619            return false;
3620        }
3621
3622        g_team = data->team;
3623
3624        std::string team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_NOTEAM);
3625
3626        if(g_team == 0)
3627            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_ANY);
3628        else if(g_team == HORDE)
3629            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_HORDE);
3630        else if(g_team == ALLIANCE)
3631            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_ALLIANCE);
3632
3633        PSendSysMessage(LANG_COMMAND_GRAVEYARDNEAREST, g_id,team_name.c_str(),player->GetZoneId());
3634    }
3635    else
3636    {
3637        std::string team_name;
3638
3639        if(g_team == 0)
3640            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_ANY);
3641        else if(g_team == HORDE)
3642            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_HORDE);
3643        else if(g_team == ALLIANCE)
3644            team_name = GetTrinityString(LANG_COMMAND_GRAVEYARD_ALLIANCE);
3645
3646        if(g_team == ~uint32(0))
3647            PSendSysMessage(LANG_COMMAND_ZONENOGRAVEYARDS, player->GetZoneId());
3648        else
3649            PSendSysMessage(LANG_COMMAND_ZONENOGRAFACTION, player->GetZoneId(),team_name.c_str());
3650    }
3651
3652    return true;
3653}
3654
3655//play npc emote
3656bool ChatHandler::HandleNpcPlayEmoteCommand(const char* args)
3657{
3658    uint32 emote = atoi((char*)args);
3659
3660    Creature* target = getSelectedCreature();
3661    if(!target)
3662    {
3663        SendSysMessage(LANG_SELECT_CREATURE);
3664        SetSentErrorMessage(true);
3665        return false;
3666    }
3667
3668    target->SetUInt32Value(UNIT_NPC_EMOTESTATE,emote);
3669
3670    return true;
3671}
3672
3673bool ChatHandler::HandleNpcInfoCommand(const char* /*args*/)
3674{
3675    Creature* target = getSelectedCreature();
3676
3677    if(!target)
3678    {
3679        SendSysMessage(LANG_SELECT_CREATURE);
3680        SetSentErrorMessage(true);
3681        return false;
3682    }
3683
3684    uint32 faction = target->getFaction();
3685    uint32 npcflags = target->GetUInt32Value(UNIT_NPC_FLAGS);
3686    uint32 displayid = target->GetDisplayId();
3687    uint32 nativeid = target->GetNativeDisplayId();
3688    uint32 Entry = target->GetEntry();
3689    CreatureInfo const* cInfo = target->GetCreatureInfo();
3690
3691    int32 curRespawnDelay = target->GetRespawnTimeEx()-time(NULL);
3692    if(curRespawnDelay < 0)
3693        curRespawnDelay = 0;
3694    std::string curRespawnDelayStr = secsToTimeString(curRespawnDelay,true);
3695    std::string defRespawnDelayStr = secsToTimeString(target->GetRespawnDelay(),true);
3696
3697    PSendSysMessage(LANG_NPCINFO_CHAR,  target->GetDBTableGUIDLow(), faction, npcflags, Entry, displayid, nativeid);
3698    PSendSysMessage(LANG_NPCINFO_LEVEL, target->getLevel());
3699    PSendSysMessage(LANG_NPCINFO_HEALTH,target->GetCreateHealth(), target->GetMaxHealth(), target->GetHealth());
3700    PSendSysMessage(LANG_NPCINFO_FLAGS, target->GetUInt32Value(UNIT_FIELD_FLAGS), target->GetUInt32Value(UNIT_DYNAMIC_FLAGS), target->getFaction());
3701    PSendSysMessage(LANG_COMMAND_RAWPAWNTIMES, defRespawnDelayStr.c_str(),curRespawnDelayStr.c_str());
3702    PSendSysMessage(LANG_NPCINFO_LOOT,  cInfo->lootid,cInfo->pickpocketLootId,cInfo->SkinLootId);
3703    PSendSysMessage(LANG_NPCINFO_DUNGEON_ID, target->GetInstanceId());
3704    PSendSysMessage(LANG_NPCINFO_POSITION,float(target->GetPositionX()), float(target->GetPositionY()), float(target->GetPositionZ()));
3705
3706    if ((npcflags & UNIT_NPC_FLAG_VENDOR) )
3707    {
3708        SendSysMessage(LANG_NPCINFO_VENDOR);
3709    }
3710    if ((npcflags & UNIT_NPC_FLAG_TRAINER) )
3711    {
3712        SendSysMessage(LANG_NPCINFO_TRAINER);
3713    }
3714
3715    return true;
3716}
3717
3718bool ChatHandler::HandleExploreCheatCommand(const char* args)
3719{
3720    if (!*args)
3721        return false;
3722
3723    int flag = atoi((char*)args);
3724
3725    Player *chr = getSelectedPlayer();
3726    if (chr == NULL)
3727    {
3728        SendSysMessage(LANG_NO_CHAR_SELECTED);
3729        SetSentErrorMessage(true);
3730        return false;
3731    }
3732
3733    if (flag != 0)
3734    {
3735        PSendSysMessage(LANG_YOU_SET_EXPLORE_ALL, chr->GetName());
3736        if (needReportToTarget(chr))
3737            ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_ALL,GetName());
3738    }
3739    else
3740    {
3741        PSendSysMessage(LANG_YOU_SET_EXPLORE_NOTHING, chr->GetName());
3742        if (needReportToTarget(chr))
3743            ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_NOTHING,GetName());
3744    }
3745
3746    for (uint8 i=0; i<128; i++)
3747    {
3748        if (flag != 0)
3749        {
3750            m_session->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1+i,0xFFFFFFFF);
3751        }
3752        else
3753        {
3754            m_session->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1+i,0);
3755        }
3756    }
3757
3758    return true;
3759}
3760
3761bool ChatHandler::HandleHoverCommand(const char* args)
3762{
3763    char* px = strtok((char*)args, " ");
3764    uint32 flag;
3765    if (!px)
3766        flag = 1;
3767    else
3768        flag = atoi(px);
3769
3770    m_session->GetPlayer()->SetHover(flag);
3771
3772    if (flag)
3773        SendSysMessage(LANG_HOVER_ENABLED);
3774    else
3775        SendSysMessage(LANG_HOVER_DISABLED);
3776
3777    return true;
3778}
3779
3780bool ChatHandler::HandleWaterwalkCommand(const char* args)
3781{
3782    if(!args)
3783        return false;
3784
3785    Player *player = getSelectedPlayer();
3786    if(!player)
3787    {
3788        PSendSysMessage(LANG_NO_CHAR_SELECTED);
3789        SetSentErrorMessage(true);
3790        return false;
3791    }
3792
3793    if (strncmp(args, "on", 3) == 0)
3794        player->SetMovement(MOVE_WATER_WALK);               // ON
3795    else if (strncmp(args, "off", 4) == 0)
3796        player->SetMovement(MOVE_LAND_WALK);                // OFF
3797    else
3798    {
3799        SendSysMessage(LANG_USE_BOL);
3800        return false;
3801    }
3802
3803    PSendSysMessage(LANG_YOU_SET_WATERWALK, args, player->GetName());
3804    if(needReportToTarget(player))
3805        ChatHandler(player).PSendSysMessage(LANG_YOUR_WATERWALK_SET, args, GetName());
3806    return true;
3807
3808}
3809
3810bool ChatHandler::HandleLevelUpCommand(const char* args)
3811{
3812    char* px = strtok((char*)args, " ");
3813    char* py = strtok((char*)NULL, " ");
3814
3815    // command format parsing
3816    char* pname = (char*)NULL;
3817    int addlevel = 1;
3818
3819    if(px && py)                                            // .levelup name level
3820    {
3821        addlevel = atoi(py);
3822        pname = px;
3823    }
3824    else if(px && !py)                                      // .levelup name OR .levelup level
3825    {
3826        if(isalpha(px[0]))                                  // .levelup name
3827            pname = px;
3828        else                                                // .levelup level
3829            addlevel = atoi(px);
3830    }
3831    // else .levelup - nothing do for preparing
3832
3833    // player
3834    Player *chr = NULL;
3835    uint64 chr_guid = 0;
3836
3837    std::string name;
3838
3839    if(pname)                                               // player by name
3840    {
3841        name = pname;
3842        if(!normalizePlayerName(name))
3843        {
3844            SendSysMessage(LANG_PLAYER_NOT_FOUND);
3845            SetSentErrorMessage(true);
3846            return false;
3847        }
3848
3849        chr = objmgr.GetPlayer(name.c_str());
3850        if(!chr)                                            // not in game
3851        {
3852            chr_guid = objmgr.GetPlayerGUIDByName(name);
3853            if (chr_guid == 0)
3854            {
3855                SendSysMessage(LANG_PLAYER_NOT_FOUND);
3856                SetSentErrorMessage(true);
3857                return false;
3858            }
3859        }
3860    }
3861    else                                                    // player by selection
3862    {
3863        chr = getSelectedPlayer();
3864
3865        if (chr == NULL)
3866        {
3867            SendSysMessage(LANG_NO_CHAR_SELECTED);
3868            SetSentErrorMessage(true);
3869            return false;
3870        }
3871
3872        name = chr->GetName();
3873    }
3874
3875    assert(chr || chr_guid);
3876
3877    int32 oldlevel = chr ? chr->getLevel() : Player::GetUInt32ValueFromDB(UNIT_FIELD_LEVEL,chr_guid);
3878    int32 newlevel = oldlevel + addlevel;
3879    if(newlevel < 1)
3880        newlevel = 1;
3881    if(newlevel > 255)                                      // hardcoded maximum level
3882        newlevel = 255;
3883
3884    if(chr)
3885    {
3886        chr->GiveLevel(newlevel);
3887        chr->InitTalentForLevel();
3888        chr->SetUInt32Value(PLAYER_XP,0);
3889
3890        if(oldlevel == newlevel)
3891            ChatHandler(chr).SendSysMessage(LANG_YOURS_LEVEL_PROGRESS_RESET);
3892        else
3893        if(oldlevel < newlevel)
3894            ChatHandler(chr).PSendSysMessage(LANG_YOURS_LEVEL_UP,newlevel-oldlevel);
3895        else
3896        if(oldlevel > newlevel)
3897            ChatHandler(chr).PSendSysMessage(LANG_YOURS_LEVEL_DOWN,newlevel-oldlevel);
3898    }
3899    else
3900    {
3901        // update level and XP at level, all other will be updated at loading
3902        Tokens values;
3903        Player::LoadValuesArrayFromDB(values,chr_guid);
3904        Player::SetUInt32ValueInArray(values,UNIT_FIELD_LEVEL,newlevel);
3905        Player::SetUInt32ValueInArray(values,PLAYER_XP,0);
3906        Player::SaveValuesArrayInDB(values,chr_guid);
3907    }
3908
3909    if(m_session->GetPlayer() != chr)                       // including chr==NULL
3910        PSendSysMessage(LANG_YOU_CHANGE_LVL,name.c_str(),newlevel);
3911    return true;
3912}
3913
3914bool ChatHandler::HandleShowAreaCommand(const char* args)
3915{
3916    if (!*args)
3917        return false;
3918
3919    int area = atoi((char*)args);
3920
3921    Player *chr = getSelectedPlayer();
3922    if (chr == NULL)
3923    {
3924        SendSysMessage(LANG_NO_CHAR_SELECTED);
3925        SetSentErrorMessage(true);
3926        return false;
3927    }
3928
3929    int offset = area / 32;
3930    uint32 val = (uint32)(1 << (area % 32));
3931
3932    if(offset >= 128)
3933    {
3934        SendSysMessage(LANG_BAD_VALUE);
3935        SetSentErrorMessage(true);
3936        return false;
3937    }
3938
3939    uint32 currFields = chr->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
3940    chr->SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
3941
3942    SendSysMessage(LANG_EXPLORE_AREA);
3943    return true;
3944}
3945
3946bool ChatHandler::HandleHideAreaCommand(const char* args)
3947{
3948    if (!*args)
3949        return false;
3950
3951    int area = atoi((char*)args);
3952
3953    Player *chr = getSelectedPlayer();
3954    if (chr == NULL)
3955    {
3956        SendSysMessage(LANG_NO_CHAR_SELECTED);
3957        SetSentErrorMessage(true);
3958        return false;
3959    }
3960
3961    int offset = area / 32;
3962    uint32 val = (uint32)(1 << (area % 32));
3963
3964    if(offset >= 128)
3965    {
3966        SendSysMessage(LANG_BAD_VALUE);
3967        SetSentErrorMessage(true);
3968        return false;
3969    }
3970
3971    uint32 currFields = chr->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
3972    chr->SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields ^ val));
3973
3974    SendSysMessage(LANG_UNEXPLORE_AREA);
3975    return true;
3976}
3977
3978bool ChatHandler::HandleUpdate(const char* args)
3979{
3980    if(!*args)
3981        return false;
3982
3983    uint32 updateIndex;
3984    uint32 value;
3985
3986    char* pUpdateIndex = strtok((char*)args, " ");
3987
3988    Unit* chr = getSelectedUnit();
3989    if (chr == NULL)
3990    {
3991        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
3992        SetSentErrorMessage(true);
3993        return false;
3994    }
3995
3996    if(!pUpdateIndex)
3997    {
3998        return true;
3999    }
4000    updateIndex = atoi(pUpdateIndex);
4001    //check updateIndex
4002    if(chr->GetTypeId() == TYPEID_PLAYER)
4003    {
4004        if (updateIndex>=PLAYER_END) return true;
4005    }
4006    else
4007    {
4008        if (updateIndex>=UNIT_END) return true;
4009    }
4010
4011    char*  pvalue = strtok(NULL, " ");
4012    if (!pvalue)
4013    {
4014        value=chr->GetUInt32Value(updateIndex);
4015
4016        PSendSysMessage(LANG_UPDATE, chr->GetGUIDLow(),updateIndex,value);
4017        return true;
4018    }
4019
4020    value=atoi(pvalue);
4021
4022    PSendSysMessage(LANG_UPDATE_CHANGE, chr->GetGUIDLow(),updateIndex,value);
4023
4024    chr->SetUInt32Value(updateIndex,value);
4025
4026    return true;
4027}
4028
4029bool ChatHandler::HandleBankCommand(const char* /*args*/)
4030{
4031    m_session->SendShowBank( m_session->GetPlayer()->GetGUID() );
4032
4033    return true;
4034}
4035
4036bool ChatHandler::HandleChangeWeather(const char* args)
4037{
4038    if(!*args)
4039        return false;
4040
4041    //Weather is OFF
4042    if (!sWorld.getConfig(CONFIG_WEATHER))
4043    {
4044        SendSysMessage(LANG_WEATHER_DISABLED);
4045        SetSentErrorMessage(true);
4046        return false;
4047    }
4048
4049    //*Change the weather of a cell
4050    char* px = strtok((char*)args, " ");
4051    char* py = strtok(NULL, " ");
4052
4053    if (!px || !py)
4054        return false;
4055
4056    uint32 type = (uint32)atoi(px);                         //0 to 3, 0: fine, 1: rain, 2: snow, 3: sand
4057    float grade = (float)atof(py);                          //0 to 1, sending -1 is instand good weather
4058
4059    Player *player = m_session->GetPlayer();
4060    uint32 zoneid = player->GetZoneId();
4061
4062    Weather* wth = sWorld.FindWeather(zoneid);
4063
4064    if(!wth)
4065        wth = sWorld.AddWeather(zoneid);
4066    if(!wth)
4067    {
4068        SendSysMessage(LANG_NO_WEATHER);
4069        SetSentErrorMessage(true);
4070        return false;
4071    }
4072
4073    wth->SetWeather(WeatherType(type), grade);
4074
4075    return true;
4076}
4077
4078bool ChatHandler::HandleSetValue(const char* args)
4079{
4080    if(!*args)
4081        return false;
4082
4083    char* px = strtok((char*)args, " ");
4084    char* py = strtok(NULL, " ");
4085    char* pz = strtok(NULL, " ");
4086
4087    if (!px || !py)
4088        return false;
4089
4090    Unit* target = getSelectedUnit();
4091    if(!target)
4092    {
4093        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
4094        SetSentErrorMessage(true);
4095        return false;
4096    }
4097
4098    uint64 guid = target->GetGUID();
4099
4100    uint32 Opcode = (uint32)atoi(px);
4101    if(Opcode >= target->GetValuesCount())
4102    {
4103        PSendSysMessage(LANG_TOO_BIG_INDEX, Opcode, GUID_LOPART(guid), target->GetValuesCount());
4104        return false;
4105    }
4106    uint32 iValue;
4107    float fValue;
4108    bool isint32 = true;
4109    if(pz)
4110        isint32 = (bool)atoi(pz);
4111    if(isint32)
4112    {
4113        iValue = (uint32)atoi(py);
4114        sLog.outDebug(GetTrinityString(LANG_SET_UINT), GUID_LOPART(guid), Opcode, iValue);
4115        target->SetUInt32Value( Opcode , iValue );
4116        PSendSysMessage(LANG_SET_UINT_FIELD, GUID_LOPART(guid), Opcode,iValue);
4117    }
4118    else
4119    {
4120        fValue = (float)atof(py);
4121        sLog.outDebug(GetTrinityString(LANG_SET_FLOAT), GUID_LOPART(guid), Opcode, fValue);
4122        target->SetFloatValue( Opcode , fValue );
4123        PSendSysMessage(LANG_SET_FLOAT_FIELD, GUID_LOPART(guid), Opcode,fValue);
4124    }
4125
4126    return true;
4127}
4128
4129bool ChatHandler::HandleGetValue(const char* args)
4130{
4131    if(!*args)
4132        return false;
4133
4134    char* px = strtok((char*)args, " ");
4135    char* pz = strtok(NULL, " ");
4136
4137    if (!px)
4138        return false;
4139
4140    Unit* target = getSelectedUnit();
4141    if(!target)
4142    {
4143        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
4144        SetSentErrorMessage(true);
4145        return false;
4146    }
4147
4148    uint64 guid = target->GetGUID();
4149
4150    uint32 Opcode = (uint32)atoi(px);
4151    if(Opcode >= target->GetValuesCount())
4152    {
4153        PSendSysMessage(LANG_TOO_BIG_INDEX, Opcode, GUID_LOPART(guid), target->GetValuesCount());
4154        return false;
4155    }
4156    uint32 iValue;
4157    float fValue;
4158    bool isint32 = true;
4159    if(pz)
4160        isint32 = (bool)atoi(pz);
4161
4162    if(isint32)
4163    {
4164        iValue = target->GetUInt32Value( Opcode );
4165        sLog.outDebug(GetTrinityString(LANG_GET_UINT), GUID_LOPART(guid), Opcode, iValue);
4166        PSendSysMessage(LANG_GET_UINT_FIELD, GUID_LOPART(guid), Opcode,    iValue);
4167    }
4168    else
4169    {
4170        fValue = target->GetFloatValue( Opcode );
4171        sLog.outDebug(GetTrinityString(LANG_GET_FLOAT), GUID_LOPART(guid), Opcode, fValue);
4172        PSendSysMessage(LANG_GET_FLOAT_FIELD, GUID_LOPART(guid), Opcode, fValue);
4173    }
4174
4175    return true;
4176}
4177
4178bool ChatHandler::HandleSet32Bit(const char* args)
4179{
4180    if(!*args)
4181        return false;
4182
4183    char* px = strtok((char*)args, " ");
4184    char* py = strtok(NULL, " ");
4185
4186    if (!px || !py)
4187        return false;
4188
4189    uint32 Opcode = (uint32)atoi(px);
4190    uint32 Value = (uint32)atoi(py);
4191    if (Value > 32)                                         //uint32 = 32 bits
4192        return false;
4193
4194    sLog.outDebug(GetTrinityString(LANG_SET_32BIT), Opcode, Value);
4195
4196    m_session->GetPlayer( )->SetUInt32Value( Opcode , 2^Value );
4197
4198    PSendSysMessage(LANG_SET_32BIT_FIELD, Opcode,1);
4199    return true;
4200}
4201
4202bool ChatHandler::HandleMod32Value(const char* args)
4203{
4204    if(!*args)
4205        return false;
4206
4207    char* px = strtok((char*)args, " ");
4208    char* py = strtok(NULL, " ");
4209
4210    if (!px || !py)
4211        return false;
4212
4213    uint32 Opcode = (uint32)atoi(px);
4214    int Value = atoi(py);
4215
4216    if(Opcode >= m_session->GetPlayer()->GetValuesCount())
4217    {
4218        PSendSysMessage(LANG_TOO_BIG_INDEX, Opcode, m_session->GetPlayer()->GetGUIDLow(), m_session->GetPlayer( )->GetValuesCount());
4219        return false;
4220    }
4221
4222    sLog.outDebug(GetTrinityString(LANG_CHANGE_32BIT), Opcode, Value);
4223
4224    int CurrentValue = (int)m_session->GetPlayer( )->GetUInt32Value( Opcode );
4225
4226    CurrentValue += Value;
4227    m_session->GetPlayer( )->SetUInt32Value( Opcode , (uint32)CurrentValue );
4228
4229    PSendSysMessage(LANG_CHANGE_32BIT_FIELD, Opcode,CurrentValue);
4230
4231    return true;
4232}
4233
4234bool ChatHandler::HandleAddTeleCommand(const char * args)
4235{
4236    if(!*args)
4237        return false;
4238
4239    Player *player=m_session->GetPlayer();
4240    if (!player)
4241        return false;
4242
4243    std::string name = args;
4244
4245    if(objmgr.GetGameTele(name))
4246    {
4247        SendSysMessage(LANG_COMMAND_TP_ALREADYEXIST);
4248        SetSentErrorMessage(true);
4249        return false;
4250    }
4251
4252    GameTele tele;
4253    tele.position_x  = player->GetPositionX();
4254    tele.position_y  = player->GetPositionY();
4255    tele.position_z  = player->GetPositionZ();
4256    tele.orientation = player->GetOrientation();
4257    tele.mapId       = player->GetMapId();
4258    tele.name        = name;
4259
4260    if(objmgr.AddGameTele(tele))
4261    {
4262        SendSysMessage(LANG_COMMAND_TP_ADDED);
4263    }
4264    else
4265    {
4266        SendSysMessage(LANG_COMMAND_TP_ADDEDERR);
4267        SetSentErrorMessage(true);
4268        return false;
4269    }
4270
4271    return true;
4272}
4273
4274bool ChatHandler::HandleDelTeleCommand(const char * args)
4275{
4276    if(!*args)
4277        return false;
4278
4279    std::string name = args;
4280
4281    if(!objmgr.DeleteGameTele(name))
4282    {
4283        SendSysMessage(LANG_COMMAND_TELE_NOTFOUND);
4284        SetSentErrorMessage(true);
4285        return false;
4286    }
4287
4288    SendSysMessage(LANG_COMMAND_TP_DELETED);
4289    return true;
4290}
4291
4292bool ChatHandler::HandleListAurasCommand (const char * /*args*/)
4293{
4294    Unit *unit = getSelectedUnit();
4295    if(!unit)
4296    {
4297        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
4298        SetSentErrorMessage(true);
4299        return false;
4300    }
4301
4302    char const* talentStr = GetTrinityString(LANG_TALENT);
4303    char const* passiveStr = GetTrinityString(LANG_PASSIVE);
4304
4305    Unit::AuraMap const& uAuras = unit->GetAuras();
4306    PSendSysMessage(LANG_COMMAND_TARGET_LISTAURAS, uAuras.size());
4307    for (Unit::AuraMap::const_iterator itr = uAuras.begin(); itr != uAuras.end(); ++itr)
4308    {
4309        bool talent = GetTalentSpellCost(itr->second->GetId()) > 0;
4310        PSendSysMessage(LANG_COMMAND_TARGET_AURADETAIL, itr->second->GetId(), itr->second->GetEffIndex(),
4311            itr->second->GetModifier()->m_auraname, itr->second->GetAuraDuration(), itr->second->GetAuraMaxDuration(),
4312            itr->second->GetSpellProto()->SpellName[m_session->GetSessionDbcLocale()],
4313            (itr->second->IsPassive() ? passiveStr : ""),(talent ? talentStr : ""),
4314            IS_PLAYER_GUID(itr->second->GetCasterGUID()) ? "player" : "creature",GUID_LOPART(itr->second->GetCasterGUID()));
4315    }
4316    for (int i = 0; i < TOTAL_AURAS; i++)
4317    {
4318        Unit::AuraList const& uAuraList = unit->GetAurasByType(AuraType(i));
4319        if (uAuraList.empty()) continue;
4320        PSendSysMessage(LANG_COMMAND_TARGET_LISTAURATYPE, uAuraList.size(), i);
4321        for (Unit::AuraList::const_iterator itr = uAuraList.begin(); itr != uAuraList.end(); ++itr)
4322        {
4323            bool talent = GetTalentSpellCost((*itr)->GetId()) > 0;
4324            PSendSysMessage(LANG_COMMAND_TARGET_AURASIMPLE, (*itr)->GetId(), (*itr)->GetEffIndex(),
4325                (*itr)->GetSpellProto()->SpellName[m_session->GetSessionDbcLocale()],((*itr)->IsPassive() ? passiveStr : ""),(talent ? talentStr : ""),
4326                IS_PLAYER_GUID((*itr)->GetCasterGUID()) ? "player" : "creature",GUID_LOPART((*itr)->GetCasterGUID()));
4327        }
4328    }
4329    return true;
4330}
4331
4332bool ChatHandler::HandleResetHonorCommand (const char * args)
4333{
4334    char* pName = strtok((char*)args, "");
4335    Player *player = NULL;
4336    if (pName)
4337    {
4338        std::string name = pName;
4339        if(!normalizePlayerName(name))
4340        {
4341            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4342            SetSentErrorMessage(true);
4343            return false;
4344        }
4345
4346        uint64 guid = objmgr.GetPlayerGUIDByName(name.c_str());
4347        player = objmgr.GetPlayer(guid);
4348    }
4349    else
4350        player = getSelectedPlayer();
4351
4352    if(!player)
4353    {
4354        SendSysMessage(LANG_NO_CHAR_SELECTED);
4355        return true;
4356    }
4357
4358    player->SetUInt32Value(PLAYER_FIELD_KILLS, 0);
4359    player->SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0);
4360    player->SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, 0);
4361    player->SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
4362    player->SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
4363
4364    return true;
4365}
4366
4367static bool HandleResetStatsOrLevelHelper(Player* player)
4368{
4369    PlayerInfo const *info = objmgr.GetPlayerInfo(player->getRace(), player->getClass());
4370    if(!info) return false;
4371
4372    ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(player->getClass());
4373    if(!cEntry)
4374    {
4375        sLog.outError("Class %u not found in DBC (Wrong DBC files?)",player->getClass());
4376        return false;
4377    }
4378
4379    uint8 powertype = cEntry->powerType;
4380
4381    uint32 unitfield;
4382    if(powertype == POWER_RAGE)
4383        unitfield = 0x1100EE00;
4384    else if(powertype == POWER_ENERGY)
4385        unitfield = 0x00000000;
4386    else if(powertype == POWER_MANA)
4387        unitfield = 0x0000EE00;
4388    else
4389    {
4390        sLog.outError("Invalid default powertype %u for player (class %u)",powertype,player->getClass());
4391        return false;
4392    }
4393
4394    // reset m_form if no aura
4395    if(!player->HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
4396        player->m_form = FORM_NONE;
4397
4398    player->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE );
4399    player->SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f   );
4400
4401    player->setFactionForRace(player->getRace());
4402
4403    player->SetUInt32Value(UNIT_FIELD_BYTES_0, ( ( player->getRace() ) | ( player->getClass() << 8 ) | ( player->getGender() << 16 ) | ( powertype << 24 ) ) );
4404
4405    // reset only if player not in some form;
4406    if(player->m_form==FORM_NONE)
4407    {
4408        switch(player->getGender())
4409        {
4410            case GENDER_FEMALE:
4411                player->SetDisplayId(info->displayId_f);
4412                player->SetNativeDisplayId(info->displayId_f);
4413                break;
4414            case GENDER_MALE:
4415                player->SetDisplayId(info->displayId_m);
4416                player->SetNativeDisplayId(info->displayId_m);
4417                break;
4418            default:
4419                break;
4420        }
4421    }
4422
4423    // set UNIT_FIELD_BYTES_1 to init state but preserve m_form value
4424    player->SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
4425    player->SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_UNK5 );
4426    player->SetByteValue(UNIT_FIELD_BYTES_2, 3, player->m_form);
4427
4428    player->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
4429
4430    //-1 is default value
4431    player->SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
4432
4433    //player->SetUInt32Value(PLAYER_FIELD_BYTES, 0xEEE00000 );
4434    return true;
4435}
4436
4437bool ChatHandler::HandleResetLevelCommand(const char * args)
4438{
4439    char* pName = strtok((char*)args, "");
4440    Player *player = NULL;
4441    if (pName)
4442    {
4443        std::string name = pName;
4444        if(!normalizePlayerName(name))
4445        {
4446            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4447            SetSentErrorMessage(true);
4448            return false;
4449        }
4450
4451        uint64 guid = objmgr.GetPlayerGUIDByName(name.c_str());
4452        player = objmgr.GetPlayer(guid);
4453    }
4454    else
4455        player = getSelectedPlayer();
4456
4457    if(!player)
4458    {
4459        SendSysMessage(LANG_NO_CHAR_SELECTED);
4460        SetSentErrorMessage(true);
4461        return false;
4462    }
4463
4464    if(!HandleResetStatsOrLevelHelper(player))
4465        return false;
4466
4467    player->SetLevel(1);
4468    player->InitStatsForLevel(true);
4469    player->InitTaxiNodesForLevel();
4470    player->InitTalentForLevel();
4471    player->SetUInt32Value(PLAYER_XP,0);
4472
4473    // reset level to summoned pet
4474    Pet* pet = player->GetPet();
4475    if(pet && pet->getPetType()==SUMMON_PET)
4476        pet->InitStatsForLevel(1);
4477
4478    return true;
4479}
4480
4481bool ChatHandler::HandleResetStatsCommand(const char * args)
4482{
4483    char* pName = strtok((char*)args, "");
4484    Player *player = NULL;
4485    if (pName)
4486    {
4487        std::string name = pName;
4488        if(!normalizePlayerName(name))
4489        {
4490            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4491            SetSentErrorMessage(true);
4492            return false;
4493        }
4494
4495        uint64 guid = objmgr.GetPlayerGUIDByName(name.c_str());
4496        player = objmgr.GetPlayer(guid);
4497    }
4498    else
4499        player = getSelectedPlayer();
4500
4501    if(!player)
4502    {
4503        SendSysMessage(LANG_NO_CHAR_SELECTED);
4504        SetSentErrorMessage(true);
4505        return false;
4506    }
4507
4508    if(!HandleResetStatsOrLevelHelper(player))
4509        return false;
4510
4511    player->InitStatsForLevel(true);
4512    player->InitTaxiNodesForLevel();
4513    player->InitTalentForLevel();
4514
4515    return true;
4516}
4517
4518bool ChatHandler::HandleResetSpellsCommand(const char * args)
4519{
4520    char* pName = strtok((char*)args, "");
4521    Player *player = NULL;
4522    uint64 playerGUID = 0;
4523    if (pName)
4524    {
4525        std::string name = pName;
4526
4527        if(!normalizePlayerName(name))
4528        {
4529            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4530            SetSentErrorMessage(true);
4531            return false;
4532        }
4533
4534        player = objmgr.GetPlayer(name.c_str());
4535        if(!player)
4536            playerGUID = objmgr.GetPlayerGUIDByName(name.c_str());
4537    }
4538    else
4539        player = getSelectedPlayer();
4540
4541    if(!player && !playerGUID)
4542    {
4543        SendSysMessage(LANG_NO_CHAR_SELECTED);
4544        SetSentErrorMessage(true);
4545        return false;
4546    }
4547
4548    if(player)
4549    {
4550        player->resetSpells();
4551
4552        ChatHandler(player).SendSysMessage(LANG_RESET_SPELLS);
4553
4554        if(m_session->GetPlayer()!=player)
4555            PSendSysMessage(LANG_RESET_SPELLS_ONLINE,player->GetName());
4556    }
4557    else
4558    {
4559        CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid = '%u'",uint32(AT_LOGIN_RESET_SPELLS), GUID_LOPART(playerGUID));
4560        PSendSysMessage(LANG_RESET_SPELLS_OFFLINE,pName);
4561    }
4562
4563    return true;
4564}
4565
4566bool ChatHandler::HandleResetTalentsCommand(const char * args)
4567{
4568    char* pName = strtok((char*)args, "");
4569    Player *player = NULL;
4570    uint64 playerGUID = 0;
4571    if (pName)
4572    {
4573        std::string name = pName;
4574        if(!normalizePlayerName(name))
4575        {
4576            SendSysMessage(LANG_PLAYER_NOT_FOUND);
4577            SetSentErrorMessage(true);
4578            return false;
4579        }
4580
4581        player = objmgr.GetPlayer(name.c_str());
4582        if(!player)
4583            playerGUID = objmgr.GetPlayerGUIDByName(name.c_str());
4584    }
4585    else
4586        player = getSelectedPlayer();
4587
4588    if(!player && !playerGUID)
4589    {
4590        SendSysMessage(LANG_NO_CHAR_SELECTED);
4591        SetSentErrorMessage(true);
4592        return false;
4593    }
4594
4595    if(player)
4596    {
4597        player->resetTalents(true);
4598
4599        ChatHandler(player).SendSysMessage(LANG_RESET_TALENTS);
4600
4601        if(m_session->GetPlayer()!=player)
4602            PSendSysMessage(LANG_RESET_TALENTS_ONLINE,player->GetName());
4603    }
4604    else
4605    {
4606        CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid = '%u'",uint32(AT_LOGIN_RESET_TALENTS), GUID_LOPART(playerGUID) );
4607        PSendSysMessage(LANG_RESET_TALENTS_OFFLINE,pName);
4608    }
4609
4610    return true;
4611}
4612
4613bool ChatHandler::HandleResetAllCommand(const char * args)
4614{
4615    if(!*args)
4616        return false;
4617
4618    std::string casename = args;
4619
4620    AtLoginFlags atLogin;
4621
4622    // Command specially created as single command to prevent using short case names
4623    if(casename=="spells")
4624    {
4625        atLogin = AT_LOGIN_RESET_SPELLS;
4626        sWorld.SendWorldText(LANG_RESETALL_SPELLS);
4627    }
4628    else if(casename=="talents")
4629    {
4630        atLogin = AT_LOGIN_RESET_TALENTS;
4631        sWorld.SendWorldText(LANG_RESETALL_TALENTS);
4632    }
4633    else
4634    {
4635        PSendSysMessage(LANG_RESETALL_UNKNOWN_CASE,args);
4636        SetSentErrorMessage(true);
4637        return false;
4638    }
4639
4640    CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u'",atLogin);
4641    HashMapHolder<Player>::MapType const& plist = ObjectAccessor::Instance().GetPlayers();
4642    for(HashMapHolder<Player>::MapType::const_iterator itr = plist.begin(); itr != plist.end(); ++itr)
4643        itr->second->SetAtLoginFlag(atLogin);
4644
4645    return true;
4646}
4647
4648bool ChatHandler::HandleShutDownCommand(const char* args)
4649{
4650    if(!*args)
4651        return false;
4652
4653    if(std::string(args)=="cancel")
4654    {
4655        sWorld.ShutdownCancel();
4656    }
4657    else
4658    {
4659        int32 time = atoi(args);
4660
4661        ///- Prevent interpret wrong arg value as 0 secs shutdown time
4662        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
4663            return false;
4664
4665        sWorld.ShutdownServ(time);
4666    }
4667    return true;
4668}
4669
4670bool ChatHandler::HandleRestartCommand(const char* args)
4671{
4672    if(!*args)
4673        return false;
4674
4675    if(std::string(args)=="cancel")
4676    {
4677        sWorld.ShutdownCancel();
4678    }
4679    else
4680    {
4681        int32 time = atoi(args);
4682
4683        ///- Prevent interpret wrong arg value as 0 secs shutdown time
4684        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
4685            return false;
4686
4687        sWorld.ShutdownServ(time, SHUTDOWN_MASK_RESTART);
4688    }
4689    return true;
4690}
4691
4692bool ChatHandler::HandleIdleRestartCommand(const char* args)
4693{
4694    if(!*args)
4695        return false;
4696
4697    if(std::string(args)=="cancel")
4698    {
4699        sWorld.ShutdownCancel();
4700    }
4701    else
4702    {
4703        int32 time = atoi(args);
4704
4705        ///- Prevent interpret wrong arg value as 0 secs shutdown time
4706        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
4707            return false;
4708
4709        sWorld.ShutdownServ(time,SHUTDOWN_MASK_RESTART+SHUTDOWN_MASK_IDLE);
4710    }
4711    return true;
4712}
4713
4714bool ChatHandler::HandleIdleShutDownCommand(const char* args)
4715{
4716    if(!*args)
4717        return false;
4718
4719    if(std::string(args)=="cancel")
4720    {
4721        sWorld.ShutdownCancel();
4722    }
4723    else
4724    {
4725        int32 time = atoi(args);
4726
4727        ///- Prevent interpret wrong arg value as 0 secs shutdown time
4728        if(time == 0 && (args[0]!='0' || args[1]!='\0') || time < 0)
4729            return false;
4730
4731        sWorld.ShutdownServ(time,SHUTDOWN_MASK_IDLE);
4732    }
4733    return true;
4734}
4735
4736bool ChatHandler::HandleAddQuest(const char* args)
4737{
4738    Player* player = getSelectedPlayer();
4739    if(!player)
4740    {
4741        SendSysMessage(LANG_NO_CHAR_SELECTED);
4742        SetSentErrorMessage(true);
4743        return false;
4744    }
4745
4746    // .addquest #entry'
4747    // number or [name] Shift-click form |color|Hquest:quest_id|h[name]|h|r
4748    char* cId = extractKeyFromLink((char*)args,"Hquest");
4749    if(!cId)
4750        return false;
4751
4752    uint32 entry = atol(cId);
4753
4754    Quest const* pQuest = objmgr.GetQuestTemplate(entry);
4755
4756    if(!pQuest)
4757    {
4758        PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND,entry);
4759        SetSentErrorMessage(true);
4760        return false;
4761    }
4762
4763    // check item starting quest (it can work incorrectly if added without item in inventory)
4764    for (uint32 id = 0; id < sItemStorage.MaxEntry; id++)
4765    {
4766        ItemPrototype const *pProto = sItemStorage.LookupEntry<ItemPrototype>(id);
4767        if (!pProto)
4768            continue;
4769
4770        if (pProto->StartQuest == entry)
4771        {
4772            PSendSysMessage(LANG_COMMAND_QUEST_STARTFROMITEM, entry, pProto->ItemId);
4773            SetSentErrorMessage(true);
4774            return false;
4775        }
4776    }
4777
4778    // ok, normal (creature/GO starting) quest
4779    if( player->CanAddQuest( pQuest, true ) )
4780    {
4781        player->AddQuest( pQuest, NULL );
4782
4783        if ( player->CanCompleteQuest( entry ) )
4784            player->CompleteQuest( entry );
4785    }
4786
4787    return true;
4788}
4789
4790bool ChatHandler::HandleRemoveQuest(const char* args)
4791{
4792    Player* player = getSelectedPlayer();
4793    if(!player)
4794    {
4795        SendSysMessage(LANG_NO_CHAR_SELECTED);
4796        SetSentErrorMessage(true);
4797        return false;
4798    }
4799
4800    // .removequest #entry'
4801    // number or [name] Shift-click form |color|Hquest:quest_id|h[name]|h|r
4802    char* cId = extractKeyFromLink((char*)args,"Hquest");
4803    if(!cId)
4804        return false;
4805
4806    uint32 entry = atol(cId);
4807
4808    Quest const* pQuest = objmgr.GetQuestTemplate(entry);
4809
4810    if(!pQuest)
4811    {
4812        PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry);
4813        SetSentErrorMessage(true);
4814        return false;
4815    }
4816
4817    // remove all quest entries for 'entry' from quest log
4818    for(uint8 slot = 0; slot < MAX_QUEST_LOG_SIZE; ++slot )
4819    {
4820        uint32 quest = player->GetQuestSlotQuestId(slot);
4821        if(quest==entry)
4822        {
4823            player->SetQuestSlot(slot,0);
4824
4825            // we ignore unequippable quest items in this case, its' still be equipped
4826            player->TakeQuestSourceItem( quest, false );
4827        }
4828    }
4829
4830    // set quest status to not started (will updated in DB at next save)
4831    player->SetQuestStatus( entry, QUEST_STATUS_NONE);
4832
4833    // reset rewarded for restart repeatable quest
4834    player->getQuestStatusMap()[entry].m_rewarded = false;
4835
4836    SendSysMessage(LANG_COMMAND_QUEST_REMOVED);
4837    return true;
4838}
4839
4840bool ChatHandler::HandleCompleteQuest(const char* args)
4841{
4842    Player* player = getSelectedPlayer();
4843    if(!player)
4844    {
4845        SendSysMessage(LANG_NO_CHAR_SELECTED);
4846        SetSentErrorMessage(true);
4847        return false;
4848    }
4849
4850    // .quest complete #entry
4851    // number or [name] Shift-click form |color|Hquest:quest_id|h[name]|h|r
4852    char* cId = extractKeyFromLink((char*)args,"Hquest");
4853    if(!cId)
4854        return false;
4855
4856    uint32 entry = atol(cId);
4857
4858    Quest const* pQuest = objmgr.GetQuestTemplate(entry);
4859
4860    // If player doesn't have the quest
4861    if(!pQuest || player->GetQuestStatus(entry) == QUEST_STATUS_NONE)
4862    {
4863        PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry);
4864        SetSentErrorMessage(true);
4865        return false;
4866    }
4867
4868    // Add quest items for quests that require items
4869    for(uint8 x = 0; x < QUEST_OBJECTIVES_COUNT; ++x)
4870    {
4871        uint32 id = pQuest->ReqItemId[x];
4872        uint32 count = pQuest->ReqItemCount[x];
4873        if(!id || !count)
4874            continue;
4875
4876        uint32 curItemCount = player->GetItemCount(id,true);
4877
4878        ItemPosCountVec dest;
4879        uint8 msg = player->CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, id, count-curItemCount );
4880        if( msg == EQUIP_ERR_OK )
4881        {
4882            Item* item = player->StoreNewItem( dest, id, true);
4883            player->SendNewItem(item,count-curItemCount,true,false);
4884        }
4885    }
4886
4887    // All creature/GO slain/casted (not required, but otherwise it will display "Creature slain 0/10")
4888    for(uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
4889    {
4890        uint32 creature = pQuest->ReqCreatureOrGOId[i];
4891        uint32 creaturecount = pQuest->ReqCreatureOrGOCount[i];
4892
4893        if(uint32 spell_id = pQuest->ReqSpell[i])
4894        {
4895            for(uint16 z = 0; z < creaturecount; ++z)
4896                player->CastedCreatureOrGO(creature,0,spell_id);
4897        }
4898        else if(creature > 0)
4899        {
4900            for(uint16 z = 0; z < creaturecount; ++z)
4901                player->KilledMonster(creature,0);
4902        }
4903        else if(creature < 0)
4904        {
4905            for(uint16 z = 0; z < creaturecount; ++z)
4906                player->CastedCreatureOrGO(creature,0,0);
4907        }
4908    }
4909
4910    // If the quest requires reputation to complete
4911    if(uint32 repFaction = pQuest->GetRepObjectiveFaction())
4912    {
4913        uint32 repValue = pQuest->GetRepObjectiveValue();
4914        uint32 curRep = player->GetReputation(repFaction);
4915        if(curRep < repValue)
4916        {
4917            FactionEntry const *factionEntry = sFactionStore.LookupEntry(repFaction);
4918            player->SetFactionReputation(factionEntry,repValue);
4919        }
4920    }
4921
4922    // If the quest requires money
4923    int32 ReqOrRewMoney = pQuest->GetRewOrReqMoney();
4924    if(ReqOrRewMoney < 0)
4925        player->ModifyMoney(-ReqOrRewMoney);
4926
4927    player->CompleteQuest(entry);
4928    return true;
4929}
4930
4931bool ChatHandler::HandleBanAccountCommand(const char* args)
4932{
4933    return HandleBanHelper(BAN_ACCOUNT,args);
4934}
4935
4936bool ChatHandler::HandleBanCharacterCommand(const char* args)
4937{
4938    return HandleBanHelper(BAN_CHARACTER,args);
4939}
4940
4941bool ChatHandler::HandleBanIPCommand(const char* args)
4942{
4943    return HandleBanHelper(BAN_IP,args);
4944}
4945
4946bool ChatHandler::HandleBanHelper(BanMode mode, const char* args)
4947{
4948    if(!args)
4949        return false;
4950
4951    char* cnameOrIP = strtok ((char*)args, " ");
4952    if (!cnameOrIP)
4953        return false;
4954
4955    std::string nameOrIP = cnameOrIP;
4956
4957    char* duration = strtok (NULL," ");
4958    if(!duration || !atoi(duration))
4959        return false;
4960
4961    char* reason = strtok (NULL,"");
4962    if(!reason)
4963        return false;
4964
4965    switch(mode)
4966    {
4967        case BAN_ACCOUNT:
4968            if(!AccountMgr::normilizeString(nameOrIP))
4969            {
4970                PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,nameOrIP.c_str());
4971                SetSentErrorMessage(true);
4972                return false;
4973            }
4974            break;
4975        case BAN_CHARACTER:
4976            if(!normalizePlayerName(nameOrIP))
4977            {
4978                SendSysMessage(LANG_PLAYER_NOT_FOUND);
4979                SetSentErrorMessage(true);
4980                return false;
4981            }
4982            break;
4983        case BAN_IP:
4984            if(!IsIPAddress(nameOrIP.c_str()))
4985                return false;
4986            break;
4987    }
4988
4989    switch(sWorld.BanAccount(mode, nameOrIP, duration, reason,m_session ? m_session->GetPlayerName() : ""))
4990    {
4991        case BAN_SUCCESS:
4992            if(atoi(duration)>0)
4993                PSendSysMessage(LANG_BAN_YOUBANNED,nameOrIP.c_str(),secsToTimeString(TimeStringToSecs(duration),true).c_str(),reason);
4994            else
4995                PSendSysMessage(LANG_BAN_YOUPERMBANNED,nameOrIP.c_str(),reason);
4996            break;
4997        case BAN_SYNTAX_ERROR:
4998            return false;
4999        case BAN_NOTFOUND:
5000            switch(mode)
5001            {
5002                default:
5003                    PSendSysMessage(LANG_BAN_NOTFOUND,"account",nameOrIP.c_str());
5004                    break;
5005                case BAN_CHARACTER:
5006                    PSendSysMessage(LANG_BAN_NOTFOUND,"character",nameOrIP.c_str());
5007                    break;
5008                case BAN_IP:
5009                    PSendSysMessage(LANG_BAN_NOTFOUND,"ip",nameOrIP.c_str());
5010                    break;
5011            }
5012            SetSentErrorMessage(true);
5013            return false;
5014    }
5015
5016    return true;
5017}
5018
5019bool ChatHandler::HandleUnBanAccountCommand(const char* args)
5020{
5021    return HandleUnBanHelper(BAN_ACCOUNT,args);
5022}
5023
5024bool ChatHandler::HandleUnBanCharacterCommand(const char* args)
5025{
5026    return HandleUnBanHelper(BAN_CHARACTER,args);
5027}
5028
5029bool ChatHandler::HandleUnBanIPCommand(const char* args)
5030{
5031    return HandleUnBanHelper(BAN_IP,args);
5032}
5033
5034bool ChatHandler::HandleUnBanHelper(BanMode mode, const char* args)
5035{
5036    if(!args)
5037        return false;
5038
5039    char* cnameOrIP = strtok ((char*)args, " ");
5040    if(!cnameOrIP)
5041        return false;
5042
5043    std::string nameOrIP = cnameOrIP;
5044
5045    switch(mode)
5046    {
5047        case BAN_ACCOUNT:
5048            if(!AccountMgr::normilizeString(nameOrIP))
5049            {
5050                PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,nameOrIP.c_str());
5051                SetSentErrorMessage(true);
5052                return false;
5053            }
5054            break;
5055        case BAN_CHARACTER:
5056            if(!normalizePlayerName(nameOrIP))
5057            {
5058                SendSysMessage(LANG_PLAYER_NOT_FOUND);
5059                SetSentErrorMessage(true);
5060                return false;
5061            }
5062            break;
5063        case BAN_IP:
5064            if(!IsIPAddress(nameOrIP.c_str()))
5065                return false;
5066            break;
5067    }
5068
5069    if(sWorld.RemoveBanAccount(mode,nameOrIP))
5070        PSendSysMessage(LANG_UNBAN_UNBANNED,nameOrIP.c_str());
5071    else
5072        PSendSysMessage(LANG_UNBAN_ERROR,nameOrIP.c_str());
5073
5074    return true;
5075}
5076
5077bool ChatHandler::HandleBanInfoAccountCommand(const char* args)
5078{
5079    if(!args)
5080        return false;
5081
5082    char* cname = strtok((char*)args, "");
5083    if(!cname)
5084        return false;
5085
5086    std::string account_name = cname;
5087    if(!AccountMgr::normilizeString(account_name))
5088    {
5089        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5090        SetSentErrorMessage(true);
5091        return false;
5092    }
5093
5094    uint32 accountid = accmgr.GetId(account_name);
5095    if(!accountid)
5096    {
5097        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5098        return true;
5099    }
5100
5101    return HandleBanInfoHelper(accountid,account_name.c_str());
5102}
5103
5104bool ChatHandler::HandleBanInfoCharacterCommand(const char* args)
5105{
5106    if(!args)
5107        return false;
5108
5109    char* cname = strtok ((char*)args, "");
5110    if(!cname)
5111        return false;
5112
5113    std::string name = cname;
5114    if(!normalizePlayerName(name))
5115    {
5116        SendSysMessage(LANG_PLAYER_NOT_FOUND);
5117        SetSentErrorMessage(true);
5118        return false;
5119    }
5120
5121    uint32 accountid = objmgr.GetPlayerAccountIdByPlayerName(name);
5122    if(!accountid)
5123    {
5124        SendSysMessage(LANG_PLAYER_NOT_FOUND);
5125        SetSentErrorMessage(true);
5126        return false;
5127    }
5128
5129    std::string accountname;
5130    if(!accmgr.GetName(accountid,accountname))
5131    {
5132        PSendSysMessage(LANG_BANINFO_NOCHARACTER);
5133        return true;
5134    }
5135
5136    return HandleBanInfoHelper(accountid,accountname.c_str());
5137}
5138
5139bool ChatHandler::HandleBanInfoHelper(uint32 accountid, char const* accountname)
5140{
5141    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);
5142    if(!result)
5143    {
5144        PSendSysMessage(LANG_BANINFO_NOACCOUNTBAN, accountname);
5145        return true;
5146    }
5147
5148    PSendSysMessage(LANG_BANINFO_BANHISTORY,accountname);
5149    do
5150    {
5151        Field* fields = result->Fetch();
5152
5153        time_t unbandate = time_t(fields[3].GetUInt64());
5154        bool active = false;
5155        if(fields[2].GetBool() && (fields[1].GetUInt64() == (uint64)0 ||unbandate >= time(NULL)) )
5156            active = true;
5157        bool permanent = (fields[1].GetUInt64() == (uint64)0);
5158        std::string bantime = permanent?GetTrinityString(LANG_BANINFO_INFINITE):secsToTimeString(fields[1].GetUInt64(), true);
5159        PSendSysMessage(LANG_BANINFO_HISTORYENTRY,
5160            fields[0].GetString(), bantime.c_str(), active ? GetTrinityString(LANG_BANINFO_YES):GetTrinityString(LANG_BANINFO_NO), fields[4].GetString(), fields[5].GetString());
5161    }while (result->NextRow());
5162
5163    delete result;
5164    return true;
5165}
5166
5167bool ChatHandler::HandleBanInfoIPCommand(const char* args)
5168{
5169    if(!args)
5170        return false;
5171
5172    char* cIP = strtok ((char*)args, "");
5173    if(!cIP)
5174        return false;
5175
5176    if (!IsIPAddress(cIP))
5177        return false;
5178
5179    std::string IP = cIP;
5180
5181    loginDatabase.escape_string(IP);
5182    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());
5183    if(!result)
5184    {
5185        PSendSysMessage(LANG_BANINFO_NOIP);
5186        return true;
5187    }
5188
5189    Field *fields = result->Fetch();
5190    bool permanent = !fields[6].GetUInt64();
5191    PSendSysMessage(LANG_BANINFO_IPENTRY,
5192        fields[0].GetString(), fields[1].GetString(), permanent ? GetTrinityString(LANG_BANINFO_NEVER):fields[2].GetString(),
5193        permanent ? GetTrinityString(LANG_BANINFO_INFINITE):secsToTimeString(fields[3].GetUInt64(), true).c_str(), fields[4].GetString(), fields[5].GetString());
5194    delete result;
5195    return true;
5196}
5197
5198bool ChatHandler::HandleBanListCharacterCommand(const char* args)
5199{
5200    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
5201
5202    char* cFilter = strtok ((char*)args, " ");
5203    if(!cFilter)
5204        return false;
5205
5206    std::string filter = cFilter;
5207    loginDatabase.escape_string(filter);
5208    QueryResult* result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'"),filter.c_str());
5209    if (!result)
5210    {
5211        PSendSysMessage(LANG_BANLIST_NOCHARACTER);
5212        return true;
5213    }
5214
5215    return HandleBanListHelper(result);
5216}
5217
5218bool ChatHandler::HandleBanListAccountCommand(const char* args)
5219{
5220    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
5221
5222    char* cFilter = strtok((char*)args, " ");
5223    std::string filter = cFilter ? cFilter : "";
5224    loginDatabase.escape_string(filter);
5225
5226    QueryResult* result;
5227
5228    if(filter.empty())
5229    {
5230        result = loginDatabase.Query("SELECT account.id, username FROM account, account_banned"
5231            " WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id");
5232    }
5233    else
5234    {
5235        result = loginDatabase.PQuery("SELECT account.id, username FROM account, account_banned"
5236            " WHERE account.id = account_banned.id AND active = 1 AND username "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'")" GROUP BY account.id",
5237            filter.c_str());
5238    }
5239
5240    if (!result)
5241    {
5242        PSendSysMessage(LANG_BANLIST_NOACCOUNT);
5243        return true;
5244    }
5245
5246    return HandleBanListHelper(result);
5247}
5248
5249bool ChatHandler::HandleBanListHelper(QueryResult* result)
5250{
5251    PSendSysMessage(LANG_BANLIST_MATCHINGACCOUNT);
5252
5253    // Chat short output
5254    if(m_session)
5255    {
5256        do
5257        {
5258            Field* fields = result->Fetch();
5259            uint32 accountid = fields[0].GetUInt32();
5260
5261            QueryResult* banresult = loginDatabase.PQuery("SELECT account.username FROM account,account_banned WHERE account_banned.id='%u' AND account_banned.id=account.id",accountid);
5262            if(banresult)
5263            {
5264                Field* fields2 = banresult->Fetch();
5265                PSendSysMessage("%s",fields2[0].GetString());
5266                delete banresult;
5267            }
5268        } while (result->NextRow());
5269    }
5270    // Console wide output
5271    else
5272    {
5273        SendSysMessage(LANG_BANLIST_ACCOUNTS);
5274        SendSysMessage("===============================================================================");
5275        SendSysMessage(LANG_BANLIST_ACCOUNTS_HEADER);
5276        do
5277        {
5278            SendSysMessage("-------------------------------------------------------------------------------");
5279            Field *fields = result->Fetch();
5280            uint32 account_id = fields[0].GetUInt32 ();
5281
5282            std::string account_name;
5283
5284            // "account" case, name can be get in same query
5285            if(result->GetFieldCount() > 1)
5286                account_name = fields[1].GetCppString();
5287            // "character" case, name need extract from another DB
5288            else
5289                accmgr.GetName (account_id,account_name);
5290
5291            // No SQL injection. id is uint32.
5292            QueryResult *banInfo = loginDatabase.PQuery("SELECT bandate,unbandate,bannedby,banreason FROM account_banned WHERE id = %u ORDER BY unbandate", account_id);
5293            if (banInfo)
5294            {
5295                Field *fields2 = banInfo->Fetch();
5296                do
5297                {
5298                    time_t t_ban = fields2[0].GetUInt64();
5299                    tm* aTm_ban = localtime(&t_ban);
5300
5301                    if (fields2[0].GetUInt64() == fields2[1].GetUInt64())
5302                    {
5303                        PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|   permanent  |%-15.15s|%-15.15s|",
5304                            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,
5305                            fields2[2].GetString(),fields2[3].GetString());
5306                    }
5307                    else
5308                    {
5309                        time_t t_unban = fields2[1].GetUInt64();
5310                        tm* aTm_unban = localtime(&t_unban);
5311                        PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-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                            aTm_unban->tm_year%100, aTm_unban->tm_mon+1, aTm_unban->tm_mday, aTm_unban->tm_hour, aTm_unban->tm_min,
5314                            fields2[2].GetString(),fields2[3].GetString());
5315                    }
5316                }while ( banInfo->NextRow() );
5317                delete banInfo;
5318            }
5319        }while( result->NextRow() );
5320        SendSysMessage("===============================================================================");
5321    }
5322
5323    delete result;
5324    return true;
5325}
5326
5327bool ChatHandler::HandleBanListIPCommand(const char* args)
5328{
5329    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
5330
5331    char* cFilter = strtok((char*)args, " ");
5332    std::string filter = cFilter ? cFilter : "";
5333    loginDatabase.escape_string(filter);
5334
5335    QueryResult* result;
5336
5337    if(filter.empty())
5338    {
5339        result = loginDatabase.Query ("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned"
5340            " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP())"
5341            " ORDER BY unbandate" );
5342    }
5343    else
5344    {
5345        result = loginDatabase.PQuery( "SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned"
5346            " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP()) AND ip "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'")
5347            " ORDER BY unbandate",filter.c_str() );
5348    }
5349
5350    if(!result)
5351    {
5352        PSendSysMessage(LANG_BANLIST_NOIP);
5353        return true;
5354    }
5355
5356    PSendSysMessage(LANG_BANLIST_MATCHINGIP);
5357    // Chat short output
5358    if(m_session)
5359    {
5360        do
5361        {
5362            Field* fields = result->Fetch();
5363            PSendSysMessage("%s",fields[0].GetString());
5364        } while (result->NextRow());
5365    }
5366    // Console wide output
5367    else
5368    {
5369        SendSysMessage(LANG_BANLIST_IPS);
5370        SendSysMessage("===============================================================================");
5371        SendSysMessage(LANG_BANLIST_IPS_HEADER);
5372        do
5373        {
5374            SendSysMessage("-------------------------------------------------------------------------------");
5375            Field *fields = result->Fetch();
5376            time_t t_ban = fields[1].GetUInt64();
5377            tm* aTm_ban = localtime(&t_ban);
5378            if ( fields[1].GetUInt64() == fields[2].GetUInt64() )
5379            {
5380                PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|   permanent  |%-15.15s|%-15.15s|",
5381                    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,
5382                    fields[3].GetString(), fields[4].GetString());
5383            }
5384            else
5385            {
5386                time_t t_unban = fields[2].GetUInt64();
5387                tm* aTm_unban = localtime(&t_unban);
5388                PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-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                    aTm_unban->tm_year%100, aTm_unban->tm_mon+1, aTm_unban->tm_mday, aTm_unban->tm_hour, aTm_unban->tm_min,
5391                    fields[3].GetString(), fields[4].GetString());
5392            }
5393        }while( result->NextRow() );
5394        SendSysMessage("===============================================================================");
5395    }
5396
5397    delete result;
5398    return true;
5399}
5400
5401bool ChatHandler::HandleRespawnCommand(const char* /*args*/)
5402{
5403    Player* pl = m_session->GetPlayer();
5404
5405    // accept only explicitly selected target (not implicitly self targeting case)
5406    Unit* target = getSelectedUnit();
5407    if(pl->GetSelection() && target)
5408    {
5409        if(target->GetTypeId()!=TYPEID_UNIT)
5410        {
5411            SendSysMessage(LANG_SELECT_CREATURE);
5412            SetSentErrorMessage(true);
5413            return false;
5414        }
5415
5416        if(target->isDead())
5417            ((Creature*)target)->Respawn();
5418        return true;
5419    }
5420
5421    CellPair p(Trinity::ComputeCellPair(pl->GetPositionX(), pl->GetPositionY()));
5422    Cell cell(p);
5423    cell.data.Part.reserved = ALL_DISTRICT;
5424    cell.SetNoCreate();
5425
5426    Trinity::RespawnDo u_do;
5427    Trinity::WorldObjectWorker<Trinity::RespawnDo> worker(u_do);
5428
5429    TypeContainerVisitor<Trinity::WorldObjectWorker<Trinity::RespawnDo>, GridTypeMapContainer > obj_worker(worker);
5430    CellLock<GridReadGuard> cell_lock(cell, p);
5431    cell_lock->Visit(cell_lock, obj_worker, *MapManager::Instance().GetMap(pl->GetMapId(), pl));
5432
5433    return true;
5434}
5435
5436bool ChatHandler::HandleFlyModeCommand(const char* args)
5437{
5438    if(!args)
5439        return false;
5440
5441    Unit *unit = getSelectedUnit();
5442    if (!unit || (unit->GetTypeId() != TYPEID_PLAYER))
5443        unit = m_session->GetPlayer();
5444
5445    WorldPacket data(12);
5446    if (strncmp(args, "on", 3) == 0)
5447        data.SetOpcode(SMSG_MOVE_SET_CAN_FLY);
5448    else if (strncmp(args, "off", 4) == 0)
5449        data.SetOpcode(SMSG_MOVE_UNSET_CAN_FLY);
5450    else
5451    {
5452        SendSysMessage(LANG_USE_BOL);
5453        return false;
5454    }
5455    data.append(unit->GetPackGUID());
5456    data << uint32(0);                                      // unknown
5457    unit->SendMessageToSet(&data, true);
5458    PSendSysMessage(LANG_COMMAND_FLYMODE_STATUS, unit->GetName(), args);
5459    return true;
5460}
5461
5462bool ChatHandler::HandleLoadPDumpCommand(const char *args)
5463{
5464    if(!args)
5465        return false;
5466
5467    char * file = strtok((char*)args, " ");
5468    if(!file)
5469        return false;
5470
5471    char * account = strtok(NULL, " ");
5472    if(!account)
5473        return false;
5474
5475    std::string account_name = account;
5476    if(!AccountMgr::normilizeString(account_name))
5477    {
5478        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5479        SetSentErrorMessage(true);
5480        return false;
5481    }
5482
5483    uint32 account_id = accmgr.GetId(account_name);
5484    if(!account_id)
5485    {
5486        account_id = atoi(account);                             // use original string
5487        if(!account_id)
5488        {
5489            PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5490            SetSentErrorMessage(true);
5491            return false;
5492        }
5493    }
5494
5495    if(!accmgr.GetName(account_id,account_name))
5496    {
5497        PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
5498        SetSentErrorMessage(true);
5499        return false;
5500    }
5501
5502    char* guid_str = NULL;
5503    char* name_str = strtok(NULL, " ");
5504
5505    std::string name;
5506    if(name_str)
5507    {
5508        name = name_str;
5509        // normalize the name if specified and check if it exists
5510        if(!normalizePlayerName(name))
5511        {
5512            PSendSysMessage(LANG_INVALID_CHARACTER_NAME);
5513            SetSentErrorMessage(true);
5514            return false;
5515        }
5516
5517        if(!ObjectMgr::IsValidName(name,true))
5518        {
5519            PSendSysMessage(LANG_INVALID_CHARACTER_NAME);
5520            SetSentErrorMessage(true);
5521            return false;
5522        }
5523
5524        guid_str = strtok(NULL, " ");
5525    }
5526
5527    uint32 guid = 0;
5528
5529    if(guid_str)
5530    {
5531        guid = atoi(guid_str);
5532        if(!guid)
5533        {
5534            PSendSysMessage(LANG_INVALID_CHARACTER_GUID);
5535            SetSentErrorMessage(true);
5536            return false;
5537        }
5538
5539        if(objmgr.GetPlayerAccountIdByGUID(guid))
5540        {
5541            PSendSysMessage(LANG_CHARACTER_GUID_IN_USE,guid);
5542            SetSentErrorMessage(true);
5543            return false;
5544        }
5545    }
5546
5547    switch(PlayerDumpReader().LoadDump(file, account_id, name, guid))
5548    {
5549        case DUMP_SUCCESS:
5550            PSendSysMessage(LANG_COMMAND_IMPORT_SUCCESS);
5551            break;
5552        case DUMP_FILE_OPEN_ERROR:
5553            PSendSysMessage(LANG_FILE_OPEN_FAIL,file);
5554            SetSentErrorMessage(true);
5555            return false;
5556        case DUMP_FILE_BROKEN:
5557            PSendSysMessage(LANG_DUMP_BROKEN,file);
5558            SetSentErrorMessage(true);
5559            return false;
5560        case DUMP_TOO_MANY_CHARS:
5561            PSendSysMessage(LANG_ACCOUNT_CHARACTER_LIST_FULL,account_name.c_str(),account_id);
5562            SetSentErrorMessage(true);
5563            return false;
5564        default:
5565            PSendSysMessage(LANG_COMMAND_IMPORT_FAILED);
5566            SetSentErrorMessage(true);
5567            return false;
5568    }
5569
5570    return true;
5571}
5572
5573bool ChatHandler::HandleNpcChangeEntryCommand(const char *args)
5574{
5575    if(!args)
5576        return false;
5577
5578    uint32 newEntryNum = atoi(args);
5579    if(!newEntryNum)
5580        return false;
5581
5582    Unit* unit = getSelectedUnit();
5583    if(!unit || unit->GetTypeId() != TYPEID_UNIT)
5584    {
5585        SendSysMessage(LANG_SELECT_CREATURE);
5586        SetSentErrorMessage(true);
5587        return false;
5588    }
5589    Creature* creature = (Creature*)unit;
5590    if(creature->UpdateEntry(newEntryNum))
5591        SendSysMessage(LANG_DONE);
5592    else
5593        SendSysMessage(LANG_ERROR);
5594    return true;
5595}
5596
5597bool ChatHandler::HandleWritePDumpCommand(const char *args)
5598{
5599    if(!args)
5600        return false;
5601
5602    char* file = strtok((char*)args, " ");
5603    char* p2 = strtok(NULL, " ");
5604
5605    if(!file || !p2)
5606        return false;
5607
5608    uint32 guid = objmgr.GetPlayerGUIDByName(p2);
5609    if(!guid)
5610        guid = atoi(p2);
5611
5612    if(!objmgr.GetPlayerAccountIdByGUID(guid))
5613    {
5614        PSendSysMessage(LANG_PLAYER_NOT_FOUND);
5615        SetSentErrorMessage(true);
5616        return false;
5617    }
5618
5619    switch(PlayerDumpWriter().WriteDump(file, guid))
5620    {
5621        case DUMP_SUCCESS:
5622            PSendSysMessage(LANG_COMMAND_EXPORT_SUCCESS);
5623            break;
5624        case DUMP_FILE_OPEN_ERROR:
5625            PSendSysMessage(LANG_FILE_OPEN_FAIL,file);
5626            SetSentErrorMessage(true);
5627            return false;
5628        default:
5629            PSendSysMessage(LANG_COMMAND_EXPORT_FAILED);
5630            SetSentErrorMessage(true);
5631            return false;
5632    }
5633
5634    return true;
5635}
5636
5637bool ChatHandler::HandleMovegensCommand(const char* /*args*/)
5638{
5639    Unit* unit = getSelectedUnit();
5640    if(!unit)
5641    {
5642        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5643        SetSentErrorMessage(true);
5644        return false;
5645    }
5646
5647    PSendSysMessage(LANG_MOVEGENS_LIST,(unit->GetTypeId()==TYPEID_PLAYER ? "Player" : "Creature" ),unit->GetGUIDLow());
5648
5649    MotionMaster* mm = unit->GetMotionMaster();
5650    for(MotionMaster::const_iterator itr = mm->begin(); itr != mm->end(); ++itr)
5651    {
5652        switch((*itr)->GetMovementGeneratorType())
5653        {
5654            case IDLE_MOTION_TYPE:          SendSysMessage(LANG_MOVEGENS_IDLE);          break;
5655            case RANDOM_MOTION_TYPE:        SendSysMessage(LANG_MOVEGENS_RANDOM);        break;
5656            case WAYPOINT_MOTION_TYPE:      SendSysMessage(LANG_MOVEGENS_WAYPOINT);      break;
5657            case ANIMAL_RANDOM_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_ANIMAL_RANDOM); break;
5658            case CONFUSED_MOTION_TYPE:      SendSysMessage(LANG_MOVEGENS_CONFUSED);      break;
5659            case TARGETED_MOTION_TYPE:
5660            {
5661                if(unit->GetTypeId()==TYPEID_PLAYER)
5662                {
5663                    TargetedMovementGenerator<Player> const* mgen = static_cast<TargetedMovementGenerator<Player> const*>(*itr);
5664                    Unit* target = mgen->GetTarget();
5665                    if(target)
5666                        PSendSysMessage(LANG_MOVEGENS_TARGETED_PLAYER,target->GetName(),target->GetGUIDLow());
5667                    else
5668                        SendSysMessage(LANG_MOVEGENS_TARGETED_NULL);
5669                }
5670                else
5671                {
5672                    TargetedMovementGenerator<Creature> const* mgen = static_cast<TargetedMovementGenerator<Creature> const*>(*itr);
5673                    Unit* target = mgen->GetTarget();
5674                    if(target)
5675                        PSendSysMessage(LANG_MOVEGENS_TARGETED_CREATURE,target->GetName(),target->GetGUIDLow());
5676                    else
5677                        SendSysMessage(LANG_MOVEGENS_TARGETED_NULL);
5678                }
5679                break;
5680            }
5681            case HOME_MOTION_TYPE:
5682                if(unit->GetTypeId()==TYPEID_UNIT)
5683                {
5684                    float x,y,z;
5685                    (*itr)->GetDestination(x,y,z);
5686                    PSendSysMessage(LANG_MOVEGENS_HOME_CREATURE,x,y,z);
5687                }
5688                else
5689                    SendSysMessage(LANG_MOVEGENS_HOME_PLAYER);
5690                break;
5691            case FLIGHT_MOTION_TYPE:   SendSysMessage(LANG_MOVEGENS_FLIGHT);  break;
5692            case POINT_MOTION_TYPE:
5693            {
5694                float x,y,z;
5695                (*itr)->GetDestination(x,y,z);
5696                PSendSysMessage(LANG_MOVEGENS_POINT,x,y,z);
5697                break;
5698            }
5699            case FLEEING_MOTION_TYPE:  SendSysMessage(LANG_MOVEGENS_FEAR);    break;
5700            case DISTRACT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_DISTRACT);  break;
5701            default:
5702                PSendSysMessage(LANG_MOVEGENS_UNKNOWN,(*itr)->GetMovementGeneratorType());
5703                break;
5704        }
5705    }
5706    return true;
5707}
5708
5709bool ChatHandler::HandlePLimitCommand(const char *args)
5710{
5711    if(*args)
5712    {
5713        char* param = strtok((char*)args, " ");
5714        if(!param)
5715            return false;
5716
5717        int l = strlen(param);
5718
5719        if(     strncmp(param,"player",l) == 0 )
5720            sWorld.SetPlayerLimit(-SEC_PLAYER);
5721        else if(strncmp(param,"moderator",l) == 0 )
5722            sWorld.SetPlayerLimit(-SEC_MODERATOR);
5723        else if(strncmp(param,"gamemaster",l) == 0 )
5724            sWorld.SetPlayerLimit(-SEC_GAMEMASTER);
5725        else if(strncmp(param,"administrator",l) == 0 )
5726            sWorld.SetPlayerLimit(-SEC_ADMINISTRATOR);
5727        else if(strncmp(param,"reset",l) == 0 )
5728            sWorld.SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT) );
5729        else
5730        {
5731            int val = atoi(param);
5732            if(val < -SEC_ADMINISTRATOR) val = -SEC_ADMINISTRATOR;
5733
5734            sWorld.SetPlayerLimit(val);
5735        }
5736
5737        // kick all low security level players
5738        if(sWorld.GetPlayerAmountLimit() > SEC_PLAYER)
5739            sWorld.KickAllLess(sWorld.GetPlayerSecurityLimit());
5740    }
5741
5742    uint32 pLimit = sWorld.GetPlayerAmountLimit();
5743    AccountTypes allowedAccountType = sWorld.GetPlayerSecurityLimit();
5744    char const* secName = "";
5745    switch(allowedAccountType)
5746    {
5747        case SEC_PLAYER:        secName = "Player";        break;
5748        case SEC_MODERATOR:     secName = "Moderator";     break;
5749        case SEC_GAMEMASTER:    secName = "Gamemaster";    break;
5750        case SEC_ADMINISTRATOR: secName = "Administrator"; break;
5751        default:                secName = "<unknown>";     break;
5752    }
5753
5754    PSendSysMessage("Player limits: amount %u, min. security level %s.",pLimit,secName);
5755
5756    return true;
5757}
5758
5759bool ChatHandler::HandleCastCommand(const char* args)
5760{
5761    if(!*args)
5762        return false;
5763
5764    Unit* target = getSelectedUnit();
5765
5766    if(!target)
5767    {
5768        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5769        SetSentErrorMessage(true);
5770        return false;
5771    }
5772
5773    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5774    uint32 spell = extractSpellIdFromLink((char*)args);
5775    if(!spell)
5776        return false;
5777
5778    SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
5779    if(!spellInfo)
5780        return false;
5781
5782    if(!SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
5783    {
5784        PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
5785        SetSentErrorMessage(true);
5786        return false;
5787    }
5788
5789    char* trig_str = strtok(NULL, " ");
5790    if(trig_str)
5791    {
5792        int l = strlen(trig_str);
5793        if(strncmp(trig_str,"triggered",l) != 0 )
5794            return false;
5795    }
5796
5797    bool triggered = (trig_str != NULL);
5798
5799    m_session->GetPlayer()->CastSpell(target,spell,triggered);
5800
5801    return true;
5802}
5803
5804bool ChatHandler::HandleCastBackCommand(const char* args)
5805{
5806    Creature* caster = getSelectedCreature();
5807
5808    if(!caster)
5809    {
5810        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5811        SetSentErrorMessage(true);
5812        return false;
5813    }
5814
5815    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r
5816    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5817    uint32 spell = extractSpellIdFromLink((char*)args);
5818    if(!spell || !sSpellStore.LookupEntry(spell))
5819        return false;
5820
5821    char* trig_str = strtok(NULL, " ");
5822    if(trig_str)
5823    {
5824        int l = strlen(trig_str);
5825        if(strncmp(trig_str,"triggered",l) != 0 )
5826            return false;
5827    }
5828
5829    bool triggered = (trig_str != NULL);
5830
5831    // update orientation at server
5832    caster->SetOrientation(caster->GetAngle(m_session->GetPlayer()));
5833
5834    // and client
5835    WorldPacket data;
5836    caster->BuildHeartBeatMsg(&data);
5837    caster->SendMessageToSet(&data,true);
5838
5839    caster->CastSpell(m_session->GetPlayer(),spell,triggered);
5840
5841    return true;
5842}
5843
5844bool ChatHandler::HandleCastDistCommand(const char* args)
5845{
5846    if(!*args)
5847        return false;
5848
5849    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5850    uint32 spell = extractSpellIdFromLink((char*)args);
5851    if(!spell)
5852        return false;
5853
5854    SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
5855    if(!spellInfo)
5856        return false;
5857
5858    if(!SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
5859    {
5860        PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
5861        SetSentErrorMessage(true);
5862        return false;
5863    }
5864
5865    char *distStr = strtok(NULL, " ");
5866
5867    float dist = 0;
5868
5869    if(distStr)
5870        sscanf(distStr, "%f", &dist);
5871
5872    char* trig_str = strtok(NULL, " ");
5873    if(trig_str)
5874    {
5875        int l = strlen(trig_str);
5876        if(strncmp(trig_str,"triggered",l) != 0 )
5877            return false;
5878    }
5879
5880    bool triggered = (trig_str != NULL);
5881
5882    float x,y,z;
5883    m_session->GetPlayer()->GetClosePoint(x,y,z,dist);
5884
5885    m_session->GetPlayer()->CastSpell(x,y,z,spell,triggered);
5886    return true;
5887}
5888
5889bool ChatHandler::HandleCastTargetCommand(const char* args)
5890{
5891    Creature* caster = getSelectedCreature();
5892
5893    if(!caster)
5894    {
5895        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5896        SetSentErrorMessage(true);
5897        return false;
5898    }
5899
5900    if(!caster->getVictim())
5901    {
5902        SendSysMessage(LANG_SELECTED_TARGET_NOT_HAVE_VICTIM);
5903        SetSentErrorMessage(true);
5904        return false;
5905    }
5906
5907    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5908    uint32 spell = extractSpellIdFromLink((char*)args);
5909    if(!spell || !sSpellStore.LookupEntry(spell))
5910        return false;
5911
5912    char* trig_str = strtok(NULL, " ");
5913    if(trig_str)
5914    {
5915        int l = strlen(trig_str);
5916        if(strncmp(trig_str,"triggered",l) != 0 )
5917            return false;
5918    }
5919
5920    bool triggered = (trig_str != NULL);
5921
5922    // update orientation at server
5923    caster->SetOrientation(caster->GetAngle(m_session->GetPlayer()));
5924
5925    // and client
5926    WorldPacket data;
5927    caster->BuildHeartBeatMsg(&data);
5928    caster->SendMessageToSet(&data,true);
5929
5930    caster->CastSpell(caster->getVictim(),spell,triggered);
5931
5932    return true;
5933}
5934
5935/*
5936ComeToMe command REQUIRED for 3rd party scripting library to have access to PointMovementGenerator
5937Without this function 3rd party scripting library will get linking errors (unresolved external)
5938when attempting to use the PointMovementGenerator
5939*/
5940bool ChatHandler::HandleComeToMeCommand(const char *args)
5941{
5942    Creature* caster = getSelectedCreature();
5943
5944    if(!caster)
5945    {
5946        SendSysMessage(LANG_SELECT_CREATURE);
5947        SetSentErrorMessage(true);
5948        return false;
5949    }
5950
5951    char* newFlagStr = strtok((char*)args, " ");
5952
5953    if(!newFlagStr)
5954        return false;
5955
5956    uint32 newFlags = atoi(newFlagStr);
5957
5958    caster->SetUnitMovementFlags(newFlags);
5959
5960    Player* pl = m_session->GetPlayer();
5961
5962    caster->GetMotionMaster()->MovePoint(0, pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ());
5963    return true;
5964}
5965
5966bool ChatHandler::HandleCastSelfCommand(const char* args)
5967{
5968    if(!*args)
5969        return false;
5970
5971    Unit* target = getSelectedUnit();
5972
5973    if(!target)
5974    {
5975        SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
5976        SetSentErrorMessage(true);
5977        return false;
5978    }
5979
5980    // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form
5981    uint32 spell = extractSpellIdFromLink((char*)args);
5982    if(!spell)
5983        return false;
5984
5985    SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell);
5986    if(!spellInfo)
5987        return false;
5988
5989    if(!SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer()))
5990    {
5991        PSendSysMessage(LANG_COMMAND_SPELL_BROKEN,spell);
5992        SetSentErrorMessage(true);
5993        return false;
5994    }
5995
5996    target->CastSpell(target,spell,false);
5997
5998    return true;
5999}
6000
6001std::string GetTimeString(uint32 time)
6002{
6003    uint16 days = time / DAY, hours = (time % DAY) / HOUR, minute = (time % HOUR) / MINUTE;
6004    std::ostringstream ss;
6005    if(days) ss << days << "d ";
6006    if(hours) ss << hours << "h ";
6007    ss << minute << "m";
6008    return ss.str();
6009}
6010
6011bool ChatHandler::HandleInstanceListBindsCommand(const char* /*args*/)
6012{
6013    Player* player = getSelectedPlayer();
6014    if (!player) player = m_session->GetPlayer();
6015    uint32 counter = 0;
6016    for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
6017    {
6018        Player::BoundInstancesMap &binds = player->GetBoundInstances(i);
6019        for(Player::BoundInstancesMap::iterator itr = binds.begin(); itr != binds.end(); ++itr)
6020        {
6021            InstanceSave *save = itr->second.save;
6022            std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL));
6023            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());
6024            counter++;
6025        }
6026    }
6027    PSendSysMessage("player binds: %d", counter);
6028    counter = 0;
6029    Group *group = player->GetGroup();
6030    if(group)
6031    {
6032        for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
6033        {
6034            Group::BoundInstancesMap &binds = group->GetBoundInstances(i);
6035            for(Group::BoundInstancesMap::iterator itr = binds.begin(); itr != binds.end(); ++itr)
6036            {
6037                InstanceSave *save = itr->second.save;
6038                std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL));
6039                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());
6040                counter++;
6041            }
6042        }
6043    }
6044    PSendSysMessage("group binds: %d", counter);
6045
6046    return true;
6047}
6048
6049bool ChatHandler::HandleInstanceUnbindCommand(const char* args)
6050{
6051    if(!*args)
6052        return false;
6053
6054    std::string cmd = args;
6055    if(cmd == "all")
6056    {
6057        Player* player = getSelectedPlayer();
6058        if (!player) player = m_session->GetPlayer();
6059        uint32 counter = 0;
6060        for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
6061        {
6062            Player::BoundInstancesMap &binds = player->GetBoundInstances(i);
6063            for(Player::BoundInstancesMap::iterator itr = binds.begin(); itr != binds.end();)
6064            {
6065                if(itr->first != player->GetMapId())
6066                {
6067                    InstanceSave *save = itr->second.save;
6068                    std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL));
6069                    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());
6070                    player->UnbindInstance(itr, i);
6071                    counter++;
6072                }
6073                else
6074                    ++itr;
6075            }
6076        }
6077        PSendSysMessage("instances unbound: %d", counter);
6078    }
6079    return true;
6080}
6081
6082bool ChatHandler::HandleInstanceStatsCommand(const char* /*args*/)
6083{
6084    PSendSysMessage("instances loaded: %d", MapManager::Instance().GetNumInstances());
6085    PSendSysMessage("players in instances: %d", MapManager::Instance().GetNumPlayersInInstances());
6086    PSendSysMessage("instance saves: %d", sInstanceSaveManager.GetNumInstanceSaves());
6087    PSendSysMessage("players bound: %d", sInstanceSaveManager.GetNumBoundPlayersTotal());
6088    PSendSysMessage("groups bound: %d", sInstanceSaveManager.GetNumBoundGroupsTotal());
6089    return true;
6090}
6091
6092bool ChatHandler::HandleInstanceSaveDataCommand(const char * /*args*/)
6093{
6094    Player* pl = m_session->GetPlayer();
6095
6096    Map* map = pl->GetMap();
6097    if (!map->IsDungeon())
6098    {
6099        PSendSysMessage("Map is not a dungeon.");
6100        SetSentErrorMessage(true);
6101        return false;
6102    }
6103
6104    if (!((InstanceMap*)map)->GetInstanceData())
6105    {
6106        PSendSysMessage("Map has no instance data.");
6107        SetSentErrorMessage(true);
6108        return false;
6109    }
6110
6111    ((InstanceMap*)map)->GetInstanceData()->SaveToDB();
6112    return true;
6113}
6114
6115/// Display the list of GMs
6116bool ChatHandler::HandleGMListFullCommand(const char* /*args*/)
6117{
6118    ///- Get the accounts with GM Level >0
6119    QueryResult *result = loginDatabase.Query( "SELECT username,gmlevel FROM account WHERE gmlevel > 0" );
6120    if(result)
6121    {
6122        SendSysMessage(LANG_GMLIST);
6123        SendSysMessage("========================");
6124        SendSysMessage(LANG_GMLIST_HEADER);
6125        SendSysMessage("========================");
6126
6127        ///- Circle through them. Display username and GM level
6128        do
6129        {
6130            Field *fields = result->Fetch();
6131            PSendSysMessage("|%15s|%6s|", fields[0].GetString(),fields[1].GetString());
6132        }while( result->NextRow() );
6133
6134        PSendSysMessage("========================");
6135        delete result;
6136    }
6137    else
6138        PSendSysMessage(LANG_GMLIST_EMPTY);
6139    return true;
6140}
6141
6142/// Define the 'Message of the day' for the realm
6143bool ChatHandler::HandleServerSetMotdCommand(const char* args)
6144{
6145    sWorld.SetMotd(args);
6146    PSendSysMessage(LANG_MOTD_NEW, args);
6147    return true;
6148}
6149
6150/// Set/Unset the expansion level for an account
6151bool ChatHandler::HandleAccountSetAddonCommand(const char* args)
6152{
6153    ///- Get the command line arguments
6154    char *szAcc = strtok((char*)args," ");
6155    char *szExp = strtok(NULL," ");
6156
6157    if(!szAcc)
6158        return false;
6159
6160    std::string account_name;
6161    uint32 account_id;
6162
6163    if(!szExp)
6164    {
6165        Player* player = getSelectedPlayer();
6166        if(!player)
6167            return false;
6168
6169        account_id = player->GetSession()->GetAccountId();
6170        accmgr.GetName(account_id,account_name);
6171        szExp = szAcc;
6172    }
6173    else
6174    {
6175        ///- Convert Account name to Upper Format
6176        account_name = szAcc;
6177        if(!AccountMgr::normilizeString(account_name))
6178        {
6179            PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
6180            SetSentErrorMessage(true);
6181            return false;
6182        }
6183
6184        account_id = accmgr.GetId(account_name);
6185        if(!account_id)
6186        {
6187            PSendSysMessage(LANG_ACCOUNT_NOT_EXIST,account_name.c_str());
6188            SetSentErrorMessage(true);
6189            return false;
6190        }
6191    }
6192
6193    int lev=atoi(szExp);                                    //get int anyway (0 if error)
6194    if(lev < 0)
6195        return false;
6196
6197    // No SQL injection
6198    loginDatabase.PExecute("UPDATE account SET expansion = '%d' WHERE id = '%u'",lev,account_id);
6199    PSendSysMessage(LANG_ACCOUNT_SETADDON,account_name.c_str(),account_id,lev);
6200    return true;
6201}
6202
6203//Send items by mail
6204bool ChatHandler::HandleSendItemsCommand(const char* args)
6205{
6206    if(!*args)
6207        return false;
6208
6209    // format: name "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12]
6210
6211    char* pName = strtok((char*)args, " ");
6212    if(!pName)
6213        return false;
6214
6215    char* tail1 = strtok(NULL, "");
6216    if(!tail1)
6217        return false;
6218
6219    char* msgSubject;
6220    if(*tail1=='"')
6221        msgSubject = strtok(tail1+1, "\"");
6222    else
6223    {
6224        char* space = strtok(tail1, "\"");
6225        if(!space)
6226            return false;
6227        msgSubject = strtok(NULL, "\"");
6228    }
6229
6230    if (!msgSubject)
6231        return false;
6232
6233    char* tail2 = strtok(NULL, "");
6234    if(!tail2)
6235        return false;
6236
6237    char* msgText;
6238    if(*tail2=='"')
6239        msgText = strtok(tail2+1, "\"");
6240    else
6241    {
6242        char* space = strtok(tail2, "\"");
6243        if(!space)
6244            return false;
6245        msgText = strtok(NULL, "\"");
6246    }
6247
6248    if (!msgText)
6249        return false;
6250
6251    // pName, msgSubject, msgText isn't NUL after prev. check
6252    std::string name    = pName;
6253    std::string subject = msgSubject;
6254    std::string text    = msgText;
6255
6256    // extract items
6257    typedef std::pair<uint32,uint32> ItemPair;
6258    typedef std::list< ItemPair > ItemPairs;
6259    ItemPairs items;
6260
6261    // get all tail string
6262    char* tail = strtok(NULL, "");
6263
6264    // get from tail next item str
6265    while(char* itemStr = strtok(tail, " "))
6266    {
6267        // and get new tail
6268        tail = strtok(NULL, "");
6269
6270        // parse item str
6271        char* itemIdStr = strtok(itemStr, ":");
6272        char* itemCountStr = strtok(NULL, " ");
6273
6274        uint32 item_id = atoi(itemIdStr);
6275        if(!item_id)
6276            return false;
6277
6278        ItemPrototype const* item_proto = objmgr.GetItemPrototype(item_id);
6279        if(!item_proto)
6280        {
6281            PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id);
6282            SetSentErrorMessage(true);
6283            return false;
6284        }
6285
6286        uint32 item_count = itemCountStr ? atoi(itemCountStr) : 1;
6287        if(item_count < 1 || item_proto->MaxCount && item_count > item_proto->MaxCount)
6288        {
6289            PSendSysMessage(LANG_COMMAND_INVALID_ITEM_COUNT, item_count,item_id);
6290            SetSentErrorMessage(true);
6291            return false;
6292        }
6293
6294        while(item_count > item_proto->Stackable)
6295        {
6296            items.push_back(ItemPair(item_id,item_proto->Stackable));
6297            item_count -= item_proto->Stackable;
6298        }
6299
6300        items.push_back(ItemPair(item_id,item_count));
6301
6302        if(items.size() > MAX_MAIL_ITEMS)
6303        {
6304            PSendSysMessage(LANG_COMMAND_MAIL_ITEMS_LIMIT, MAX_MAIL_ITEMS);
6305            SetSentErrorMessage(true);
6306            return false;
6307        }
6308    }
6309
6310    if(!normalizePlayerName(name))
6311    {
6312        SendSysMessage(LANG_PLAYER_NOT_FOUND);
6313        SetSentErrorMessage(true);
6314        return false;
6315    }
6316
6317    uint64 receiver_guid = objmgr.GetPlayerGUIDByName(name);
6318    if(!receiver_guid)
6319    {
6320        SendSysMessage(LANG_PLAYER_NOT_FOUND);
6321        SetSentErrorMessage(true);
6322        return false;
6323    }
6324
6325    // from console show not existed sender
6326    uint32 sender_guidlo = m_session ? m_session->GetPlayer()->GetGUIDLow() : 0;
6327
6328    uint32 messagetype = MAIL_NORMAL;
6329    uint32 stationery = MAIL_STATIONERY_GM;
6330    uint32 itemTextId = !text.empty() ? objmgr.CreateItemText( text ) : 0;
6331
6332    Player *receiver = objmgr.GetPlayer(receiver_guid);
6333
6334    // fill mail
6335    MailItemsInfo mi;                                       // item list preparing
6336
6337    for(ItemPairs::const_iterator itr = items.begin(); itr != items.end(); ++itr)
6338    {
6339        if(Item* item = Item::CreateItem(itr->first,itr->second,m_session ? m_session->GetPlayer() : 0))
6340        {
6341            item->SaveToDB();                               // save for prevent lost at next mail load, if send fail then item will deleted
6342            mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
6343        }
6344    }
6345
6346    WorldSession::SendMailTo(receiver,messagetype, stationery, sender_guidlo, GUID_LOPART(receiver_guid), subject, itemTextId, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
6347
6348    PSendSysMessage(LANG_MAIL_SENT, name.c_str());
6349    return true;
6350}
6351
6352///Send money by mail
6353bool ChatHandler::HandleSendMoneyCommand(const char* args)
6354{
6355    if (!*args)
6356        return false;
6357
6358    /// format: name "subject text" "mail text" money
6359
6360    char* pName = strtok((char*)args, " ");
6361    if (!pName)
6362        return false;
6363
6364    char* tail1 = strtok(NULL, "");
6365    if (!tail1)
6366        return false;
6367
6368    char* msgSubject;
6369    if (*tail1=='"')
6370        msgSubject = strtok(tail1+1, "\"");
6371    else
6372    {
6373        char* space = strtok(tail1, "\"");
6374        if (!space)
6375            return false;
6376        msgSubject = strtok(NULL, "\"");
6377    }
6378
6379    if (!msgSubject)
6380        return false;
6381
6382    char* tail2 = strtok(NULL, "");
6383    if (!tail2)
6384        return false;
6385
6386    char* msgText;
6387    if (*tail2=='"')
6388        msgText = strtok(tail2+1, "\"");
6389    else
6390    {
6391        char* space = strtok(tail2, "\"");
6392        if (!space)
6393            return false;
6394        msgText = strtok(NULL, "\"");
6395    }
6396
6397    if (!msgText)
6398        return false;
6399
6400    char* money_str = strtok(NULL, "");
6401    int32 money = money_str ? atoi(money_str) : 0;
6402    if (money <= 0)
6403        return false;
6404
6405    // pName, msgSubject, msgText isn't NUL after prev. check
6406    std::string name    = pName;
6407    std::string subject = msgSubject;
6408    std::string text    = msgText;
6409
6410    if (!normalizePlayerName(name))
6411    {
6412        SendSysMessage(LANG_PLAYER_NOT_FOUND);
6413        SetSentErrorMessage(true);
6414        return false;
6415    }
6416
6417    uint64 receiver_guid = objmgr.GetPlayerGUIDByName(name);
6418    if (!receiver_guid)
6419    {
6420        SendSysMessage(LANG_PLAYER_NOT_FOUND);
6421        SetSentErrorMessage(true);
6422        return false;
6423    }
6424
6425    uint32 mailId = objmgr.GenerateMailID();
6426
6427    // from console show not existed sender
6428    uint32 sender_guidlo = m_session ? m_session->GetPlayer()->GetGUIDLow() : 0;
6429
6430    uint32 messagetype = MAIL_NORMAL;
6431    uint32 stationery = MAIL_STATIONERY_GM;
6432    uint32 itemTextId = !text.empty() ? objmgr.CreateItemText( text ) : 0;
6433
6434    Player *receiver = objmgr.GetPlayer(receiver_guid);
6435
6436    WorldSession::SendMailTo(receiver,messagetype, stationery, sender_guidlo, GUID_LOPART(receiver_guid), subject, itemTextId, NULL, money, 0, MAIL_CHECK_MASK_NONE);
6437
6438    PSendSysMessage(LANG_MAIL_SENT, name.c_str());
6439    return true;
6440}
6441
6442/// Send a message to a player in game
6443bool ChatHandler::HandleSendMessageCommand(const char* args)
6444{
6445    ///- Get the command line arguments
6446    char* name_str = strtok((char*)args, " ");
6447    char* msg_str = strtok(NULL, "");
6448
6449    if(!name_str || !msg_str)
6450        return false;
6451
6452    std::string name = name_str;
6453
6454    if(!normalizePlayerName(name))
6455        return false;
6456
6457    ///- Find the player and check that he is not logging out.
6458    Player *rPlayer = objmgr.GetPlayer(name.c_str());
6459    if(!rPlayer)
6460    {
6461        SendSysMessage(LANG_PLAYER_NOT_FOUND);
6462        SetSentErrorMessage(true);
6463        return false;
6464    }
6465
6466    if(rPlayer->GetSession()->isLogingOut())
6467    {
6468        SendSysMessage(LANG_PLAYER_NOT_FOUND);
6469        SetSentErrorMessage(true);
6470        return false;
6471    }
6472
6473    ///- Send the message
6474    //Use SendAreaTriggerMessage for fastest delivery.
6475    rPlayer->GetSession()->SendAreaTriggerMessage("%s", msg_str);
6476    rPlayer->GetSession()->SendAreaTriggerMessage("|cffff0000[Message from administrator]:|r");
6477
6478    //Confirmation message
6479    PSendSysMessage(LANG_SENDMESSAGE,name.c_str(),msg_str);
6480    return true;
6481}
6482
6483bool ChatHandler::HandlePlayAllCommand(const char* args)
6484{
6485    if(!*args)
6486        return false;
6487
6488    uint32 soundId = atoi((char*)args);
6489
6490    if(!sSoundEntriesStore.LookupEntry(soundId))
6491    {
6492        PSendSysMessage(LANG_SOUND_NOT_EXIST, soundId);
6493        SetSentErrorMessage(true);
6494        return false;
6495    }
6496
6497    WorldPacket data(SMSG_PLAY_SOUND, 4);
6498    data << uint32(soundId) << m_session->GetPlayer()->GetGUID();
6499    sWorld.SendGlobalMessage(&data);
6500
6501    PSendSysMessage(LANG_COMMAND_PLAYED_TO_ALL, soundId);
6502    return true;
6503}
6504
6505bool ChatHandler::HandleModifyGenderCommand(const char *args)
6506{
6507    if(!*args)  return false;
6508    Player *player = getSelectedPlayer();
6509
6510    if(!player)
6511    {
6512        PSendSysMessage(LANG_NO_PLAYER);
6513        SetSentErrorMessage(true);
6514        return false;
6515    }
6516
6517    std::string gender = (char*)args;
6518    uint32 displayId = player->GetNativeDisplayId();
6519
6520    if(gender == "male") // MALE
6521    {
6522        if(player->getGender() == GENDER_MALE)
6523        {
6524            PSendSysMessage("%s is already male", player->GetName());
6525            SetSentErrorMessage(true);
6526            return false;
6527        }
6528
6529        // Set gender
6530        player->SetByteValue(UNIT_FIELD_BYTES_0, 2, GENDER_MALE);
6531        // Change display ID
6532        player->SetDisplayId(player->getRace() == RACE_BLOODELF ? displayId+1 : displayId-1);
6533        player->SetNativeDisplayId(player->getRace() == RACE_BLOODELF ? displayId+1 : displayId-1);
6534
6535        ChatHandler(player).PSendSysMessage("Gender changed. You are now a man!");
6536        PSendSysMessage("Gender changed for %s", player->GetName());
6537        return true;
6538    }
6539    else if(gender == "female") // FEMALE
6540    {
6541        if(player->getGender() == GENDER_FEMALE)
6542        {
6543            PSendSysMessage("%s is already female", player->GetName());
6544            SetSentErrorMessage(true);
6545            return false;
6546        }
6547
6548        // Set gender
6549        player->SetByteValue(UNIT_FIELD_BYTES_0, 2, GENDER_FEMALE);
6550        // Change display ID
6551        player->SetDisplayId(player->getRace() == RACE_BLOODELF ? displayId-1 : displayId+1);
6552        player->SetNativeDisplayId(player->getRace() == RACE_BLOODELF ? displayId-1 : displayId+1);
6553
6554        ChatHandler(player).PSendSysMessage("Gender changed. You are now a woman!");
6555        PSendSysMessage("Gender changed for %s", player->GetName());
6556        return true;
6557    }
6558    else
6559    {
6560        PSendSysMessage("You must use male or female as gender.");
6561        SetSentErrorMessage(true);
6562        return false;
6563    }
6564
6565    return true;
6566}
6567
6568bool ChatHandler::HandleFreezeCommand(const char *args)
6569{
6570    std::string name;
6571    Player* player;
6572    char* TargetName = strtok((char*)args, " "); //get entered name
6573    if (!TargetName) //if no name entered use target
6574    {
6575        player = getSelectedPlayer();
6576        if (player) //prevent crash with creature as target
6577        {   
6578            name = player->GetName();
6579            normalizePlayerName(name);
6580        }
6581    }
6582    else // if name entered
6583    {
6584        name = TargetName;
6585        normalizePlayerName(name);
6586        player = objmgr.GetPlayer(name.c_str()); //get player by name
6587    }
6588
6589    if (!player)
6590    {
6591        SendSysMessage(LANG_COMMAND_FREEZE_WRONG);
6592        return true;
6593    }
6594
6595    if (player==m_session->GetPlayer())
6596    {
6597        SendSysMessage(LANG_COMMAND_FREEZE_ERROR);
6598        return true;
6599    }
6600
6601    //effect
6602    if ((player) && (!(player==m_session->GetPlayer())))
6603    {
6604        PSendSysMessage(LANG_COMMAND_FREEZE,name.c_str());
6605
6606        //stop combat + make player unattackable + duel stop + stop some spells
6607        player->setFaction(35);
6608        player->CombatStop();
6609        if(player->IsNonMeleeSpellCasted(true))
6610            player->InterruptNonMeleeSpells(true);
6611        player->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
6612        player->SetUInt32Value(PLAYER_DUEL_TEAM, 1);
6613
6614        //if player class = hunter || warlock remove pet if alive
6615        if((player->getClass() == CLASS_HUNTER) || (player->getClass() == CLASS_WARLOCK))
6616        {
6617            if(Pet* pet = player->GetPet())
6618            {
6619                pet->SavePetToDB(PET_SAVE_AS_CURRENT);
6620                // not let dismiss dead pet
6621                if(pet && pet->isAlive())
6622                    player->RemovePet(pet,PET_SAVE_NOT_IN_SLOT);
6623            }
6624        }
6625
6626        //stop movement and disable spells
6627        uint32 spellID = 9454;
6628        //m_session->GetPlayer()->CastSpell(player,spellID,false);
6629        SpellEntry const *spellInfo = sSpellStore.LookupEntry( spellID );
6630        if(spellInfo) //TODO: Change the duration of the aura to -1 instead of 5000000
6631        {
6632            for(uint32 i = 0;i<3;i++)
6633            {
6634                uint8 eff = spellInfo->Effect[i];
6635                if (eff>=TOTAL_SPELL_EFFECTS)
6636                    continue;
6637                if( eff == SPELL_EFFECT_APPLY_AREA_AURA_PARTY || eff == SPELL_EFFECT_APPLY_AURA ||
6638                    eff == SPELL_EFFECT_PERSISTENT_AREA_AURA || eff == SPELL_EFFECT_APPLY_AREA_AURA_FRIEND || 
6639                    eff == SPELL_EFFECT_APPLY_AREA_AURA_ENEMY)
6640                {
6641                    Aura *Aur = CreateAura(spellInfo, i, NULL, player);
6642                    player->AddAura(Aur);
6643                }
6644            }
6645        }
6646
6647        //save player
6648        player->SaveToDB();
6649    }
6650    return true;
6651}
6652
6653bool ChatHandler::HandleUnFreezeCommand(const char *args)
6654{
6655    std::string name;
6656    Player* player;
6657    char* TargetName = strtok((char*)args, " "); //get entered name
6658    if (!TargetName) //if no name entered use target
6659    {
6660        player = getSelectedPlayer();
6661        if (player) //prevent crash with creature as target
6662        {   
6663            name = player->GetName();
6664        }
6665    }
6666
6667    else // if name entered
6668    {
6669        name = TargetName;
6670        normalizePlayerName(name);
6671        player = objmgr.GetPlayer(name.c_str()); //get player by name
6672    }
6673
6674    //effect
6675    if (player)
6676    {
6677        PSendSysMessage(LANG_COMMAND_UNFREEZE,name.c_str());
6678
6679        //Reset player faction + allow combat + allow duels
6680        player->setFactionForRace(player->getRace());
6681        player->RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
6682
6683        //allow movement and spells
6684        uint32 spellID = 9454;
6685        player->RemoveAurasDueToSpell(spellID);
6686
6687        //save player
6688        player->SaveToDB();
6689    }
6690
6691    if (!player)
6692    {
6693        if (TargetName)
6694        {       
6695            //check for offline players
6696            QueryResult *result = CharacterDatabase.PQuery("SELECT characters.guid FROM `characters` WHERE characters.name = '%s'",name.c_str());
6697            if(!result)
6698            {
6699                SendSysMessage(LANG_COMMAND_FREEZE_WRONG);
6700                return true;
6701            }
6702            //if player found: delete his freeze aura
6703            Field *fields=result->Fetch();
6704            uint64 pguid = fields[0].GetUInt64();
6705            delete result;
6706            CharacterDatabase.PQuery("DELETE FROM `character_aura` WHERE character_aura.spell = 9454 AND character_aura.guid = '%u'",pguid);
6707            PSendSysMessage(LANG_COMMAND_UNFREEZE,name.c_str());
6708            return true;
6709        }
6710        else
6711        {
6712            SendSysMessage(LANG_COMMAND_FREEZE_WRONG);
6713            return true;
6714        }
6715    }
6716
6717    return true;
6718}
6719
6720bool ChatHandler::HandleListFreezeCommand(const char* args)
6721{
6722    //Get names from DB
6723    QueryResult *result = CharacterDatabase.PQuery("SELECT characters.name FROM `characters` LEFT JOIN `character_aura` ON (characters.guid = character_aura.guid) WHERE character_aura.spell = 9454");
6724    if(!result)
6725    {
6726        SendSysMessage(LANG_COMMAND_NO_FROZEN_PLAYERS);
6727        return true;
6728    }
6729    //Header of the names
6730    PSendSysMessage(LANG_COMMAND_LIST_FREEZE);
6731
6732    //Output of the results
6733    do
6734    {
6735        Field *fields = result->Fetch();
6736        std::string fplayers = fields[0].GetCppString();
6737        PSendSysMessage(LANG_COMMAND_FROZEN_PLAYERS,fplayers.c_str());
6738    } while (result->NextRow());
6739
6740    delete result;
6741    return true;
6742}
6743
6744bool ChatHandler::HandleFlushArenaPointsCommand(const char * /*args*/)
6745{
6746    sBattleGroundMgr.DistributeArenaPoints();
6747    return true;
6748}
6749
6750bool ChatHandler::HandleGroupLeaderCommand(const char* args)
6751{
6752    Player* plr  = NULL;
6753    Group* group = NULL;
6754    uint64 guid  = 0;
6755    char* cname  = strtok((char*)args, " ");
6756
6757    if(GetPlayerGroupAndGUIDByName(cname, plr, group, guid))
6758        if(group && group->GetLeaderGUID() != guid)
6759            group->ChangeLeader(guid);
6760
6761    return true;
6762}
6763
6764bool ChatHandler::HandleGroupDisbandCommand(const char* args)
6765{
6766    Player* plr  = NULL;
6767    Group* group = NULL;
6768    uint64 guid  = 0;
6769    char* cname  = strtok((char*)args, " ");
6770
6771    if(GetPlayerGroupAndGUIDByName(cname, plr, group, guid))
6772        if(group)
6773            group->Disband();
6774
6775    return true;
6776}
6777
6778bool ChatHandler::HandleGroupRemoveCommand(const char* args)
6779{
6780    Player* plr  = NULL;
6781    Group* group = NULL;
6782    uint64 guid  = 0;
6783    char* cname  = strtok((char*)args, " ");
6784
6785    if(GetPlayerGroupAndGUIDByName(cname, plr, group, guid, true))
6786        if(group)
6787            group->RemoveMember(guid, 0);
6788
6789    return true;
6790}
6791
6792bool ChatHandler::HandlePossessCommand(const char* args)
6793{
6794    Unit* pUnit = getSelectedUnit();
6795    if(!pUnit)
6796        return false;
6797
6798    // Don't allow unlimited possession of players
6799    if (pUnit->GetTypeId() == TYPEID_PLAYER)
6800        return false;
6801
6802    m_session->GetPlayer()->Possess(pUnit);
6803
6804    return true;
6805}
6806
6807bool ChatHandler::HandleUnPossessCommand(const char* args)
6808{
6809    // Use this command to also unpossess ourselves
6810    if (m_session->GetPlayer()->isPossessed())
6811        m_session->GetPlayer()->UnpossessSelf(false);
6812    else
6813        m_session->GetPlayer()->RemovePossess(false);
6814
6815    return true;
6816}
6817
6818bool ChatHandler::HandleBindSightCommand(const char* args)
6819{
6820    Unit* pUnit = getSelectedUnit();
6821    if (!pUnit)
6822        return false;
6823       
6824    if (m_session->GetPlayer()->isPossessing())
6825        return false;
6826
6827    pUnit->AddPlayerToVision(m_session->GetPlayer());
6828
6829    return true;
6830}
6831
6832bool ChatHandler::HandleUnbindSightCommand(const char* args)
6833{
6834    if (m_session->GetPlayer()->isPossessing())
6835        return false;
6836       
6837    m_session->GetPlayer()->RemoveFarsightTarget();
6838    return true;
6839}
Note: See TracBrowser for help on using the browser.