[9033] Fixed percent mana regneration from spell 53228 and ranks buff.
[getmangos.git] / src / game / Level2.cpp
blob3e28e8c852694381d02f5f2c84a0847522510044
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Database/DatabaseEnv.h"
21 #include "DBCStores.h"
22 #include "ObjectMgr.h"
23 #include "ObjectDefines.h"
24 #include "Player.h"
25 #include "Item.h"
26 #include "GameObject.h"
27 #include "Opcodes.h"
28 #include "Chat.h"
29 #include "ObjectAccessor.h"
30 #include "MapManager.h"
31 #include "Language.h"
32 #include "World.h"
33 #include "GameEventMgr.h"
34 #include "SpellMgr.h"
35 #include "PoolManager.h"
36 #include "AccountMgr.h"
37 #include "GMTicketMgr.h"
38 #include "WaypointManager.h"
39 #include "Util.h"
40 #include <cctype>
41 #include <iostream>
42 #include <fstream>
43 #include <map>
44 #include "GlobalEvents.h"
46 #include "TargetedMovementGenerator.h" // for HandleNpcUnFollowCommand
48 static uint32 ReputationRankStrIndex[MAX_REPUTATION_RANK] =
50 LANG_REP_HATED, LANG_REP_HOSTILE, LANG_REP_UNFRIENDLY, LANG_REP_NEUTRAL,
51 LANG_REP_FRIENDLY, LANG_REP_HONORED, LANG_REP_REVERED, LANG_REP_EXALTED
54 //mute player for some times
55 bool ChatHandler::HandleMuteCommand(const char* args)
57 char* nameStr;
58 char* delayStr;
59 extractOptFirstArg((char*)args,&nameStr,&delayStr);
60 if(!delayStr)
61 return false;
63 Player* target;
64 uint64 target_guid;
65 std::string target_name;
66 if(!extractPlayerTarget(nameStr,&target,&target_guid,&target_name))
67 return false;
69 uint32 account_id = target ? target->GetSession()->GetAccountId() : sObjectMgr.GetPlayerAccountIdByGUID(target_guid);
71 // find only player from same account if any
72 if(!target)
74 if(WorldSession* session = sWorld.FindSession(account_id))
75 target = session->GetPlayer();
78 uint32 notspeaktime = (uint32) atoi(delayStr);
80 // must have strong lesser security level
81 if(HasLowerSecurity (target,target_guid,true))
82 return false;
84 time_t mutetime = time(NULL) + notspeaktime*60;
86 if (target)
87 target->GetSession()->m_muteTime = mutetime;
89 loginDatabase.PExecute("UPDATE account SET mutetime = " UI64FMTD " WHERE id = '%u'",uint64(mutetime), account_id );
91 if(target)
92 ChatHandler(target).PSendSysMessage(LANG_YOUR_CHAT_DISABLED, notspeaktime);
94 std::string nameLink = playerLink(target_name);
96 PSendSysMessage(LANG_YOU_DISABLE_CHAT, nameLink.c_str(), notspeaktime);
97 return true;
100 //unmute player
101 bool ChatHandler::HandleUnmuteCommand(const char* args)
103 Player* target;
104 uint64 target_guid;
105 std::string target_name;
106 if(!extractPlayerTarget((char*)args,&target,&target_guid,&target_name))
107 return false;
109 uint32 account_id = target ? target->GetSession()->GetAccountId() : sObjectMgr.GetPlayerAccountIdByGUID(target_guid);
111 // find only player from same account if any
112 if(!target)
114 if(WorldSession* session = sWorld.FindSession(account_id))
115 target = session->GetPlayer();
118 // must have strong lesser security level
119 if(HasLowerSecurity (target,target_guid,true))
120 return false;
122 if (target)
124 if(target->CanSpeak())
126 SendSysMessage(LANG_CHAT_ALREADY_ENABLED);
127 SetSentErrorMessage(true);
128 return false;
131 target->GetSession()->m_muteTime = 0;
134 loginDatabase.PExecute("UPDATE account SET mutetime = '0' WHERE id = '%u'", account_id );
136 if(target)
137 ChatHandler(target).PSendSysMessage(LANG_YOUR_CHAT_ENABLED);
139 std::string nameLink = playerLink(target_name);
141 PSendSysMessage(LANG_YOU_ENABLE_CHAT, nameLink.c_str());
142 return true;
145 bool ChatHandler::HandleGoTriggerCommand(const char* args)
147 Player* _player = m_session->GetPlayer();
149 if (!*args)
150 return false;
152 char *atId = strtok((char*)args, " ");
153 if (!atId)
154 return false;
156 int32 i_atId = atoi(atId);
158 if(!i_atId)
159 return false;
161 AreaTriggerEntry const* at = sAreaTriggerStore.LookupEntry(i_atId);
162 if (!at)
164 PSendSysMessage(LANG_COMMAND_GOAREATRNOTFOUND,i_atId);
165 SetSentErrorMessage(true);
166 return false;
169 if(!MapManager::IsValidMapCoord(at->mapid,at->x,at->y,at->z))
171 PSendSysMessage(LANG_INVALID_TARGET_COORD,at->x,at->y,at->mapid);
172 SetSentErrorMessage(true);
173 return false;
176 // stop flight if need
177 if(_player->isInFlight())
179 _player->GetMotionMaster()->MovementExpired();
180 _player->m_taxi.ClearTaxiDestinations();
182 // save only in non-flight case
183 else
184 _player->SaveRecallPosition();
186 _player->TeleportTo(at->mapid, at->x, at->y, at->z, _player->GetOrientation());
187 return true;
190 bool ChatHandler::HandleGoGraveyardCommand(const char* args)
192 Player* _player = m_session->GetPlayer();
194 if (!*args)
195 return false;
197 char *gyId = strtok((char*)args, " ");
198 if (!gyId)
199 return false;
201 int32 i_gyId = atoi(gyId);
203 if(!i_gyId)
204 return false;
206 WorldSafeLocsEntry const* gy = sWorldSafeLocsStore.LookupEntry(i_gyId);
207 if (!gy)
209 PSendSysMessage(LANG_COMMAND_GRAVEYARDNOEXIST,i_gyId);
210 SetSentErrorMessage(true);
211 return false;
214 if(!MapManager::IsValidMapCoord(gy->map_id,gy->x,gy->y,gy->z))
216 PSendSysMessage(LANG_INVALID_TARGET_COORD,gy->x,gy->y,gy->map_id);
217 SetSentErrorMessage(true);
218 return false;
221 // stop flight if need
222 if(_player->isInFlight())
224 _player->GetMotionMaster()->MovementExpired();
225 _player->m_taxi.ClearTaxiDestinations();
227 // save only in non-flight case
228 else
229 _player->SaveRecallPosition();
231 _player->TeleportTo(gy->map_id, gy->x, gy->y, gy->z, _player->GetOrientation());
232 return true;
235 /** \brief Teleport the GM to the specified creature
237 * .gocreature <GUID> --> TP using creature.guid
238 * .gocreature azuregos --> TP player to the mob with this name
239 * Warning: If there is more than one mob with this name
240 * you will be teleported to the first one that is found.
241 * .gocreature id 6109 --> TP player to the mob, that has this creature_template.entry
242 * Warning: If there is more than one mob with this "id"
243 * you will be teleported to the first one that is found.
245 //teleport to creature
246 bool ChatHandler::HandleGoCreatureCommand(const char* args)
248 if(!*args)
249 return false;
250 Player* _player = m_session->GetPlayer();
252 // "id" or number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
253 char* pParam1 = extractKeyFromLink((char*)args,"Hcreature");
254 if (!pParam1)
255 return false;
257 std::ostringstream whereClause;
259 // User wants to teleport to the NPC's template entry
260 if( strcmp(pParam1, "id") == 0 )
262 //sLog.outError("DEBUG: ID found");
264 // Get the "creature_template.entry"
265 // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
266 char* tail = strtok(NULL,"");
267 if(!tail)
268 return false;
269 char* cId = extractKeyFromLink(tail,"Hcreature_entry");
270 if(!cId)
271 return false;
273 int32 tEntry = atoi(cId);
274 //sLog.outError("DEBUG: ID value: %d", tEntry);
275 if(!tEntry)
276 return false;
278 whereClause << "WHERE id = '" << tEntry << "'";
280 else
282 //sLog.outError("DEBUG: ID *not found*");
284 int32 guid = atoi(pParam1);
286 // Number is invalid - maybe the user specified the mob's name
287 if(!guid)
289 std::string name = pParam1;
290 WorldDatabase.escape_string(name);
291 whereClause << ", creature_template WHERE creature.id = creature_template.entry AND creature_template.name "_LIKE_" '" << name << "'";
293 else
295 whereClause << "WHERE guid = '" << guid << "'";
298 //sLog.outError("DEBUG: %s", whereClause.c_str());
300 QueryResult *result = WorldDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map FROM creature %s", whereClause.str().c_str() );
301 if (!result)
303 SendSysMessage(LANG_COMMAND_GOCREATNOTFOUND);
304 SetSentErrorMessage(true);
305 return false;
307 if( result->GetRowCount() > 1 )
309 SendSysMessage(LANG_COMMAND_GOCREATMULTIPLE);
312 Field *fields = result->Fetch();
313 float x = fields[0].GetFloat();
314 float y = fields[1].GetFloat();
315 float z = fields[2].GetFloat();
316 float ort = fields[3].GetFloat();
317 int mapid = fields[4].GetUInt16();
319 delete result;
321 if(!MapManager::IsValidMapCoord(mapid,x,y,z,ort))
323 PSendSysMessage(LANG_INVALID_TARGET_COORD,x,y,mapid);
324 SetSentErrorMessage(true);
325 return false;
328 // stop flight if need
329 if(_player->isInFlight())
331 _player->GetMotionMaster()->MovementExpired();
332 _player->m_taxi.ClearTaxiDestinations();
334 // save only in non-flight case
335 else
336 _player->SaveRecallPosition();
338 _player->TeleportTo(mapid, x, y, z, ort);
339 return true;
342 //teleport to gameobject
343 bool ChatHandler::HandleGoObjectCommand(const char* args)
345 if(!*args)
346 return false;
348 Player* _player = m_session->GetPlayer();
350 // number or [name] Shift-click form |color|Hgameobject:go_guid|h[name]|h|r
351 char* cId = extractKeyFromLink((char*)args,"Hgameobject");
352 if(!cId)
353 return false;
355 int32 guid = atoi(cId);
356 if(!guid)
357 return false;
359 float x, y, z, ort;
360 int mapid;
362 // by DB guid
363 if (GameObjectData const* go_data = sObjectMgr.GetGOData(guid))
365 x = go_data->posX;
366 y = go_data->posY;
367 z = go_data->posZ;
368 ort = go_data->orientation;
369 mapid = go_data->mapid;
371 else
373 SendSysMessage(LANG_COMMAND_GOOBJNOTFOUND);
374 SetSentErrorMessage(true);
375 return false;
378 if(!MapManager::IsValidMapCoord(mapid,x,y,z,ort))
380 PSendSysMessage(LANG_INVALID_TARGET_COORD,x,y,mapid);
381 SetSentErrorMessage(true);
382 return false;
385 // stop flight if need
386 if(_player->isInFlight())
388 _player->GetMotionMaster()->MovementExpired();
389 _player->m_taxi.ClearTaxiDestinations();
391 // save only in non-flight case
392 else
393 _player->SaveRecallPosition();
395 _player->TeleportTo(mapid, x, y, z, ort);
396 return true;
399 bool ChatHandler::HandleGameObjectTargetCommand(const char* args)
401 Player* pl = m_session->GetPlayer();
402 QueryResult *result;
403 GameEventMgr::ActiveEvents const& activeEventsList = sGameEventMgr.GetActiveEventList();
404 if(*args)
406 // number or [name] Shift-click form |color|Hgameobject_entry:go_id|h[name]|h|r
407 char* cId = extractKeyFromLink((char*)args,"Hgameobject_entry");
408 if(!cId)
409 return false;
411 uint32 id = atol(cId);
413 if(id)
414 result = WorldDatabase.PQuery("SELECT guid, id, position_x, position_y, position_z, orientation, map, (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ FROM gameobject WHERE map = '%i' AND id = '%u' ORDER BY order_ ASC LIMIT 1",
415 pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), pl->GetMapId(),id);
416 else
418 std::string name = cId;
419 WorldDatabase.escape_string(name);
420 result = WorldDatabase.PQuery(
421 "SELECT guid, id, position_x, position_y, position_z, orientation, map, (POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ "
422 "FROM gameobject,gameobject_template WHERE gameobject_template.entry = gameobject.id AND map = %i AND name "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'")" ORDER BY order_ ASC LIMIT 1",
423 pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), pl->GetMapId(),name.c_str());
426 else
428 std::ostringstream eventFilter;
429 eventFilter << " AND (event IS NULL ";
430 bool initString = true;
432 for (GameEventMgr::ActiveEvents::const_iterator itr = activeEventsList.begin(); itr != activeEventsList.end(); ++itr)
434 if (initString)
436 eventFilter << "OR event IN (" <<*itr;
437 initString =false;
439 else
440 eventFilter << "," << *itr;
443 if (!initString)
444 eventFilter << "))";
445 else
446 eventFilter << ")";
448 result = WorldDatabase.PQuery("SELECT gameobject.guid, id, position_x, position_y, position_z, orientation, map, "
449 "(POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ FROM gameobject "
450 "LEFT OUTER JOIN game_event_gameobject on gameobject.guid=game_event_gameobject.guid WHERE map = '%i' %s ORDER BY order_ ASC LIMIT 10",
451 m_session->GetPlayer()->GetPositionX(), m_session->GetPlayer()->GetPositionY(), m_session->GetPlayer()->GetPositionZ(), m_session->GetPlayer()->GetMapId(),eventFilter.str().c_str());
454 if (!result)
456 SendSysMessage(LANG_COMMAND_TARGETOBJNOTFOUND);
457 return true;
460 bool found = false;
461 float x, y, z, o;
462 uint32 lowguid, id;
463 uint16 mapid, pool_id;
467 Field *fields = result->Fetch();
468 lowguid = fields[0].GetUInt32();
469 id = fields[1].GetUInt32();
470 x = fields[2].GetFloat();
471 y = fields[3].GetFloat();
472 z = fields[4].GetFloat();
473 o = fields[5].GetFloat();
474 mapid = fields[6].GetUInt16();
475 pool_id = sPoolMgr.IsPartOfAPool(lowguid, TYPEID_GAMEOBJECT);
476 if (!pool_id || (pool_id && sPoolMgr.IsSpawnedObject(pool_id, lowguid, TYPEID_GAMEOBJECT)))
477 found = true;
478 } while( result->NextRow() && (!found) );
480 delete result;
482 if (!found)
484 PSendSysMessage(LANG_GAMEOBJECT_NOT_EXIST,id);
485 return false;
488 GameObjectInfo const* goI = ObjectMgr::GetGameObjectInfo(id);
490 if (!goI)
492 PSendSysMessage(LANG_GAMEOBJECT_NOT_EXIST,id);
493 return false;
496 GameObject* target = m_session->GetPlayer()->GetMap()->GetGameObject(MAKE_NEW_GUID(lowguid,id,HIGHGUID_GAMEOBJECT));
498 PSendSysMessage(LANG_GAMEOBJECT_DETAIL, lowguid, goI->name, lowguid, id, x, y, z, mapid, o);
500 if(target)
502 int32 curRespawnDelay = target->GetRespawnTimeEx()-time(NULL);
503 if(curRespawnDelay < 0)
504 curRespawnDelay = 0;
506 std::string curRespawnDelayStr = secsToTimeString(curRespawnDelay,true);
507 std::string defRespawnDelayStr = secsToTimeString(target->GetRespawnDelay(),true);
509 PSendSysMessage(LANG_COMMAND_RAWPAWNTIMES, defRespawnDelayStr.c_str(),curRespawnDelayStr.c_str());
511 return true;
514 //delete object by selection or guid
515 bool ChatHandler::HandleGameObjectDeleteCommand(const char* args)
517 // number or [name] Shift-click form |color|Hgameobject:go_guid|h[name]|h|r
518 char* cId = extractKeyFromLink((char*)args,"Hgameobject");
519 if(!cId)
520 return false;
522 uint32 lowguid = atoi(cId);
523 if(!lowguid)
524 return false;
526 GameObject* obj = NULL;
528 // by DB guid
529 if (GameObjectData const* go_data = sObjectMgr.GetGOData(lowguid))
530 obj = GetObjectGlobalyWithGuidOrNearWithDbGuid(lowguid,go_data->id);
532 if(!obj)
534 PSendSysMessage(LANG_COMMAND_OBJNOTFOUND, lowguid);
535 SetSentErrorMessage(true);
536 return false;
539 uint64 owner_guid = obj->GetOwnerGUID();
540 if(owner_guid)
542 Unit* owner = ObjectAccessor::GetUnit(*m_session->GetPlayer(),owner_guid);
543 if(!owner || !IS_PLAYER_GUID(owner_guid))
545 PSendSysMessage(LANG_COMMAND_DELOBJREFERCREATURE, GUID_LOPART(owner_guid), obj->GetGUIDLow());
546 SetSentErrorMessage(true);
547 return false;
550 owner->RemoveGameObject(obj,false);
553 obj->SetRespawnTime(0); // not save respawn time
554 obj->Delete();
555 obj->DeleteFromDB();
557 PSendSysMessage(LANG_COMMAND_DELOBJMESSAGE, obj->GetGUIDLow());
559 return true;
562 //turn selected object
563 bool ChatHandler::HandleGameObjectTurnCommand(const char* args)
565 // number or [name] Shift-click form |color|Hgameobject:go_id|h[name]|h|r
566 char* cId = extractKeyFromLink((char*)args,"Hgameobject");
567 if(!cId)
568 return false;
570 uint32 lowguid = atoi(cId);
571 if(!lowguid)
572 return false;
574 GameObject* obj = NULL;
576 // by DB guid
577 if (GameObjectData const* go_data = sObjectMgr.GetGOData(lowguid))
578 obj = GetObjectGlobalyWithGuidOrNearWithDbGuid(lowguid,go_data->id);
580 if(!obj)
582 PSendSysMessage(LANG_COMMAND_OBJNOTFOUND, lowguid);
583 SetSentErrorMessage(true);
584 return false;
587 char* po = strtok(NULL, " ");
588 float o;
590 if (po)
592 o = (float)atof(po);
594 else
596 Player *chr = m_session->GetPlayer();
597 o = chr->GetOrientation();
600 Map* map = obj->GetMap();
601 map->Remove(obj,false);
603 obj->Relocate(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), o);
604 obj->UpdateRotationFields();
606 map->Add(obj);
608 obj->SaveToDB();
609 obj->Refresh();
611 PSendSysMessage(LANG_COMMAND_TURNOBJMESSAGE, obj->GetGUIDLow(), obj->GetGOInfo()->name, obj->GetGUIDLow(), o);
613 return true;
616 //move selected object
617 bool ChatHandler::HandleGameObjectMoveCommand(const char* args)
619 // number or [name] Shift-click form |color|Hgameobject:go_guid|h[name]|h|r
620 char* cId = extractKeyFromLink((char*)args,"Hgameobject");
621 if(!cId)
622 return false;
624 uint32 lowguid = atoi(cId);
625 if(!lowguid)
626 return false;
628 GameObject* obj = NULL;
630 // by DB guid
631 if (GameObjectData const* go_data = sObjectMgr.GetGOData(lowguid))
632 obj = GetObjectGlobalyWithGuidOrNearWithDbGuid(lowguid,go_data->id);
634 if(!obj)
636 PSendSysMessage(LANG_COMMAND_OBJNOTFOUND, lowguid);
637 SetSentErrorMessage(true);
638 return false;
641 char* px = strtok(NULL, " ");
642 char* py = strtok(NULL, " ");
643 char* pz = strtok(NULL, " ");
645 if (!px)
647 Player *chr = m_session->GetPlayer();
649 Map* map = obj->GetMap();
650 map->Remove(obj,false);
652 obj->Relocate(chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), obj->GetOrientation());
654 map->Add(obj);
656 else
658 if(!py || !pz)
659 return false;
661 float x = (float)atof(px);
662 float y = (float)atof(py);
663 float z = (float)atof(pz);
665 if(!MapManager::IsValidMapCoord(obj->GetMapId(),x,y,z))
667 PSendSysMessage(LANG_INVALID_TARGET_COORD,x,y,obj->GetMapId());
668 SetSentErrorMessage(true);
669 return false;
672 Map* map = obj->GetMap();
673 map->Remove(obj,false);
675 obj->Relocate(x, y, z, obj->GetOrientation());
677 map->Add(obj);
680 obj->SaveToDB();
681 obj->Refresh();
683 PSendSysMessage(LANG_COMMAND_MOVEOBJMESSAGE, obj->GetGUIDLow(), obj->GetGOInfo()->name, obj->GetGUIDLow());
685 return true;
688 //spawn go
689 bool ChatHandler::HandleGameObjectAddCommand(const char* args)
691 if (!*args)
692 return false;
694 // number or [name] Shift-click form |color|Hgameobject_entry:go_id|h[name]|h|r
695 char* cId = extractKeyFromLink((char*)args,"Hgameobject_entry");
696 if(!cId)
697 return false;
699 uint32 id = atol(cId);
700 if(!id)
701 return false;
703 char* spawntimeSecs = strtok(NULL, " ");
705 const GameObjectInfo *gInfo = ObjectMgr::GetGameObjectInfo(id);
707 if (!gInfo)
709 PSendSysMessage(LANG_GAMEOBJECT_NOT_EXIST,id);
710 SetSentErrorMessage(true);
711 return false;
714 if (gInfo->displayId && !sGameObjectDisplayInfoStore.LookupEntry(gInfo->displayId))
716 // report to DB errors log as in loading case
717 sLog.outErrorDb("Gameobject (Entry %u GoType: %u) have invalid displayId (%u), not spawned.",id, gInfo->type, gInfo->displayId);
718 PSendSysMessage(LANG_GAMEOBJECT_HAVE_INVALID_DATA,id);
719 SetSentErrorMessage(true);
720 return false;
723 Player *chr = m_session->GetPlayer();
724 float x = float(chr->GetPositionX());
725 float y = float(chr->GetPositionY());
726 float z = float(chr->GetPositionZ());
727 float o = float(chr->GetOrientation());
728 Map *map = chr->GetMap();
730 GameObject* pGameObj = new GameObject;
731 uint32 db_lowGUID = sObjectMgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT);
733 if(!pGameObj->Create(db_lowGUID, gInfo->id, map, chr->GetPhaseMaskForSpawn(), x, y, z, o, 0.0f, 0.0f, 0.0f, 0.0f, 0, GO_STATE_READY))
735 delete pGameObj;
736 return false;
739 if( spawntimeSecs )
741 uint32 value = atoi((char*)spawntimeSecs);
742 pGameObj->SetRespawnTime(value);
743 //sLog.outDebug("*** spawntimeSecs: %d", value);
746 // fill the gameobject data and save to the db
747 pGameObj->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()),chr->GetPhaseMaskForSpawn());
749 // this will generate a new guid if the object is in an instance
750 if(!pGameObj->LoadFromDB(db_lowGUID, map))
752 delete pGameObj;
753 return false;
756 sLog.outDebug(GetMangosString(LANG_GAMEOBJECT_CURRENT), gInfo->name, db_lowGUID, x, y, z, o);
758 map->Add(pGameObj);
760 // TODO: is it really necessary to add both the real and DB table guid here ?
761 sObjectMgr.AddGameobjectToGrid(db_lowGUID, sObjectMgr.GetGOData(db_lowGUID));
763 PSendSysMessage(LANG_GAMEOBJECT_ADD,id,gInfo->name,db_lowGUID,x,y,z);
764 return true;
767 //set pahsemask for selected object
768 bool ChatHandler::HandleGameObjectPhaseCommand(const char* args)
770 // number or [name] Shift-click form |color|Hgameobject:go_id|h[name]|h|r
771 char* cId = extractKeyFromLink((char*)args,"Hgameobject");
772 if(!cId)
773 return false;
775 uint32 lowguid = atoi(cId);
776 if(!lowguid)
777 return false;
779 GameObject* obj = NULL;
781 // by DB guid
782 if (GameObjectData const* go_data = sObjectMgr.GetGOData(lowguid))
783 obj = GetObjectGlobalyWithGuidOrNearWithDbGuid(lowguid,go_data->id);
785 if(!obj)
787 PSendSysMessage(LANG_COMMAND_OBJNOTFOUND, lowguid);
788 SetSentErrorMessage(true);
789 return false;
792 char* phaseStr = strtok (NULL, " ");
793 uint32 phasemask = phaseStr? atoi(phaseStr) : 0;
794 if ( phasemask == 0 )
796 SendSysMessage(LANG_BAD_VALUE);
797 SetSentErrorMessage(true);
798 return false;
801 obj->SetPhaseMask(phasemask,true);
802 obj->SaveToDB();
803 return true;
806 bool ChatHandler::HandleGameObjectNearCommand(const char* args)
808 float distance = (!*args) ? 10 : atol(args);
809 uint32 count = 0;
811 Player* pl = m_session->GetPlayer();
812 QueryResult *result = WorldDatabase.PQuery("SELECT guid, id, position_x, position_y, position_z, map, "
813 "(POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ "
814 "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_",
815 pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(),
816 pl->GetMapId(),pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(),distance*distance);
818 if (result)
822 Field *fields = result->Fetch();
823 uint32 guid = fields[0].GetUInt32();
824 uint32 entry = fields[1].GetUInt32();
825 float x = fields[2].GetFloat();
826 float y = fields[3].GetFloat();
827 float z = fields[4].GetFloat();
828 int mapid = fields[5].GetUInt16();
830 GameObjectInfo const * gInfo = ObjectMgr::GetGameObjectInfo(entry);
832 if(!gInfo)
833 continue;
835 PSendSysMessage(LANG_GO_LIST_CHAT, guid, guid, gInfo->name, x, y, z, mapid);
837 ++count;
838 } while (result->NextRow());
840 delete result;
843 PSendSysMessage(LANG_COMMAND_NEAROBJMESSAGE,distance,count);
844 return true;
847 bool ChatHandler::HandleGUIDCommand(const char* /*args*/)
849 uint64 guid = m_session->GetPlayer()->GetSelection();
851 if (guid == 0)
853 SendSysMessage(LANG_NO_SELECTION);
854 SetSentErrorMessage(true);
855 return false;
858 PSendSysMessage(LANG_OBJECT_GUID, GUID_LOPART(guid), GUID_HIPART(guid));
859 return true;
862 bool ChatHandler::HandleLookupFactionCommand(const char* args)
864 if (!*args)
865 return false;
867 // Can be NULL at console call
868 Player *target = getSelectedPlayer ();
870 std::string namepart = args;
871 std::wstring wnamepart;
873 if (!Utf8toWStr (namepart,wnamepart))
874 return false;
876 // converting string that we try to find to lower case
877 wstrToLower (wnamepart);
879 uint32 counter = 0; // Counter for figure out that we found smth.
881 for (uint32 id = 0; id < sFactionStore.GetNumRows(); ++id)
883 FactionEntry const *factionEntry = sFactionStore.LookupEntry (id);
884 if (factionEntry)
886 FactionState const* repState = target ? target->GetReputationMgr().GetState(factionEntry) : NULL;
888 int loc = GetSessionDbcLocale();
889 std::string name = factionEntry->name[loc];
890 if(name.empty())
891 continue;
893 if (!Utf8FitTo(name, wnamepart))
895 loc = 0;
896 for(; loc < MAX_LOCALE; ++loc)
898 if(loc==GetSessionDbcLocale())
899 continue;
901 name = factionEntry->name[loc];
902 if(name.empty())
903 continue;
905 if (Utf8FitTo(name, wnamepart))
906 break;
910 if(loc < MAX_LOCALE)
912 // send faction in "id - [faction] rank reputation [visible] [at war] [own team] [unknown] [invisible] [inactive]" format
913 // or "id - [faction] [no reputation]" format
914 std::ostringstream ss;
915 if (m_session)
916 ss << id << " - |cffffffff|Hfaction:" << id << "|h[" << name << " " << localeNames[loc] << "]|h|r";
917 else
918 ss << id << " - " << name << " " << localeNames[loc];
920 if (repState) // and then target!=NULL also
922 ReputationRank rank = target->GetReputationMgr().GetRank(factionEntry);
923 std::string rankName = GetMangosString(ReputationRankStrIndex[rank]);
925 ss << " " << rankName << "|h|r (" << target->GetReputationMgr().GetReputation(factionEntry) << ")";
927 if(repState->Flags & FACTION_FLAG_VISIBLE)
928 ss << GetMangosString(LANG_FACTION_VISIBLE);
929 if(repState->Flags & FACTION_FLAG_AT_WAR)
930 ss << GetMangosString(LANG_FACTION_ATWAR);
931 if(repState->Flags & FACTION_FLAG_PEACE_FORCED)
932 ss << GetMangosString(LANG_FACTION_PEACE_FORCED);
933 if(repState->Flags & FACTION_FLAG_HIDDEN)
934 ss << GetMangosString(LANG_FACTION_HIDDEN);
935 if(repState->Flags & FACTION_FLAG_INVISIBLE_FORCED)
936 ss << GetMangosString(LANG_FACTION_INVISIBLE_FORCED);
937 if(repState->Flags & FACTION_FLAG_INACTIVE)
938 ss << GetMangosString(LANG_FACTION_INACTIVE);
940 else
941 ss << GetMangosString(LANG_FACTION_NOREPUTATION);
943 SendSysMessage(ss.str().c_str());
944 counter++;
949 if (counter == 0) // if counter == 0 then we found nth
950 SendSysMessage(LANG_COMMAND_FACTION_NOTFOUND);
951 return true;
954 bool ChatHandler::HandleModifyRepCommand(const char * args)
956 if (!*args) return false;
958 Player* target = NULL;
959 target = getSelectedPlayer();
961 if(!target)
963 SendSysMessage(LANG_PLAYER_NOT_FOUND);
964 SetSentErrorMessage(true);
965 return false;
968 // check online security
969 if (HasLowerSecurity(target, 0))
970 return false;
972 char* factionTxt = extractKeyFromLink((char*)args,"Hfaction");
973 if(!factionTxt)
974 return false;
976 uint32 factionId = atoi(factionTxt);
978 int32 amount = 0;
979 char *rankTxt = strtok(NULL, " ");
980 if (!factionTxt || !rankTxt)
981 return false;
983 amount = atoi(rankTxt);
984 if ((amount == 0) && (rankTxt[0] != '-') && !isdigit(rankTxt[0]))
986 std::string rankStr = rankTxt;
987 std::wstring wrankStr;
988 if(!Utf8toWStr(rankStr,wrankStr))
989 return false;
990 wstrToLower( wrankStr );
992 int r = 0;
993 amount = -42000;
994 for (; r < MAX_REPUTATION_RANK; ++r)
996 std::string rank = GetMangosString(ReputationRankStrIndex[r]);
997 if(rank.empty())
998 continue;
1000 std::wstring wrank;
1001 if(!Utf8toWStr(rank,wrank))
1002 continue;
1004 wstrToLower(wrank);
1006 if(wrank.substr(0,wrankStr.size())==wrankStr)
1008 char *deltaTxt = strtok(NULL, " ");
1009 if (deltaTxt)
1011 int32 delta = atoi(deltaTxt);
1012 if ((delta < 0) || (delta > ReputationMgr::PointsInRank[r] -1))
1014 PSendSysMessage(LANG_COMMAND_FACTION_DELTA, (ReputationMgr::PointsInRank[r]-1));
1015 SetSentErrorMessage(true);
1016 return false;
1018 amount += delta;
1020 break;
1022 amount += ReputationMgr::PointsInRank[r];
1024 if (r >= MAX_REPUTATION_RANK)
1026 PSendSysMessage(LANG_COMMAND_FACTION_INVPARAM, rankTxt);
1027 SetSentErrorMessage(true);
1028 return false;
1032 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionId);
1034 if (!factionEntry)
1036 PSendSysMessage(LANG_COMMAND_FACTION_UNKNOWN, factionId);
1037 SetSentErrorMessage(true);
1038 return false;
1041 if (factionEntry->reputationListID < 0)
1043 PSendSysMessage(LANG_COMMAND_FACTION_NOREP_ERROR, factionEntry->name[GetSessionDbcLocale()], factionId);
1044 SetSentErrorMessage(true);
1045 return false;
1048 target->GetReputationMgr().SetReputation(factionEntry,amount);
1049 PSendSysMessage(LANG_COMMAND_MODIFY_REP, factionEntry->name[GetSessionDbcLocale()], factionId,
1050 GetNameLink(target).c_str(), target->GetReputationMgr().GetReputation(factionEntry));
1051 return true;
1054 //-----------------------Npc Commands-----------------------
1055 //add spawn of creature
1056 bool ChatHandler::HandleNpcAddCommand(const char* args)
1058 if(!*args)
1059 return false;
1060 char* charID = extractKeyFromLink((char*)args,"Hcreature_entry");
1061 if(!charID)
1062 return false;
1064 char* team = strtok(NULL, " ");
1065 int32 teamval = 0;
1066 if (team) { teamval = atoi(team); }
1067 if (teamval < 0) { teamval = 0; }
1069 uint32 id = atoi(charID);
1071 Player *chr = m_session->GetPlayer();
1072 float x = chr->GetPositionX();
1073 float y = chr->GetPositionY();
1074 float z = chr->GetPositionZ();
1075 float o = chr->GetOrientation();
1076 Map *map = chr->GetMap();
1078 Creature* pCreature = new Creature;
1079 if (!pCreature->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT), map, chr->GetPhaseMaskForSpawn(), id, (uint32)teamval))
1081 delete pCreature;
1082 return false;
1085 pCreature->Relocate(x,y,z,o);
1087 if(!pCreature->IsPositionValid())
1089 sLog.outError("Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
1090 delete pCreature;
1091 return false;
1094 pCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn());
1096 uint32 db_guid = pCreature->GetDBTableGUIDLow();
1098 // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
1099 pCreature->LoadFromDB(db_guid, map);
1101 map->Add(pCreature);
1102 sObjectMgr.AddCreatureToGrid(db_guid, sObjectMgr.GetCreatureData(db_guid));
1103 return true;
1106 //add item in vendorlist
1107 bool ChatHandler::HandleNpcAddVendorItemCommand(const char* args)
1109 if (!*args)
1110 return false;
1112 char* pitem = extractKeyFromLink((char*)args,"Hitem");
1113 if (!pitem)
1115 SendSysMessage(LANG_COMMAND_NEEDITEMSEND);
1116 SetSentErrorMessage(true);
1117 return false;
1120 uint32 itemId = atol(pitem);
1122 char* fmaxcount = strtok(NULL, " "); //add maxcount, default: 0
1123 uint32 maxcount = 0;
1124 if (fmaxcount)
1125 maxcount = atol(fmaxcount);
1127 char* fincrtime = strtok(NULL, " "); //add incrtime, default: 0
1128 uint32 incrtime = 0;
1129 if (fincrtime)
1130 incrtime = atol(fincrtime);
1132 char* fextendedcost = strtok(NULL, " "); //add ExtendedCost, default: 0
1133 uint32 extendedcost = fextendedcost ? atol(fextendedcost) : 0;
1135 Creature* vendor = getSelectedCreature();
1137 uint32 vendor_entry = vendor ? vendor->GetEntry() : 0;
1139 if(!sObjectMgr.IsVendorItemValid(vendor_entry,itemId,maxcount,incrtime,extendedcost,m_session->GetPlayer()))
1141 SetSentErrorMessage(true);
1142 return false;
1145 sObjectMgr.AddVendorItem(vendor_entry,itemId,maxcount,incrtime,extendedcost);
1147 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(itemId);
1149 PSendSysMessage(LANG_ITEM_ADDED_TO_LIST,itemId,pProto->Name1,maxcount,incrtime,extendedcost);
1150 return true;
1153 //del item from vendor list
1154 bool ChatHandler::HandleNpcDelVendorItemCommand(const char* args)
1156 if (!*args)
1157 return false;
1159 Creature* vendor = getSelectedCreature();
1160 if (!vendor || !vendor->isVendor())
1162 SendSysMessage(LANG_COMMAND_VENDORSELECTION);
1163 SetSentErrorMessage(true);
1164 return false;
1167 char* pitem = extractKeyFromLink((char*)args,"Hitem");
1168 if (!pitem)
1170 SendSysMessage(LANG_COMMAND_NEEDITEMSEND);
1171 SetSentErrorMessage(true);
1172 return false;
1174 uint32 itemId = atol(pitem);
1176 if(!sObjectMgr.RemoveVendorItem(vendor->GetEntry(),itemId))
1178 PSendSysMessage(LANG_ITEM_NOT_IN_LIST,itemId);
1179 SetSentErrorMessage(true);
1180 return false;
1183 ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(itemId);
1185 PSendSysMessage(LANG_ITEM_DELETED_FROM_LIST,itemId,pProto->Name1);
1186 return true;
1189 //add move for creature
1190 bool ChatHandler::HandleNpcAddMoveCommand(const char* args)
1192 if(!*args)
1193 return false;
1195 char* guid_str = strtok((char*)args, " ");
1196 char* wait_str = strtok((char*)NULL, " ");
1198 uint32 lowguid = atoi((char*)guid_str);
1200 Creature* pCreature = NULL;
1202 /* FIXME: impossible without entry
1203 if(lowguid)
1204 pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_GUID(lowguid,HIGHGUID_UNIT));
1207 // attempt check creature existence by DB data
1208 if(!pCreature)
1210 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
1211 if(!data)
1213 PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid);
1214 SetSentErrorMessage(true);
1215 return false;
1218 else
1220 // obtain real GUID for DB operations
1221 lowguid = pCreature->GetDBTableGUIDLow();
1224 int wait = wait_str ? atoi(wait_str) : 0;
1226 if(wait < 0)
1227 wait = 0;
1229 Player* player = m_session->GetPlayer();
1231 sWaypointMgr.AddLastNode(lowguid, player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetOrientation(), wait, 0);
1233 // update movement type
1234 WorldDatabase.PExecuteLog("UPDATE creature SET MovementType = '%u' WHERE guid = '%u'", WAYPOINT_MOTION_TYPE,lowguid);
1235 if(pCreature)
1237 pCreature->SetDefaultMovementType(WAYPOINT_MOTION_TYPE);
1238 pCreature->GetMotionMaster()->Initialize();
1239 if(pCreature->isAlive()) // dead creature will reset movement generator at respawn
1241 pCreature->setDeathState(JUST_DIED);
1242 pCreature->Respawn();
1244 pCreature->SaveToDB();
1247 SendSysMessage(LANG_WAYPOINT_ADDED);
1249 return true;
1252 //change level of creature or pet
1253 bool ChatHandler::HandleNpcChangeLevelCommand(const char* args)
1255 if (!*args)
1256 return false;
1258 uint8 lvl = (uint8) atoi((char*)args);
1259 if ( lvl < 1 || lvl > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) + 3)
1261 SendSysMessage(LANG_BAD_VALUE);
1262 SetSentErrorMessage(true);
1263 return false;
1266 Creature* pCreature = getSelectedCreature();
1267 if(!pCreature)
1269 SendSysMessage(LANG_SELECT_CREATURE);
1270 SetSentErrorMessage(true);
1271 return false;
1274 if(pCreature->isPet())
1276 if(((Pet*)pCreature)->getPetType()==HUNTER_PET)
1278 pCreature->SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, sObjectMgr.GetXPForLevel(lvl)/4);
1279 pCreature->SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0);
1281 ((Pet*)pCreature)->GivePetLevel(lvl);
1283 else
1285 pCreature->SetMaxHealth( 100 + 30*lvl);
1286 pCreature->SetHealth( 100 + 30*lvl);
1287 pCreature->SetLevel( lvl);
1288 pCreature->SaveToDB();
1291 return true;
1294 //set npcflag of creature
1295 bool ChatHandler::HandleNpcFlagCommand(const char* args)
1297 if (!*args)
1298 return false;
1300 uint32 npcFlags = (uint32) atoi((char*)args);
1302 Creature* pCreature = getSelectedCreature();
1304 if(!pCreature)
1306 SendSysMessage(LANG_SELECT_CREATURE);
1307 SetSentErrorMessage(true);
1308 return false;
1311 pCreature->SetUInt32Value(UNIT_NPC_FLAGS, npcFlags);
1313 WorldDatabase.PExecuteLog("UPDATE creature_template SET npcflag = '%u' WHERE entry = '%u'", npcFlags, pCreature->GetEntry());
1315 SendSysMessage(LANG_VALUE_SAVED_REJOIN);
1317 return true;
1320 bool ChatHandler::HandleNpcDeleteCommand(const char* args)
1322 Creature* unit = NULL;
1324 if(*args)
1326 // number or [name] Shift-click form |color|Hcreature:creature_guid|h[name]|h|r
1327 char* cId = extractKeyFromLink((char*)args,"Hcreature");
1328 if(!cId)
1329 return false;
1331 uint32 lowguid = atoi(cId);
1332 if(!lowguid)
1333 return false;
1335 if (CreatureData const* cr_data = sObjectMgr.GetCreatureData(lowguid))
1336 unit = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(lowguid, cr_data->id, HIGHGUID_UNIT));
1338 else
1339 unit = getSelectedCreature();
1341 if(!unit || unit->isPet() || unit->isTotem() || unit->isVehicle())
1343 SendSysMessage(LANG_SELECT_CREATURE);
1344 SetSentErrorMessage(true);
1345 return false;
1348 // Delete the creature
1349 unit->CombatStop();
1350 unit->DeleteFromDB();
1351 unit->AddObjectToRemoveList();
1353 SendSysMessage(LANG_COMMAND_DELCREATMESSAGE);
1355 return true;
1358 //move selected creature
1359 bool ChatHandler::HandleNpcMoveCommand(const char* args)
1361 uint32 lowguid = 0;
1363 Creature* pCreature = getSelectedCreature();
1365 if(!pCreature)
1367 // number or [name] Shift-click form |color|Hcreature:creature_guid|h[name]|h|r
1368 char* cId = extractKeyFromLink((char*)args,"Hcreature");
1369 if(!cId)
1370 return false;
1372 lowguid = atoi(cId);
1374 /* FIXME: impossibel without entry
1375 if(lowguid)
1376 pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_GUID(lowguid,HIGHGUID_UNIT));
1379 // Attempting creature load from DB data
1380 if(!pCreature)
1382 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
1383 if(!data)
1385 PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid);
1386 SetSentErrorMessage(true);
1387 return false;
1390 uint32 map_id = data->mapid;
1392 if(m_session->GetPlayer()->GetMapId()!=map_id)
1394 PSendSysMessage(LANG_COMMAND_CREATUREATSAMEMAP, lowguid);
1395 SetSentErrorMessage(true);
1396 return false;
1399 else
1401 lowguid = pCreature->GetDBTableGUIDLow();
1404 else
1406 lowguid = pCreature->GetDBTableGUIDLow();
1409 float x = m_session->GetPlayer()->GetPositionX();
1410 float y = m_session->GetPlayer()->GetPositionY();
1411 float z = m_session->GetPlayer()->GetPositionZ();
1412 float o = m_session->GetPlayer()->GetOrientation();
1414 if (pCreature)
1416 if(CreatureData const* data = sObjectMgr.GetCreatureData(pCreature->GetDBTableGUIDLow()))
1418 const_cast<CreatureData*>(data)->posX = x;
1419 const_cast<CreatureData*>(data)->posY = y;
1420 const_cast<CreatureData*>(data)->posZ = z;
1421 const_cast<CreatureData*>(data)->orientation = o;
1423 pCreature->GetMap()->CreatureRelocation(pCreature,x, y, z,o);
1424 pCreature->GetMotionMaster()->Initialize();
1425 if(pCreature->isAlive()) // dead creature will reset movement generator at respawn
1427 pCreature->setDeathState(JUST_DIED);
1428 pCreature->Respawn();
1432 WorldDatabase.PExecuteLog("UPDATE creature SET position_x = '%f', position_y = '%f', position_z = '%f', orientation = '%f' WHERE guid = '%u'", x, y, z, o, lowguid);
1433 PSendSysMessage(LANG_COMMAND_CREATUREMOVED);
1434 return true;
1437 /**HandleNpcSetMoveTypeCommand
1438 * Set the movement type for an NPC.<br/>
1439 * <br/>
1440 * Valid movement types are:
1441 * <ul>
1442 * <li> stay - NPC wont move </li>
1443 * <li> random - NPC will move randomly according to the spawndist </li>
1444 * <li> way - NPC will move with given waypoints set </li>
1445 * </ul>
1446 * additional parameter: NODEL - so no waypoints are deleted, if you
1447 * change the movement type
1449 bool ChatHandler::HandleNpcSetMoveTypeCommand(const char* args)
1451 if(!*args)
1452 return false;
1454 // 3 arguments:
1455 // GUID (optional - you can also select the creature)
1456 // stay|random|way (determines the kind of movement)
1457 // NODEL (optional - tells the system NOT to delete any waypoints)
1458 // this is very handy if you want to do waypoints, that are
1459 // later switched on/off according to special events (like escort
1460 // quests, etc)
1461 char* guid_str = strtok((char*)args, " ");
1462 char* type_str = strtok((char*)NULL, " ");
1463 char* dontdel_str = strtok((char*)NULL, " ");
1465 bool doNotDelete = false;
1467 if(!guid_str)
1468 return false;
1470 uint32 lowguid = 0;
1471 Creature* pCreature = NULL;
1473 if( dontdel_str )
1475 //sLog.outError("DEBUG: All 3 params are set");
1477 // All 3 params are set
1478 // GUID
1479 // type
1480 // doNotDEL
1481 if( stricmp( dontdel_str, "NODEL" ) == 0 )
1483 //sLog.outError("DEBUG: doNotDelete = true;");
1484 doNotDelete = true;
1487 else
1489 // Only 2 params - but maybe NODEL is set
1490 if( type_str )
1492 sLog.outError("DEBUG: Only 2 params ");
1493 if( stricmp( type_str, "NODEL" ) == 0 )
1495 //sLog.outError("DEBUG: type_str, NODEL ");
1496 doNotDelete = true;
1497 type_str = NULL;
1502 if(!type_str) // case .setmovetype $move_type (with selected creature)
1504 type_str = guid_str;
1505 pCreature = getSelectedCreature();
1506 if(!pCreature || pCreature->isPet())
1507 return false;
1508 lowguid = pCreature->GetDBTableGUIDLow();
1510 else // case .setmovetype #creature_guid $move_type (with selected creature)
1512 lowguid = atoi((char*)guid_str);
1514 /* impossible without entry
1515 if(lowguid)
1516 pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_GUID(lowguid,HIGHGUID_UNIT));
1519 // attempt check creature existence by DB data
1520 if(!pCreature)
1522 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
1523 if(!data)
1525 PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid);
1526 SetSentErrorMessage(true);
1527 return false;
1530 else
1532 lowguid = pCreature->GetDBTableGUIDLow();
1536 // now lowguid is low guid really existed creature
1537 // and pCreature point (maybe) to this creature or NULL
1539 MovementGeneratorType move_type;
1541 std::string type = type_str;
1543 if(type == "stay")
1544 move_type = IDLE_MOTION_TYPE;
1545 else if(type == "random")
1546 move_type = RANDOM_MOTION_TYPE;
1547 else if(type == "way")
1548 move_type = WAYPOINT_MOTION_TYPE;
1549 else
1550 return false;
1552 // update movement type
1553 if(doNotDelete == false)
1554 sWaypointMgr.DeletePath(lowguid);
1556 if(pCreature)
1558 pCreature->SetDefaultMovementType(move_type);
1559 pCreature->GetMotionMaster()->Initialize();
1560 if(pCreature->isAlive()) // dead creature will reset movement generator at respawn
1562 pCreature->setDeathState(JUST_DIED);
1563 pCreature->Respawn();
1565 pCreature->SaveToDB();
1567 if( doNotDelete == false )
1569 PSendSysMessage(LANG_MOVE_TYPE_SET,type_str);
1571 else
1573 PSendSysMessage(LANG_MOVE_TYPE_SET_NODEL,type_str);
1576 return true;
1579 //set model of creature
1580 bool ChatHandler::HandleNpcSetModelCommand(const char* args)
1582 if (!*args)
1583 return false;
1585 uint32 displayId = (uint32) atoi((char*)args);
1587 Creature *pCreature = getSelectedCreature();
1589 if(!pCreature || pCreature->isPet())
1591 SendSysMessage(LANG_SELECT_CREATURE);
1592 SetSentErrorMessage(true);
1593 return false;
1596 pCreature->SetDisplayId(displayId);
1597 pCreature->SetNativeDisplayId(displayId);
1599 pCreature->SaveToDB();
1601 return true;
1603 //set faction of creature
1604 bool ChatHandler::HandleNpcFactionIdCommand(const char* args)
1606 if (!*args)
1607 return false;
1609 uint32 factionId = (uint32) atoi((char*)args);
1611 if (!sFactionTemplateStore.LookupEntry(factionId))
1613 PSendSysMessage(LANG_WRONG_FACTION, factionId);
1614 SetSentErrorMessage(true);
1615 return false;
1618 Creature* pCreature = getSelectedCreature();
1620 if(!pCreature)
1622 SendSysMessage(LANG_SELECT_CREATURE);
1623 SetSentErrorMessage(true);
1624 return false;
1627 pCreature->setFaction(factionId);
1629 // faction is set in creature_template - not inside creature
1631 // update in memory
1632 if(CreatureInfo const *cinfo = pCreature->GetCreatureInfo())
1634 const_cast<CreatureInfo*>(cinfo)->faction_A = factionId;
1635 const_cast<CreatureInfo*>(cinfo)->faction_H = factionId;
1638 // and DB
1639 WorldDatabase.PExecuteLog("UPDATE creature_template SET faction_A = '%u', faction_H = '%u' WHERE entry = '%u'", factionId, factionId, pCreature->GetEntry());
1641 return true;
1643 //set spawn dist of creature
1644 bool ChatHandler::HandleNpcSpawnDistCommand(const char* args)
1646 if(!*args)
1647 return false;
1649 float option = atof((char*)args);
1650 if (option < 0.0f)
1652 SendSysMessage(LANG_BAD_VALUE);
1653 return false;
1656 MovementGeneratorType mtype = IDLE_MOTION_TYPE;
1657 if (option >0.0f)
1658 mtype = RANDOM_MOTION_TYPE;
1660 Creature *pCreature = getSelectedCreature();
1661 uint32 u_guidlow = 0;
1663 if (pCreature)
1664 u_guidlow = pCreature->GetDBTableGUIDLow();
1665 else
1666 return false;
1668 pCreature->SetRespawnRadius((float)option);
1669 pCreature->SetDefaultMovementType(mtype);
1670 pCreature->GetMotionMaster()->Initialize();
1671 if(pCreature->isAlive()) // dead creature will reset movement generator at respawn
1673 pCreature->setDeathState(JUST_DIED);
1674 pCreature->Respawn();
1677 WorldDatabase.PExecuteLog("UPDATE creature SET spawndist=%f, MovementType=%i WHERE guid=%u",option,mtype,u_guidlow);
1678 PSendSysMessage(LANG_COMMAND_SPAWNDIST,option);
1679 return true;
1681 //spawn time handling
1682 bool ChatHandler::HandleNpcSpawnTimeCommand(const char* args)
1684 if(!*args)
1685 return false;
1687 char* stime = strtok((char*)args, " ");
1689 if (!stime)
1690 return false;
1692 int i_stime = atoi((char*)stime);
1694 if (i_stime < 0)
1696 SendSysMessage(LANG_BAD_VALUE);
1697 SetSentErrorMessage(true);
1698 return false;
1701 Creature *pCreature = getSelectedCreature();
1702 uint32 u_guidlow = 0;
1704 if (pCreature)
1705 u_guidlow = pCreature->GetDBTableGUIDLow();
1706 else
1707 return false;
1709 WorldDatabase.PExecuteLog("UPDATE creature SET spawntimesecs=%i WHERE guid=%u",i_stime,u_guidlow);
1710 pCreature->SetRespawnDelay((uint32)i_stime);
1711 PSendSysMessage(LANG_COMMAND_SPAWNTIME,i_stime);
1713 return true;
1715 //npc follow handling
1716 bool ChatHandler::HandleNpcFollowCommand(const char* /*args*/)
1718 Player *player = m_session->GetPlayer();
1719 Creature *creature = getSelectedCreature();
1721 if(!creature)
1723 PSendSysMessage(LANG_SELECT_CREATURE);
1724 SetSentErrorMessage(true);
1725 return false;
1728 // Follow player - Using pet's default dist and angle
1729 creature->GetMotionMaster()->MoveFollow(player, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
1731 PSendSysMessage(LANG_CREATURE_FOLLOW_YOU_NOW, creature->GetName());
1732 return true;
1734 //npc unfollow handling
1735 bool ChatHandler::HandleNpcUnFollowCommand(const char* /*args*/)
1737 Player *player = m_session->GetPlayer();
1738 Creature *creature = getSelectedCreature();
1740 if(!creature)
1742 PSendSysMessage(LANG_SELECT_CREATURE);
1743 SetSentErrorMessage(true);
1744 return false;
1747 if (creature->GetMotionMaster()->empty() ||
1748 creature->GetMotionMaster()->GetCurrentMovementGeneratorType ()!=TARGETED_MOTION_TYPE)
1750 PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU);
1751 SetSentErrorMessage(true);
1752 return false;
1755 TargetedMovementGenerator<Creature> const* mgen
1756 = static_cast<TargetedMovementGenerator<Creature> const*>((creature->GetMotionMaster()->top()));
1758 if(mgen->GetTarget()!=player)
1760 PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU);
1761 SetSentErrorMessage(true);
1762 return false;
1765 // reset movement
1766 creature->GetMotionMaster()->MovementExpired(true);
1768 PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU_NOW, creature->GetName());
1769 return true;
1771 //npc tame handling
1772 bool ChatHandler::HandleNpcTameCommand(const char* /*args*/)
1774 Creature *creatureTarget = getSelectedCreature ();
1775 if (!creatureTarget || creatureTarget->isPet ())
1777 PSendSysMessage (LANG_SELECT_CREATURE);
1778 SetSentErrorMessage (true);
1779 return false;
1782 Player *player = m_session->GetPlayer ();
1784 if(player->GetPetGUID ())
1786 SendSysMessage (LANG_YOU_ALREADY_HAVE_PET);
1787 SetSentErrorMessage (true);
1788 return false;
1791 CreatureInfo const* cInfo = creatureTarget->GetCreatureInfo();
1793 if (!cInfo->isTameable (player->CanTameExoticPets()))
1795 PSendSysMessage (LANG_CREATURE_NON_TAMEABLE,cInfo->Entry);
1796 SetSentErrorMessage (true);
1797 return false;
1800 // Everything looks OK, create new pet
1801 Pet* pet = player->CreateTamedPetFrom (creatureTarget);
1802 if (!pet)
1804 PSendSysMessage (LANG_CREATURE_NON_TAMEABLE,cInfo->Entry);
1805 SetSentErrorMessage (true);
1806 return false;
1809 // place pet before player
1810 float x,y,z;
1811 player->GetClosePoint (x,y,z,creatureTarget->GetObjectSize (),CONTACT_DISTANCE);
1812 pet->Relocate (x,y,z,M_PI-player->GetOrientation ());
1814 // set pet to defensive mode by default (some classes can't control controlled pets in fact).
1815 pet->GetCharmInfo()->SetReactState(REACT_DEFENSIVE);
1817 // calculate proper level
1818 uint32 level = (creatureTarget->getLevel() < (player->getLevel() - 5)) ? (player->getLevel() - 5) : creatureTarget->getLevel();
1820 // prepare visual effect for levelup
1821 pet->SetUInt32Value(UNIT_FIELD_LEVEL, level - 1);
1823 // add to world
1824 pet->GetMap()->Add((Creature*)pet);
1826 // visual effect for levelup
1827 pet->SetUInt32Value(UNIT_FIELD_LEVEL, level);
1829 // caster have pet now
1830 player->SetPet(pet);
1832 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
1833 player->PetSpellInitialize();
1835 return true;
1837 //npc phasemask handling
1838 //change phasemask of creature or pet
1839 bool ChatHandler::HandleNpcSetPhaseCommand(const char* args)
1841 if (!*args)
1842 return false;
1844 uint32 phasemask = (uint32) atoi((char*)args);
1845 if ( phasemask == 0 )
1847 SendSysMessage(LANG_BAD_VALUE);
1848 SetSentErrorMessage(true);
1849 return false;
1852 Creature* pCreature = getSelectedCreature();
1853 if(!pCreature)
1855 SendSysMessage(LANG_SELECT_CREATURE);
1856 SetSentErrorMessage(true);
1857 return false;
1860 pCreature->SetPhaseMask(phasemask,true);
1862 if(!pCreature->isPet())
1863 pCreature->SaveToDB();
1865 return true;
1867 //npc deathstate handling
1868 bool ChatHandler::HandleNpcSetDeathStateCommand(const char* args)
1870 if (!*args)
1871 return false;
1873 Creature* pCreature = getSelectedCreature();
1874 if(!pCreature || pCreature->isPet())
1876 SendSysMessage(LANG_SELECT_CREATURE);
1877 SetSentErrorMessage(true);
1878 return false;
1881 if (strncmp(args, "on", 3) == 0)
1882 pCreature->SetDeadByDefault(true);
1883 else if (strncmp(args, "off", 4) == 0)
1884 pCreature->SetDeadByDefault(false);
1885 else
1887 SendSysMessage(LANG_USE_BOL);
1888 SetSentErrorMessage(true);
1889 return false;
1892 pCreature->SaveToDB();
1893 pCreature->Respawn();
1895 return true;
1898 //TODO: NpcCommands that need to be fixed :
1900 bool ChatHandler::HandleNpcNameCommand(const char* /*args*/)
1902 /* Temp. disabled
1903 if(!*args)
1904 return false;
1906 if(strlen((char*)args)>75)
1908 PSendSysMessage(LANG_TOO_LONG_NAME, strlen((char*)args)-75);
1909 return true;
1912 for (uint8 i = 0; i < strlen(args); ++i)
1914 if(!isalpha(args[i]) && args[i]!=' ')
1916 SendSysMessage(LANG_CHARS_ONLY);
1917 return false;
1921 uint64 guid;
1922 guid = m_session->GetPlayer()->GetSelection();
1923 if (guid == 0)
1925 SendSysMessage(LANG_NO_SELECTION);
1926 return true;
1929 Creature* pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), guid);
1931 if(!pCreature)
1933 SendSysMessage(LANG_SELECT_CREATURE);
1934 return true;
1937 pCreature->SetName(args);
1938 uint32 idname = sObjectMgr.AddCreatureTemplate(pCreature->GetName());
1939 pCreature->SetUInt32Value(OBJECT_FIELD_ENTRY, idname);
1941 pCreature->SaveToDB();
1944 return true;
1947 bool ChatHandler::HandleNpcSubNameCommand(const char* /*args*/)
1949 /* Temp. disabled
1951 if(!*args)
1952 args = "";
1954 if(strlen((char*)args)>75)
1957 PSendSysMessage(LANG_TOO_LONG_SUBNAME, strlen((char*)args)-75);
1958 return true;
1961 for (uint8 i = 0; i < strlen(args); i++)
1963 if(!isalpha(args[i]) && args[i]!=' ')
1965 SendSysMessage(LANG_CHARS_ONLY);
1966 return false;
1969 uint64 guid;
1970 guid = m_session->GetPlayer()->GetSelection();
1971 if (guid == 0)
1973 SendSysMessage(LANG_NO_SELECTION);
1974 return true;
1977 Creature* pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), guid);
1979 if(!pCreature)
1981 SendSysMessage(LANG_SELECT_CREATURE);
1982 return true;
1985 uint32 idname = sObjectMgr.AddCreatureSubName(pCreature->GetName(),args,pCreature->GetUInt32Value(UNIT_FIELD_DISPLAYID));
1986 pCreature->SetUInt32Value(OBJECT_FIELD_ENTRY, idname);
1988 pCreature->SaveToDB();
1990 return true;
1993 //move item to other slot
1994 bool ChatHandler::HandleItemMoveCommand(const char* args)
1996 if(!*args)
1997 return false;
1998 uint8 srcslot, dstslot;
2000 char* pParam1 = strtok((char*)args, " ");
2001 if (!pParam1)
2002 return false;
2004 char* pParam2 = strtok(NULL, " ");
2005 if (!pParam2)
2006 return false;
2008 srcslot = (uint8)atoi(pParam1);
2009 dstslot = (uint8)atoi(pParam2);
2011 if(srcslot==dstslot)
2012 return true;
2014 if(!m_session->GetPlayer()->IsValidPos(INVENTORY_SLOT_BAG_0, srcslot, true))
2015 return false;
2017 // can be autostore pos
2018 if(!m_session->GetPlayer()->IsValidPos(INVENTORY_SLOT_BAG_0,dstslot, false))
2019 return false;
2021 uint16 src = ((INVENTORY_SLOT_BAG_0 << 8) | srcslot);
2022 uint16 dst = ((INVENTORY_SLOT_BAG_0 << 8) | dstslot);
2024 m_session->GetPlayer()->SwapItem( src, dst );
2026 return true;
2029 //demorph player or unit
2030 bool ChatHandler::HandleDeMorphCommand(const char* /*args*/)
2032 Unit *target = getSelectedUnit();
2033 if(!target)
2034 target = m_session->GetPlayer();
2037 // check online security
2038 else if (target->GetTypeId() == TYPEID_PLAYER && HasLowerSecurity((Player*)target, 0))
2039 return false;
2041 target->DeMorph();
2043 return true;
2046 //morph creature or player
2047 bool ChatHandler::HandleModifyMorphCommand(const char* args)
2049 if (!*args)
2050 return false;
2052 uint16 display_id = (uint16)atoi((char*)args);
2054 Unit *target = getSelectedUnit();
2055 if(!target)
2056 target = m_session->GetPlayer();
2058 // check online security
2059 else if (target->GetTypeId() == TYPEID_PLAYER && HasLowerSecurity((Player*)target, 0))
2060 return false;
2062 target->SetDisplayId(display_id);
2064 return true;
2067 //kick player
2068 bool ChatHandler::HandleKickPlayerCommand(const char *args)
2070 Player* target;
2071 if(!extractPlayerTarget((char*)args,&target))
2072 return false;
2074 if (m_session && target==m_session->GetPlayer())
2076 SendSysMessage(LANG_COMMAND_KICKSELF);
2077 SetSentErrorMessage(true);
2078 return false;
2081 // check online security
2082 if (HasLowerSecurity(target, 0))
2083 return false;
2085 // send before target pointer invalidate
2086 PSendSysMessage(LANG_COMMAND_KICKMESSAGE,GetNameLink(target).c_str());
2087 target->GetSession()->KickPlayer();
2088 return true;
2091 //set temporary phase mask for player
2092 bool ChatHandler::HandleModifyPhaseCommand(const char* args)
2094 if (!*args)
2095 return false;
2097 uint32 phasemask = (uint32)atoi((char*)args);
2099 Unit *target = getSelectedUnit();
2100 if(!target)
2101 target = m_session->GetPlayer();
2103 // check online security
2104 else if (target->GetTypeId() == TYPEID_PLAYER && HasLowerSecurity((Player*)target, 0))
2105 return false;
2107 target->SetPhaseMask(phasemask,true);
2109 return true;
2112 //show info of player
2113 bool ChatHandler::HandlePInfoCommand(const char* args)
2115 Player* target;
2116 uint64 target_guid;
2117 std::string target_name;
2118 if(!extractPlayerTarget((char*)args,&target,&target_guid,&target_name))
2119 return false;
2121 uint32 accId = 0;
2122 uint32 money = 0;
2123 uint32 total_player_time = 0;
2124 uint32 level = 0;
2125 uint32 latency = 0;
2127 // get additional information from Player object
2128 if(target)
2130 // check online security
2131 if (HasLowerSecurity(target, 0))
2132 return false;
2134 accId = target->GetSession()->GetAccountId();
2135 money = target->GetMoney();
2136 total_player_time = target->GetTotalPlayedTime();
2137 level = target->getLevel();
2138 latency = target->GetSession()->GetLatency();
2140 // get additional information from DB
2141 else
2143 // check offline security
2144 if (HasLowerSecurity(NULL, target_guid))
2145 return false;
2147 // 0 1 2 3
2148 QueryResult *result = CharacterDatabase.PQuery("SELECT totaltime, level, money, account FROM characters WHERE guid = '%u'", GUID_LOPART(target_guid));
2149 if (!result)
2150 return false;
2152 Field *fields = result->Fetch();
2153 total_player_time = fields[0].GetUInt32();
2154 level = fields[1].GetUInt32();
2155 money = fields[2].GetUInt32();
2156 accId = fields[3].GetUInt32();
2157 delete result;
2160 std::string username = GetMangosString(LANG_ERROR);
2161 std::string last_ip = GetMangosString(LANG_ERROR);
2162 uint32 security = 0;
2163 std::string last_login = GetMangosString(LANG_ERROR);
2165 QueryResult* result = loginDatabase.PQuery("SELECT username,gmlevel,last_ip,last_login FROM account WHERE id = '%u'",accId);
2166 if(result)
2168 Field* fields = result->Fetch();
2169 username = fields[0].GetCppString();
2170 security = fields[1].GetUInt32();
2172 if(!m_session || m_session->GetSecurity() >= security)
2174 last_ip = fields[2].GetCppString();
2175 last_login = fields[3].GetCppString();
2177 else
2179 last_ip = "-";
2180 last_login = "-";
2183 delete result;
2186 std::string nameLink = playerLink(target_name);
2188 PSendSysMessage(LANG_PINFO_ACCOUNT, (target?"":GetMangosString(LANG_OFFLINE)), nameLink.c_str(), GUID_LOPART(target_guid), username.c_str(), accId, security, last_ip.c_str(), last_login.c_str(), latency);
2190 std::string timeStr = secsToTimeString(total_player_time,true,true);
2191 uint32 gold = money /GOLD;
2192 uint32 silv = (money % GOLD) / SILVER;
2193 uint32 copp = (money % GOLD) % SILVER;
2194 PSendSysMessage(LANG_PINFO_LEVEL, timeStr.c_str(), level, gold,silv,copp );
2196 return true;
2199 //show tickets
2200 void ChatHandler::ShowTicket(uint64 guid, char const* text, char const* time)
2202 std::string name;
2203 if(!sObjectMgr.GetPlayerNameByGUID(guid,name))
2204 name = GetMangosString(LANG_UNKNOWN);
2206 std::string nameLink = playerLink(name);
2208 PSendSysMessage(LANG_COMMAND_TICKETVIEW, nameLink.c_str(),time,text);
2211 //ticket commands
2212 bool ChatHandler::HandleTicketCommand(const char* args)
2214 char* px = strtok((char*)args, " ");
2216 // ticket<end>
2217 if (!px)
2219 if(!m_session)
2221 SendSysMessage(LANG_PLAYER_NOT_FOUND);
2222 SetSentErrorMessage(true);
2223 return false;
2226 size_t count = sTicketMgr.GetTicketCount();
2228 bool accept = m_session->GetPlayer()->isAcceptTickets();
2230 PSendSysMessage(LANG_COMMAND_TICKETCOUNT, count, accept ? GetMangosString(LANG_ON) : GetMangosString(LANG_OFF));
2231 return true;
2234 // ticket on
2235 if(strncmp(px,"on",3) == 0)
2237 if(!m_session)
2239 SendSysMessage(LANG_PLAYER_NOT_FOUND);
2240 SetSentErrorMessage(true);
2241 return false;
2244 m_session->GetPlayer()->SetAcceptTicket(true);
2245 SendSysMessage(LANG_COMMAND_TICKETON);
2246 return true;
2249 // ticket off
2250 if(strncmp(px,"off",4) == 0)
2252 if(!m_session)
2254 SendSysMessage(LANG_PLAYER_NOT_FOUND);
2255 SetSentErrorMessage(true);
2256 return false;
2259 m_session->GetPlayer()->SetAcceptTicket(false);
2260 SendSysMessage(LANG_COMMAND_TICKETOFF);
2261 return true;
2264 // ticket #num
2265 int num = atoi(px);
2266 if(num > 0)
2268 QueryResult *result = CharacterDatabase.PQuery("SELECT guid,ticket_text,ticket_lastchange FROM character_ticket ORDER BY ticket_id ASC "_OFFSET_, num-1);
2270 if(!result)
2272 PSendSysMessage(LANG_COMMAND_TICKENOTEXIST, num);
2273 SetSentErrorMessage(true);
2274 return false;
2277 Field* fields = result->Fetch();
2279 uint32 guid = fields[0].GetUInt32();
2280 char const* text = fields[1].GetString();
2281 char const* time = fields[2].GetString();
2283 ShowTicket(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),text,time);
2284 delete result;
2285 return true;
2288 uint64 target_guid;
2289 if(!extractPlayerTarget(px,NULL,&target_guid))
2290 return false;
2292 // ticket $char_name
2293 GMTicket* ticket = sTicketMgr.GetGMTicket(GUID_LOPART(target_guid));
2294 if(!ticket)
2295 return false;
2297 std::string time = TimeToTimestampStr(ticket->GetLastUpdate());
2299 ShowTicket(target_guid, ticket->GetText(), time.c_str());
2301 return true;
2304 //dell all tickets
2305 bool ChatHandler::HandleDelTicketCommand(const char *args)
2307 char* px = strtok((char*)args, " ");
2308 if (!px)
2309 return false;
2311 // delticket all
2312 if(strncmp(px,"all",4) == 0)
2314 sTicketMgr.DeleteAll();
2315 SendSysMessage(LANG_COMMAND_ALLTICKETDELETED);
2316 return true;
2319 int num = (uint32)atoi(px);
2321 // delticket #num
2322 if(num > 0)
2324 QueryResult* result = CharacterDatabase.PQuery("SELECT guid FROM character_ticket ORDER BY ticket_id ASC "_OFFSET_,num-1);
2325 if(!result)
2327 PSendSysMessage(LANG_COMMAND_TICKENOTEXIST, num);
2328 SetSentErrorMessage(true);
2329 return false;
2331 Field* fields = result->Fetch();
2332 uint32 guid = fields[0].GetUInt32();
2333 delete result;
2335 sTicketMgr.Delete(guid);
2337 //notify player
2338 if(Player* pl = sObjectMgr.GetPlayer(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)))
2340 pl->GetSession()->SendGMTicketGetTicket(0x0A, 0);
2341 PSendSysMessage(LANG_COMMAND_TICKETPLAYERDEL, GetNameLink(pl).c_str());
2343 else
2344 PSendSysMessage(LANG_COMMAND_TICKETDEL);
2346 return true;
2349 Player* target;
2350 uint64 target_guid;
2351 std::string target_name;
2352 if(!extractPlayerTarget(px,&target,&target_guid,&target_name))
2353 return false;
2355 // delticket $char_name
2356 sTicketMgr.Delete(GUID_LOPART(target_guid));
2358 // notify players about ticket deleting
2359 if(target)
2360 target->GetSession()->SendGMTicketGetTicket(0x0A,0);
2362 std::string nameLink = playerLink(target_name);
2364 PSendSysMessage(LANG_COMMAND_TICKETPLAYERDEL,nameLink.c_str());
2365 return true;
2369 * Add a waypoint to a creature.
2371 * The user can either select an npc or provide its GUID.
2373 * The user can even select a visual waypoint - then the new waypoint
2374 * is placed *after* the selected one - this makes insertion of new
2375 * waypoints possible.
2377 * eg:
2378 * .wp add 12345
2379 * -> adds a waypoint to the npc with the GUID 12345
2381 * .wp add
2382 * -> adds a waypoint to the currently selected creature
2385 * @param args if the user did not provide a GUID, it is NULL
2387 * @return true - command did succeed, false - something went wrong
2389 bool ChatHandler::HandleWpAddCommand(const char* args)
2391 sLog.outDebug("DEBUG: HandleWpAddCommand");
2393 // optional
2394 char* guid_str = NULL;
2396 if(*args)
2398 guid_str = strtok((char*)args, " ");
2401 uint32 lowguid = 0;
2402 uint32 point = 0;
2403 Creature* target = getSelectedCreature();
2404 // Did player provide a GUID?
2405 if (!guid_str)
2407 sLog.outDebug("DEBUG: HandleWpAddCommand - No GUID provided");
2409 // No GUID provided
2410 // -> Player must have selected a creature
2412 if(!target || target->isPet())
2414 SendSysMessage(LANG_SELECT_CREATURE);
2415 SetSentErrorMessage(true);
2416 return false;
2418 if (target->GetEntry() == VISUAL_WAYPOINT )
2420 sLog.outDebug("DEBUG: HandleWpAddCommand - target->GetEntry() == VISUAL_WAYPOINT (1) ");
2422 QueryResult *result =
2423 WorldDatabase.PQuery( "SELECT id, point FROM creature_movement WHERE wpguid = %u",
2424 target->GetGUIDLow() );
2425 if(!result)
2427 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, target->GetGUIDLow());
2428 // User selected a visual spawnpoint -> get the NPC
2429 // Select NPC GUID
2430 // Since we compare float values, we have to deal with
2431 // some difficulties.
2432 // Here we search for all waypoints that only differ in one from 1 thousand
2433 // (0.001) - There is no other way to compare C++ floats with mySQL floats
2434 // See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-float.html
2435 const char* maxDIFF = "0.01";
2436 result = WorldDatabase.PQuery( "SELECT id, point FROM creature_movement WHERE (abs(position_x - %f) <= %s ) and (abs(position_y - %f) <= %s ) and (abs(position_z - %f) <= %s )",
2437 target->GetPositionX(), maxDIFF, target->GetPositionY(), maxDIFF, target->GetPositionZ(), maxDIFF);
2438 if(!result)
2440 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, target->GetGUIDLow());
2441 SetSentErrorMessage(true);
2442 return false;
2447 Field *fields = result->Fetch();
2448 lowguid = fields[0].GetUInt32();
2449 point = fields[1].GetUInt32();
2450 }while( result->NextRow() );
2451 delete result;
2453 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
2454 if(!data)
2456 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2457 SetSentErrorMessage(true);
2458 return false;
2461 target = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(lowguid,data->id,HIGHGUID_UNIT));
2462 if(!target)
2464 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, lowguid);
2465 SetSentErrorMessage(true);
2466 return false;
2469 else
2471 lowguid = target->GetDBTableGUIDLow();
2474 else
2476 sLog.outDebug("DEBUG: HandleWpAddCommand - GUID provided");
2478 // GUID provided
2479 // Warn if player also selected a creature
2480 // -> Creature selection is ignored <-
2481 if(target)
2483 SendSysMessage(LANG_WAYPOINT_CREATSELECTED);
2485 lowguid = atoi((char*)guid_str);
2487 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
2488 if(!data)
2490 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2491 SetSentErrorMessage(true);
2492 return false;
2495 target = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(lowguid,data->id,HIGHGUID_UNIT));
2496 if(!target || target->isPet())
2498 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2499 SetSentErrorMessage(true);
2500 return false;
2503 // lowguid -> GUID of the NPC
2504 // point -> number of the waypoint (if not 0)
2505 sLog.outDebug("DEBUG: HandleWpAddCommand - danach");
2507 sLog.outDebug("DEBUG: HandleWpAddCommand - point == 0");
2509 Player* player = m_session->GetPlayer();
2510 sWaypointMgr.AddLastNode(lowguid, player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetOrientation(), 0, 0);
2512 // update movement type
2513 if(target)
2515 target->SetDefaultMovementType(WAYPOINT_MOTION_TYPE);
2516 target->GetMotionMaster()->Initialize();
2517 if(target->isAlive()) // dead creature will reset movement generator at respawn
2519 target->setDeathState(JUST_DIED);
2520 target->Respawn();
2522 target->SaveToDB();
2524 else
2525 WorldDatabase.PExecuteLog("UPDATE creature SET MovementType = '%u' WHERE guid = '%u'", WAYPOINT_MOTION_TYPE,lowguid);
2527 PSendSysMessage(LANG_WAYPOINT_ADDED, point, lowguid);
2529 return true;
2530 } // HandleWpAddCommand
2533 * .wp modify emote | spell | text | del | move | add
2535 * add -> add a WP after the selected visual waypoint
2536 * User must select a visual waypoint and then issue ".wp modify add"
2538 * emote <emoteID>
2539 * User has selected a visual waypoint before.
2540 * <emoteID> is added to this waypoint. Everytime the
2541 * NPC comes to this waypoint, the emote is called.
2543 * emote <GUID> <WPNUM> <emoteID>
2544 * User has not selected visual waypoint before.
2545 * For the waypoint <WPNUM> for the NPC with <GUID>
2546 * an emote <emoteID> is added.
2547 * Everytime the NPC comes to this waypoint, the emote is called.
2550 * info <GUID> <WPNUM> -> User did not select a visual waypoint and
2552 bool ChatHandler::HandleWpModifyCommand(const char* args)
2554 sLog.outDebug("DEBUG: HandleWpModifyCommand");
2556 if(!*args)
2557 return false;
2559 // first arg: add del text emote spell waittime move
2560 char* show_str = strtok((char*)args, " ");
2561 if (!show_str)
2563 return false;
2566 std::string show = show_str;
2567 // Check
2568 // Remember: "show" must also be the name of a column!
2569 if( (show != "emote") && (show != "spell") && (show != "textid1") && (show != "textid2")
2570 && (show != "textid3") && (show != "textid4") && (show != "textid5")
2571 && (show != "waittime") && (show != "del") && (show != "move") && (show != "add")
2572 && (show != "model1") && (show != "model2") && (show != "orientation"))
2574 return false;
2577 // Next arg is: <GUID> <WPNUM> <ARGUMENT>
2579 // Did user provide a GUID
2580 // or did the user select a creature?
2581 // -> variable lowguid is filled with the GUID of the NPC
2582 uint32 lowguid = 0;
2583 uint32 point = 0;
2584 uint32 wpGuid = 0;
2585 Creature* target = getSelectedCreature();
2587 if(target)
2589 sLog.outDebug("DEBUG: HandleWpModifyCommand - User did select an NPC");
2591 // Did the user select a visual spawnpoint?
2592 if (target->GetEntry() != VISUAL_WAYPOINT )
2594 PSendSysMessage(LANG_WAYPOINT_VP_SELECT);
2595 SetSentErrorMessage(true);
2596 return false;
2599 wpGuid = target->GetGUIDLow();
2601 // The visual waypoint
2602 QueryResult *result =
2603 WorldDatabase.PQuery( "SELECT id, point FROM creature_movement WHERE wpguid = %u LIMIT 1",
2604 target->GetGUIDLow() );
2605 if(!result)
2607 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, wpGuid);
2608 SetSentErrorMessage(true);
2609 return false;
2611 sLog.outDebug("DEBUG: HandleWpModifyCommand - After getting wpGuid");
2613 Field *fields = result->Fetch();
2614 lowguid = fields[0].GetUInt32();
2615 point = fields[1].GetUInt32();
2617 // Cleanup memory
2618 sLog.outDebug("DEBUG: HandleWpModifyCommand - Cleanup memory");
2619 delete result;
2621 else
2623 // User did provide <GUID> <WPNUM>
2625 char* guid_str = strtok((char*)NULL, " ");
2626 if( !guid_str )
2628 SendSysMessage(LANG_WAYPOINT_NOGUID);
2629 return false;
2631 lowguid = atoi((char*)guid_str);
2633 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
2634 if(!data)
2636 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2637 SetSentErrorMessage(true);
2638 return false;
2641 PSendSysMessage("DEBUG: GUID provided: %d", lowguid);
2643 char* point_str = strtok((char*)NULL, " ");
2644 if( !point_str )
2646 SendSysMessage(LANG_WAYPOINT_NOWAYPOINTGIVEN);
2647 return false;
2649 point = atoi((char*)point_str);
2651 PSendSysMessage("DEBUG: wpNumber provided: %d", point);
2653 // Now we need the GUID of the visual waypoint
2654 // -> "del", "move", "add" command
2656 QueryResult *result = WorldDatabase.PQuery( "SELECT wpguid FROM creature_movement WHERE id = '%u' AND point = '%u' LIMIT 1", lowguid, point);
2657 if (!result)
2659 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, lowguid, point);
2660 SetSentErrorMessage(true);
2661 return false;
2664 Field *fields = result->Fetch();
2665 wpGuid = fields[0].GetUInt32();
2667 // Free memory
2668 delete result;
2671 char* arg_str = NULL;
2672 // Check for argument
2673 if( (show.find("text") == std::string::npos ) && (show != "del") && (show != "move") && (show != "add"))
2675 // Text is enclosed in "<>", all other arguments not
2676 if( show.find("text") != std::string::npos )
2677 arg_str = strtok((char*)NULL, "<>");
2678 else
2679 arg_str = strtok((char*)NULL, " ");
2681 if( !arg_str)
2683 PSendSysMessage(LANG_WAYPOINT_ARGUMENTREQ, show_str);
2684 return false;
2688 sLog.outDebug("DEBUG: HandleWpModifyCommand - Parameters parsed - now execute the command");
2690 // wpGuid -> GUID of the waypoint creature
2691 // lowguid -> GUID of the NPC
2692 // point -> waypoint number
2694 // Special functions:
2695 // add - move - del -> no args commands
2696 // Add a waypoint after the selected visual
2697 if(show == "add" && target)
2699 PSendSysMessage("DEBUG: wp modify add, GUID: %u", lowguid);
2701 // Get the creature for which we read the waypoint
2702 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
2703 if(!data)
2705 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2706 SetSentErrorMessage(true);
2707 return false;
2710 Creature* npcCreature = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT));
2712 if( !npcCreature )
2714 PSendSysMessage(LANG_WAYPOINT_NPCNOTFOUND);
2715 SetSentErrorMessage(true);
2716 return false;
2719 sLog.outDebug("DEBUG: HandleWpModifyCommand - add -- npcCreature");
2721 // What to do:
2722 // Add the visual spawnpoint (DB only)
2723 // Adjust the waypoints
2724 // Respawn the owner of the waypoints
2725 sLog.outDebug("DEBUG: HandleWpModifyCommand - add");
2727 Player* chr = m_session->GetPlayer();
2728 Map *map = chr->GetMap();
2730 if(npcCreature)
2732 npcCreature->GetMotionMaster()->Initialize();
2733 if(npcCreature->isAlive()) // dead creature will reset movement generator at respawn
2735 npcCreature->setDeathState(JUST_DIED);
2736 npcCreature->Respawn();
2740 // create the waypoint creature
2741 wpGuid = 0;
2742 Creature* wpCreature = new Creature;
2743 if (!wpCreature->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT), map, chr->GetPhaseMaskForSpawn(), VISUAL_WAYPOINT,0))
2745 PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, VISUAL_WAYPOINT);
2746 delete wpCreature;
2748 else
2750 wpCreature->Relocate(chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), chr->GetOrientation());
2752 if(!wpCreature->IsPositionValid())
2754 sLog.outError("Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",wpCreature->GetGUIDLow(),wpCreature->GetEntry(),wpCreature->GetPositionX(),wpCreature->GetPositionY());
2755 delete wpCreature;
2757 else
2759 wpCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn());
2760 // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
2761 wpCreature->LoadFromDB(wpCreature->GetDBTableGUIDLow(), map);
2762 map->Add(wpCreature);
2763 wpGuid = wpCreature->GetGUIDLow();
2767 sWaypointMgr.AddAfterNode(lowguid, point, chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), 0, 0, wpGuid);
2769 if(!wpGuid)
2770 return false;
2772 PSendSysMessage(LANG_WAYPOINT_ADDED_NO, point+1);
2773 return true;
2774 } // add
2776 if(show == "del" && target)
2778 PSendSysMessage("DEBUG: wp modify del, GUID: %u", lowguid);
2780 // Get the creature for which we read the waypoint
2781 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
2782 if(!data)
2784 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2785 SetSentErrorMessage(true);
2786 return false;
2789 Creature* npcCreature = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT));
2791 // wpCreature
2792 Creature* wpCreature = NULL;
2793 if( wpGuid != 0 )
2795 wpCreature = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT));
2796 wpCreature->DeleteFromDB();
2797 wpCreature->AddObjectToRemoveList();
2800 // What to do:
2801 // Remove the visual spawnpoint
2802 // Adjust the waypoints
2803 // Respawn the owner of the waypoints
2805 sWaypointMgr.DeleteNode(lowguid, point);
2807 if(npcCreature)
2809 // Any waypoints left?
2810 QueryResult *result2 = WorldDatabase.PQuery( "SELECT point FROM creature_movement WHERE id = '%u'",lowguid);
2811 if(!result2)
2813 npcCreature->SetDefaultMovementType(RANDOM_MOTION_TYPE);
2815 else
2817 npcCreature->SetDefaultMovementType(WAYPOINT_MOTION_TYPE);
2818 delete result2;
2820 npcCreature->GetMotionMaster()->Initialize();
2821 if(npcCreature->isAlive()) // dead creature will reset movement generator at respawn
2823 npcCreature->setDeathState(JUST_DIED);
2824 npcCreature->Respawn();
2826 npcCreature->SaveToDB();
2829 PSendSysMessage(LANG_WAYPOINT_REMOVED);
2830 return true;
2831 } // del
2833 if(show == "move" && target)
2835 PSendSysMessage("DEBUG: wp move, GUID: %u", lowguid);
2837 Player *chr = m_session->GetPlayer();
2838 Map *map = chr->GetMap();
2840 // Get the creature for which we read the waypoint
2841 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
2842 if(!data)
2844 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2845 SetSentErrorMessage(true);
2846 return false;
2849 Creature* npcCreature = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT));
2851 // wpCreature
2852 Creature* wpCreature = NULL;
2853 // What to do:
2854 // Move the visual spawnpoint
2855 // Respawn the owner of the waypoints
2856 if( wpGuid != 0 )
2858 wpCreature = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT));
2859 wpCreature->DeleteFromDB();
2860 wpCreature->AddObjectToRemoveList();
2861 // re-create
2862 Creature* wpCreature2 = new Creature;
2863 if (!wpCreature2->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT), map, chr->GetPhaseMaskForSpawn(), VISUAL_WAYPOINT, 0))
2865 PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, VISUAL_WAYPOINT);
2866 delete wpCreature2;
2867 return false;
2870 wpCreature2->Relocate(chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), chr->GetOrientation());
2872 if(!wpCreature2->IsPositionValid())
2874 sLog.outError("Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",wpCreature2->GetGUIDLow(),wpCreature2->GetEntry(),wpCreature2->GetPositionX(),wpCreature2->GetPositionY());
2875 delete wpCreature2;
2876 return false;
2879 wpCreature2->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn());
2880 // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
2881 wpCreature2->LoadFromDB(wpCreature2->GetDBTableGUIDLow(), map);
2882 map->Add(wpCreature2);
2883 //npcCreature->GetMap()->Add(wpCreature2);
2886 sWaypointMgr.SetNodePosition(lowguid, point, chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ());
2888 if(npcCreature)
2890 npcCreature->GetMotionMaster()->Initialize();
2891 if(npcCreature->isAlive()) // dead creature will reset movement generator at respawn
2893 npcCreature->setDeathState(JUST_DIED);
2894 npcCreature->Respawn();
2897 PSendSysMessage(LANG_WAYPOINT_CHANGED);
2899 return true;
2900 } // move
2902 // Create creature - npc that has the waypoint
2903 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
2904 if(!data)
2906 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2907 SetSentErrorMessage(true);
2908 return false;
2911 // set in game textids not supported
2912 if( show == "textid1" || show == "textid2" || show == "textid3" ||
2913 show == "textid4" || show == "textid5" )
2915 return false;
2918 sWaypointMgr.SetNodeText(lowguid, point, show_str, arg_str);
2920 Creature* npcCreature = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT));
2921 if(npcCreature)
2923 npcCreature->SetDefaultMovementType(WAYPOINT_MOTION_TYPE);
2924 npcCreature->GetMotionMaster()->Initialize();
2925 if(npcCreature->isAlive()) // dead creature will reset movement generator at respawn
2927 npcCreature->setDeathState(JUST_DIED);
2928 npcCreature->Respawn();
2931 PSendSysMessage(LANG_WAYPOINT_CHANGED_NO, show_str);
2933 return true;
2937 * .wp show info | on | off
2939 * info -> User has selected a visual waypoint before
2941 * info <GUID> <WPNUM> -> User did not select a visual waypoint and
2942 * provided the GUID of the NPC and the number of
2943 * the waypoint.
2945 * on -> User has selected an NPC; all visual waypoints for this
2946 * NPC are added to the world
2948 * on <GUID> -> User did not select an NPC - instead the GUID of the
2949 * NPC is provided. All visual waypoints for this NPC
2950 * are added from the world.
2952 * off -> User has selected an NPC; all visual waypoints for this
2953 * NPC are removed from the world.
2955 * on <GUID> -> User did not select an NPC - instead the GUID of the
2956 * NPC is provided. All visual waypoints for this NPC
2957 * are removed from the world.
2961 bool ChatHandler::HandleWpShowCommand(const char* args)
2963 sLog.outDebug("DEBUG: HandleWpShowCommand");
2965 if(!*args)
2966 return false;
2968 // first arg: on, off, first, last
2969 char* show_str = strtok((char*)args, " ");
2970 if (!show_str)
2972 return false;
2974 // second arg: GUID (optional, if a creature is selected)
2975 char* guid_str = strtok((char*)NULL, " ");
2976 sLog.outDebug("DEBUG: HandleWpShowCommand: show_str: %s guid_str: %s", show_str, guid_str);
2977 //if (!guid_str) {
2978 // return false;
2981 // Did user provide a GUID
2982 // or did the user select a creature?
2983 // -> variable lowguid is filled with the GUID
2984 Creature* target = getSelectedCreature();
2985 // Did player provide a GUID?
2986 if (!guid_str)
2988 sLog.outDebug("DEBUG: HandleWpShowCommand: !guid_str");
2989 // No GUID provided
2990 // -> Player must have selected a creature
2992 if(!target)
2994 SendSysMessage(LANG_SELECT_CREATURE);
2995 SetSentErrorMessage(true);
2996 return false;
2999 else
3001 sLog.outDebug("DEBUG: HandleWpShowCommand: GUID provided");
3002 // GUID provided
3003 // Warn if player also selected a creature
3004 // -> Creature selection is ignored <-
3005 if(target)
3007 SendSysMessage(LANG_WAYPOINT_CREATSELECTED);
3010 uint32 lowguid = atoi((char*)guid_str);
3012 CreatureData const* data = sObjectMgr.GetCreatureData(lowguid);
3013 if(!data)
3015 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
3016 SetSentErrorMessage(true);
3017 return false;
3020 target = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(lowguid,data->id,HIGHGUID_UNIT));
3022 if(!target)
3024 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
3025 SetSentErrorMessage(true);
3026 return false;
3030 uint32 lowguid = target->GetDBTableGUIDLow();
3032 std::string show = show_str;
3033 uint32 Maxpoint;
3035 sLog.outDebug("DEBUG: HandleWpShowCommand: lowguid: %u show: %s", lowguid, show_str);
3037 // Show info for the selected waypoint
3038 if(show == "info")
3040 PSendSysMessage("DEBUG: wp info, GUID: %u", lowguid);
3042 // Check if the user did specify a visual waypoint
3043 if( target->GetEntry() != VISUAL_WAYPOINT )
3045 PSendSysMessage(LANG_WAYPOINT_VP_SELECT);
3046 SetSentErrorMessage(true);
3047 return false;
3050 //PSendSysMessage("wp on, GUID: %u", lowguid);
3052 //pCreature->GetPositionX();
3054 QueryResult *result =
3055 WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5, model1, model2 FROM creature_movement WHERE wpguid = %u",
3056 target->GetGUIDLow() );
3057 if(!result)
3059 // Since we compare float values, we have to deal with
3060 // some difficulties.
3061 // Here we search for all waypoints that only differ in one from 1 thousand
3062 // (0.001) - There is no other way to compare C++ floats with mySQL floats
3063 // See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-float.html
3064 const char* maxDIFF = "0.01";
3065 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, target->GetGUID());
3067 result = WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5, model1, model2 FROM creature_movement WHERE (abs(position_x - %f) <= %s ) and (abs(position_y - %f) <= %s ) and (abs(position_z - %f) <= %s )",
3068 target->GetPositionX(), maxDIFF, target->GetPositionY(), maxDIFF, target->GetPositionZ(), maxDIFF);
3069 if(!result)
3071 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, lowguid);
3072 SetSentErrorMessage(true);
3073 return false;
3078 Field *fields = result->Fetch();
3079 uint32 creGUID = fields[0].GetUInt32();
3080 uint32 point = fields[1].GetUInt32();
3081 int waittime = fields[2].GetUInt32();
3082 uint32 emote = fields[3].GetUInt32();
3083 uint32 spell = fields[4].GetUInt32();
3084 uint32 textid[MAX_WAYPOINT_TEXT];
3085 for(int i = 0; i < MAX_WAYPOINT_TEXT; ++i)
3086 textid[i] = fields[5+i].GetUInt32();
3087 uint32 model1 = fields[10].GetUInt32();
3088 uint32 model2 = fields[11].GetUInt32();
3090 // Get the creature for which we read the waypoint
3091 Creature* wpCreature = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(creGUID,VISUAL_WAYPOINT,HIGHGUID_UNIT));
3093 PSendSysMessage(LANG_WAYPOINT_INFO_TITLE, point, (wpCreature ? wpCreature->GetName() : "<not found>"), creGUID);
3094 PSendSysMessage(LANG_WAYPOINT_INFO_WAITTIME, waittime);
3095 PSendSysMessage(LANG_WAYPOINT_INFO_MODEL, 1, model1);
3096 PSendSysMessage(LANG_WAYPOINT_INFO_MODEL, 2, model2);
3097 PSendSysMessage(LANG_WAYPOINT_INFO_EMOTE, emote);
3098 PSendSysMessage(LANG_WAYPOINT_INFO_SPELL, spell);
3099 for(int i = 0; i < MAX_WAYPOINT_TEXT; ++i)
3100 PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, i+1, textid[i], (textid[i] ? GetMangosString(textid[i]) : ""));
3102 }while( result->NextRow() );
3103 // Cleanup memory
3104 delete result;
3105 return true;
3108 if(show == "on")
3110 PSendSysMessage("DEBUG: wp on, GUID: %u", lowguid);
3112 QueryResult *result = WorldDatabase.PQuery( "SELECT point, position_x,position_y,position_z FROM creature_movement WHERE id = '%u'",lowguid);
3113 if(!result)
3115 PSendSysMessage(LANG_WAYPOINT_NOTFOUND, lowguid);
3116 SetSentErrorMessage(true);
3117 return false;
3119 // Delete all visuals for this NPC
3120 QueryResult *result2 = WorldDatabase.PQuery( "SELECT wpguid FROM creature_movement WHERE id = '%u' and wpguid <> 0", lowguid);
3121 if(result2)
3123 bool hasError = false;
3126 Field *fields = result2->Fetch();
3127 uint32 wpguid = fields[0].GetUInt32();
3128 Creature* pCreature = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(wpguid,VISUAL_WAYPOINT,HIGHGUID_UNIT));
3130 if(!pCreature)
3132 PSendSysMessage(LANG_WAYPOINT_NOTREMOVED, wpguid);
3133 hasError = true;
3134 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", wpguid);
3136 else
3138 pCreature->DeleteFromDB();
3139 pCreature->AddObjectToRemoveList();
3142 }while( result2->NextRow() );
3143 delete result2;
3144 if( hasError )
3146 PSendSysMessage(LANG_WAYPOINT_TOOFAR1);
3147 PSendSysMessage(LANG_WAYPOINT_TOOFAR2);
3148 PSendSysMessage(LANG_WAYPOINT_TOOFAR3);
3154 Field *fields = result->Fetch();
3155 uint32 point = fields[0].GetUInt32();
3156 float x = fields[1].GetFloat();
3157 float y = fields[2].GetFloat();
3158 float z = fields[3].GetFloat();
3160 uint32 id = VISUAL_WAYPOINT;
3162 Player *chr = m_session->GetPlayer();
3163 Map *map = chr->GetMap();
3164 float o = chr->GetOrientation();
3166 Creature* wpCreature = new Creature;
3167 if (!wpCreature->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT), map, chr->GetPhaseMaskForSpawn(), id, 0))
3169 PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, id);
3170 delete wpCreature;
3171 delete result;
3172 return false;
3175 wpCreature->Relocate(x, y, z, o);
3177 if(!wpCreature->IsPositionValid())
3179 sLog.outError("Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",wpCreature->GetGUIDLow(),wpCreature->GetEntry(),wpCreature->GetPositionX(),wpCreature->GetPositionY());
3180 delete wpCreature;
3181 delete result;
3182 return false;
3185 wpCreature->SetVisibility(VISIBILITY_OFF);
3186 sLog.outDebug("DEBUG: UPDATE creature_movement SET wpguid = '%u", wpCreature->GetGUIDLow());
3187 // set "wpguid" column to the visual waypoint
3188 WorldDatabase.PExecuteLog("UPDATE creature_movement SET wpguid = '%u' WHERE id = '%u' and point = '%u'", wpCreature->GetGUIDLow(), lowguid, point);
3190 wpCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn());
3191 // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
3192 wpCreature->LoadFromDB(wpCreature->GetDBTableGUIDLow(),map);
3193 map->Add(wpCreature);
3194 //wpCreature->GetMap()->Add(wpCreature);
3195 }while( result->NextRow() );
3197 // Cleanup memory
3198 delete result;
3199 return true;
3202 if(show == "first")
3204 PSendSysMessage("DEBUG: wp first, GUID: %u", lowguid);
3206 QueryResult *result = WorldDatabase.PQuery( "SELECT position_x,position_y,position_z FROM creature_movement WHERE point='1' AND id = '%u'",lowguid);
3207 if(!result)
3209 PSendSysMessage(LANG_WAYPOINT_NOTFOUND, lowguid);
3210 SetSentErrorMessage(true);
3211 return false;
3214 Field *fields = result->Fetch();
3215 float x = fields[0].GetFloat();
3216 float y = fields[1].GetFloat();
3217 float z = fields[2].GetFloat();
3218 uint32 id = VISUAL_WAYPOINT;
3220 Player *chr = m_session->GetPlayer();
3221 float o = chr->GetOrientation();
3222 Map *map = chr->GetMap();
3224 Creature* pCreature = new Creature;
3225 if (!pCreature->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT),map, chr->GetPhaseMaskForSpawn(), id, 0))
3227 PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, id);
3228 delete pCreature;
3229 delete result;
3230 return false;
3233 pCreature->Relocate(x, y, z, o);
3235 if(!pCreature->IsPositionValid())
3237 sLog.outError("Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
3238 delete pCreature;
3239 delete result;
3240 return false;
3243 pCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn());
3244 pCreature->LoadFromDB(pCreature->GetDBTableGUIDLow(), map);
3245 map->Add(pCreature);
3246 //player->PlayerTalkClass->SendPointOfInterest(x, y, 6, 6, 0, "First Waypoint");
3248 // Cleanup memory
3249 delete result;
3250 return true;
3253 if(show == "last")
3255 PSendSysMessage("DEBUG: wp last, GUID: %u", lowguid);
3257 QueryResult *result = WorldDatabase.PQuery( "SELECT MAX(point) FROM creature_movement WHERE id = '%u'",lowguid);
3258 if( result )
3260 Maxpoint = (*result)[0].GetUInt32();
3262 delete result;
3264 else
3265 Maxpoint = 0;
3267 result = WorldDatabase.PQuery( "SELECT position_x,position_y,position_z FROM creature_movement WHERE point ='%u' AND id = '%u'",Maxpoint, lowguid);
3268 if(!result)
3270 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDLAST, lowguid);
3271 SetSentErrorMessage(true);
3272 return false;
3274 Field *fields = result->Fetch();
3275 float x = fields[0].GetFloat();
3276 float y = fields[1].GetFloat();
3277 float z = fields[2].GetFloat();
3278 uint32 id = VISUAL_WAYPOINT;
3280 Player *chr = m_session->GetPlayer();
3281 float o = chr->GetOrientation();
3282 Map *map = chr->GetMap();
3284 Creature* pCreature = new Creature;
3285 if (!pCreature->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_UNIT), map, chr->GetPhaseMaskForSpawn(), id, 0))
3287 PSendSysMessage(LANG_WAYPOINT_NOTCREATED, id);
3288 delete pCreature;
3289 delete result;
3290 return false;
3293 pCreature->Relocate(x, y, z, o);
3295 if(!pCreature->IsPositionValid())
3297 sLog.outError("Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
3298 delete pCreature;
3299 delete result;
3300 return false;
3303 pCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn());
3304 pCreature->LoadFromDB(pCreature->GetDBTableGUIDLow(), map);
3305 map->Add(pCreature);
3306 //player->PlayerTalkClass->SendPointOfInterest(x, y, 6, 6, 0, "Last Waypoint");
3307 // Cleanup memory
3308 delete result;
3309 return true;
3312 if(show == "off")
3314 QueryResult *result = WorldDatabase.PQuery("SELECT guid FROM creature WHERE id = '%d'", VISUAL_WAYPOINT);
3315 if(!result)
3317 SendSysMessage(LANG_WAYPOINT_VP_NOTFOUND);
3318 SetSentErrorMessage(true);
3319 return false;
3321 bool hasError = false;
3324 Field *fields = result->Fetch();
3325 uint32 guid = fields[0].GetUInt32();
3326 Creature* pCreature = m_session->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(guid,VISUAL_WAYPOINT,HIGHGUID_UNIT));
3327 if(!pCreature)
3329 PSendSysMessage(LANG_WAYPOINT_NOTREMOVED, guid);
3330 hasError = true;
3331 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", guid);
3333 else
3335 pCreature->DeleteFromDB();
3336 pCreature->AddObjectToRemoveList();
3338 }while(result->NextRow());
3339 // set "wpguid" column to "empty" - no visual waypoint spawned
3340 WorldDatabase.PExecuteLog("UPDATE creature_movement SET wpguid = '0' WHERE wpguid <> '0'");
3342 if( hasError )
3344 PSendSysMessage(LANG_WAYPOINT_TOOFAR1);
3345 PSendSysMessage(LANG_WAYPOINT_TOOFAR2);
3346 PSendSysMessage(LANG_WAYPOINT_TOOFAR3);
3349 SendSysMessage(LANG_WAYPOINT_VP_ALLREMOVED);
3350 // Cleanup memory
3351 delete result;
3353 return true;
3356 PSendSysMessage("DEBUG: wpshow - no valid command found");
3358 return true;
3359 } // HandleWpShowCommand
3361 bool ChatHandler::HandleWpExportCommand(const char *args)
3363 if(!*args)
3364 return false;
3366 // Next arg is: <GUID> <ARGUMENT>
3368 // Did user provide a GUID
3369 // or did the user select a creature?
3370 // -> variable lowguid is filled with the GUID of the NPC
3371 uint32 lowguid = 0;
3372 Creature* target = getSelectedCreature();
3373 char* arg_str = NULL;
3374 if (target)
3376 if (target->GetEntry() != VISUAL_WAYPOINT)
3377 lowguid = target->GetGUIDLow();
3378 else
3380 QueryResult *result = WorldDatabase.PQuery( "SELECT id FROM creature_movement WHERE wpguid = %u LIMIT 1", target->GetGUIDLow() );
3381 if (!result)
3383 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, target->GetGUIDLow());
3384 return true;
3386 Field *fields = result->Fetch();
3387 lowguid = fields[0].GetUInt32();;
3388 delete result;
3391 arg_str = strtok((char*)args, " ");
3393 else
3395 // user provided <GUID>
3396 char* guid_str = strtok((char*)args, " ");
3397 if( !guid_str )
3399 SendSysMessage(LANG_WAYPOINT_NOGUID);
3400 return false;
3402 lowguid = atoi((char*)guid_str);
3404 arg_str = strtok((char*)NULL, " ");
3407 if( !arg_str)
3409 PSendSysMessage(LANG_WAYPOINT_ARGUMENTREQ, "export");
3410 return false;
3413 PSendSysMessage("DEBUG: wp export, GUID: %u", lowguid);
3415 QueryResult *result = WorldDatabase.PQuery(
3416 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
3417 "SELECT point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5, id FROM creature_movement WHERE id = '%u' ORDER BY point", lowguid );
3419 if (!result)
3421 PSendSysMessage(LANG_WAYPOINT_NOTHINGTOEXPORT);
3422 SetSentErrorMessage(true);
3423 return false;
3426 std::ofstream outfile;
3427 outfile.open (arg_str);
3431 Field *fields = result->Fetch();
3433 outfile << "INSERT INTO creature_movement ";
3434 outfile << "( id, point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, textid1, textid2, textid3, textid4, textid5 ) VALUES ";
3436 outfile << "( ";
3437 outfile << fields[15].GetUInt32(); // id
3438 outfile << ", ";
3439 outfile << fields[0].GetUInt32(); // point
3440 outfile << ", ";
3441 outfile << fields[1].GetFloat(); // position_x
3442 outfile << ", ";
3443 outfile << fields[2].GetFloat(); // position_y
3444 outfile << ", ";
3445 outfile << fields[3].GetUInt32(); // position_z
3446 outfile << ", ";
3447 outfile << fields[4].GetUInt32(); // orientation
3448 outfile << ", ";
3449 outfile << fields[5].GetUInt32(); // model1
3450 outfile << ", ";
3451 outfile << fields[6].GetUInt32(); // model2
3452 outfile << ", ";
3453 outfile << fields[7].GetUInt16(); // waittime
3454 outfile << ", ";
3455 outfile << fields[8].GetUInt32(); // emote
3456 outfile << ", ";
3457 outfile << fields[9].GetUInt32(); // spell
3458 outfile << ", ";
3459 outfile << fields[10].GetUInt32(); // textid1
3460 outfile << ", ";
3461 outfile << fields[11].GetUInt32(); // textid2
3462 outfile << ", ";
3463 outfile << fields[12].GetUInt32(); // textid3
3464 outfile << ", ";
3465 outfile << fields[13].GetUInt32(); // textid4
3466 outfile << ", ";
3467 outfile << fields[14].GetUInt32(); // textid5
3468 outfile << ");\n ";
3470 } while( result->NextRow() );
3471 delete result;
3473 PSendSysMessage(LANG_WAYPOINT_EXPORTED);
3474 outfile.close();
3476 return true;
3479 bool ChatHandler::HandleWpImportCommand(const char *args)
3481 if(!*args)
3482 return false;
3484 char* arg_str = strtok((char*)args, " ");
3485 if (!arg_str)
3486 return false;
3488 std::string line;
3489 std::ifstream infile (arg_str);
3490 if (infile.is_open())
3492 while (! infile.eof() )
3494 getline (infile,line);
3495 //cout << line << endl;
3496 QueryResult *result = WorldDatabase.Query(line.c_str());
3497 delete result;
3499 infile.close();
3501 PSendSysMessage(LANG_WAYPOINT_IMPORTED);
3503 return true;
3506 //rename characters
3507 bool ChatHandler::HandleCharacterRenameCommand(const char* args)
3509 Player* target;
3510 uint64 target_guid;
3511 std::string target_name;
3512 if(!extractPlayerTarget((char*)args,&target,&target_guid,&target_name))
3513 return false;
3515 if(target)
3517 // check online security
3518 if (HasLowerSecurity(target, 0))
3519 return false;
3521 PSendSysMessage(LANG_RENAME_PLAYER, GetNameLink(target).c_str());
3522 target->SetAtLoginFlag(AT_LOGIN_RENAME);
3523 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '1' WHERE guid = '%u'", target->GetGUIDLow());
3525 else
3527 // check offline security
3528 if (HasLowerSecurity(NULL, target_guid))
3529 return false;
3531 std::string oldNameLink = playerLink(target_name);
3533 PSendSysMessage(LANG_RENAME_PLAYER_GUID, oldNameLink.c_str(), GUID_LOPART(target_guid));
3534 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '1' WHERE guid = '%u'", GUID_LOPART(target_guid));
3537 return true;
3540 // customize characters
3541 bool ChatHandler::HandleCharacterCustomizeCommand(const char* args)
3543 Player* target;
3544 uint64 target_guid;
3545 std::string target_name;
3546 if(!extractPlayerTarget((char*)args,&target,&target_guid,&target_name))
3547 return false;
3549 if(target)
3551 PSendSysMessage(LANG_CUSTOMIZE_PLAYER, GetNameLink(target).c_str());
3552 target->SetAtLoginFlag(AT_LOGIN_CUSTOMIZE);
3553 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '8' WHERE guid = '%u'", target->GetGUIDLow());
3555 else
3557 std::string oldNameLink = playerLink(target_name);
3559 PSendSysMessage(LANG_CUSTOMIZE_PLAYER_GUID, oldNameLink.c_str(), GUID_LOPART(target_guid));
3560 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '8' WHERE guid = '%u'", GUID_LOPART(target_guid));
3563 return true;
3566 bool ChatHandler::HandleCharacterReputationCommand(const char* args)
3568 Player* target;
3569 if(!extractPlayerTarget((char*)args,&target))
3570 return false;
3572 LocaleConstant loc = GetSessionDbcLocale();
3574 FactionStateList const& targetFSL = target->GetReputationMgr().GetStateList();
3575 for(FactionStateList::const_iterator itr = targetFSL.begin(); itr != targetFSL.end(); ++itr)
3577 FactionEntry const *factionEntry = sFactionStore.LookupEntry(itr->second.ID);
3578 char const* factionName = factionEntry ? factionEntry->name[loc] : "#Not found#";
3579 ReputationRank rank = target->GetReputationMgr().GetRank(factionEntry);
3580 std::string rankName = GetMangosString(ReputationRankStrIndex[rank]);
3581 std::ostringstream ss;
3582 if (m_session)
3583 ss << itr->second.ID << " - |cffffffff|Hfaction:" << itr->second.ID << "|h[" << factionName << " " << localeNames[loc] << "]|h|r";
3584 else
3585 ss << itr->second.ID << " - " << factionName << " " << localeNames[loc];
3587 ss << " " << rankName << " (" << target->GetReputationMgr().GetReputation(factionEntry) << ")";
3589 if(itr->second.Flags & FACTION_FLAG_VISIBLE)
3590 ss << GetMangosString(LANG_FACTION_VISIBLE);
3591 if(itr->second.Flags & FACTION_FLAG_AT_WAR)
3592 ss << GetMangosString(LANG_FACTION_ATWAR);
3593 if(itr->second.Flags & FACTION_FLAG_PEACE_FORCED)
3594 ss << GetMangosString(LANG_FACTION_PEACE_FORCED);
3595 if(itr->second.Flags & FACTION_FLAG_HIDDEN)
3596 ss << GetMangosString(LANG_FACTION_HIDDEN);
3597 if(itr->second.Flags & FACTION_FLAG_INVISIBLE_FORCED)
3598 ss << GetMangosString(LANG_FACTION_INVISIBLE_FORCED);
3599 if(itr->second.Flags & FACTION_FLAG_INACTIVE)
3600 ss << GetMangosString(LANG_FACTION_INACTIVE);
3602 SendSysMessage(ss.str().c_str());
3604 return true;
3607 //change standstate
3608 bool ChatHandler::HandleModifyStandStateCommand(const char* args)
3610 if (!*args)
3611 return false;
3613 uint32 anim_id = atoi((char*)args);
3614 m_session->GetPlayer( )->SetUInt32Value( UNIT_NPC_EMOTESTATE , anim_id );
3616 return true;
3619 bool ChatHandler::HandleHonorAddCommand(const char* args)
3621 if (!*args)
3622 return false;
3624 Player *target = getSelectedPlayer();
3625 if(!target)
3627 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3628 SetSentErrorMessage(true);
3629 return false;
3632 // check online security
3633 if (HasLowerSecurity(target, 0))
3634 return false;
3636 uint32 amount = (uint32)atoi(args);
3637 target->RewardHonor(NULL, 1, amount);
3638 return true;
3641 bool ChatHandler::HandleHonorAddKillCommand(const char* /*args*/)
3643 Unit *target = getSelectedUnit();
3644 if(!target)
3646 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3647 SetSentErrorMessage(true);
3648 return false;
3651 // check online security
3652 if (target->GetTypeId() == TYPEID_PLAYER && HasLowerSecurity((Player*)target, 0))
3653 return false;
3655 m_session->GetPlayer()->RewardHonor(target, 1);
3656 return true;
3659 bool ChatHandler::HandleHonorUpdateCommand(const char* /*args*/)
3661 Player *target = getSelectedPlayer();
3662 if(!target)
3664 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3665 SetSentErrorMessage(true);
3666 return false;
3669 // check online security
3670 if (HasLowerSecurity(target, 0))
3671 return false;
3673 target->UpdateHonorFields();
3674 return true;
3677 bool ChatHandler::HandleLookupEventCommand(const char* args)
3679 if(!*args)
3680 return false;
3682 std::string namepart = args;
3683 std::wstring wnamepart;
3685 // converting string that we try to find to lower case
3686 if(!Utf8toWStr(namepart,wnamepart))
3687 return false;
3689 wstrToLower(wnamepart);
3691 uint32 counter = 0;
3693 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
3694 GameEventMgr::ActiveEvents const& activeEvents = sGameEventMgr.GetActiveEventList();
3696 for(uint32 id = 0; id < events.size(); ++id )
3698 GameEventData const& eventData = events[id];
3700 std::string descr = eventData.description;
3701 if(descr.empty())
3702 continue;
3704 if (Utf8FitTo(descr, wnamepart))
3706 char const* active = activeEvents.find(id) != activeEvents.end() ? GetMangosString(LANG_ACTIVE) : "";
3708 if(m_session)
3709 PSendSysMessage(LANG_EVENT_ENTRY_LIST_CHAT,id,id,eventData.description.c_str(),active );
3710 else
3711 PSendSysMessage(LANG_EVENT_ENTRY_LIST_CONSOLE,id,eventData.description.c_str(),active );
3713 ++counter;
3717 if (counter==0)
3718 SendSysMessage(LANG_NOEVENTFOUND);
3720 return true;
3723 bool ChatHandler::HandleEventListCommand(const char* args)
3725 uint32 counter = 0;
3726 bool all = false;
3727 std::string arg = args;
3728 if (arg == "all")
3729 all = true;
3731 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
3732 GameEventMgr::ActiveEvents const& activeEvents = sGameEventMgr.GetActiveEventList();
3734 char const* active = GetMangosString(LANG_ACTIVE);
3735 char const* inactive = GetMangosString(LANG_FACTION_INACTIVE);
3736 char const* state = "";
3738 for (uint32 event_id = 0; event_id < events.size(); ++event_id)
3740 if (activeEvents.find(event_id) == activeEvents.end())
3742 if (!all)
3743 continue;
3744 state = inactive;
3746 else
3747 state = active;
3749 GameEventData const& eventData = events[event_id];
3751 if(m_session)
3752 PSendSysMessage(LANG_EVENT_ENTRY_LIST_CHAT, event_id, event_id, eventData.description.c_str(), state);
3753 else
3754 PSendSysMessage(LANG_EVENT_ENTRY_LIST_CONSOLE, event_id, eventData.description.c_str(), state);
3756 ++counter;
3759 if (counter==0)
3760 SendSysMessage(LANG_NOEVENTFOUND);
3762 return true;
3765 bool ChatHandler::HandleEventInfoCommand(const char* args)
3767 if(!*args)
3768 return false;
3770 // id or [name] Shift-click form |color|Hgameevent:id|h[name]|h|r
3771 char* cId = extractKeyFromLink((char*)args,"Hgameevent");
3772 if(!cId)
3773 return false;
3775 uint32 event_id = atoi(cId);
3777 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
3779 if(event_id >=events.size())
3781 SendSysMessage(LANG_EVENT_NOT_EXIST);
3782 SetSentErrorMessage(true);
3783 return false;
3786 GameEventData const& eventData = events[event_id];
3787 if(!eventData.isValid())
3789 SendSysMessage(LANG_EVENT_NOT_EXIST);
3790 SetSentErrorMessage(true);
3791 return false;
3794 GameEventMgr::ActiveEvents const& activeEvents = sGameEventMgr.GetActiveEventList();
3795 bool active = activeEvents.find(event_id) != activeEvents.end();
3796 char const* activeStr = active ? GetMangosString(LANG_ACTIVE) : "";
3798 std::string startTimeStr = TimeToTimestampStr(eventData.start);
3799 std::string endTimeStr = TimeToTimestampStr(eventData.end);
3801 uint32 delay = sGameEventMgr.NextCheck(event_id);
3802 time_t nextTime = time(NULL)+delay;
3803 std::string nextStr = nextTime >= eventData.start && nextTime < eventData.end ? TimeToTimestampStr(time(NULL)+delay) : "-";
3805 std::string occurenceStr = secsToTimeString(eventData.occurence * MINUTE);
3806 std::string lengthStr = secsToTimeString(eventData.length * MINUTE);
3808 PSendSysMessage(LANG_EVENT_INFO,event_id,eventData.description.c_str(),activeStr,
3809 startTimeStr.c_str(),endTimeStr.c_str(),occurenceStr.c_str(),lengthStr.c_str(),
3810 nextStr.c_str());
3811 return true;
3814 bool ChatHandler::HandleEventStartCommand(const char* args)
3816 if(!*args)
3817 return false;
3819 // id or [name] Shift-click form |color|Hgameevent:id|h[name]|h|r
3820 char* cId = extractKeyFromLink((char*)args,"Hgameevent");
3821 if(!cId)
3822 return false;
3824 int32 event_id = atoi(cId);
3826 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
3828 if(event_id < 1 || event_id >=events.size())
3830 SendSysMessage(LANG_EVENT_NOT_EXIST);
3831 SetSentErrorMessage(true);
3832 return false;
3835 GameEventData const& eventData = events[event_id];
3836 if(!eventData.isValid())
3838 SendSysMessage(LANG_EVENT_NOT_EXIST);
3839 SetSentErrorMessage(true);
3840 return false;
3843 GameEventMgr::ActiveEvents const& activeEvents = sGameEventMgr.GetActiveEventList();
3844 if(activeEvents.find(event_id) != activeEvents.end())
3846 PSendSysMessage(LANG_EVENT_ALREADY_ACTIVE,event_id);
3847 SetSentErrorMessage(true);
3848 return false;
3851 PSendSysMessage(LANG_EVENT_STARTED, event_id, eventData.description.c_str());
3852 sGameEventMgr.StartEvent(event_id,true);
3853 return true;
3856 bool ChatHandler::HandleEventStopCommand(const char* args)
3858 if(!*args)
3859 return false;
3861 // id or [name] Shift-click form |color|Hgameevent:id|h[name]|h|r
3862 char* cId = extractKeyFromLink((char*)args,"Hgameevent");
3863 if(!cId)
3864 return false;
3866 int32 event_id = atoi(cId);
3868 GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap();
3870 if(event_id < 1 || event_id >=events.size())
3872 SendSysMessage(LANG_EVENT_NOT_EXIST);
3873 SetSentErrorMessage(true);
3874 return false;
3877 GameEventData const& eventData = events[event_id];
3878 if(!eventData.isValid())
3880 SendSysMessage(LANG_EVENT_NOT_EXIST);
3881 SetSentErrorMessage(true);
3882 return false;
3885 GameEventMgr::ActiveEvents const& activeEvents = sGameEventMgr.GetActiveEventList();
3887 if(activeEvents.find(event_id) == activeEvents.end())
3889 PSendSysMessage(LANG_EVENT_NOT_ACTIVE,event_id);
3890 SetSentErrorMessage(true);
3891 return false;
3894 PSendSysMessage(LANG_EVENT_STOPPED, event_id, eventData.description.c_str());
3895 sGameEventMgr.StopEvent(event_id,true);
3896 return true;
3899 bool ChatHandler::HandleCombatStopCommand(const char* args)
3901 Player* target;
3902 if(!extractPlayerTarget((char*)args,&target))
3903 return false;
3905 // check online security
3906 if (HasLowerSecurity(target, 0))
3907 return false;
3909 target->CombatStop();
3910 target->getHostileRefManager().deleteReferences();
3911 return true;
3914 void ChatHandler::HandleLearnSkillRecipesHelper(Player* player,uint32 skill_id)
3916 uint32 classmask = player->getClassMask();
3918 for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
3920 SkillLineAbilityEntry const *skillLine = sSkillLineAbilityStore.LookupEntry(j);
3921 if (!skillLine)
3922 continue;
3924 // wrong skill
3925 if( skillLine->skillId != skill_id)
3926 continue;
3928 // not high rank
3929 if(skillLine->forward_spellid )
3930 continue;
3932 // skip racial skills
3933 if (skillLine->racemask != 0)
3934 continue;
3936 // skip wrong class skills
3937 if( skillLine->classmask && (skillLine->classmask & classmask) == 0)
3938 continue;
3940 SpellEntry const* spellInfo = sSpellStore.LookupEntry(skillLine->spellId);
3941 if(!spellInfo || !SpellMgr::IsSpellValid(spellInfo,player,false))
3942 continue;
3944 player->learnSpell(skillLine->spellId,false);
3948 bool ChatHandler::HandleLearnAllCraftsCommand(const char* /*args*/)
3950 for (uint32 i = 0; i < sSkillLineStore.GetNumRows(); ++i)
3952 SkillLineEntry const *skillInfo = sSkillLineStore.LookupEntry(i);
3953 if( !skillInfo )
3954 continue;
3956 if ((skillInfo->categoryId == SKILL_CATEGORY_PROFESSION || skillInfo->categoryId == SKILL_CATEGORY_SECONDARY) &&
3957 skillInfo->canLink) // only prof. with recipes have
3959 HandleLearnSkillRecipesHelper(m_session->GetPlayer(),skillInfo->id);
3963 SendSysMessage(LANG_COMMAND_LEARN_ALL_CRAFT);
3964 return true;
3967 bool ChatHandler::HandleLearnAllRecipesCommand(const char* args)
3969 // Learns all recipes of specified profession and sets skill to max
3970 // Example: .learn all_recipes enchanting
3972 Player* target = getSelectedPlayer();
3973 if( !target )
3975 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3976 return false;
3979 if(!*args)
3980 return false;
3982 std::wstring wnamepart;
3984 if(!Utf8toWStr(args,wnamepart))
3985 return false;
3987 // converting string that we try to find to lower case
3988 wstrToLower( wnamepart );
3990 std::string name;
3992 SkillLineEntry const *targetSkillInfo = NULL;
3993 for (uint32 i = 1; i < sSkillLineStore.GetNumRows(); ++i)
3995 SkillLineEntry const *skillInfo = sSkillLineStore.LookupEntry(i);
3996 if (!skillInfo)
3997 continue;
3999 if ((skillInfo->categoryId != SKILL_CATEGORY_PROFESSION &&
4000 skillInfo->categoryId != SKILL_CATEGORY_SECONDARY) ||
4001 !skillInfo->canLink) // only prof with recipes have set
4002 continue;
4004 int loc = GetSessionDbcLocale();
4005 name = skillInfo->name[loc];
4006 if(name.empty())
4007 continue;
4009 if (!Utf8FitTo(name, wnamepart))
4011 loc = 0;
4012 for(; loc < MAX_LOCALE; ++loc)
4014 if(loc==GetSessionDbcLocale())
4015 continue;
4017 name = skillInfo->name[loc];
4018 if(name.empty())
4019 continue;
4021 if (Utf8FitTo(name, wnamepart))
4022 break;
4026 if(loc < MAX_LOCALE)
4028 targetSkillInfo = skillInfo;
4029 break;
4033 if(!targetSkillInfo)
4034 return false;
4036 HandleLearnSkillRecipesHelper(target,targetSkillInfo->id);
4038 uint16 maxLevel = target->GetPureMaxSkillValue(targetSkillInfo->id);
4039 target->SetSkill(targetSkillInfo->id, maxLevel, maxLevel);
4040 PSendSysMessage(LANG_COMMAND_LEARN_ALL_RECIPES, name.c_str());
4041 return true;
4044 bool ChatHandler::HandleLookupPlayerIpCommand(const char* args)
4047 if (!*args)
4048 return false;
4050 std::string ip = strtok ((char*)args, " ");
4051 char* limit_str = strtok (NULL, " ");
4052 int32 limit = limit_str ? atoi (limit_str) : -1;
4054 loginDatabase.escape_string (ip);
4056 QueryResult* result = loginDatabase.PQuery ("SELECT id,username FROM account WHERE last_ip = '%s'", ip.c_str ());
4058 return LookupPlayerSearchCommand (result,limit);
4061 bool ChatHandler::HandleLookupPlayerAccountCommand(const char* args)
4063 if (!*args)
4064 return false;
4066 std::string account = strtok ((char*)args, " ");
4067 char* limit_str = strtok (NULL, " ");
4068 int32 limit = limit_str ? atoi (limit_str) : -1;
4070 if (!AccountMgr::normalizeString (account))
4071 return false;
4073 loginDatabase.escape_string (account);
4075 QueryResult* result = loginDatabase.PQuery ("SELECT id,username FROM account WHERE username = '%s'", account.c_str ());
4077 return LookupPlayerSearchCommand (result,limit);
4080 bool ChatHandler::HandleLookupPlayerEmailCommand(const char* args)
4083 if (!*args)
4084 return false;
4086 std::string email = strtok ((char*)args, " ");
4087 char* limit_str = strtok (NULL, " ");
4088 int32 limit = limit_str ? atoi (limit_str) : -1;
4090 loginDatabase.escape_string (email);
4092 QueryResult* result = loginDatabase.PQuery ("SELECT id,username FROM account WHERE email = '%s'", email.c_str ());
4094 return LookupPlayerSearchCommand (result,limit);
4097 bool ChatHandler::LookupPlayerSearchCommand(QueryResult* result, int32 limit)
4099 if(!result)
4101 PSendSysMessage(LANG_NO_PLAYERS_FOUND);
4102 SetSentErrorMessage(true);
4103 return false;
4106 int i =0;
4109 Field* fields = result->Fetch();
4110 uint32 acc_id = fields[0].GetUInt32();
4111 std::string acc_name = fields[1].GetCppString();
4113 QueryResult* chars = CharacterDatabase.PQuery("SELECT guid,name FROM characters WHERE account = '%u'", acc_id);
4114 if(chars)
4116 PSendSysMessage(LANG_LOOKUP_PLAYER_ACCOUNT,acc_name.c_str(),acc_id);
4118 uint64 guid = 0;
4119 std::string name;
4123 Field* charfields = chars->Fetch();
4124 guid = charfields[0].GetUInt64();
4125 name = charfields[1].GetCppString();
4127 PSendSysMessage(LANG_LOOKUP_PLAYER_CHARACTER,name.c_str(),guid);
4128 ++i;
4130 } while( chars->NextRow() && ( limit == -1 || i < limit ) );
4132 delete chars;
4134 } while(result->NextRow());
4136 delete result;
4138 if(i==0) // empty accounts only
4140 PSendSysMessage(LANG_NO_PLAYERS_FOUND);
4141 SetSentErrorMessage(true);
4142 return false;
4145 return true;
4148 /// Triggering corpses expire check in world
4149 bool ChatHandler::HandleServerCorpsesCommand(const char* /*args*/)
4151 CorpsesErase();
4152 return true;
4155 bool ChatHandler::HandleRepairitemsCommand(const char* args)
4157 Player* target;
4158 if(!extractPlayerTarget((char*)args,&target))
4159 return false;
4161 // check online security
4162 if (HasLowerSecurity(target, 0))
4163 return false;
4165 // Repair items
4166 target->DurabilityRepairAll(false, 0, false);
4168 PSendSysMessage(LANG_YOU_REPAIR_ITEMS, GetNameLink(target).c_str());
4169 if(needReportToTarget(target))
4170 ChatHandler(target).PSendSysMessage(LANG_YOUR_ITEMS_REPAIRED, GetNameLink().c_str());
4171 return true;
4174 bool ChatHandler::HandleWaterwalkCommand(const char* args)
4176 if(!*args)
4177 return false;
4179 Player *player = getSelectedPlayer();
4181 if(!player)
4183 PSendSysMessage(LANG_NO_CHAR_SELECTED);
4184 SetSentErrorMessage(true);
4185 return false;
4188 // check online security
4189 if (HasLowerSecurity(player, 0))
4190 return false;
4192 if (strncmp(args, "on", 3) == 0)
4193 player->SetMovement(MOVE_WATER_WALK); // ON
4194 else if (strncmp(args, "off", 4) == 0)
4195 player->SetMovement(MOVE_LAND_WALK); // OFF
4196 else
4198 SendSysMessage(LANG_USE_BOL);
4199 return false;
4202 PSendSysMessage(LANG_YOU_SET_WATERWALK, args, GetNameLink(player).c_str());
4203 if(needReportToTarget(player))
4204 ChatHandler(player).PSendSysMessage(LANG_YOUR_WATERWALK_SET, args, GetNameLink().c_str());
4205 return true;
4208 bool ChatHandler::HandleLookupTitleCommand(const char* args)
4210 if(!*args)
4211 return false;
4213 // can be NULL in console call
4214 Player* target = getSelectedPlayer();
4216 // title name have single string arg for player name
4217 char const* targetName = target ? target->GetName() : "NAME";
4219 std::string namepart = args;
4220 std::wstring wnamepart;
4222 if(!Utf8toWStr(namepart,wnamepart))
4223 return false;
4225 // converting string that we try to find to lower case
4226 wstrToLower( wnamepart );
4228 uint32 counter = 0; // Counter for figure out that we found smth.
4230 // Search in CharTitles.dbc
4231 for (uint32 id = 0; id < sCharTitlesStore.GetNumRows(); id++)
4233 CharTitlesEntry const *titleInfo = sCharTitlesStore.LookupEntry(id);
4234 if(titleInfo)
4236 int loc = GetSessionDbcLocale();
4237 std::string name = titleInfo->name[loc];
4238 if(name.empty())
4239 continue;
4241 if (!Utf8FitTo(name, wnamepart))
4243 loc = 0;
4244 for(; loc < MAX_LOCALE; ++loc)
4246 if(loc==GetSessionDbcLocale())
4247 continue;
4249 name = titleInfo->name[loc];
4250 if(name.empty())
4251 continue;
4253 if (Utf8FitTo(name, wnamepart))
4254 break;
4258 if(loc < MAX_LOCALE)
4260 char const* knownStr = target && target->HasTitle(titleInfo) ? GetMangosString(LANG_KNOWN) : "";
4262 char const* activeStr = target && target->GetUInt32Value(PLAYER_CHOSEN_TITLE)==titleInfo->bit_index
4263 ? GetMangosString(LANG_ACTIVE)
4264 : "";
4266 char titleNameStr[80];
4267 snprintf(titleNameStr,80,name.c_str(),targetName);
4269 // send title in "id (idx:idx) - [namedlink locale]" format
4270 if (m_session)
4271 PSendSysMessage(LANG_TITLE_LIST_CHAT,id,titleInfo->bit_index,id,titleNameStr,localeNames[loc],knownStr,activeStr);
4272 else
4273 PSendSysMessage(LANG_TITLE_LIST_CONSOLE,id,titleInfo->bit_index,titleNameStr,localeNames[loc],knownStr,activeStr);
4275 ++counter;
4279 if (counter == 0) // if counter == 0 then we found nth
4280 SendSysMessage(LANG_COMMAND_NOTITLEFOUND);
4281 return true;
4284 bool ChatHandler::HandleTitlesAddCommand(const char* args)
4286 // number or [name] Shift-click form |color|Htitle:title_id|h[name]|h|r
4287 char* id_p = extractKeyFromLink((char*)args,"Htitle");
4288 if(!id_p)
4289 return false;
4291 int32 id = atoi(id_p);
4292 if (id <= 0)
4294 PSendSysMessage(LANG_INVALID_TITLE_ID, id);
4295 SetSentErrorMessage(true);
4296 return false;
4299 Player * target = getSelectedPlayer();
4300 if(!target)
4302 SendSysMessage(LANG_NO_CHAR_SELECTED);
4303 SetSentErrorMessage(true);
4304 return false;
4307 // check online security
4308 if (HasLowerSecurity(target, 0))
4309 return false;
4311 CharTitlesEntry const* titleInfo = sCharTitlesStore.LookupEntry(id);
4312 if(!titleInfo)
4314 PSendSysMessage(LANG_INVALID_TITLE_ID, id);
4315 SetSentErrorMessage(true);
4316 return false;
4319 std::string tNameLink = GetNameLink(target);
4321 char const* targetName = target->GetName();
4322 char titleNameStr[80];
4323 snprintf(titleNameStr,80,titleInfo->name[GetSessionDbcLocale()],targetName);
4325 target->SetTitle(titleInfo);
4326 PSendSysMessage(LANG_TITLE_ADD_RES, id, titleNameStr, tNameLink.c_str());
4328 return true;
4331 bool ChatHandler::HandleTitlesRemoveCommand(const char* args)
4333 // number or [name] Shift-click form |color|Htitle:title_id|h[name]|h|r
4334 char* id_p = extractKeyFromLink((char*)args,"Htitle");
4335 if(!id_p)
4336 return false;
4338 int32 id = atoi(id_p);
4339 if (id <= 0)
4341 PSendSysMessage(LANG_INVALID_TITLE_ID, id);
4342 SetSentErrorMessage(true);
4343 return false;
4346 Player * target = getSelectedPlayer();
4347 if(!target)
4349 SendSysMessage(LANG_NO_CHAR_SELECTED);
4350 SetSentErrorMessage(true);
4351 return false;
4354 // check online security
4355 if (HasLowerSecurity(target, 0))
4356 return false;
4358 CharTitlesEntry const* titleInfo = sCharTitlesStore.LookupEntry(id);
4359 if(!titleInfo)
4361 PSendSysMessage(LANG_INVALID_TITLE_ID, id);
4362 SetSentErrorMessage(true);
4363 return false;
4366 target->SetTitle(titleInfo,true);
4368 std::string tNameLink = GetNameLink(target);
4370 char const* targetName = target->GetName();
4371 char titleNameStr[80];
4372 snprintf(titleNameStr,80,titleInfo->name[GetSessionDbcLocale()],targetName);
4374 PSendSysMessage(LANG_TITLE_REMOVE_RES, id, titleNameStr, tNameLink.c_str());
4376 if (!target->HasTitle(target->GetInt32Value(PLAYER_CHOSEN_TITLE)))
4378 target->SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
4379 PSendSysMessage(LANG_CURRENT_TITLE_RESET, tNameLink.c_str());
4382 return true;
4385 //Edit Player KnownTitles
4386 bool ChatHandler::HandleTitlesSetMaskCommand(const char* args)
4388 if(!*args)
4389 return false;
4391 uint64 titles = 0;
4393 sscanf((char*)args, UI64FMTD, &titles);
4395 Player *target = getSelectedPlayer();
4396 if (!target)
4398 SendSysMessage(LANG_NO_CHAR_SELECTED);
4399 SetSentErrorMessage(true);
4400 return false;
4403 // check online security
4404 if (HasLowerSecurity(target, 0))
4405 return false;
4407 uint64 titles2 = titles;
4409 for(uint32 i = 1; i < sCharTitlesStore.GetNumRows(); ++i)
4410 if(CharTitlesEntry const* tEntry = sCharTitlesStore.LookupEntry(i))
4411 titles2 &= ~(uint64(1) << tEntry->bit_index);
4413 titles &= ~titles2; // remove not existed titles
4415 target->SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES, titles);
4416 SendSysMessage(LANG_DONE);
4418 if (!target->HasTitle(target->GetInt32Value(PLAYER_CHOSEN_TITLE)))
4420 target->SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
4421 PSendSysMessage(LANG_CURRENT_TITLE_RESET,GetNameLink(target).c_str());
4424 return true;
4427 bool ChatHandler::HandleCharacterTitlesCommand(const char* args)
4429 Player* target;
4430 if(!extractPlayerTarget((char*)args,&target))
4431 return false;
4433 LocaleConstant loc = GetSessionDbcLocale();
4434 char const* targetName = target->GetName();
4435 char const* knownStr = GetMangosString(LANG_KNOWN);
4437 // Search in CharTitles.dbc
4438 for (uint32 id = 0; id < sCharTitlesStore.GetNumRows(); id++)
4440 CharTitlesEntry const *titleInfo = sCharTitlesStore.LookupEntry(id);
4441 if (titleInfo && target->HasTitle(titleInfo))
4443 std::string name = titleInfo->name[loc];
4444 if(name.empty())
4445 continue;
4447 char const* activeStr = target && target->GetUInt32Value(PLAYER_CHOSEN_TITLE)==titleInfo->bit_index
4448 ? GetMangosString(LANG_ACTIVE)
4449 : "";
4451 char titleNameStr[80];
4452 snprintf(titleNameStr,80,name.c_str(),targetName);
4454 // send title in "id (idx:idx) - [namedlink locale]" format
4455 if (m_session)
4456 PSendSysMessage(LANG_TITLE_LIST_CHAT,id,titleInfo->bit_index,id,titleNameStr,localeNames[loc],knownStr,activeStr);
4457 else
4458 PSendSysMessage(LANG_TITLE_LIST_CONSOLE,id,titleInfo->bit_index,name.c_str(),localeNames[loc],knownStr,activeStr);
4461 return true;
4464 bool ChatHandler::HandleTitlesCurrentCommand(const char* args)
4466 // number or [name] Shift-click form |color|Htitle:title_id|h[name]|h|r
4467 char* id_p = extractKeyFromLink((char*)args,"Htitle");
4468 if(!id_p)
4469 return false;
4471 int32 id = atoi(id_p);
4472 if (id <= 0)
4474 PSendSysMessage(LANG_INVALID_TITLE_ID, id);
4475 SetSentErrorMessage(true);
4476 return false;
4479 Player * target = getSelectedPlayer();
4480 if(!target)
4482 SendSysMessage(LANG_NO_CHAR_SELECTED);
4483 SetSentErrorMessage(true);
4484 return false;
4487 // check online security
4488 if (HasLowerSecurity(target, 0))
4489 return false;
4491 CharTitlesEntry const* titleInfo = sCharTitlesStore.LookupEntry(id);
4492 if(!titleInfo)
4494 PSendSysMessage(LANG_INVALID_TITLE_ID, id);
4495 SetSentErrorMessage(true);
4496 return false;
4499 std::string tNameLink = GetNameLink(target);
4501 target->SetTitle(titleInfo); // to be sure that title now known
4502 target->SetUInt32Value(PLAYER_CHOSEN_TITLE,titleInfo->bit_index);
4504 PSendSysMessage(LANG_TITLE_CURRENT_RES, id, titleInfo->name[GetSessionDbcLocale()], tNameLink.c_str());
4506 return true;