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

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

[svn] * Reimplemented packet/update forwarding in more generic way
* Implemented far sight spells (Far Sight, Eagle Eye, etc) at unlimited range and properly forward packets
* Implemented bind vision spells (Mind Vision, etc) to forward packets at unlimited distance
* Implemented Sentry Totem (both vision switching/forwarding and alerting)
* Other misc possession fixes
* Added .bindsight and .unbindsight commands

Please test out the above spells (including Mind Control) and report any issues on the forums.

Original author: gvcoman
Date: 2008-11-14 20:40:35-06:00

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