Merge branch 'master' into 303
[getmangos.git] / src / game / Level2.cpp
blobddc53099f1599cf9bd7cd18ec8bfdfb653581b4b
1 /*
2 * Copyright (C) 2005-2008 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 "WorldPacket.h"
22 #include "WorldSession.h"
23 #include "World.h"
24 #include "ObjectMgr.h"
25 #include "Player.h"
26 #include "Item.h"
27 #include "GameObject.h"
28 #include "Opcodes.h"
29 #include "Chat.h"
30 #include "ObjectAccessor.h"
31 #include "MapManager.h"
32 #include "Language.h"
33 #include "World.h"
34 #include "GameEvent.h"
35 #include "SpellMgr.h"
36 #include "AccountMgr.h"
37 #include "WaypointManager.h"
38 #include "Util.h"
39 #include <cctype>
40 #include <iostream>
41 #include <fstream>
42 #include <map>
43 #include "GlobalEvents.h"
45 #include "TargetedMovementGenerator.h" // for HandleNpcUnFollowCommand
47 static uint32 ReputationRankStrIndex[MAX_REPUTATION_RANK] =
49 LANG_REP_HATED, LANG_REP_HOSTILE, LANG_REP_UNFRIENDLY, LANG_REP_NEUTRAL,
50 LANG_REP_FRIENDLY, LANG_REP_HONORED, LANG_REP_REVERED, LANG_REP_EXALTED
53 //mute player for some times
54 bool ChatHandler::HandleMuteCommand(const char* args)
56 if (!*args)
57 return false;
59 char *charname = strtok((char*)args, " ");
60 if (!charname)
61 return false;
63 std::string cname = charname;
65 char *timetonotspeak = strtok(NULL, " ");
66 if(!timetonotspeak)
67 return false;
69 uint32 notspeaktime = (uint32) atoi(timetonotspeak);
71 if(!normalizePlayerName(cname))
73 SendSysMessage(LANG_PLAYER_NOT_FOUND);
74 SetSentErrorMessage(true);
75 return false;
78 uint64 guid = objmgr.GetPlayerGUIDByName(cname.c_str());
79 if(!guid)
81 SendSysMessage(LANG_PLAYER_NOT_FOUND);
82 SetSentErrorMessage(true);
83 return false;
86 Player *chr = objmgr.GetPlayer(guid);
88 // check security
89 uint32 account_id = 0;
90 uint32 security = 0;
92 if (chr)
94 account_id = chr->GetSession()->GetAccountId();
95 security = chr->GetSession()->GetSecurity();
97 else
99 account_id = objmgr.GetPlayerAccountIdByGUID(guid);
100 security = accmgr.GetSecurity(account_id);
103 if(m_session && security >= m_session->GetSecurity())
105 SendSysMessage(LANG_YOURS_SECURITY_IS_LOW);
106 SetSentErrorMessage(true);
107 return false;
110 time_t mutetime = time(NULL) + notspeaktime*60;
112 if (chr)
113 chr->GetSession()->m_muteTime = mutetime;
115 loginDatabase.PExecute("UPDATE account SET mutetime = " I64FMTD " WHERE id = '%u'",uint64(mutetime), account_id );
117 if(chr)
118 ChatHandler(chr).PSendSysMessage(LANG_YOUR_CHAT_DISABLED, notspeaktime);
120 PSendSysMessage(LANG_YOU_DISABLE_CHAT, cname.c_str(), notspeaktime);
122 return true;
125 //unmute player
126 bool ChatHandler::HandleUnmuteCommand(const char* args)
128 if (!*args)
129 return false;
131 char *charname = strtok((char*)args, " ");
132 if (!charname)
133 return false;
135 std::string cname = charname;
137 if(!normalizePlayerName(cname))
139 SendSysMessage(LANG_PLAYER_NOT_FOUND);
140 SetSentErrorMessage(true);
141 return false;
144 uint64 guid = objmgr.GetPlayerGUIDByName(cname.c_str());
145 if(!guid)
147 SendSysMessage(LANG_PLAYER_NOT_FOUND);
148 SetSentErrorMessage(true);
149 return false;
152 Player *chr = objmgr.GetPlayer(guid);
154 // check security
155 uint32 account_id = 0;
156 uint32 security = 0;
158 if (chr)
160 account_id = chr->GetSession()->GetAccountId();
161 security = chr->GetSession()->GetSecurity();
163 else
165 account_id = objmgr.GetPlayerAccountIdByGUID(guid);
166 security = accmgr.GetSecurity(account_id);
169 if(m_session && security >= m_session->GetSecurity())
171 SendSysMessage(LANG_YOURS_SECURITY_IS_LOW);
172 SetSentErrorMessage(true);
173 return false;
176 if (chr)
178 if(chr->CanSpeak())
180 SendSysMessage(LANG_CHAT_ALREADY_ENABLED);
181 SetSentErrorMessage(true);
182 return false;
185 chr->GetSession()->m_muteTime = 0;
188 loginDatabase.PExecute("UPDATE account SET mutetime = '0' WHERE id = '%u'", account_id );
190 if(chr)
191 ChatHandler(chr).PSendSysMessage(LANG_YOUR_CHAT_ENABLED);
193 PSendSysMessage(LANG_YOU_ENABLE_CHAT, cname.c_str());
194 return true;
197 bool ChatHandler::HandleTargetObjectCommand(const char* args)
199 Player* pl = m_session->GetPlayer();
200 QueryResult *result;
201 GameEvent::ActiveEvents const& activeEventsList = gameeventmgr.GetActiveEventList();
202 if(*args)
204 int32 id = atoi((char*)args);
205 if(id)
206 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",
207 pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), pl->GetMapId(),id);
208 else
210 std::string name = args;
211 WorldDatabase.escape_string(name);
212 result = WorldDatabase.PQuery(
213 "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_ "
214 "FROM gameobject,gameobject_template WHERE gameobject_template.entry = gameobject.id AND map = %i AND name "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'")" ORDER BY order_ ASC LIMIT 1",
215 pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), pl->GetMapId(),name.c_str());
218 else
220 std::ostringstream eventFilter;
221 eventFilter << " AND (event IS NULL ";
222 bool initString = true;
224 for (GameEvent::ActiveEvents::const_iterator itr = activeEventsList.begin(); itr != activeEventsList.end(); ++itr)
226 if (initString)
228 eventFilter << "OR event IN (" <<*itr;
229 initString =false;
231 else
232 eventFilter << "," << *itr;
235 if (!initString)
236 eventFilter << "))";
237 else
238 eventFilter << ")";
240 result = WorldDatabase.PQuery("SELECT gameobject.guid, id, position_x, position_y, position_z, orientation, map, "
241 "(POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ FROM gameobject "
242 "LEFT OUTER JOIN game_event_gameobject on gameobject.guid=game_event_gameobject.guid WHERE map = '%i' %s ORDER BY order_ ASC LIMIT 1",
243 m_session->GetPlayer()->GetPositionX(), m_session->GetPlayer()->GetPositionY(), m_session->GetPlayer()->GetPositionZ(), m_session->GetPlayer()->GetMapId(),eventFilter.str().c_str());
246 if (!result)
248 SendSysMessage(LANG_COMMAND_TARGETOBJNOTFOUND);
249 return true;
252 Field *fields = result->Fetch();
253 uint32 lowguid = fields[0].GetUInt32();
254 uint32 id = fields[1].GetUInt32();
255 float x = fields[2].GetFloat();
256 float y = fields[3].GetFloat();
257 float z = fields[4].GetFloat();
258 float o = fields[5].GetFloat();
259 int mapid = fields[6].GetUInt16();
260 delete result;
262 GameObjectInfo const* goI = objmgr.GetGameObjectInfo(id);
264 if (!goI)
266 PSendSysMessage(LANG_GAMEOBJECT_NOT_EXIST,id);
267 return false;
270 GameObject* target = ObjectAccessor::GetGameObject(*m_session->GetPlayer(),MAKE_NEW_GUID(lowguid,id,HIGHGUID_GAMEOBJECT));
272 PSendSysMessage(LANG_GAMEOBJECT_DETAIL, lowguid, goI->name, lowguid, id, x, y, z, mapid, o);
274 if(target)
276 int32 curRespawnDelay = target->GetRespawnTimeEx()-time(NULL);
277 if(curRespawnDelay < 0)
278 curRespawnDelay = 0;
280 std::string curRespawnDelayStr = secsToTimeString(curRespawnDelay,true);
281 std::string defRespawnDelayStr = secsToTimeString(target->GetRespawnDelay(),true);
283 PSendSysMessage(LANG_COMMAND_RAWPAWNTIMES, defRespawnDelayStr.c_str(),curRespawnDelayStr.c_str());
285 return true;
288 //teleport to gameobject
289 bool ChatHandler::HandleGoObjectCommand(const char* args)
291 if(!*args)
292 return false;
294 Player* _player = m_session->GetPlayer();
296 // number or [name] Shift-click form |color|Hgameobject:go_guid|h[name]|h|r
297 char* cId = extractKeyFromLink((char*)args,"Hgameobject");
298 if(!cId)
299 return false;
301 int32 guid = atoi(cId);
302 if(!guid)
303 return false;
305 float x, y, z, ort;
306 int mapid;
308 // by DB guid
309 if (GameObjectData const* go_data = objmgr.GetGOData(guid))
311 x = go_data->posX;
312 y = go_data->posY;
313 z = go_data->posZ;
314 ort = go_data->orientation;
315 mapid = go_data->mapid;
317 else
319 SendSysMessage(LANG_COMMAND_GOOBJNOTFOUND);
320 SetSentErrorMessage(true);
321 return false;
324 if(!MapManager::IsValidMapCoord(mapid,x,y,z,ort))
326 PSendSysMessage(LANG_INVALID_TARGET_COORD,x,y,mapid);
327 SetSentErrorMessage(true);
328 return false;
331 // stop flight if need
332 if(_player->isInFlight())
334 _player->GetMotionMaster()->MovementExpired();
335 _player->m_taxi.ClearTaxiDestinations();
337 // save only in non-flight case
338 else
339 _player->SaveRecallPosition();
341 _player->TeleportTo(mapid, x, y, z, ort);
342 return true;
345 bool ChatHandler::HandleGoTriggerCommand(const char* args)
347 Player* _player = m_session->GetPlayer();
349 if (!*args)
350 return false;
352 char *atId = strtok((char*)args, " ");
353 if (!atId)
354 return false;
356 int32 i_atId = atoi(atId);
358 if(!i_atId)
359 return false;
361 AreaTriggerEntry const* at = sAreaTriggerStore.LookupEntry(i_atId);
362 if (!at)
364 PSendSysMessage(LANG_COMMAND_GOAREATRNOTFOUND,i_atId);
365 SetSentErrorMessage(true);
366 return false;
369 if(!MapManager::IsValidMapCoord(at->mapid,at->x,at->y,at->z))
371 PSendSysMessage(LANG_INVALID_TARGET_COORD,at->x,at->y,at->mapid);
372 SetSentErrorMessage(true);
373 return false;
376 // stop flight if need
377 if(_player->isInFlight())
379 _player->GetMotionMaster()->MovementExpired();
380 _player->m_taxi.ClearTaxiDestinations();
382 // save only in non-flight case
383 else
384 _player->SaveRecallPosition();
386 _player->TeleportTo(at->mapid, at->x, at->y, at->z, _player->GetOrientation());
387 return true;
390 bool ChatHandler::HandleGoGraveyardCommand(const char* args)
392 Player* _player = m_session->GetPlayer();
394 if (!*args)
395 return false;
397 char *gyId = strtok((char*)args, " ");
398 if (!gyId)
399 return false;
401 int32 i_gyId = atoi(gyId);
403 if(!i_gyId)
404 return false;
406 WorldSafeLocsEntry const* gy = sWorldSafeLocsStore.LookupEntry(i_gyId);
407 if (!gy)
409 PSendSysMessage(LANG_COMMAND_GRAVEYARDNOEXIST,i_gyId);
410 SetSentErrorMessage(true);
411 return false;
414 if(!MapManager::IsValidMapCoord(gy->map_id,gy->x,gy->y,gy->z))
416 PSendSysMessage(LANG_INVALID_TARGET_COORD,gy->x,gy->y,gy->map_id);
417 SetSentErrorMessage(true);
418 return false;
421 // stop flight if need
422 if(_player->isInFlight())
424 _player->GetMotionMaster()->MovementExpired();
425 _player->m_taxi.ClearTaxiDestinations();
427 // save only in non-flight case
428 else
429 _player->SaveRecallPosition();
431 _player->TeleportTo(gy->map_id, gy->x, gy->y, gy->z, _player->GetOrientation());
432 return true;
435 /** \brief Teleport the GM to the specified creature
437 * .gocreature <GUID> --> TP using creature.guid
438 * .gocreature azuregos --> TP player to the mob with this name
439 * Warning: If there is more than one mob with this name
440 * you will be teleported to the first one that is found.
441 * .gocreature id 6109 --> TP player to the mob, that has this creature_template.entry
442 * Warning: If there is more than one mob with this "id"
443 * you will be teleported to the first one that is found.
445 //teleport to creature
446 bool ChatHandler::HandleGoCreatureCommand(const char* args)
448 if(!*args)
449 return false;
450 Player* _player = m_session->GetPlayer();
452 // "id" or number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
453 char* pParam1 = extractKeyFromLink((char*)args,"Hcreature");
454 if (!pParam1)
455 return false;
457 std::ostringstream whereClause;
459 // User wants to teleport to the NPC's template entry
460 if( strcmp(pParam1, "id") == 0 )
462 //sLog.outError("DEBUG: ID found");
464 // Get the "creature_template.entry"
465 // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
466 char* tail = strtok(NULL,"");
467 if(!tail)
468 return false;
469 char* cId = extractKeyFromLink(tail,"Hcreature_entry");
470 if(!cId)
471 return false;
473 int32 tEntry = atoi(cId);
474 //sLog.outError("DEBUG: ID value: %d", tEntry);
475 if(!tEntry)
476 return false;
478 whereClause << "WHERE id = '" << tEntry << "'";
480 else
482 //sLog.outError("DEBUG: ID *not found*");
484 int32 guid = atoi(pParam1);
486 // Number is invalid - maybe the user specified the mob's name
487 if(!guid)
489 std::string name = pParam1;
490 WorldDatabase.escape_string(name);
491 whereClause << ", creature_template WHERE creature.id = creature_template.entry AND creature_template.name "_LIKE_" '" << name << "'";
493 else
495 whereClause << "WHERE guid = '" << guid << "'";
498 //sLog.outError("DEBUG: %s", whereClause.c_str());
500 QueryResult *result = WorldDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map FROM creature %s", whereClause.str().c_str() );
501 if (!result)
503 SendSysMessage(LANG_COMMAND_GOCREATNOTFOUND);
504 SetSentErrorMessage(true);
505 return false;
507 if( result->GetRowCount() > 1 )
509 SendSysMessage(LANG_COMMAND_GOCREATMULTIPLE);
512 Field *fields = result->Fetch();
513 float x = fields[0].GetFloat();
514 float y = fields[1].GetFloat();
515 float z = fields[2].GetFloat();
516 float ort = fields[3].GetFloat();
517 int mapid = fields[4].GetUInt16();
519 delete result;
521 if(!MapManager::IsValidMapCoord(mapid,x,y,z,ort))
523 PSendSysMessage(LANG_INVALID_TARGET_COORD,x,y,mapid);
524 SetSentErrorMessage(true);
525 return false;
528 // stop flight if need
529 if(_player->isInFlight())
531 _player->GetMotionMaster()->MovementExpired();
532 _player->m_taxi.ClearTaxiDestinations();
534 // save only in non-flight case
535 else
536 _player->SaveRecallPosition();
538 _player->TeleportTo(mapid, x, y, z, ort);
539 return true;
542 bool ChatHandler::HandleGUIDCommand(const char* /*args*/)
544 uint64 guid = m_session->GetPlayer()->GetSelection();
546 if (guid == 0)
548 SendSysMessage(LANG_NO_SELECTION);
549 SetSentErrorMessage(true);
550 return false;
553 PSendSysMessage(LANG_OBJECT_GUID, GUID_LOPART(guid), GUID_HIPART(guid));
554 return true;
557 bool ChatHandler::HandleLookupFactionCommand(const char* args)
559 if (!*args)
560 return false;
562 // Can be NULL at console call
563 Player *target = getSelectedPlayer ();
565 std::string namepart = args;
566 std::wstring wnamepart;
568 if (!Utf8toWStr (namepart,wnamepart))
569 return false;
571 // converting string that we try to find to lower case
572 wstrToLower (wnamepart);
574 uint32 counter = 0; // Counter for figure out that we found smth.
576 for (uint32 id = 0; id < sFactionStore.GetNumRows(); ++id)
578 FactionEntry const *factionEntry = sFactionStore.LookupEntry (id);
579 if (factionEntry)
581 FactionState const* repState = NULL;
582 if(target)
584 FactionStateList::const_iterator repItr = target->m_factions.find (factionEntry->reputationListID);
585 if(repItr != target->m_factions.end())
586 repState = &repItr->second;
590 int loc = m_session ? m_session->GetSessionDbcLocale() : sWorld.GetDefaultDbcLocale();
591 std::string name = factionEntry->name[loc];
592 if(name.empty())
593 continue;
595 if (!Utf8FitTo(name, wnamepart))
597 loc = 0;
598 for(; loc < MAX_LOCALE; ++loc)
600 if(m_session && loc==m_session->GetSessionDbcLocale())
601 continue;
603 name = factionEntry->name[loc];
604 if(name.empty())
605 continue;
607 if (Utf8FitTo(name, wnamepart))
608 break;
612 if(loc < MAX_LOCALE)
614 // send faction in "id - [faction] rank reputation [visible] [at war] [own team] [unknown] [invisible] [inactive]" format
615 // or "id - [faction] [no reputation]" format
616 std::ostringstream ss;
617 if (m_session)
618 ss << id << " - |cffffffff|Hfaction:" << id << "|h[" << name << " " << localeNames[loc] << "]|h|r";
619 else
620 ss << id << " - " << name << " " << localeNames[loc];
622 if (repState) // and then target!=NULL also
624 ReputationRank rank = target->GetReputationRank(factionEntry);
625 std::string rankName = GetMangosString(ReputationRankStrIndex[rank]);
627 ss << " " << rankName << "|h|r (" << target->GetReputation(factionEntry) << ")";
629 if(repState->Flags & FACTION_FLAG_VISIBLE)
630 ss << GetMangosString(LANG_FACTION_VISIBLE);
631 if(repState->Flags & FACTION_FLAG_AT_WAR)
632 ss << GetMangosString(LANG_FACTION_ATWAR);
633 if(repState->Flags & FACTION_FLAG_PEACE_FORCED)
634 ss << GetMangosString(LANG_FACTION_PEACE_FORCED);
635 if(repState->Flags & FACTION_FLAG_HIDDEN)
636 ss << GetMangosString(LANG_FACTION_HIDDEN);
637 if(repState->Flags & FACTION_FLAG_INVISIBLE_FORCED)
638 ss << GetMangosString(LANG_FACTION_INVISIBLE_FORCED);
639 if(repState->Flags & FACTION_FLAG_INACTIVE)
640 ss << GetMangosString(LANG_FACTION_INACTIVE);
642 else
643 ss << GetMangosString(LANG_FACTION_NOREPUTATION);
645 SendSysMessage(ss.str().c_str());
646 counter++;
651 if (counter == 0) // if counter == 0 then we found nth
652 SendSysMessage(LANG_COMMAND_FACTION_NOTFOUND);
653 return true;
656 bool ChatHandler::HandleModifyRepCommand(const char * args)
658 if (!*args) return false;
660 Player* target = NULL;
661 target = getSelectedPlayer();
663 if(!target)
665 SendSysMessage(LANG_PLAYER_NOT_FOUND);
666 SetSentErrorMessage(true);
667 return false;
670 char* factionTxt = extractKeyFromLink((char*)args,"Hfaction");
671 if(!factionTxt)
672 return false;
674 uint32 factionId = atoi(factionTxt);
676 int32 amount = 0;
677 char *rankTxt = strtok(NULL, " ");
678 if (!factionTxt || !rankTxt)
679 return false;
681 amount = atoi(rankTxt);
682 if ((amount == 0) && (rankTxt[0] != '-') && !isdigit(rankTxt[0]))
684 std::string rankStr = rankTxt;
685 std::wstring wrankStr;
686 if(!Utf8toWStr(rankStr,wrankStr))
687 return false;
688 wstrToLower( wrankStr );
690 int r = 0;
691 amount = -42000;
692 for (; r < MAX_REPUTATION_RANK; ++r)
694 std::string rank = GetMangosString(ReputationRankStrIndex[r]);
695 if(rank.empty())
696 continue;
698 std::wstring wrank;
699 if(!Utf8toWStr(rank,wrank))
700 continue;
702 wstrToLower(wrank);
704 if(wrank.substr(0,wrankStr.size())==wrankStr)
706 char *deltaTxt = strtok(NULL, " ");
707 if (deltaTxt)
709 int32 delta = atoi(deltaTxt);
710 if ((delta < 0) || (delta > Player::ReputationRank_Length[r] -1))
712 PSendSysMessage(LANG_COMMAND_FACTION_DELTA, (Player::ReputationRank_Length[r]-1));
713 SetSentErrorMessage(true);
714 return false;
716 amount += delta;
718 break;
720 amount += Player::ReputationRank_Length[r];
722 if (r >= MAX_REPUTATION_RANK)
724 PSendSysMessage(LANG_COMMAND_FACTION_INVPARAM, rankTxt);
725 SetSentErrorMessage(true);
726 return false;
730 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionId);
732 if (!factionEntry)
734 PSendSysMessage(LANG_COMMAND_FACTION_UNKNOWN, factionId);
735 SetSentErrorMessage(true);
736 return false;
739 if (factionEntry->reputationListID < 0)
741 PSendSysMessage(LANG_COMMAND_FACTION_NOREP_ERROR, factionEntry->name[m_session->GetSessionDbcLocale()], factionId);
742 SetSentErrorMessage(true);
743 return false;
746 target->SetFactionReputation(factionEntry,amount);
747 PSendSysMessage(LANG_COMMAND_MODIFY_REP, factionEntry->name[m_session->GetSessionDbcLocale()], factionId, target->GetName(), target->GetReputation(factionId));
748 return true;
751 bool ChatHandler::HandleNameCommand(const char* args)
753 /* Temp. disabled
754 if(!*args)
755 return false;
757 if(strlen((char*)args)>75)
759 PSendSysMessage(LANG_TOO_LONG_NAME, strlen((char*)args)-75);
760 return true;
763 for (uint8 i = 0; i < strlen(args); i++)
765 if(!isalpha(args[i]) && args[i]!=' ')
767 SendSysMessage(LANG_CHARS_ONLY);
768 return false;
772 uint64 guid;
773 guid = m_session->GetPlayer()->GetSelection();
774 if (guid == 0)
776 SendSysMessage(LANG_NO_SELECTION);
777 return true;
780 Creature* pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), guid);
782 if(!pCreature)
784 SendSysMessage(LANG_SELECT_CREATURE);
785 return true;
788 pCreature->SetName(args);
789 uint32 idname = objmgr.AddCreatureTemplate(pCreature->GetName());
790 pCreature->SetUInt32Value(OBJECT_FIELD_ENTRY, idname);
792 pCreature->SaveToDB();
795 return true;
798 bool ChatHandler::HandleSubNameCommand(const char* /*args*/)
800 /* Temp. disabled
802 if(!*args)
803 args = "";
805 if(strlen((char*)args)>75)
808 PSendSysMessage(LANG_TOO_LONG_SUBNAME, strlen((char*)args)-75);
809 return true;
812 for (uint8 i = 0; i < strlen(args); i++)
814 if(!isalpha(args[i]) && args[i]!=' ')
816 SendSysMessage(LANG_CHARS_ONLY);
817 return false;
820 uint64 guid;
821 guid = m_session->GetPlayer()->GetSelection();
822 if (guid == 0)
824 SendSysMessage(LANG_NO_SELECTION);
825 return true;
828 Creature* pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), guid);
830 if(!pCreature)
832 SendSysMessage(LANG_SELECT_CREATURE);
833 return true;
836 uint32 idname = objmgr.AddCreatureSubName(pCreature->GetName(),args,pCreature->GetUInt32Value(UNIT_FIELD_DISPLAYID));
837 pCreature->SetUInt32Value(OBJECT_FIELD_ENTRY, idname);
839 pCreature->SaveToDB();
841 return true;
844 //move item to other slot
845 bool ChatHandler::HandleItemMoveCommand(const char* args)
847 if(!*args)
848 return false;
849 uint8 srcslot, dstslot;
851 char* pParam1 = strtok((char*)args, " ");
852 if (!pParam1)
853 return false;
855 char* pParam2 = strtok(NULL, " ");
856 if (!pParam2)
857 return false;
859 srcslot = (uint8)atoi(pParam1);
860 dstslot = (uint8)atoi(pParam2);
862 uint16 src = ((INVENTORY_SLOT_BAG_0 << 8) | srcslot);
863 uint16 dst = ((INVENTORY_SLOT_BAG_0 << 8) | dstslot);
865 if(srcslot==dstslot)
866 return true;
868 m_session->GetPlayer()->SwapItem( src, dst );
870 return true;
873 //add spawn of creature
874 bool ChatHandler::HandleNpcAddCommand(const char* args)
876 if(!*args)
877 return false;
878 char* charID = strtok((char*)args, " ");
879 if (!charID)
880 return false;
882 char* team = strtok(NULL, " ");
883 int32 teamval = 0;
884 if (team) { teamval = atoi(team); }
885 if (teamval < 0) { teamval = 0; }
887 uint32 id = atoi(charID);
889 Player *chr = m_session->GetPlayer();
890 float x = chr->GetPositionX();
891 float y = chr->GetPositionY();
892 float z = chr->GetPositionZ();
893 float o = chr->GetOrientation();
894 Map *map = chr->GetMap();
896 Creature* pCreature = new Creature;
897 if (!pCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), map, id, (uint32)teamval))
899 delete pCreature;
900 return false;
903 pCreature->Relocate(x,y,z,o);
905 if(!pCreature->IsPositionValid())
907 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
908 delete pCreature;
909 return false;
912 pCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()));
914 uint32 db_guid = pCreature->GetDBTableGUIDLow();
916 // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
917 pCreature->LoadFromDB(db_guid, map);
919 map->Add(pCreature);
920 objmgr.AddCreatureToGrid(db_guid, objmgr.GetCreatureData(db_guid));
921 return true;
924 bool ChatHandler::HandleNpcDeleteCommand(const char* args)
926 Creature* unit = NULL;
928 if(*args)
930 // number or [name] Shift-click form |color|Hcreature:creature_guid|h[name]|h|r
931 char* cId = extractKeyFromLink((char*)args,"Hcreature");
932 if(!cId)
933 return false;
935 uint32 lowguid = atoi(cId);
936 if(!lowguid)
937 return false;
939 if (CreatureData const* cr_data = objmgr.GetCreatureData(lowguid))
940 unit = ObjectAccessor::GetCreature(*m_session->GetPlayer(), MAKE_NEW_GUID(lowguid, cr_data->id, HIGHGUID_UNIT));
942 else
943 unit = getSelectedCreature();
945 if(!unit || unit->isPet() || unit->isTotem())
947 SendSysMessage(LANG_SELECT_CREATURE);
948 SetSentErrorMessage(true);
949 return false;
952 // Delete the creature
953 unit->CombatStop();
954 unit->DeleteFromDB();
955 unit->CleanupsBeforeDelete();
956 unit->AddObjectToRemoveList();
958 SendSysMessage(LANG_COMMAND_DELCREATMESSAGE);
960 return true;
963 //delete object by selection or guid
964 bool ChatHandler::HandleDelObjectCommand(const char* args)
966 // number or [name] Shift-click form |color|Hgameobject:go_guid|h[name]|h|r
967 char* cId = extractKeyFromLink((char*)args,"Hgameobject");
968 if(!cId)
969 return false;
971 uint32 lowguid = atoi(cId);
972 if(!lowguid)
973 return false;
975 GameObject* obj = NULL;
977 // by DB guid
978 if (GameObjectData const* go_data = objmgr.GetGOData(lowguid))
979 obj = GetObjectGlobalyWithGuidOrNearWithDbGuid(lowguid,go_data->id);
981 if(!obj)
983 PSendSysMessage(LANG_COMMAND_OBJNOTFOUND, lowguid);
984 SetSentErrorMessage(true);
985 return false;
988 uint64 owner_guid = obj->GetOwnerGUID();
989 if(owner_guid)
991 Unit* owner = ObjectAccessor::GetUnit(*m_session->GetPlayer(),owner_guid);
992 if(!owner && !IS_PLAYER_GUID(owner_guid))
994 PSendSysMessage(LANG_COMMAND_DELOBJREFERCREATURE, GUID_LOPART(owner_guid), obj->GetGUIDLow());
995 SetSentErrorMessage(true);
996 return false;
999 owner->RemoveGameObject(obj,false);
1002 obj->SetRespawnTime(0); // not save respawn time
1003 obj->Delete();
1004 obj->DeleteFromDB();
1006 PSendSysMessage(LANG_COMMAND_DELOBJMESSAGE, obj->GetGUIDLow());
1008 return true;
1011 //turn selected object
1012 bool ChatHandler::HandleTurnObjectCommand(const char* args)
1014 // number or [name] Shift-click form |color|Hgameobject:go_id|h[name]|h|r
1015 char* cId = extractKeyFromLink((char*)args,"Hgameobject");
1016 if(!cId)
1017 return false;
1019 uint32 lowguid = atoi(cId);
1020 if(!lowguid)
1021 return false;
1023 GameObject* obj = NULL;
1025 // by DB guid
1026 if (GameObjectData const* go_data = objmgr.GetGOData(lowguid))
1027 obj = GetObjectGlobalyWithGuidOrNearWithDbGuid(lowguid,go_data->id);
1029 if(!obj)
1031 PSendSysMessage(LANG_COMMAND_OBJNOTFOUND, lowguid);
1032 SetSentErrorMessage(true);
1033 return false;
1036 char* po = strtok(NULL, " ");
1037 float o;
1039 if (po)
1041 o = (float)atof(po);
1043 else
1045 Player *chr = m_session->GetPlayer();
1046 o = chr->GetOrientation();
1049 float rot2 = sin(o/2);
1050 float rot3 = cos(o/2);
1052 Map* map = MapManager::Instance().GetMap(obj->GetMapId(),obj);
1053 map->Remove(obj,false);
1055 obj->Relocate(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), o);
1057 obj->SetFloatValue(GAMEOBJECT_FACING, o);
1058 obj->SetFloatValue(GAMEOBJECT_PARENTROTATION+2, rot2);
1059 obj->SetFloatValue(GAMEOBJECT_PARENTROTATION+3, rot3);
1061 map->Add(obj);
1063 obj->SaveToDB();
1064 obj->Refresh();
1066 PSendSysMessage(LANG_COMMAND_TURNOBJMESSAGE, obj->GetGUIDLow(), o);
1068 return true;
1071 //move selected creature
1072 bool ChatHandler::HandleNpcMoveCommand(const char* args)
1074 uint32 lowguid = 0;
1076 Creature* pCreature = getSelectedCreature();
1078 if(!pCreature)
1080 // number or [name] Shift-click form |color|Hcreature:creature_guid|h[name]|h|r
1081 char* cId = extractKeyFromLink((char*)args,"Hcreature");
1082 if(!cId)
1083 return false;
1085 uint32 lowguid = atoi(cId);
1087 /* FIXME: impossibel without entry
1088 if(lowguid)
1089 pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_GUID(lowguid,HIGHGUID_UNIT));
1092 // Attempting creature load from DB data
1093 if(!pCreature)
1095 CreatureData const* data = objmgr.GetCreatureData(lowguid);
1096 if(!data)
1098 PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid);
1099 SetSentErrorMessage(true);
1100 return false;
1103 uint32 map_id = data->mapid;
1105 if(m_session->GetPlayer()->GetMapId()!=map_id)
1107 PSendSysMessage(LANG_COMMAND_CREATUREATSAMEMAP, lowguid);
1108 SetSentErrorMessage(true);
1109 return false;
1112 else
1114 lowguid = pCreature->GetDBTableGUIDLow();
1117 else
1119 lowguid = pCreature->GetDBTableGUIDLow();
1122 float x = m_session->GetPlayer()->GetPositionX();
1123 float y = m_session->GetPlayer()->GetPositionY();
1124 float z = m_session->GetPlayer()->GetPositionZ();
1125 float o = m_session->GetPlayer()->GetOrientation();
1127 if (pCreature)
1129 if(CreatureData const* data = objmgr.GetCreatureData(pCreature->GetDBTableGUIDLow()))
1131 const_cast<CreatureData*>(data)->posX = x;
1132 const_cast<CreatureData*>(data)->posY = y;
1133 const_cast<CreatureData*>(data)->posZ = z;
1134 const_cast<CreatureData*>(data)->orientation = o;
1136 MapManager::Instance().GetMap(pCreature->GetMapId(),pCreature)->CreatureRelocation(pCreature,x, y, z,o);
1137 pCreature->GetMotionMaster()->Initialize();
1138 if(pCreature->isAlive()) // dead creature will reset movement generator at respawn
1140 pCreature->setDeathState(JUST_DIED);
1141 pCreature->Respawn();
1145 WorldDatabase.PExecuteLog("UPDATE creature SET position_x = '%f', position_y = '%f', position_z = '%f', orientation = '%f' WHERE guid = '%u'", x, y, z, o, lowguid);
1146 PSendSysMessage(LANG_COMMAND_CREATUREMOVED);
1147 return true;
1150 //move selected object
1151 bool ChatHandler::HandleMoveObjectCommand(const char* args)
1153 // number or [name] Shift-click form |color|Hgameobject:go_guid|h[name]|h|r
1154 char* cId = extractKeyFromLink((char*)args,"Hgameobject");
1155 if(!cId)
1156 return false;
1158 uint32 lowguid = atoi(cId);
1159 if(!lowguid)
1160 return false;
1162 GameObject* obj = NULL;
1164 // by DB guid
1165 if (GameObjectData const* go_data = objmgr.GetGOData(lowguid))
1166 obj = GetObjectGlobalyWithGuidOrNearWithDbGuid(lowguid,go_data->id);
1168 if(!obj)
1170 PSendSysMessage(LANG_COMMAND_OBJNOTFOUND, lowguid);
1171 SetSentErrorMessage(true);
1172 return false;
1175 char* px = strtok(NULL, " ");
1176 char* py = strtok(NULL, " ");
1177 char* pz = strtok(NULL, " ");
1179 if (!px)
1181 Player *chr = m_session->GetPlayer();
1183 Map* map = MapManager::Instance().GetMap(obj->GetMapId(),obj);
1184 map->Remove(obj,false);
1186 obj->Relocate(chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), obj->GetOrientation());
1187 obj->SetFloatValue(GAMEOBJECT_POS_X, chr->GetPositionX());
1188 obj->SetFloatValue(GAMEOBJECT_POS_Y, chr->GetPositionY());
1189 obj->SetFloatValue(GAMEOBJECT_POS_Z, chr->GetPositionZ());
1191 map->Add(obj);
1193 else
1195 if(!py || !pz)
1196 return false;
1198 float x = (float)atof(px);
1199 float y = (float)atof(py);
1200 float z = (float)atof(pz);
1202 if(!MapManager::IsValidMapCoord(obj->GetMapId(),x,y,z))
1204 PSendSysMessage(LANG_INVALID_TARGET_COORD,x,y,obj->GetMapId());
1205 SetSentErrorMessage(true);
1206 return false;
1209 Map* map = MapManager::Instance().GetMap(obj->GetMapId(),obj);
1210 map->Remove(obj,false);
1212 obj->Relocate(x, y, z, obj->GetOrientation());
1213 obj->SetFloatValue(GAMEOBJECT_POS_X, x);
1214 obj->SetFloatValue(GAMEOBJECT_POS_Y, y);
1215 obj->SetFloatValue(GAMEOBJECT_POS_Z, z);
1217 map->Add(obj);
1220 obj->SaveToDB();
1221 obj->Refresh();
1223 PSendSysMessage(LANG_COMMAND_MOVEOBJMESSAGE, obj->GetGUIDLow());
1225 return true;
1228 //demorph player or unit
1229 bool ChatHandler::HandleDeMorphCommand(const char* /*args*/)
1231 Unit *target = getSelectedUnit();
1232 if(!target)
1233 target = m_session->GetPlayer();
1235 target->DeMorph();
1237 return true;
1240 //add item in vendorlist
1241 bool ChatHandler::HandleAddVendorItemCommand(const char* args)
1243 if (!*args)
1244 return false;
1246 char* pitem = extractKeyFromLink((char*)args,"Hitem");
1247 if (!pitem)
1249 SendSysMessage(LANG_COMMAND_NEEDITEMSEND);
1250 SetSentErrorMessage(true);
1251 return false;
1254 uint32 itemId = atol(pitem);
1256 char* fmaxcount = strtok(NULL, " "); //add maxcount, default: 0
1257 uint32 maxcount = 0;
1258 if (fmaxcount)
1259 maxcount = atol(fmaxcount);
1261 char* fincrtime = strtok(NULL, " "); //add incrtime, default: 0
1262 uint32 incrtime = 0;
1263 if (fincrtime)
1264 incrtime = atol(fincrtime);
1266 char* fextendedcost = strtok(NULL, " "); //add ExtendedCost, default: 0
1267 uint32 extendedcost = fextendedcost ? atol(fextendedcost) : 0;
1269 Creature* vendor = getSelectedCreature();
1271 uint32 vendor_entry = vendor ? vendor->GetEntry() : 0;
1273 if(!objmgr.IsVendorItemValid(vendor_entry,itemId,maxcount,incrtime,extendedcost,m_session->GetPlayer()))
1275 SetSentErrorMessage(true);
1276 return false;
1279 objmgr.AddVendorItem(vendor_entry,itemId,maxcount,incrtime,extendedcost);
1281 ItemPrototype const* pProto = objmgr.GetItemPrototype(itemId);
1283 PSendSysMessage(LANG_ITEM_ADDED_TO_LIST,itemId,pProto->Name1,maxcount,incrtime,extendedcost);
1284 return true;
1287 //del item from vendor list
1288 bool ChatHandler::HandleDelVendorItemCommand(const char* args)
1290 if (!*args)
1291 return false;
1293 Creature* vendor = getSelectedCreature();
1294 if (!vendor || !vendor->isVendor())
1296 SendSysMessage(LANG_COMMAND_VENDORSELECTION);
1297 SetSentErrorMessage(true);
1298 return false;
1301 char* pitem = extractKeyFromLink((char*)args,"Hitem");
1302 if (!pitem)
1304 SendSysMessage(LANG_COMMAND_NEEDITEMSEND);
1305 SetSentErrorMessage(true);
1306 return false;
1308 uint32 itemId = atol(pitem);
1310 if(!objmgr.RemoveVendorItem(vendor->GetEntry(),itemId))
1312 PSendSysMessage(LANG_ITEM_NOT_IN_LIST,itemId);
1313 SetSentErrorMessage(true);
1314 return false;
1317 ItemPrototype const* pProto = objmgr.GetItemPrototype(itemId);
1319 PSendSysMessage(LANG_ITEM_DELETED_FROM_LIST,itemId,pProto->Name1);
1320 return true;
1323 //add move for creature
1324 bool ChatHandler::HandleNpcAddMoveCommand(const char* args)
1326 if(!*args)
1327 return false;
1329 char* guid_str = strtok((char*)args, " ");
1330 char* wait_str = strtok((char*)NULL, " ");
1332 uint32 lowguid = atoi((char*)guid_str);
1334 Creature* pCreature = NULL;
1336 /* FIXME: impossible without entry
1337 if(lowguid)
1338 pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_GUID(lowguid,HIGHGUID_UNIT));
1341 // attempt check creature existence by DB data
1342 if(!pCreature)
1344 CreatureData const* data = objmgr.GetCreatureData(lowguid);
1345 if(!data)
1347 PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid);
1348 SetSentErrorMessage(true);
1349 return false;
1352 else
1354 // obtain real GUID for DB operations
1355 lowguid = pCreature->GetDBTableGUIDLow();
1358 int wait = wait_str ? atoi(wait_str) : 0;
1360 if(wait < 0)
1361 wait = 0;
1363 Player* player = m_session->GetPlayer();
1365 WaypointMgr.AddLastNode(lowguid, player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetOrientation(), wait, 0);
1367 // update movement type
1368 WorldDatabase.PExecuteLog("UPDATE creature SET MovementType = '%u' WHERE guid = '%u'", WAYPOINT_MOTION_TYPE,lowguid);
1369 if(pCreature)
1371 pCreature->SetDefaultMovementType(WAYPOINT_MOTION_TYPE);
1372 pCreature->GetMotionMaster()->Initialize();
1373 if(pCreature->isAlive()) // dead creature will reset movement generator at respawn
1375 pCreature->setDeathState(JUST_DIED);
1376 pCreature->Respawn();
1378 pCreature->SaveToDB();
1381 SendSysMessage(LANG_WAYPOINT_ADDED);
1383 return true;
1387 * Set the movement type for an NPC.<br/>
1388 * <br/>
1389 * Valid movement types are:
1390 * <ul>
1391 * <li> stay - NPC wont move </li>
1392 * <li> random - NPC will move randomly according to the spawndist </li>
1393 * <li> way - NPC will move with given waypoints set </li>
1394 * </ul>
1395 * additional parameter: NODEL - so no waypoints are deleted, if you
1396 * change the movement type
1398 bool ChatHandler::HandleNpcSetMoveTypeCommand(const char* args)
1400 if(!*args)
1401 return false;
1403 // 3 arguments:
1404 // GUID (optional - you can also select the creature)
1405 // stay|random|way (determines the kind of movement)
1406 // NODEL (optional - tells the system NOT to delete any waypoints)
1407 // this is very handy if you want to do waypoints, that are
1408 // later switched on/off according to special events (like escort
1409 // quests, etc)
1410 char* guid_str = strtok((char*)args, " ");
1411 char* type_str = strtok((char*)NULL, " ");
1412 char* dontdel_str = strtok((char*)NULL, " ");
1414 bool doNotDelete = false;
1416 if(!guid_str)
1417 return false;
1419 uint32 lowguid = 0;
1420 Creature* pCreature = NULL;
1422 if( dontdel_str )
1424 //sLog.outError("DEBUG: All 3 params are set");
1426 // All 3 params are set
1427 // GUID
1428 // type
1429 // doNotDEL
1430 if( stricmp( dontdel_str, "NODEL" ) == 0 )
1432 //sLog.outError("DEBUG: doNotDelete = true;");
1433 doNotDelete = true;
1436 else
1438 // Only 2 params - but maybe NODEL is set
1439 if( type_str )
1441 sLog.outError("DEBUG: Only 2 params ");
1442 if( stricmp( type_str, "NODEL" ) == 0 )
1444 //sLog.outError("DEBUG: type_str, NODEL ");
1445 doNotDelete = true;
1446 type_str = NULL;
1451 if(!type_str) // case .setmovetype $move_type (with selected creature)
1453 type_str = guid_str;
1454 pCreature = getSelectedCreature();
1455 if(!pCreature || pCreature->isPet())
1456 return false;
1457 lowguid = pCreature->GetDBTableGUIDLow();
1459 else // case .setmovetype #creature_guid $move_type (with selected creature)
1461 lowguid = atoi((char*)guid_str);
1463 /* impossible without entry
1464 if(lowguid)
1465 pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_GUID(lowguid,HIGHGUID_UNIT));
1468 // attempt check creature existence by DB data
1469 if(!pCreature)
1471 CreatureData const* data = objmgr.GetCreatureData(lowguid);
1472 if(!data)
1474 PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid);
1475 SetSentErrorMessage(true);
1476 return false;
1479 else
1481 lowguid = pCreature->GetDBTableGUIDLow();
1485 // now lowguid is low guid really existed creature
1486 // and pCreature point (maybe) to this creature or NULL
1488 MovementGeneratorType move_type;
1490 std::string type = type_str;
1492 if(type == "stay")
1493 move_type = IDLE_MOTION_TYPE;
1494 else if(type == "random")
1495 move_type = RANDOM_MOTION_TYPE;
1496 else if(type == "way")
1497 move_type = WAYPOINT_MOTION_TYPE;
1498 else
1499 return false;
1501 // update movement type
1502 if(doNotDelete == false)
1503 WaypointMgr.DeletePath(lowguid);
1505 if(pCreature)
1507 pCreature->SetDefaultMovementType(move_type);
1508 pCreature->GetMotionMaster()->Initialize();
1509 if(pCreature->isAlive()) // dead creature will reset movement generator at respawn
1511 pCreature->setDeathState(JUST_DIED);
1512 pCreature->Respawn();
1514 pCreature->SaveToDB();
1516 if( doNotDelete == false )
1518 PSendSysMessage(LANG_MOVE_TYPE_SET,type_str);
1520 else
1522 PSendSysMessage(LANG_MOVE_TYPE_SET_NODEL,type_str);
1525 return true;
1526 } // HandleNpcSetMoveTypeCommand
1528 //change level of creature or pet
1529 bool ChatHandler::HandleChangeLevelCommand(const char* args)
1531 if (!*args)
1532 return false;
1534 uint8 lvl = (uint8) atoi((char*)args);
1535 if ( lvl < 1 || lvl > sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) + 3)
1537 SendSysMessage(LANG_BAD_VALUE);
1538 SetSentErrorMessage(true);
1539 return false;
1542 Creature* pCreature = getSelectedCreature();
1543 if(!pCreature)
1545 SendSysMessage(LANG_SELECT_CREATURE);
1546 SetSentErrorMessage(true);
1547 return false;
1550 if(pCreature->isPet())
1552 ((Pet*)pCreature)->GivePetLevel(lvl);
1554 else
1556 pCreature->SetMaxHealth( 100 + 30*lvl);
1557 pCreature->SetHealth( 100 + 30*lvl);
1558 pCreature->SetLevel( lvl);
1559 pCreature->SaveToDB();
1562 return true;
1565 //set npcflag of creature
1566 bool ChatHandler::HandleNpcFlagCommand(const char* args)
1568 if (!*args)
1569 return false;
1571 uint32 npcFlags = (uint32) atoi((char*)args);
1573 Creature* pCreature = getSelectedCreature();
1575 if(!pCreature)
1577 SendSysMessage(LANG_SELECT_CREATURE);
1578 SetSentErrorMessage(true);
1579 return false;
1582 pCreature->SetUInt32Value(UNIT_NPC_FLAGS, npcFlags);
1584 WorldDatabase.PExecuteLog("UPDATE creature_template SET npcflag = '%u' WHERE entry = '%u'", npcFlags, pCreature->GetEntry());
1586 SendSysMessage(LANG_VALUE_SAVED_REJOIN);
1588 return true;
1591 //set model of creature
1592 bool ChatHandler::HandleNpcSetModelCommand(const char* args)
1594 if (!*args)
1595 return false;
1597 uint32 displayId = (uint32) atoi((char*)args);
1599 Creature *pCreature = getSelectedCreature();
1601 if(!pCreature || pCreature->isPet())
1603 SendSysMessage(LANG_SELECT_CREATURE);
1604 SetSentErrorMessage(true);
1605 return false;
1608 pCreature->SetDisplayId(displayId);
1609 pCreature->SetNativeDisplayId(displayId);
1611 pCreature->SaveToDB();
1613 return true;
1616 //morph creature or player
1617 bool ChatHandler::HandleMorphCommand(const char* args)
1619 if (!*args)
1620 return false;
1622 uint16 display_id = (uint16)atoi((char*)args);
1624 Unit *target = getSelectedUnit();
1625 if(!target)
1626 target = m_session->GetPlayer();
1628 target->SetDisplayId(display_id);
1630 return true;
1633 //set faction of creature
1634 bool ChatHandler::HandleNpcFactionIdCommand(const char* args)
1636 if (!*args)
1637 return false;
1639 uint32 factionId = (uint32) atoi((char*)args);
1641 if (!sFactionTemplateStore.LookupEntry(factionId))
1643 PSendSysMessage(LANG_WRONG_FACTION, factionId);
1644 SetSentErrorMessage(true);
1645 return false;
1648 Creature* pCreature = getSelectedCreature();
1650 if(!pCreature)
1652 SendSysMessage(LANG_SELECT_CREATURE);
1653 SetSentErrorMessage(true);
1654 return false;
1657 pCreature->setFaction(factionId);
1659 // faction is set in creature_template - not inside creature
1661 // update in memory
1662 if(CreatureInfo const *cinfo = pCreature->GetCreatureInfo())
1664 const_cast<CreatureInfo*>(cinfo)->faction_A = factionId;
1665 const_cast<CreatureInfo*>(cinfo)->faction_H = factionId;
1668 // and DB
1669 WorldDatabase.PExecuteLog("UPDATE creature_template SET faction_A = '%u', faction_H = '%u' WHERE entry = '%u'", factionId, factionId, pCreature->GetEntry());
1671 return true;
1674 //kick player
1675 bool ChatHandler::HandleKickPlayerCommand(const char *args)
1677 char* kickName = strtok((char*)args, " ");
1678 if (!kickName)
1680 Player* player = getSelectedPlayer();
1682 if(!player)
1684 SendSysMessage(LANG_NO_CHAR_SELECTED);
1685 SetSentErrorMessage(true);
1686 return false;
1689 if(player==m_session->GetPlayer())
1691 SendSysMessage(LANG_COMMAND_KICKSELF);
1692 SetSentErrorMessage(true);
1693 return false;
1696 player->GetSession()->KickPlayer();
1698 else
1700 std::string name = kickName;
1701 if(!normalizePlayerName(name))
1703 SendSysMessage(LANG_PLAYER_NOT_FOUND);
1704 SetSentErrorMessage(true);
1705 return false;
1708 if(m_session && name==m_session->GetPlayer()->GetName())
1710 SendSysMessage(LANG_COMMAND_KICKSELF);
1711 SetSentErrorMessage(true);
1712 return false;
1715 if(sWorld.KickPlayer(name))
1717 PSendSysMessage(LANG_COMMAND_KICKMESSAGE,name.c_str());
1719 else
1720 PSendSysMessage(LANG_COMMAND_KICKNOTFOUNDPLAYER,name.c_str());
1723 return true;
1726 //show info of player
1727 bool ChatHandler::HandlePInfoCommand(const char* args)
1729 Player* target = NULL;
1730 uint64 targetGUID = 0;
1732 char* px = strtok((char*)args, " ");
1733 char* py = NULL;
1735 std::string name;
1737 if (px)
1739 name = px;
1741 if(name.empty())
1742 return false;
1744 if(!normalizePlayerName(name))
1746 SendSysMessage(LANG_PLAYER_NOT_FOUND);
1747 SetSentErrorMessage(true);
1748 return false;
1751 target = objmgr.GetPlayer(name.c_str());
1752 if (target)
1753 py = strtok(NULL, " ");
1754 else
1756 targetGUID = objmgr.GetPlayerGUIDByName(name);
1757 if(targetGUID)
1758 py = strtok(NULL, " ");
1759 else
1760 py = px;
1764 if(!target && !targetGUID)
1766 target = getSelectedPlayer();
1769 if(!target && !targetGUID)
1771 SendSysMessage(LANG_PLAYER_NOT_FOUND);
1772 SetSentErrorMessage(true);
1773 return false;
1776 uint32 accId = 0;
1777 uint32 money = 0;
1778 uint32 total_player_time = 0;
1779 uint32 level = 0;
1780 uint32 latency = 0;
1782 // get additional information from Player object
1783 if(target)
1785 targetGUID = target->GetGUID();
1786 name = target->GetName(); // re-read for case getSelectedPlayer() target
1787 accId = target->GetSession()->GetAccountId();
1788 money = target->GetMoney();
1789 total_player_time = target->GetTotalPlayedTime();
1790 level = target->getLevel();
1791 latency = target->GetSession()->GetLatency();
1793 // get additional information from DB
1794 else
1796 accId = objmgr.GetPlayerAccountIdByGUID(targetGUID);
1797 Player plr(m_session); // use current session for temporary load
1798 plr.MinimalLoadFromDB(NULL, targetGUID);
1799 money = plr.GetMoney();
1800 total_player_time = plr.GetTotalPlayedTime();
1801 level = plr.getLevel();
1804 std::string username = GetMangosString(LANG_ERROR);
1805 std::string last_ip = GetMangosString(LANG_ERROR);
1806 uint32 security = 0;
1807 std::string last_login = GetMangosString(LANG_ERROR);
1809 QueryResult* result = loginDatabase.PQuery("SELECT username,gmlevel,last_ip,last_login FROM account WHERE id = '%u'",accId);
1810 if(result)
1812 Field* fields = result->Fetch();
1813 username = fields[0].GetCppString();
1814 security = fields[1].GetUInt32();
1816 if(!m_session || m_session->GetSecurity() >= security)
1818 last_ip = fields[2].GetCppString();
1819 last_login = fields[3].GetCppString();
1821 else
1823 last_ip = "-";
1824 last_login = "-";
1827 delete result;
1830 PSendSysMessage(LANG_PINFO_ACCOUNT, (target?"":GetMangosString(LANG_OFFLINE)), name.c_str(), GUID_LOPART(targetGUID), username.c_str(), accId, security, last_ip.c_str(), last_login.c_str(), latency);
1832 std::string timeStr = secsToTimeString(total_player_time,true,true);
1833 uint32 gold = money /GOLD;
1834 uint32 silv = (money % GOLD) / SILVER;
1835 uint32 copp = (money % GOLD) % SILVER;
1836 PSendSysMessage(LANG_PINFO_LEVEL, timeStr.c_str(), level, gold,silv,copp );
1838 if ( py && strncmp(py, "rep", 3) == 0 )
1840 if(!target)
1842 // rep option not implemented for offline case
1843 SendSysMessage(LANG_PINFO_NO_REP);
1844 SetSentErrorMessage(true);
1845 return false;
1848 char* FactionName;
1849 for(FactionStateList::const_iterator itr = target->m_factions.begin(); itr != target->m_factions.end(); ++itr)
1851 FactionEntry const *factionEntry = sFactionStore.LookupEntry(itr->second.ID);
1852 if (factionEntry)
1853 FactionName = factionEntry->name[m_session->GetSessionDbcLocale()];
1854 else
1855 FactionName = "#Not found#";
1856 ReputationRank rank = target->GetReputationRank(factionEntry);
1857 std::string rankName = GetMangosString(ReputationRankStrIndex[rank]);
1858 std::ostringstream ss;
1859 ss << itr->second.ID << ": |cffffffff|Hfaction:" << itr->second.ID << "|h[" << FactionName << "]|h|r " << rankName << "|h|r (" << target->GetReputation(factionEntry) << ")";
1861 if(itr->second.Flags & FACTION_FLAG_VISIBLE)
1862 ss << GetMangosString(LANG_FACTION_VISIBLE);
1863 if(itr->second.Flags & FACTION_FLAG_AT_WAR)
1864 ss << GetMangosString(LANG_FACTION_ATWAR);
1865 if(itr->second.Flags & FACTION_FLAG_PEACE_FORCED)
1866 ss << GetMangosString(LANG_FACTION_PEACE_FORCED);
1867 if(itr->second.Flags & FACTION_FLAG_HIDDEN)
1868 ss << GetMangosString(LANG_FACTION_HIDDEN);
1869 if(itr->second.Flags & FACTION_FLAG_INVISIBLE_FORCED)
1870 ss << GetMangosString(LANG_FACTION_INVISIBLE_FORCED);
1871 if(itr->second.Flags & FACTION_FLAG_INACTIVE)
1872 ss << GetMangosString(LANG_FACTION_INACTIVE);
1874 SendSysMessage(ss.str().c_str());
1877 return true;
1880 //show tickets
1881 void ChatHandler::ShowTicket(uint64 guid, char const* text, char const* time)
1883 std::string name;
1884 if(!objmgr.GetPlayerNameByGUID(guid,name))
1885 name = GetMangosString(LANG_UNKNOWN);
1887 PSendSysMessage(LANG_COMMAND_TICKETVIEW, name.c_str(),time,text);
1890 //ticket commands
1891 bool ChatHandler::HandleTicketCommand(const char* args)
1893 char* px = strtok((char*)args, " ");
1895 // ticket<end>
1896 if (!px)
1898 if(!m_session)
1900 SendSysMessage(LANG_PLAYER_NOT_FOUND);
1901 SetSentErrorMessage(true);
1902 return false;
1905 size_t count;
1906 QueryResult *result = CharacterDatabase.Query("SELECT COUNT(ticket_id) FROM character_ticket");
1907 if(result)
1909 count = (*result)[0].GetUInt32();
1910 delete result;
1912 else
1913 count = 0;
1915 bool accept = m_session->GetPlayer()->isAcceptTickets();
1917 PSendSysMessage(LANG_COMMAND_TICKETCOUNT, count, accept ? GetMangosString(LANG_ON) : GetMangosString(LANG_OFF));
1918 return true;
1921 // ticket on
1922 if(strncmp(px,"on",3) == 0)
1924 if(!m_session)
1926 SendSysMessage(LANG_PLAYER_NOT_FOUND);
1927 SetSentErrorMessage(true);
1928 return false;
1931 m_session->GetPlayer()->SetAcceptTicket(true);
1932 SendSysMessage(LANG_COMMAND_TICKETON);
1933 return true;
1936 // ticket off
1937 if(strncmp(px,"off",4) == 0)
1939 if(!m_session)
1941 SendSysMessage(LANG_PLAYER_NOT_FOUND);
1942 SetSentErrorMessage(true);
1943 return false;
1946 m_session->GetPlayer()->SetAcceptTicket(false);
1947 SendSysMessage(LANG_COMMAND_TICKETOFF);
1948 return true;
1951 // ticket #num
1952 int num = atoi(px);
1953 if(num > 0)
1955 QueryResult *result = CharacterDatabase.PQuery("SELECT guid,ticket_text,ticket_lastchange FROM character_ticket ORDER BY ticket_id ASC "_OFFSET_, num-1);
1957 if(!result)
1959 PSendSysMessage(LANG_COMMAND_TICKENOTEXIST, num);
1960 delete result;
1961 SetSentErrorMessage(true);
1962 return false;
1965 Field* fields = result->Fetch();
1967 uint64 guid = fields[0].GetUInt64();
1968 char const* text = fields[1].GetString();
1969 char const* time = fields[2].GetString();
1971 ShowTicket(guid,text,time);
1972 delete result;
1973 return true;
1976 std::string name = px;
1978 if(!normalizePlayerName(name))
1980 SendSysMessage(LANG_PLAYER_NOT_FOUND);
1981 SetSentErrorMessage(true);
1982 return false;
1985 uint64 guid = objmgr.GetPlayerGUIDByName(name);
1987 if(!guid)
1988 return false;
1990 // ticket $char_name
1991 QueryResult *result = CharacterDatabase.PQuery("SELECT ticket_text,ticket_lastchange FROM character_ticket WHERE guid = '%u' ORDER BY ticket_id ASC",GUID_LOPART(guid));
1993 if(!result)
1994 return false;
1996 Field* fields = result->Fetch();
1998 char const* text = fields[0].GetString();
1999 char const* time = fields[1].GetString();
2001 ShowTicket(guid,text,time);
2002 delete result;
2004 return true;
2007 uint32 ChatHandler::GetTicketIDByNum(uint32 num)
2009 QueryResult *result = CharacterDatabase.Query("SELECT ticket_id FROM character_ticket");
2011 if(!result || num > result->GetRowCount())
2013 PSendSysMessage(LANG_COMMAND_TICKENOTEXIST, num);
2014 delete result;
2015 return 0;
2018 for(uint32 i = 1; i < num; ++i)
2019 result->NextRow();
2021 Field* fields = result->Fetch();
2023 uint32 id = fields[0].GetUInt32();
2024 delete result;
2025 return id;
2028 //dell all tickets
2029 bool ChatHandler::HandleDelTicketCommand(const char *args)
2031 char* px = strtok((char*)args, " ");
2032 if (!px)
2033 return false;
2035 // delticket all
2036 if(strncmp(px,"all",4) == 0)
2038 QueryResult *result = CharacterDatabase.Query("SELECT guid FROM character_ticket");
2040 if(!result)
2041 return true;
2043 // notify players about ticket deleting
2046 Field* fields = result->Fetch();
2048 uint64 guid = fields[0].GetUInt64();
2050 if(Player* sender = objmgr.GetPlayer(guid))
2051 sender->GetSession()->SendGMTicketGetTicket(0x0A,0);
2053 }while(result->NextRow());
2055 delete result;
2057 CharacterDatabase.PExecute("DELETE FROM character_ticket");
2058 SendSysMessage(LANG_COMMAND_ALLTICKETDELETED);
2059 return true;
2062 int num = (uint32)atoi(px);
2064 // delticket #num
2065 if(num > 0)
2067 QueryResult *result = CharacterDatabase.PQuery("SELECT ticket_id,guid FROM character_ticket ORDER BY ticket_id ASC "_OFFSET_,num-1);
2069 if(!result)
2071 PSendSysMessage(LANG_COMMAND_TICKENOTEXIST, num);
2072 delete result;
2073 SetSentErrorMessage(true);
2074 return false;
2077 Field* fields = result->Fetch();
2079 uint32 id = fields[0].GetUInt32();
2080 uint64 guid = fields[1].GetUInt64();
2081 delete result;
2083 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE ticket_id = '%u'", id);
2085 // notify players about ticket deleting
2086 if(Player* sender = objmgr.GetPlayer(guid))
2088 sender->GetSession()->SendGMTicketGetTicket(0x0A,0);
2089 PSendSysMessage(LANG_COMMAND_TICKETPLAYERDEL,sender->GetName());
2091 else
2092 SendSysMessage(LANG_COMMAND_TICKETDEL);
2094 return true;
2097 std::string name = px;
2099 if(!normalizePlayerName(name))
2101 SendSysMessage(LANG_PLAYER_NOT_FOUND);
2102 SetSentErrorMessage(true);
2103 return false;
2106 uint64 guid = objmgr.GetPlayerGUIDByName(name);
2108 if(!guid)
2109 return false;
2111 // delticket $char_name
2112 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",GUID_LOPART(guid));
2114 // notify players about ticket deleting
2115 if(Player* sender = objmgr.GetPlayer(guid))
2116 sender->GetSession()->SendGMTicketGetTicket(0x0A,0);
2118 PSendSysMessage(LANG_COMMAND_TICKETPLAYERDEL,px);
2119 return true;
2122 //set spawn dist of creature
2123 bool ChatHandler::HandleNpcSpawnDistCommand(const char* args)
2125 if(!*args)
2126 return false;
2128 float option = atof((char*)args);
2129 if (option < 0.0f)
2131 SendSysMessage(LANG_BAD_VALUE);
2132 return false;
2135 MovementGeneratorType mtype = IDLE_MOTION_TYPE;
2136 if (option >0.0f)
2137 mtype = RANDOM_MOTION_TYPE;
2139 Creature *pCreature = getSelectedCreature();
2140 uint32 u_guidlow = 0;
2142 if (pCreature)
2143 u_guidlow = pCreature->GetDBTableGUIDLow();
2144 else
2145 return false;
2147 pCreature->SetRespawnRadius((float)option);
2148 pCreature->SetDefaultMovementType(mtype);
2149 pCreature->GetMotionMaster()->Initialize();
2150 if(pCreature->isAlive()) // dead creature will reset movement generator at respawn
2152 pCreature->setDeathState(JUST_DIED);
2153 pCreature->Respawn();
2156 WorldDatabase.PExecuteLog("UPDATE creature SET spawndist=%f, MovementType=%i WHERE guid=%u",option,mtype,u_guidlow);
2157 PSendSysMessage(LANG_COMMAND_SPAWNDIST,option);
2158 return true;
2161 bool ChatHandler::HandleNpcSpawnTimeCommand(const char* args)
2163 if(!*args)
2164 return false;
2166 char* stime = strtok((char*)args, " ");
2168 if (!stime)
2169 return false;
2171 int i_stime = atoi((char*)stime);
2173 if (i_stime < 0)
2175 SendSysMessage(LANG_BAD_VALUE);
2176 SetSentErrorMessage(true);
2177 return false;
2180 Creature *pCreature = getSelectedCreature();
2181 uint32 u_guidlow = 0;
2183 if (pCreature)
2184 u_guidlow = pCreature->GetDBTableGUIDLow();
2185 else
2186 return false;
2188 WorldDatabase.PExecuteLog("UPDATE creature SET spawntimesecs=%i WHERE guid=%u",i_stime,u_guidlow);
2189 pCreature->SetRespawnDelay((uint32)i_stime);
2190 PSendSysMessage(LANG_COMMAND_SPAWNTIME,i_stime);
2192 return true;
2196 * Add a waypoint to a creature.
2198 * The user can either select an npc or provide its GUID.
2200 * The user can even select a visual waypoint - then the new waypoint
2201 * is placed *after* the selected one - this makes insertion of new
2202 * waypoints possible.
2204 * eg:
2205 * .wp add 12345
2206 * -> adds a waypoint to the npc with the GUID 12345
2208 * .wp add
2209 * -> adds a waypoint to the currently selected creature
2212 * @param args if the user did not provide a GUID, it is NULL
2214 * @return true - command did succeed, false - something went wrong
2216 bool ChatHandler::HandleWpAddCommand(const char* args)
2218 sLog.outDebug("DEBUG: HandleWpAddCommand");
2220 // optional
2221 char* guid_str = NULL;
2223 if(*args)
2225 guid_str = strtok((char*)args, " ");
2228 uint32 lowguid = 0;
2229 uint32 point = 0;
2230 Creature* target = getSelectedCreature();
2231 // Did player provide a GUID?
2232 if (!guid_str)
2234 sLog.outDebug("DEBUG: HandleWpAddCommand - No GUID provided");
2236 // No GUID provided
2237 // -> Player must have selected a creature
2239 if(!target || target->isPet())
2241 SendSysMessage(LANG_SELECT_CREATURE);
2242 SetSentErrorMessage(true);
2243 return false;
2245 if (target->GetEntry() == VISUAL_WAYPOINT )
2247 sLog.outDebug("DEBUG: HandleWpAddCommand - target->GetEntry() == VISUAL_WAYPOINT (1) ");
2249 QueryResult *result =
2250 WorldDatabase.PQuery( "SELECT id, point FROM creature_movement WHERE wpguid = %u",
2251 target->GetGUIDLow() );
2252 if(!result)
2254 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, target->GetGUIDLow());
2255 // User selected a visual spawnpoint -> get the NPC
2256 // Select NPC GUID
2257 // Since we compare float values, we have to deal with
2258 // some difficulties.
2259 // Here we search for all waypoints that only differ in one from 1 thousand
2260 // (0.001) - There is no other way to compare C++ floats with mySQL floats
2261 // See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-float.html
2262 const char* maxDIFF = "0.01";
2263 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 )",
2264 target->GetPositionX(), maxDIFF, target->GetPositionY(), maxDIFF, target->GetPositionZ(), maxDIFF);
2265 if(!result)
2267 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, target->GetGUIDLow());
2268 SetSentErrorMessage(true);
2269 return false;
2274 Field *fields = result->Fetch();
2275 lowguid = fields[0].GetUInt32();
2276 point = fields[1].GetUInt32();
2277 }while( result->NextRow() );
2278 delete result;
2280 CreatureData const* data = objmgr.GetCreatureData(lowguid);
2281 if(!data)
2283 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2284 SetSentErrorMessage(true);
2285 return false;
2288 target = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_NEW_GUID(lowguid,data->id,HIGHGUID_UNIT));
2289 if(!target)
2291 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, lowguid);
2292 SetSentErrorMessage(true);
2293 return false;
2296 else
2298 lowguid = target->GetDBTableGUIDLow();
2301 else
2303 sLog.outDebug("DEBUG: HandleWpAddCommand - GUID provided");
2305 // GUID provided
2306 // Warn if player also selected a creature
2307 // -> Creature selection is ignored <-
2308 if(target)
2310 SendSysMessage(LANG_WAYPOINT_CREATSELECTED);
2312 lowguid = atoi((char*)guid_str);
2314 CreatureData const* data = objmgr.GetCreatureData(lowguid);
2315 if(!data)
2317 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2318 SetSentErrorMessage(true);
2319 return false;
2322 target = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_NEW_GUID(lowguid,data->id,HIGHGUID_UNIT));
2323 if(!target || target->isPet())
2325 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2326 SetSentErrorMessage(true);
2327 return false;
2330 // lowguid -> GUID of the NPC
2331 // point -> number of the waypoint (if not 0)
2332 sLog.outDebug("DEBUG: HandleWpAddCommand - danach");
2334 sLog.outDebug("DEBUG: HandleWpAddCommand - point == 0");
2336 Player* player = m_session->GetPlayer();
2337 WaypointMgr.AddLastNode(lowguid, player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetOrientation(), 0, 0);
2339 // update movement type
2340 if(target)
2342 target->SetDefaultMovementType(WAYPOINT_MOTION_TYPE);
2343 target->GetMotionMaster()->Initialize();
2344 if(target->isAlive()) // dead creature will reset movement generator at respawn
2346 target->setDeathState(JUST_DIED);
2347 target->Respawn();
2349 target->SaveToDB();
2351 else
2352 WorldDatabase.PExecuteLog("UPDATE creature SET MovementType = '%u' WHERE guid = '%u'", WAYPOINT_MOTION_TYPE,lowguid);
2354 PSendSysMessage(LANG_WAYPOINT_ADDED, point, lowguid);
2356 return true;
2357 } // HandleWpAddCommand
2360 * .wp modify emote | spell | text | del | move | add
2362 * add -> add a WP after the selected visual waypoint
2363 * User must select a visual waypoint and then issue ".wp modify add"
2365 * emote <emoteID>
2366 * User has selected a visual waypoint before.
2367 * <emoteID> is added to this waypoint. Everytime the
2368 * NPC comes to this waypoint, the emote is called.
2370 * emote <GUID> <WPNUM> <emoteID>
2371 * User has not selected visual waypoint before.
2372 * For the waypoint <WPNUM> for the NPC with <GUID>
2373 * an emote <emoteID> is added.
2374 * Everytime the NPC comes to this waypoint, the emote is called.
2377 * info <GUID> <WPNUM> -> User did not select a visual waypoint and
2379 bool ChatHandler::HandleWpModifyCommand(const char* args)
2381 sLog.outDebug("DEBUG: HandleWpModifyCommand");
2383 if(!*args)
2384 return false;
2386 // first arg: add del text emote spell waittime move
2387 char* show_str = strtok((char*)args, " ");
2388 if (!show_str)
2390 return false;
2393 std::string show = show_str;
2394 // Check
2395 // Remember: "show" must also be the name of a column!
2396 if( (show != "emote") && (show != "spell") && (show != "text1") && (show != "text2")
2397 && (show != "text3") && (show != "text4") && (show != "text5")
2398 && (show != "waittime") && (show != "del") && (show != "move") && (show != "add")
2399 && (show != "model1") && (show != "model2") && (show != "orientation"))
2401 return false;
2404 // Next arg is: <GUID> <WPNUM> <ARGUMENT>
2406 // Did user provide a GUID
2407 // or did the user select a creature?
2408 // -> variable lowguid is filled with the GUID of the NPC
2409 uint32 lowguid = 0;
2410 uint32 point = 0;
2411 uint32 wpGuid = 0;
2412 Creature* target = getSelectedCreature();
2414 if(target)
2416 sLog.outDebug("DEBUG: HandleWpModifyCommand - User did select an NPC");
2418 // Did the user select a visual spawnpoint?
2419 if (target->GetEntry() != VISUAL_WAYPOINT )
2421 PSendSysMessage(LANG_WAYPOINT_VP_SELECT);
2422 SetSentErrorMessage(true);
2423 return false;
2426 wpGuid = target->GetGUIDLow();
2428 // The visual waypoint
2429 QueryResult *result =
2430 WorldDatabase.PQuery( "SELECT id, point FROM creature_movement WHERE wpguid = %u LIMIT 1",
2431 target->GetGUIDLow() );
2432 if(!result)
2434 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, wpGuid);
2435 SetSentErrorMessage(true);
2436 return false;
2438 sLog.outDebug("DEBUG: HandleWpModifyCommand - After getting wpGuid");
2440 Field *fields = result->Fetch();
2441 lowguid = fields[0].GetUInt32();
2442 point = fields[1].GetUInt32();
2444 // Cleanup memory
2445 sLog.outDebug("DEBUG: HandleWpModifyCommand - Cleanup memory");
2446 delete result;
2448 else
2450 // User did provide <GUID> <WPNUM>
2452 char* guid_str = strtok((char*)NULL, " ");
2453 if( !guid_str )
2455 SendSysMessage(LANG_WAYPOINT_NOGUID);
2456 return false;
2458 lowguid = atoi((char*)guid_str);
2460 CreatureData const* data = objmgr.GetCreatureData(lowguid);
2461 if(!data)
2463 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2464 SetSentErrorMessage(true);
2465 return false;
2468 PSendSysMessage("DEBUG: GUID provided: %d", lowguid);
2470 char* point_str = strtok((char*)NULL, " ");
2471 if( !point_str )
2473 SendSysMessage(LANG_WAYPOINT_NOWAYPOINTGIVEN);
2474 return false;
2476 point = atoi((char*)point_str);
2478 PSendSysMessage("DEBUG: wpNumber provided: %d", point);
2480 // Now we need the GUID of the visual waypoint
2481 // -> "del", "move", "add" command
2483 QueryResult *result = WorldDatabase.PQuery( "SELECT wpguid FROM creature_movement WHERE id = '%u' AND point = '%u' LIMIT 1", lowguid, point);
2484 if (!result)
2486 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, lowguid, point);
2487 SetSentErrorMessage(true);
2488 return false;
2491 Field *fields = result->Fetch();
2492 wpGuid = fields[0].GetUInt32();
2494 // Free memory
2495 delete result;
2498 char* arg_str = NULL;
2499 // Check for argument
2500 if( (show.find("text") == std::string::npos ) && (show != "del") && (show != "move") && (show != "add"))
2502 // Text is enclosed in "<>", all other arguments not
2503 if( show.find("text") != std::string::npos )
2504 arg_str = strtok((char*)NULL, "<>");
2505 else
2506 arg_str = strtok((char*)NULL, " ");
2508 if( !arg_str)
2510 PSendSysMessage(LANG_WAYPOINT_ARGUMENTREQ, show_str);
2511 return false;
2515 sLog.outDebug("DEBUG: HandleWpModifyCommand - Parameters parsed - now execute the command");
2517 // wpGuid -> GUID of the waypoint creature
2518 // lowguid -> GUID of the NPC
2519 // point -> waypoint number
2521 // Special functions:
2522 // add - move - del -> no args commands
2523 // Add a waypoint after the selected visual
2524 if(show == "add" && target)
2526 PSendSysMessage("DEBUG: wp modify add, GUID: %u", lowguid);
2528 // Get the creature for which we read the waypoint
2529 CreatureData const* data = objmgr.GetCreatureData(lowguid);
2530 if(!data)
2532 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2533 SetSentErrorMessage(true);
2534 return false;
2537 Creature* npcCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT));
2539 if( !npcCreature )
2541 PSendSysMessage(LANG_WAYPOINT_NPCNOTFOUND);
2542 SetSentErrorMessage(true);
2543 return false;
2546 sLog.outDebug("DEBUG: HandleWpModifyCommand - add -- npcCreature");
2548 // What to do:
2549 // Add the visual spawnpoint (DB only)
2550 // Adjust the waypoints
2551 // Respawn the owner of the waypoints
2552 sLog.outDebug("DEBUG: HandleWpModifyCommand - add");
2554 Player* chr = m_session->GetPlayer();
2555 Map *map = chr->GetMap();
2557 if(npcCreature)
2559 npcCreature->GetMotionMaster()->Initialize();
2560 if(npcCreature->isAlive()) // dead creature will reset movement generator at respawn
2562 npcCreature->setDeathState(JUST_DIED);
2563 npcCreature->Respawn();
2567 // create the waypoint creature
2568 wpGuid = 0;
2569 Creature* wpCreature = new Creature;
2570 if (!wpCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), map,VISUAL_WAYPOINT,0))
2572 PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, VISUAL_WAYPOINT);
2573 delete wpCreature;
2575 else
2577 wpCreature->Relocate(chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), chr->GetOrientation());
2579 if(!wpCreature->IsPositionValid())
2581 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",wpCreature->GetGUIDLow(),wpCreature->GetEntry(),wpCreature->GetPositionX(),wpCreature->GetPositionY());
2582 delete wpCreature;
2584 else
2586 wpCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()));
2587 // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
2588 wpCreature->LoadFromDB(wpCreature->GetDBTableGUIDLow(), map);
2589 map->Add(wpCreature);
2590 wpGuid = wpCreature->GetGUIDLow();
2594 WaypointMgr.AddAfterNode(lowguid, point, chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), 0, 0, wpGuid);
2596 if(!wpGuid)
2597 return false;
2599 PSendSysMessage(LANG_WAYPOINT_ADDED_NO, point+1);
2600 return true;
2601 } // add
2603 if(show == "del" && target)
2605 PSendSysMessage("DEBUG: wp modify del, GUID: %u", lowguid);
2607 // Get the creature for which we read the waypoint
2608 CreatureData const* data = objmgr.GetCreatureData(lowguid);
2609 if(!data)
2611 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2612 SetSentErrorMessage(true);
2613 return false;
2616 Creature* npcCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT));
2618 // wpCreature
2619 Creature* wpCreature = NULL;
2620 if( wpGuid != 0 )
2622 wpCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT));
2623 wpCreature->DeleteFromDB();
2624 wpCreature->CleanupsBeforeDelete();
2625 wpCreature->AddObjectToRemoveList();
2628 // What to do:
2629 // Remove the visual spawnpoint
2630 // Adjust the waypoints
2631 // Respawn the owner of the waypoints
2633 WaypointMgr.DeleteNode(lowguid, point);
2635 if(npcCreature)
2637 // Any waypoints left?
2638 QueryResult *result2 = WorldDatabase.PQuery( "SELECT point FROM creature_movement WHERE id = '%u'",lowguid);
2639 if(!result2)
2641 npcCreature->SetDefaultMovementType(RANDOM_MOTION_TYPE);
2643 else
2645 npcCreature->SetDefaultMovementType(WAYPOINT_MOTION_TYPE);
2646 delete result2;
2648 npcCreature->GetMotionMaster()->Initialize();
2649 if(npcCreature->isAlive()) // dead creature will reset movement generator at respawn
2651 npcCreature->setDeathState(JUST_DIED);
2652 npcCreature->Respawn();
2654 npcCreature->SaveToDB();
2657 PSendSysMessage(LANG_WAYPOINT_REMOVED);
2658 return true;
2659 } // del
2661 if(show == "move" && target)
2663 PSendSysMessage("DEBUG: wp move, GUID: %u", lowguid);
2665 Player *chr = m_session->GetPlayer();
2666 Map *map = chr->GetMap();
2668 // Get the creature for which we read the waypoint
2669 CreatureData const* data = objmgr.GetCreatureData(lowguid);
2670 if(!data)
2672 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2673 SetSentErrorMessage(true);
2674 return false;
2677 Creature* npcCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT));
2679 // wpCreature
2680 Creature* wpCreature = NULL;
2681 // What to do:
2682 // Move the visual spawnpoint
2683 // Respawn the owner of the waypoints
2684 if( wpGuid != 0 )
2686 wpCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT));
2687 wpCreature->DeleteFromDB();
2688 wpCreature->CleanupsBeforeDelete();
2689 wpCreature->AddObjectToRemoveList();
2690 // re-create
2691 Creature* wpCreature2 = new Creature;
2692 if (!wpCreature2->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), map, VISUAL_WAYPOINT, 0))
2694 PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, VISUAL_WAYPOINT);
2695 delete wpCreature2;
2696 return false;
2699 wpCreature2->Relocate(chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), chr->GetOrientation());
2701 if(!wpCreature2->IsPositionValid())
2703 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",wpCreature2->GetGUIDLow(),wpCreature2->GetEntry(),wpCreature2->GetPositionX(),wpCreature2->GetPositionY());
2704 delete wpCreature2;
2705 return false;
2708 wpCreature2->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()));
2709 // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
2710 wpCreature2->LoadFromDB(wpCreature2->GetDBTableGUIDLow(), map);
2711 map->Add(wpCreature2);
2712 //MapManager::Instance().GetMap(npcCreature->GetMapId())->Add(wpCreature2);
2715 WaypointMgr.SetNodePosition(lowguid, point, chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ());
2717 if(npcCreature)
2719 npcCreature->GetMotionMaster()->Initialize();
2720 if(npcCreature->isAlive()) // dead creature will reset movement generator at respawn
2722 npcCreature->setDeathState(JUST_DIED);
2723 npcCreature->Respawn();
2726 PSendSysMessage(LANG_WAYPOINT_CHANGED);
2728 return true;
2729 } // move
2731 // Create creature - npc that has the waypoint
2732 CreatureData const* data = objmgr.GetCreatureData(lowguid);
2733 if(!data)
2735 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2736 SetSentErrorMessage(true);
2737 return false;
2740 WaypointMgr.SetNodeText(lowguid, point, show_str, arg_str);
2742 Creature* npcCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT));
2743 if(npcCreature)
2745 npcCreature->SetDefaultMovementType(WAYPOINT_MOTION_TYPE);
2746 npcCreature->GetMotionMaster()->Initialize();
2747 if(npcCreature->isAlive()) // dead creature will reset movement generator at respawn
2749 npcCreature->setDeathState(JUST_DIED);
2750 npcCreature->Respawn();
2753 PSendSysMessage(LANG_WAYPOINT_CHANGED_NO, show_str);
2755 return true;
2759 * .wp show info | on | off
2761 * info -> User has selected a visual waypoint before
2763 * info <GUID> <WPNUM> -> User did not select a visual waypoint and
2764 * provided the GUID of the NPC and the number of
2765 * the waypoint.
2767 * on -> User has selected an NPC; all visual waypoints for this
2768 * NPC are added to the world
2770 * on <GUID> -> User did not select an NPC - instead the GUID of the
2771 * NPC is provided. All visual waypoints for this NPC
2772 * are added from the world.
2774 * off -> User has selected an NPC; all visual waypoints for this
2775 * NPC are removed from the world.
2777 * on <GUID> -> User did not select an NPC - instead the GUID of the
2778 * NPC is provided. All visual waypoints for this NPC
2779 * are removed from the world.
2783 bool ChatHandler::HandleWpShowCommand(const char* args)
2785 sLog.outDebug("DEBUG: HandleWpShowCommand");
2787 if(!*args)
2788 return false;
2790 // first arg: on, off, first, last
2791 char* show_str = strtok((char*)args, " ");
2792 if (!show_str)
2794 return false;
2796 // second arg: GUID (optional, if a creature is selected)
2797 char* guid_str = strtok((char*)NULL, " ");
2798 sLog.outDebug("DEBUG: HandleWpShowCommand: show_str: %s guid_str: %s", show_str, guid_str);
2799 //if (!guid_str) {
2800 // return false;
2803 // Did user provide a GUID
2804 // or did the user select a creature?
2805 // -> variable lowguid is filled with the GUID
2806 Creature* target = getSelectedCreature();
2807 // Did player provide a GUID?
2808 if (!guid_str)
2810 sLog.outDebug("DEBUG: HandleWpShowCommand: !guid_str");
2811 // No GUID provided
2812 // -> Player must have selected a creature
2814 if(!target)
2816 SendSysMessage(LANG_SELECT_CREATURE);
2817 SetSentErrorMessage(true);
2818 return false;
2821 else
2823 sLog.outDebug("DEBUG: HandleWpShowCommand: GUID provided");
2824 // GUID provided
2825 // Warn if player also selected a creature
2826 // -> Creature selection is ignored <-
2827 if(target)
2829 SendSysMessage(LANG_WAYPOINT_CREATSELECTED);
2832 uint32 lowguid = atoi((char*)guid_str);
2834 CreatureData const* data = objmgr.GetCreatureData(lowguid);
2835 if(!data)
2837 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2838 SetSentErrorMessage(true);
2839 return false;
2842 target = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_NEW_GUID(lowguid,data->id,HIGHGUID_UNIT));
2844 if(!target)
2846 PSendSysMessage(LANG_WAYPOINT_CREATNOTFOUND, lowguid);
2847 SetSentErrorMessage(true);
2848 return false;
2852 uint32 lowguid = target->GetDBTableGUIDLow();
2854 std::string show = show_str;
2855 uint32 Maxpoint;
2857 sLog.outDebug("DEBUG: HandleWpShowCommand: lowguid: %u", lowguid);
2859 sLog.outDebug("DEBUG: HandleWpShowCommand: Habe creature: %ld", target );
2861 sLog.outDebug("DEBUG: HandleWpShowCommand: wpshow - show: %s", show_str);
2862 //PSendSysMessage("wpshow - show: %s", show);
2864 // Show info for the selected waypoint
2865 if(show == "info")
2867 PSendSysMessage("DEBUG: wp info, GUID: %u", lowguid);
2869 // Check if the user did specify a visual waypoint
2870 if( target->GetEntry() != VISUAL_WAYPOINT )
2872 PSendSysMessage(LANG_WAYPOINT_VP_SELECT);
2873 SetSentErrorMessage(true);
2874 return false;
2877 //PSendSysMessage("wp on, GUID: %u", lowguid);
2879 //pCreature->GetPositionX();
2881 QueryResult *result =
2882 WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, text1, text2, text3, text4, text5, model1, model2 FROM creature_movement WHERE wpguid = %u",
2883 target->GetGUID() );
2884 if(!result)
2886 // Since we compare float values, we have to deal with
2887 // some difficulties.
2888 // Here we search for all waypoints that only differ in one from 1 thousand
2889 // (0.001) - There is no other way to compare C++ floats with mySQL floats
2890 // See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-float.html
2891 const char* maxDIFF = "0.01";
2892 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, target->GetGUID());
2894 result = WorldDatabase.PQuery( "SELECT id, point, waittime, emote, spell, text1, text2, text3, text4, text5, model1, model2 FROM creature_movement WHERE (abs(position_x - %f) <= %s ) and (abs(position_y - %f) <= %s ) and (abs(position_z - %f) <= %s )",
2895 target->GetPositionX(), maxDIFF, target->GetPositionY(), maxDIFF, target->GetPositionZ(), maxDIFF);
2896 if(!result)
2898 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, lowguid);
2899 SetSentErrorMessage(true);
2900 return false;
2905 Field *fields = result->Fetch();
2906 uint32 creGUID = fields[0].GetUInt32();
2907 uint32 point = fields[1].GetUInt32();
2908 int waittime = fields[2].GetUInt32();
2909 uint32 emote = fields[3].GetUInt32();
2910 uint32 spell = fields[4].GetUInt32();
2911 const char * text1 = fields[5].GetString();
2912 const char * text2 = fields[6].GetString();
2913 const char * text3 = fields[7].GetString();
2914 const char * text4 = fields[8].GetString();
2915 const char * text5 = fields[9].GetString();
2916 uint32 model1 = fields[10].GetUInt32();
2917 uint32 model2 = fields[11].GetUInt32();
2919 // Get the creature for which we read the waypoint
2920 Creature* wpCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_NEW_GUID(creGUID,VISUAL_WAYPOINT,HIGHGUID_UNIT));
2922 PSendSysMessage(LANG_WAYPOINT_INFO_TITLE, point, (wpCreature ? wpCreature->GetName() : "<not found>"), creGUID);
2923 PSendSysMessage(LANG_WAYPOINT_INFO_WAITTIME, waittime);
2924 PSendSysMessage(LANG_WAYPOINT_INFO_MODEL, 1, model1);
2925 PSendSysMessage(LANG_WAYPOINT_INFO_MODEL, 2, model2);
2926 PSendSysMessage(LANG_WAYPOINT_INFO_EMOTE, emote);
2927 PSendSysMessage(LANG_WAYPOINT_INFO_SPELL, spell);
2928 PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 1, text1);
2929 PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 2, text2);
2930 PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 3, text3);
2931 PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 4, text4);
2932 PSendSysMessage(LANG_WAYPOINT_INFO_TEXT, 5, text5);
2934 }while( result->NextRow() );
2935 // Cleanup memory
2936 delete result;
2937 return true;
2940 if(show == "on")
2942 PSendSysMessage("DEBUG: wp on, GUID: %u", lowguid);
2944 QueryResult *result = WorldDatabase.PQuery( "SELECT point, position_x,position_y,position_z FROM creature_movement WHERE id = '%u'",lowguid);
2945 if(!result)
2947 PSendSysMessage(LANG_WAYPOINT_NOTFOUND, lowguid);
2948 SetSentErrorMessage(true);
2949 return false;
2951 // Delete all visuals for this NPC
2952 QueryResult *result2 = WorldDatabase.PQuery( "SELECT wpguid FROM creature_movement WHERE id = '%u' and wpguid <> 0", lowguid);
2953 if(result2)
2955 bool hasError = false;
2958 Field *fields = result2->Fetch();
2959 uint32 wpguid = fields[0].GetUInt32();
2960 Creature* pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_NEW_GUID(wpguid,VISUAL_WAYPOINT,HIGHGUID_UNIT));
2962 if(!pCreature)
2964 PSendSysMessage(LANG_WAYPOINT_NOTREMOVED, wpguid);
2965 hasError = true;
2966 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", wpguid);
2968 else
2970 pCreature->DeleteFromDB();
2971 pCreature->CleanupsBeforeDelete();
2972 pCreature->AddObjectToRemoveList();
2975 }while( result2->NextRow() );
2976 delete result2;
2977 if( hasError )
2979 PSendSysMessage(LANG_WAYPOINT_TOOFAR1);
2980 PSendSysMessage(LANG_WAYPOINT_TOOFAR2);
2981 PSendSysMessage(LANG_WAYPOINT_TOOFAR3);
2987 Field *fields = result->Fetch();
2988 uint32 point = fields[0].GetUInt32();
2989 float x = fields[1].GetFloat();
2990 float y = fields[2].GetFloat();
2991 float z = fields[3].GetFloat();
2993 uint32 id = VISUAL_WAYPOINT;
2995 Player *chr = m_session->GetPlayer();
2996 Map *map = chr->GetMap();
2997 float o = chr->GetOrientation();
2999 Creature* wpCreature = new Creature;
3000 if (!wpCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), map, id, 0))
3002 PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, id);
3003 delete wpCreature;
3004 delete result;
3005 return false;
3008 wpCreature->Relocate(x, y, z, o);
3010 if(!wpCreature->IsPositionValid())
3012 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",wpCreature->GetGUIDLow(),wpCreature->GetEntry(),wpCreature->GetPositionX(),wpCreature->GetPositionY());
3013 delete wpCreature;
3014 delete result;
3015 return false;
3018 wpCreature->SetVisibility(VISIBILITY_OFF);
3019 sLog.outDebug("DEBUG: UPDATE creature_movement SET wpguid = '%u");
3020 // set "wpguid" column to the visual waypoint
3021 WorldDatabase.PExecuteLog("UPDATE creature_movement SET wpguid = '%u' WHERE id = '%u' and point = '%u'", wpCreature->GetGUIDLow(), lowguid, point);
3023 wpCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()));
3024 // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
3025 wpCreature->LoadFromDB(wpCreature->GetDBTableGUIDLow(),map);
3026 map->Add(wpCreature);
3027 //MapManager::Instance().GetMap(wpCreature->GetMapId())->Add(wpCreature);
3028 }while( result->NextRow() );
3030 // Cleanup memory
3031 delete result;
3032 return true;
3035 if(show == "first")
3037 PSendSysMessage("DEBUG: wp first, GUID: %u", lowguid);
3039 QueryResult *result = WorldDatabase.PQuery( "SELECT position_x,position_y,position_z FROM creature_movement WHERE point='1' AND id = '%u'",lowguid);
3040 if(!result)
3042 PSendSysMessage(LANG_WAYPOINT_NOTFOUND, lowguid);
3043 SetSentErrorMessage(true);
3044 return false;
3047 Field *fields = result->Fetch();
3048 float x = fields[0].GetFloat();
3049 float y = fields[1].GetFloat();
3050 float z = fields[2].GetFloat();
3051 uint32 id = VISUAL_WAYPOINT;
3053 Player *chr = m_session->GetPlayer();
3054 float o = chr->GetOrientation();
3055 Map *map = chr->GetMap();
3057 Creature* pCreature = new Creature;
3058 if (!pCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT),map, id, 0))
3060 PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, id);
3061 delete pCreature;
3062 delete result;
3063 return false;
3066 pCreature->Relocate(x, y, z, o);
3068 if(!pCreature->IsPositionValid())
3070 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
3071 delete pCreature;
3072 delete result;
3073 return false;
3076 pCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()));
3077 pCreature->LoadFromDB(pCreature->GetDBTableGUIDLow(), map);
3078 map->Add(pCreature);
3079 //player->PlayerTalkClass->SendPointOfInterest(x, y, 6, 6, 0, "First Waypoint");
3081 // Cleanup memory
3082 delete result;
3083 return true;
3086 if(show == "last")
3088 PSendSysMessage("DEBUG: wp last, GUID: %u", lowguid);
3090 QueryResult *result = WorldDatabase.PQuery( "SELECT MAX(point) FROM creature_movement WHERE id = '%u'",lowguid);
3091 if( result )
3093 Maxpoint = (*result)[0].GetUInt32();
3095 delete result;
3097 else
3098 Maxpoint = 0;
3100 result = WorldDatabase.PQuery( "SELECT position_x,position_y,position_z FROM creature_movement WHERE point ='%u' AND id = '%u'",Maxpoint, lowguid);
3101 if(!result)
3103 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDLAST, lowguid);
3104 SetSentErrorMessage(true);
3105 return false;
3107 Field *fields = result->Fetch();
3108 float x = fields[0].GetFloat();
3109 float y = fields[1].GetFloat();
3110 float z = fields[2].GetFloat();
3111 uint32 id = VISUAL_WAYPOINT;
3113 Player *chr = m_session->GetPlayer();
3114 float o = chr->GetOrientation();
3115 Map *map = chr->GetMap();
3117 Creature* pCreature = new Creature;
3118 if (!pCreature->Create(objmgr.GenerateLowGuid(HIGHGUID_UNIT), map, id, 0))
3120 PSendSysMessage(LANG_WAYPOINT_NOTCREATED, id);
3121 delete pCreature;
3122 delete result;
3123 return false;
3126 pCreature->Relocate(x, y, z, o);
3128 if(!pCreature->IsPositionValid())
3130 sLog.outError("ERROR: Creature (guidlow %d, entry %d) not created. Suggested coordinates isn't valid (X: %f Y: %f)",pCreature->GetGUIDLow(),pCreature->GetEntry(),pCreature->GetPositionX(),pCreature->GetPositionY());
3131 delete pCreature;
3132 delete result;
3133 return false;
3136 pCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()));
3137 pCreature->LoadFromDB(pCreature->GetDBTableGUIDLow(), map);
3138 map->Add(pCreature);
3139 //player->PlayerTalkClass->SendPointOfInterest(x, y, 6, 6, 0, "Last Waypoint");
3140 // Cleanup memory
3141 delete result;
3142 return true;
3145 if(show == "off")
3147 QueryResult *result = WorldDatabase.PQuery("SELECT guid FROM creature WHERE id = '%d'", VISUAL_WAYPOINT);
3148 if(!result)
3150 SendSysMessage(LANG_WAYPOINT_VP_NOTFOUND);
3151 SetSentErrorMessage(true);
3152 return false;
3154 bool hasError = false;
3157 Field *fields = result->Fetch();
3158 uint32 guid = fields[0].GetUInt32();
3159 Creature* pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(),MAKE_NEW_GUID(guid,VISUAL_WAYPOINT,HIGHGUID_UNIT));
3161 //Creature* pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), guid);
3163 if(!pCreature)
3165 PSendSysMessage(LANG_WAYPOINT_NOTREMOVED, guid);
3166 hasError = true;
3167 WorldDatabase.PExecuteLog("DELETE FROM creature WHERE guid = '%u'", guid);
3169 else
3171 pCreature->DeleteFromDB();
3172 pCreature->CleanupsBeforeDelete();
3173 pCreature->AddObjectToRemoveList();
3175 }while(result->NextRow());
3176 // set "wpguid" column to "empty" - no visual waypoint spawned
3177 WorldDatabase.PExecuteLog("UPDATE creature_movement SET wpguid = '0'");
3179 if( hasError )
3181 PSendSysMessage(LANG_WAYPOINT_TOOFAR1);
3182 PSendSysMessage(LANG_WAYPOINT_TOOFAR2);
3183 PSendSysMessage(LANG_WAYPOINT_TOOFAR3);
3186 SendSysMessage(LANG_WAYPOINT_VP_ALLREMOVED);
3187 // Cleanup memory
3188 delete result;
3190 return true;
3193 PSendSysMessage("DEBUG: wpshow - no valid command found");
3195 return true;
3196 } // HandleWpShowCommand
3198 bool ChatHandler::HandleWpExportCommand(const char *args)
3200 if(!*args)
3201 return false;
3203 // Next arg is: <GUID> <ARGUMENT>
3205 // Did user provide a GUID
3206 // or did the user select a creature?
3207 // -> variable lowguid is filled with the GUID of the NPC
3208 uint32 lowguid = 0;
3209 Creature* target = getSelectedCreature();
3210 char* arg_str = NULL;
3211 if (target)
3213 if (target->GetEntry() != VISUAL_WAYPOINT)
3214 lowguid = target->GetGUIDLow();
3215 else
3217 QueryResult *result = WorldDatabase.PQuery( "SELECT id FROM creature_movement WHERE wpguid = %u LIMIT 1", target->GetGUIDLow() );
3218 if (!result)
3220 PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, target->GetGUIDLow());
3221 return true;
3223 Field *fields = result->Fetch();
3224 lowguid = fields[0].GetUInt32();;
3225 delete result;
3228 arg_str = strtok((char*)args, " ");
3230 else
3232 // user provided <GUID>
3233 char* guid_str = strtok((char*)args, " ");
3234 if( !guid_str )
3236 SendSysMessage(LANG_WAYPOINT_NOGUID);
3237 return false;
3239 lowguid = atoi((char*)guid_str);
3241 arg_str = strtok((char*)NULL, " ");
3244 if( !arg_str)
3246 PSendSysMessage(LANG_WAYPOINT_ARGUMENTREQ, "export");
3247 return false;
3250 PSendSysMessage("DEBUG: wp export, GUID: %u", lowguid);
3252 QueryResult *result = WorldDatabase.PQuery(
3253 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
3254 "SELECT point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, text1, text2, text3, text4, text5, id FROM creature_movement WHERE id = '%u' ORDER BY point", lowguid );
3256 if (!result)
3258 PSendSysMessage(LANG_WAYPOINT_NOTHINGTOEXPORT);
3259 SetSentErrorMessage(true);
3260 return false;
3263 std::ofstream outfile;
3264 outfile.open (arg_str);
3268 Field *fields = result->Fetch();
3270 outfile << "INSERT INTO creature_movement ";
3271 outfile << "( id, point, position_x, position_y, position_z, orientation, model1, model2, waittime, emote, spell, text1, text2, text3, text4, text5 ) VALUES ";
3273 outfile << "( ";
3274 outfile << fields[15].GetUInt32(); // id
3275 outfile << ", ";
3276 outfile << fields[0].GetUInt32(); // point
3277 outfile << ", ";
3278 outfile << fields[1].GetFloat(); // position_x
3279 outfile << ", ";
3280 outfile << fields[2].GetFloat(); // position_y
3281 outfile << ", ";
3282 outfile << fields[3].GetUInt32(); // position_z
3283 outfile << ", ";
3284 outfile << fields[4].GetUInt32(); // orientation
3285 outfile << ", ";
3286 outfile << fields[5].GetUInt32(); // model1
3287 outfile << ", ";
3288 outfile << fields[6].GetUInt32(); // model2
3289 outfile << ", ";
3290 outfile << fields[7].GetUInt16(); // waittime
3291 outfile << ", ";
3292 outfile << fields[8].GetUInt32(); // emote
3293 outfile << ", ";
3294 outfile << fields[9].GetUInt32(); // spell
3295 outfile << ", ";
3296 const char *tmpChar = fields[10].GetString();
3297 if( !tmpChar )
3299 outfile << "NULL"; // text1
3301 else
3303 outfile << "'";
3304 outfile << tmpChar; // text1
3305 outfile << "'";
3307 outfile << ", ";
3308 tmpChar = fields[11].GetString();
3309 if( !tmpChar )
3311 outfile << "NULL"; // text2
3313 else
3315 outfile << "'";
3316 outfile << tmpChar; // text2
3317 outfile << "'";
3319 outfile << ", ";
3320 tmpChar = fields[12].GetString();
3321 if( !tmpChar )
3323 outfile << "NULL"; // text3
3325 else
3327 outfile << "'";
3328 outfile << tmpChar; // text3
3329 outfile << "'";
3331 outfile << ", ";
3332 tmpChar = fields[13].GetString();
3333 if( !tmpChar )
3335 outfile << "NULL"; // text4
3337 else
3339 outfile << "'";
3340 outfile << tmpChar; // text4
3341 outfile << "'";
3343 outfile << ", ";
3344 tmpChar = fields[14].GetString();
3345 if( !tmpChar )
3347 outfile << "NULL"; // text5
3349 else
3351 outfile << "'";
3352 outfile << tmpChar; // text5
3353 outfile << "'";
3355 outfile << ");\n ";
3357 } while( result->NextRow() );
3358 delete result;
3360 PSendSysMessage(LANG_WAYPOINT_EXPORTED);
3361 outfile.close();
3363 return true;
3366 bool ChatHandler::HandleWpImportCommand(const char *args)
3368 if(!*args)
3369 return false;
3371 char* arg_str = strtok((char*)args, " ");
3372 if (!arg_str)
3373 return false;
3375 std::string line;
3376 std::ifstream infile (arg_str);
3377 if (infile.is_open())
3379 while (! infile.eof() )
3381 getline (infile,line);
3382 //cout << line << endl;
3383 QueryResult *result = WorldDatabase.PQuery(line.c_str());
3384 delete result;
3386 infile.close();
3388 PSendSysMessage(LANG_WAYPOINT_IMPORTED);
3390 return true;
3393 //rename characters
3394 bool ChatHandler::HandleRenameCommand(const char* args)
3396 Player* target = NULL;
3397 uint64 targetGUID = 0;
3398 std::string oldname;
3400 char* px = strtok((char*)args, " ");
3402 if(px)
3404 oldname = px;
3406 if(!normalizePlayerName(oldname))
3408 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3409 SetSentErrorMessage(true);
3410 return false;
3413 target = objmgr.GetPlayer(oldname.c_str());
3415 if (!target)
3416 targetGUID = objmgr.GetPlayerGUIDByName(oldname);
3419 if(!target && !targetGUID)
3421 target = getSelectedPlayer();
3424 if(!target && !targetGUID)
3426 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3427 SetSentErrorMessage(true);
3428 return false;
3431 if(target)
3433 PSendSysMessage(LANG_RENAME_PLAYER, target->GetName());
3434 target->SetAtLoginFlag(AT_LOGIN_RENAME);
3435 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '1' WHERE guid = '%u'", target->GetGUIDLow());
3437 else
3439 PSendSysMessage(LANG_RENAME_PLAYER_GUID, oldname.c_str(), GUID_LOPART(targetGUID));
3440 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '1' WHERE guid = '%u'", GUID_LOPART(targetGUID));
3443 return true;
3446 //spawn go
3447 bool ChatHandler::HandleGameObjectCommand(const char* args)
3449 if (!*args)
3450 return false;
3452 char* pParam1 = strtok((char*)args, " ");
3453 if (!pParam1)
3454 return false;
3456 uint32 id = atoi((char*)pParam1);
3457 if(!id)
3458 return false;
3460 char* spawntimeSecs = strtok(NULL, " ");
3462 const GameObjectInfo *goI = objmgr.GetGameObjectInfo(id);
3464 if (!goI)
3466 PSendSysMessage(LANG_GAMEOBJECT_NOT_EXIST,id);
3467 SetSentErrorMessage(true);
3468 return false;
3471 Player *chr = m_session->GetPlayer();
3472 float x = float(chr->GetPositionX());
3473 float y = float(chr->GetPositionY());
3474 float z = float(chr->GetPositionZ());
3475 float o = float(chr->GetOrientation());
3476 Map *map = chr->GetMap();
3478 float rot2 = sin(o/2);
3479 float rot3 = cos(o/2);
3481 GameObject* pGameObj = new GameObject;
3482 uint32 db_lowGUID = objmgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT);
3484 if(!pGameObj->Create(db_lowGUID, goI->id, map, x, y, z, o, 0, 0, rot2, rot3, 0, 1))
3486 delete pGameObj;
3487 return false;
3490 if( spawntimeSecs )
3492 uint32 value = atoi((char*)spawntimeSecs);
3493 pGameObj->SetRespawnTime(value);
3494 //sLog.outDebug("*** spawntimeSecs: %d", value);
3497 // fill the gameobject data and save to the db
3498 pGameObj->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()));
3500 // this will generate a new guid if the object is in an instance
3501 if(!pGameObj->LoadFromDB(db_lowGUID, map))
3503 delete pGameObj;
3504 return false;
3507 sLog.outDebug(GetMangosString(LANG_GAMEOBJECT_CURRENT), goI->name, db_lowGUID, x, y, z, o);
3509 map->Add(pGameObj);
3511 // TODO: is it really necessary to add both the real and DB table guid here ?
3512 objmgr.AddGameobjectToGrid(db_lowGUID, objmgr.GetGOData(db_lowGUID));
3514 PSendSysMessage(LANG_GAMEOBJECT_ADD,id,goI->name,db_lowGUID,x,y,z);
3515 return true;
3518 //show animation
3519 bool ChatHandler::HandleAnimCommand(const char* args)
3521 if (!*args)
3522 return false;
3524 uint32 anim_id = atoi((char*)args);
3525 m_session->GetPlayer()->HandleEmoteCommand(anim_id);
3526 return true;
3529 //change standstate
3530 bool ChatHandler::HandleStandStateCommand(const char* args)
3532 if (!*args)
3533 return false;
3535 uint32 anim_id = atoi((char*)args);
3536 m_session->GetPlayer( )->SetUInt32Value( UNIT_NPC_EMOTESTATE , anim_id );
3538 return true;
3541 bool ChatHandler::HandleAddHonorCommand(const char* args)
3543 if (!*args)
3544 return false;
3546 Player *target = getSelectedPlayer();
3547 if(!target)
3549 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3550 SetSentErrorMessage(true);
3551 return false;
3554 uint32 amount = (uint32)atoi(args);
3555 target->RewardHonor(NULL, 1, amount);
3556 return true;
3559 bool ChatHandler::HandleHonorAddKillCommand(const char* /*args*/)
3561 Unit *target = getSelectedUnit();
3562 if(!target)
3564 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3565 SetSentErrorMessage(true);
3566 return false;
3569 m_session->GetPlayer()->RewardHonor(target, 1);
3570 return true;
3573 bool ChatHandler::HandleUpdateHonorFieldsCommand(const char* /*args*/)
3575 Player *target = getSelectedPlayer();
3576 if(!target)
3578 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3579 SetSentErrorMessage(true);
3580 return false;
3583 target->UpdateHonorFields();
3584 return true;
3587 bool ChatHandler::HandleLookupEventCommand(const char* args)
3589 if(!*args)
3590 return false;
3592 std::string namepart = args;
3593 std::wstring wnamepart;
3595 // converting string that we try to find to lower case
3596 if(!Utf8toWStr(namepart,wnamepart))
3597 return false;
3599 wstrToLower(wnamepart);
3601 uint32 counter = 0;
3603 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
3604 GameEvent::ActiveEvents const& activeEvents = gameeventmgr.GetActiveEventList();
3606 for(uint32 id = 0; id < events.size(); ++id )
3608 GameEventData const& eventData = events[id];
3610 std::string descr = eventData.description;
3611 if(descr.empty())
3612 continue;
3614 if (Utf8FitTo(descr, wnamepart))
3616 char const* active = activeEvents.find(id) != activeEvents.end() ? GetMangosString(LANG_ACTIVE) : "";
3618 if(m_session)
3619 PSendSysMessage(LANG_EVENT_ENTRY_LIST_CHAT,id,id,eventData.description.c_str(),active );
3620 else
3621 PSendSysMessage(LANG_EVENT_ENTRY_LIST_CONSOLE,id,eventData.description.c_str(),active );
3623 ++counter;
3627 if (counter==0)
3628 SendSysMessage(LANG_NOEVENTFOUND);
3630 return true;
3633 bool ChatHandler::HandleEventActiveListCommand(const char* args)
3635 uint32 counter = 0;
3637 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
3638 GameEvent::ActiveEvents const& activeEvents = gameeventmgr.GetActiveEventList();
3640 char const* active = GetMangosString(LANG_ACTIVE);
3642 for(GameEvent::ActiveEvents::const_iterator itr = activeEvents.begin(); itr != activeEvents.end(); ++itr )
3644 uint32 event_id = *itr;
3645 GameEventData const& eventData = events[event_id];
3647 if(m_session)
3648 PSendSysMessage(LANG_EVENT_ENTRY_LIST_CHAT,event_id,event_id,eventData.description.c_str(),active );
3649 else
3650 PSendSysMessage(LANG_EVENT_ENTRY_LIST_CONSOLE,event_id,eventData.description.c_str(),active );
3652 ++counter;
3655 if (counter==0)
3656 SendSysMessage(LANG_NOEVENTFOUND);
3658 return true;
3661 bool ChatHandler::HandleEventInfoCommand(const char* args)
3663 if(!*args)
3664 return false;
3666 // id or [name] Shift-click form |color|Hgameevent:id|h[name]|h|r
3667 char* cId = extractKeyFromLink((char*)args,"Hgameevent");
3668 if(!cId)
3669 return false;
3671 uint32 event_id = atoi(cId);
3673 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
3675 if(event_id >=events.size())
3677 SendSysMessage(LANG_EVENT_NOT_EXIST);
3678 SetSentErrorMessage(true);
3679 return false;
3682 GameEventData const& eventData = events[event_id];
3683 if(!eventData.isValid())
3685 SendSysMessage(LANG_EVENT_NOT_EXIST);
3686 SetSentErrorMessage(true);
3687 return false;
3690 GameEvent::ActiveEvents const& activeEvents = gameeventmgr.GetActiveEventList();
3691 bool active = activeEvents.find(event_id) != activeEvents.end();
3692 char const* activeStr = active ? GetMangosString(LANG_ACTIVE) : "";
3694 std::string startTimeStr = TimeToTimestampStr(eventData.start);
3695 std::string endTimeStr = TimeToTimestampStr(eventData.end);
3697 uint32 delay = gameeventmgr.NextCheck(event_id);
3698 time_t nextTime = time(NULL)+delay;
3699 std::string nextStr = nextTime >= eventData.start && nextTime < eventData.end ? TimeToTimestampStr(time(NULL)+delay) : "-";
3701 std::string occurenceStr = secsToTimeString(eventData.occurence * MINUTE);
3702 std::string lengthStr = secsToTimeString(eventData.length * MINUTE);
3704 PSendSysMessage(LANG_EVENT_INFO,event_id,eventData.description.c_str(),activeStr,
3705 startTimeStr.c_str(),endTimeStr.c_str(),occurenceStr.c_str(),lengthStr.c_str(),
3706 nextStr.c_str());
3707 return true;
3710 bool ChatHandler::HandleEventStartCommand(const char* args)
3712 if(!*args)
3713 return false;
3715 // id or [name] Shift-click form |color|Hgameevent:id|h[name]|h|r
3716 char* cId = extractKeyFromLink((char*)args,"Hgameevent");
3717 if(!cId)
3718 return false;
3720 int32 event_id = atoi(cId);
3722 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
3724 if(event_id < 1 || event_id >=events.size())
3726 SendSysMessage(LANG_EVENT_NOT_EXIST);
3727 SetSentErrorMessage(true);
3728 return false;
3731 GameEventData const& eventData = events[event_id];
3732 if(!eventData.isValid())
3734 SendSysMessage(LANG_EVENT_NOT_EXIST);
3735 SetSentErrorMessage(true);
3736 return false;
3739 GameEvent::ActiveEvents const& activeEvents = gameeventmgr.GetActiveEventList();
3740 if(activeEvents.find(event_id) != activeEvents.end())
3742 PSendSysMessage(LANG_EVENT_ALREADY_ACTIVE,event_id);
3743 SetSentErrorMessage(true);
3744 return false;
3747 gameeventmgr.StartEvent(event_id,true);
3748 return true;
3751 bool ChatHandler::HandleEventStopCommand(const char* args)
3753 if(!*args)
3754 return false;
3756 // id or [name] Shift-click form |color|Hgameevent:id|h[name]|h|r
3757 char* cId = extractKeyFromLink((char*)args,"Hgameevent");
3758 if(!cId)
3759 return false;
3761 int32 event_id = atoi(cId);
3763 GameEvent::GameEventDataMap const& events = gameeventmgr.GetEventMap();
3765 if(event_id < 1 || event_id >=events.size())
3767 SendSysMessage(LANG_EVENT_NOT_EXIST);
3768 SetSentErrorMessage(true);
3769 return false;
3772 GameEventData const& eventData = events[event_id];
3773 if(!eventData.isValid())
3775 SendSysMessage(LANG_EVENT_NOT_EXIST);
3776 SetSentErrorMessage(true);
3777 return false;
3780 GameEvent::ActiveEvents const& activeEvents = gameeventmgr.GetActiveEventList();
3782 if(activeEvents.find(event_id) == activeEvents.end())
3784 PSendSysMessage(LANG_EVENT_NOT_ACTIVE,event_id);
3785 SetSentErrorMessage(true);
3786 return false;
3789 gameeventmgr.StopEvent(event_id,true);
3790 return true;
3793 bool ChatHandler::HandleCombatStopCommand(const char* args)
3795 Player *player;
3797 if(*args)
3799 std::string playername = args;
3801 if(!normalizePlayerName(playername))
3803 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3804 SetSentErrorMessage(true);
3805 return false;
3808 player = objmgr.GetPlayer(playername.c_str());
3810 if(!player)
3812 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3813 SetSentErrorMessage(true);
3814 return false;
3817 else
3819 player = getSelectedPlayer();
3821 if (!player)
3822 player = m_session->GetPlayer();
3825 player->CombatStop();
3826 player->getHostilRefManager().deleteReferences();
3827 return true;
3830 bool ChatHandler::HandleLearnAllCraftsCommand(const char* /*args*/)
3832 uint32 classmask = m_session->GetPlayer()->getClassMask();
3834 for (uint32 i = 0; i < sSkillLineStore.GetNumRows(); ++i)
3836 SkillLineEntry const *skillInfo = sSkillLineStore.LookupEntry(i);
3837 if( !skillInfo )
3838 continue;
3840 if( skillInfo->categoryId == SKILL_CATEGORY_PROFESSION || skillInfo->categoryId == SKILL_CATEGORY_SECONDARY )
3842 for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
3844 SkillLineAbilityEntry const *skillLine = sSkillLineAbilityStore.LookupEntry(j);
3845 if( !skillLine )
3846 continue;
3848 // skip racial skills
3849 if( skillLine->racemask != 0 )
3850 continue;
3852 // skip wrong class skills
3853 if( skillLine->classmask && (skillLine->classmask & classmask) == 0)
3854 continue;
3856 if( skillLine->skillId != i || skillLine->forward_spellid )
3857 continue;
3859 SpellEntry const* spellInfo = sSpellStore.LookupEntry(skillLine->spellId);
3860 if(!spellInfo || !SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer(),false))
3861 continue;
3863 m_session->GetPlayer()->learnSpell(skillLine->spellId);
3868 SendSysMessage(LANG_COMMAND_LEARN_ALL_CRAFT);
3869 return true;
3872 bool ChatHandler::HandleLearnAllRecipesCommand(const char* args)
3874 // Learns all recipes of specified profession and sets skill to max
3875 // Example: .learn all_recipes enchanting
3877 Player* target = getSelectedPlayer();
3878 if( !target )
3880 SendSysMessage(LANG_PLAYER_NOT_FOUND);
3881 return false;
3884 if(!*args)
3885 return false;
3887 std::wstring wnamepart;
3889 if(!Utf8toWStr(args,wnamepart))
3890 return false;
3892 uint32 counter = 0; // Counter for figure out that we found smth.
3894 // converting string that we try to find to lower case
3895 wstrToLower( wnamepart );
3897 uint32 classmask = m_session->GetPlayer()->getClassMask();
3899 for (uint32 i = 0; i < sSkillLineStore.GetNumRows(); ++i)
3901 SkillLineEntry const *skillInfo = sSkillLineStore.LookupEntry(i);
3902 if( !skillInfo )
3903 continue;
3905 if( skillInfo->categoryId != SKILL_CATEGORY_PROFESSION &&
3906 skillInfo->categoryId != SKILL_CATEGORY_SECONDARY )
3907 continue;
3909 int loc = m_session->GetSessionDbcLocale();
3910 std::string name = skillInfo->name[loc];
3912 if(Utf8FitTo(name, wnamepart))
3914 for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
3916 SkillLineAbilityEntry const *skillLine = sSkillLineAbilityStore.LookupEntry(j);
3917 if( !skillLine )
3918 continue;
3920 if( skillLine->skillId != i || skillLine->forward_spellid )
3921 continue;
3923 // skip racial skills
3924 if( skillLine->racemask != 0 )
3925 continue;
3927 // skip wrong class skills
3928 if( skillLine->classmask && (skillLine->classmask & classmask) == 0)
3929 continue;
3931 SpellEntry const* spellInfo = sSpellStore.LookupEntry(skillLine->spellId);
3932 if(!spellInfo || !SpellMgr::IsSpellValid(spellInfo,m_session->GetPlayer(),false))
3933 continue;
3935 if( !target->HasSpell(spellInfo->Id) )
3936 m_session->GetPlayer()->learnSpell(skillLine->spellId);
3939 uint16 maxLevel = target->GetPureMaxSkillValue(skillInfo->id);
3940 target->SetSkill(skillInfo->id, maxLevel, maxLevel);
3941 PSendSysMessage(LANG_COMMAND_LEARN_ALL_RECIPES, name.c_str());
3942 return true;
3946 return false;
3949 bool ChatHandler::HandleLookupPlayerIpCommand(const char* args)
3952 if (!*args)
3953 return false;
3955 std::string ip = strtok ((char*)args, " ");
3956 char* limit_str = strtok (NULL, " ");
3957 int32 limit = limit_str ? atoi (limit_str) : -1;
3959 loginDatabase.escape_string (ip);
3961 QueryResult* result = loginDatabase.PQuery ("SELECT id,username FROM account WHERE last_ip = '%s'", ip.c_str ());
3963 return LookupPlayerSearchCommand (result,limit);
3966 bool ChatHandler::HandleLookupPlayerAccountCommand(const char* args)
3968 if (!*args)
3969 return false;
3971 std::string account = strtok ((char*)args, " ");
3972 char* limit_str = strtok (NULL, " ");
3973 int32 limit = limit_str ? atoi (limit_str) : -1;
3975 if (!AccountMgr::normilizeString (account))
3976 return false;
3978 loginDatabase.escape_string (account);
3980 QueryResult* result = loginDatabase.PQuery ("SELECT id,username FROM account WHERE username = '%s'", account.c_str ());
3982 return LookupPlayerSearchCommand (result,limit);
3985 bool ChatHandler::HandleLookupPlayerEmailCommand(const char* args)
3988 if (!*args)
3989 return false;
3991 std::string email = strtok ((char*)args, " ");
3992 char* limit_str = strtok (NULL, " ");
3993 int32 limit = limit_str ? atoi (limit_str) : -1;
3995 loginDatabase.escape_string (email);
3997 QueryResult* result = loginDatabase.PQuery ("SELECT id,username FROM account WHERE email = '%s'", email.c_str ());
3999 return LookupPlayerSearchCommand (result,limit);
4002 bool ChatHandler::LookupPlayerSearchCommand(QueryResult* result, int32 limit)
4004 if(!result)
4006 PSendSysMessage(LANG_NO_PLAYERS_FOUND);
4007 SetSentErrorMessage(true);
4008 return false;
4011 int i =0;
4014 Field* fields = result->Fetch();
4015 uint32 acc_id = fields[0].GetUInt32();
4016 std::string acc_name = fields[1].GetCppString();
4018 QueryResult* chars = CharacterDatabase.PQuery("SELECT guid,name FROM characters WHERE account = '%u'", acc_id);
4019 if(chars)
4021 PSendSysMessage(LANG_LOOKUP_PLAYER_ACCOUNT,acc_name.c_str(),acc_id);
4023 uint64 guid = 0;
4024 std::string name;
4028 Field* charfields = chars->Fetch();
4029 guid = charfields[0].GetUInt64();
4030 name = charfields[1].GetCppString();
4032 PSendSysMessage(LANG_LOOKUP_PLAYER_CHARACTER,name.c_str(),guid);
4033 ++i;
4035 } while( chars->NextRow() && ( limit == -1 || i < limit ) );
4037 delete chars;
4039 } while(result->NextRow());
4041 delete result;
4043 return true;
4046 /// Triggering corpses expire check in world
4047 bool ChatHandler::HandleServerCorpsesCommand(const char* /*args*/)
4049 CorpsesErase();
4050 return true;
4053 bool ChatHandler::HandleRepairitemsCommand(const char* /*args*/)
4055 Player *target = getSelectedPlayer();
4057 if(!target)
4059 PSendSysMessage(LANG_NO_CHAR_SELECTED);
4060 SetSentErrorMessage(true);
4061 return false;
4064 // Repair items
4065 target->DurabilityRepairAll(false, 0, false);
4067 PSendSysMessage(LANG_YOU_REPAIR_ITEMS, target->GetName());
4068 if(needReportToTarget(target))
4069 ChatHandler(target).PSendSysMessage(LANG_YOUR_ITEMS_REPAIRED, GetName());
4070 return true;
4073 bool ChatHandler::HandleWaterwalkCommand(const char* args)
4075 if(!*args)
4076 return false;
4078 Player *player = getSelectedPlayer();
4080 if(!player)
4082 PSendSysMessage(LANG_NO_CHAR_SELECTED);
4083 SetSentErrorMessage(true);
4084 return false;
4087 if (strncmp(args, "on", 3) == 0)
4088 player->SetMovement(MOVE_WATER_WALK); // ON
4089 else if (strncmp(args, "off", 4) == 0)
4090 player->SetMovement(MOVE_LAND_WALK); // OFF
4091 else
4093 SendSysMessage(LANG_USE_BOL);
4094 return false;
4097 PSendSysMessage(LANG_YOU_SET_WATERWALK, args, player->GetName());
4098 if(needReportToTarget(player))
4099 ChatHandler(player).PSendSysMessage(LANG_YOUR_WATERWALK_SET, args, GetName());
4100 return true;
4103 bool ChatHandler::HandleNpcFollowCommand(const char* /*args*/)
4105 Player *player = m_session->GetPlayer();
4106 Creature *creature = getSelectedCreature();
4108 if(!creature)
4110 PSendSysMessage(LANG_SELECT_CREATURE);
4111 SetSentErrorMessage(true);
4112 return false;
4115 // Follow player - Using pet's default dist and angle
4116 creature->GetMotionMaster()->MoveFollow(player, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);
4118 PSendSysMessage(LANG_CREATURE_FOLLOW_YOU_NOW, creature->GetName());
4119 return true;
4122 bool ChatHandler::HandleNpcUnFollowCommand(const char* /*args*/)
4124 Player *player = m_session->GetPlayer();
4125 Creature *creature = getSelectedCreature();
4127 if(!creature)
4129 PSendSysMessage(LANG_SELECT_CREATURE);
4130 SetSentErrorMessage(true);
4131 return false;
4134 if (creature->GetMotionMaster()->empty() ||
4135 creature->GetMotionMaster()->GetCurrentMovementGeneratorType ()!=TARGETED_MOTION_TYPE)
4137 PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU);
4138 SetSentErrorMessage(true);
4139 return false;
4142 TargetedMovementGenerator<Creature> const* mgen
4143 = static_cast<TargetedMovementGenerator<Creature> const*>((creature->GetMotionMaster()->top()));
4145 if(mgen->GetTarget()!=player)
4147 PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU);
4148 SetSentErrorMessage(true);
4149 return false;
4152 // reset movement
4153 creature->GetMotionMaster()->MovementExpired(true);
4155 PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU_NOW, creature->GetName());
4156 return true;