[8483] Implement glyph 43361.
[getmangos.git] / src / game / PlayerDump.cpp
blob27ff17502f7c8ec261b7dca68e190e7d9778759e
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "PlayerDump.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Database/SQLStorage.h"
23 #include "UpdateFields.h"
24 #include "ObjectMgr.h"
26 // Character Dump tables
27 #define DUMP_TABLE_COUNT 21
29 struct DumpTable
31 char const* name;
32 DumpTableType type;
35 static DumpTable dumpTables[DUMP_TABLE_COUNT] =
37 { "characters", DTT_CHARACTER },
38 { "character_achievement", DTT_CHAR_TABLE },
39 { "character_achievement_progress", DTT_CHAR_TABLE },
40 { "character_queststatus", DTT_CHAR_TABLE },
41 { "character_reputation", DTT_CHAR_TABLE },
42 { "character_spell", DTT_CHAR_TABLE },
43 { "character_spell_cooldown", DTT_CHAR_TABLE },
44 { "character_action", DTT_CHAR_TABLE },
45 { "character_aura", DTT_CHAR_TABLE },
46 { "character_homebind", DTT_CHAR_TABLE },
47 { "character_ticket", DTT_CHAR_TABLE },
48 { "character_inventory", DTT_INVENTORY },
49 { "mail", DTT_MAIL },
50 { "mail_items", DTT_MAIL_ITEM },
51 { "item_instance", DTT_ITEM },
52 { "character_gifts", DTT_ITEM_GIFT },
53 { "item_text", DTT_ITEM_TEXT },
54 { "character_pet", DTT_PET },
55 { "pet_aura", DTT_PET_TABLE },
56 { "pet_spell", DTT_PET_TABLE },
57 { "pet_spell_cooldown", DTT_PET_TABLE },
60 // Low level functions
61 static bool findtoknth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e)
63 int i; s = e = 0;
64 std::string::size_type size = str.size();
65 for(i = 1; s < size && i < n; s++) if(str[s] == ' ') ++i;
66 if (i < n)
67 return false;
69 e = str.find(' ', s);
71 return e != std::string::npos;
74 std::string gettoknth(std::string &str, int n)
76 std::string::size_type s = 0, e = 0;
77 if(!findtoknth(str, n, s, e))
78 return "";
80 return str.substr(s, e-s);
83 bool findnth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e)
85 s = str.find("VALUES ('")+9;
86 if (s == std::string::npos) return false;
90 e = str.find("'",s);
91 if (e == std::string::npos) return false;
92 } while(str[e-1] == '\\');
94 for(int i = 1; i < n; ++i)
98 s = e+4;
99 e = str.find("'",s);
100 if (e == std::string::npos) return false;
101 } while (str[e-1] == '\\');
103 return true;
106 std::string gettablename(std::string &str)
108 std::string::size_type s = 13;
109 std::string::size_type e = str.find(_TABLE_SIM_, s);
110 if (e == std::string::npos)
111 return "";
113 return str.substr(s, e-s);
116 bool changenth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false)
118 std::string::size_type s, e;
119 if(!findnth(str,n,s,e))
120 return false;
122 if(nonzero && str.substr(s,e-s) == "0")
123 return true; // not an error
124 if(!insert)
125 str.replace(s,e-s, with);
126 else
127 str.insert(s, with);
129 return true;
132 std::string getnth(std::string &str, int n)
134 std::string::size_type s, e;
135 if(!findnth(str,n,s,e))
136 return "";
138 return str.substr(s, e-s);
141 bool changetoknth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false)
143 std::string::size_type s = 0, e = 0;
144 if(!findtoknth(str, n, s, e))
145 return false;
146 if(nonzero && str.substr(s,e-s) == "0")
147 return true; // not an error
148 if(!insert)
149 str.replace(s, e-s, with);
150 else
151 str.insert(s, with);
153 return true;
156 uint32 registerNewGuid(uint32 oldGuid, std::map<uint32, uint32> &guidMap, uint32 hiGuid)
158 std::map<uint32, uint32>::const_iterator itr = guidMap.find(oldGuid);
159 if(itr != guidMap.end())
160 return itr->second;
162 uint32 newguid = hiGuid + guidMap.size();
163 guidMap[oldGuid] = newguid;
164 return newguid;
167 bool changeGuid(std::string &str, int n, std::map<uint32, uint32> &guidMap, uint32 hiGuid, bool nonzero = false)
169 char chritem[20];
170 uint32 oldGuid = atoi(getnth(str, n).c_str());
171 if (nonzero && oldGuid == 0)
172 return true; // not an error
174 uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid);
175 snprintf(chritem, 20, "%d", newGuid);
177 return changenth(str, n, chritem, false, nonzero);
180 bool changetokGuid(std::string &str, int n, std::map<uint32, uint32> &guidMap, uint32 hiGuid, bool nonzero = false)
182 char chritem[20];
183 uint32 oldGuid = atoi(gettoknth(str, n).c_str());
184 if (nonzero && oldGuid == 0)
185 return true; // not an error
187 uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid);
188 snprintf(chritem, 20, "%d", newGuid);
190 return changetoknth(str, n, chritem, false, nonzero);
193 std::string CreateDumpString(char const* tableName, QueryResult *result)
195 if(!tableName || !result) return "";
196 std::ostringstream ss;
197 ss << "INSERT INTO "<< _TABLE_SIM_ << tableName << _TABLE_SIM_ << " VALUES (";
198 Field *fields = result->Fetch();
199 for(uint32 i = 0; i < result->GetFieldCount(); ++i)
201 if (i == 0) ss << "'";
202 else ss << ", '";
204 std::string s = fields[i].GetCppString();
205 CharacterDatabase.escape_string(s);
206 ss << s;
208 ss << "'";
210 ss << ");";
211 return ss.str();
214 std::string PlayerDumpWriter::GenerateWhereStr(char const* field, uint32 guid)
216 std::ostringstream wherestr;
217 wherestr << field << " = '" << guid << "'";
218 return wherestr.str();
221 std::string PlayerDumpWriter::GenerateWhereStr(char const* field, GUIDs const& guids, GUIDs::const_iterator& itr)
223 std::ostringstream wherestr;
224 wherestr << field << " IN ('";
225 for(; itr != guids.end(); ++itr)
227 wherestr << *itr;
229 if(wherestr.str().size() > MAX_QUERY_LEN - 50) // near to max query
231 ++itr;
232 break;
235 GUIDs::const_iterator itr2 = itr;
236 if(++itr2 != guids.end())
237 wherestr << "','";
239 wherestr << "')";
240 return wherestr.str();
243 void StoreGUID(QueryResult *result,uint32 field,std::set<uint32>& guids)
245 Field* fields = result->Fetch();
246 uint32 guid = fields[field].GetUInt32();
247 if(guid)
248 guids.insert(guid);
251 void StoreGUID(QueryResult *result,uint32 data,uint32 field, std::set<uint32>& guids)
253 Field* fields = result->Fetch();
254 std::string dataStr = fields[data].GetCppString();
255 uint32 guid = atoi(gettoknth(dataStr, field).c_str());
256 if(guid)
257 guids.insert(guid);
260 // Writing - High-level functions
261 void PlayerDumpWriter::DumpTable(std::string& dump, uint32 guid, char const*tableFrom, char const*tableTo, DumpTableType type)
263 GUIDs const* guids = NULL;
264 char const* fieldname = NULL;
266 switch ( type )
268 case DTT_ITEM: fieldname = "guid"; guids = &items; break;
269 case DTT_ITEM_GIFT: fieldname = "item_guid"; guids = &items; break;
270 case DTT_PET: fieldname = "owner"; break;
271 case DTT_PET_TABLE: fieldname = "guid"; guids = &pets; break;
272 case DTT_MAIL: fieldname = "receiver"; break;
273 case DTT_MAIL_ITEM: fieldname = "mail_id"; guids = &mails; break;
274 case DTT_ITEM_TEXT: fieldname = "id"; guids = &texts; break;
275 default: fieldname = "guid"; break;
278 // for guid set stop if set is empty
279 if(guids && guids->empty())
280 return; // nothing to do
282 // setup for guids case start position
283 GUIDs::const_iterator guids_itr;
284 if(guids)
285 guids_itr = guids->begin();
289 std::string wherestr;
291 if(guids) // set case, get next guids string
292 wherestr = GenerateWhereStr(fieldname,*guids,guids_itr);
293 else // not set case, get single guid string
294 wherestr = GenerateWhereStr(fieldname,guid);
296 QueryResult *result = CharacterDatabase.PQuery("SELECT * FROM %s WHERE %s", tableFrom, wherestr.c_str());
297 if(!result)
298 return;
302 // collect guids
303 switch ( type )
305 case DTT_INVENTORY:
306 StoreGUID(result,3,items); break; // item guid collection
307 case DTT_ITEM:
308 StoreGUID(result,0,ITEM_FIELD_ITEM_TEXT_ID,texts); break;
309 // item text id collection
310 case DTT_PET:
311 StoreGUID(result,0,pets); break; // pet guid collection
312 case DTT_MAIL:
313 StoreGUID(result,0,mails); // mail id collection
314 StoreGUID(result,7,texts); break; // item text id collection
315 case DTT_MAIL_ITEM:
316 StoreGUID(result,1,items); break; // item guid collection
317 default: break;
320 dump += CreateDumpString(tableTo, result);
321 dump += "\n";
323 while (result->NextRow());
325 delete result;
327 while(guids && guids_itr != guids->end()); // not set case iterate single time, set case iterate for all guids
330 std::string PlayerDumpWriter::GetDump(uint32 guid)
332 std::string dump;
334 dump += "IMPORTANT NOTE: This sql queries not created for apply directly, use '.pdump load' command in console or client chat instead.\n";
335 dump += "IMPORTANT NOTE: NOT APPLY ITS DIRECTLY to character DB or you will DAMAGE and CORRUPT character DB\n\n";
337 // revision check guard
338 QueryNamedResult* result = CharacterDatabase.QueryNamed("SELECT * FROM character_db_version LIMIT 1");
339 if(result)
341 QueryFieldNames const& namesMap = result->GetFieldNames();
342 std::string reqName;
343 for(QueryFieldNames::const_iterator itr = namesMap.begin(); itr != namesMap.end(); ++itr)
345 if(itr->substr(0,9)=="required_")
347 reqName = *itr;
348 break;
352 if(!reqName.empty())
354 // this will fail at wrong character DB version
355 dump += "UPDATE character_db_version SET "+reqName+" = 1 WHERE FALSE;\n\n";
357 else
358 sLog.outError("Table 'character_db_version' not have revision guard field, revision guard query not added to pdump.");
360 delete result;
362 else
363 sLog.outError("Character DB not have 'character_db_version' table, revision guard query not added to pdump.");
365 for(int i = 0; i < DUMP_TABLE_COUNT; ++i)
366 DumpTable(dump, guid, dumpTables[i].name, dumpTables[i].name, dumpTables[i].type);
368 // TODO: Add instance/group..
369 // TODO: Add a dump level option to skip some non-important tables
371 return dump;
374 DumpReturn PlayerDumpWriter::WriteDump(const std::string& file, uint32 guid)
376 FILE *fout = fopen(file.c_str(), "w");
377 if (!fout)
378 return DUMP_FILE_OPEN_ERROR;
380 std::string dump = GetDump(guid);
382 fprintf(fout,"%s\n",dump.c_str());
383 fclose(fout);
384 return DUMP_SUCCESS;
387 // Reading - High-level functions
388 #define ROLLBACK(DR) {CharacterDatabase.RollbackTransaction(); fclose(fin); return (DR);}
390 DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, std::string name, uint32 guid)
392 // check character count
394 QueryResult *result = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%d'", account);
395 uint8 charcount = 0;
396 if (result)
398 Field *fields=result->Fetch();
399 charcount = fields[0].GetUInt8();
400 delete result;
402 if (charcount >= 10)
403 return DUMP_TOO_MANY_CHARS;
407 FILE *fin = fopen(file.c_str(), "r");
408 if (!fin)
409 return DUMP_FILE_OPEN_ERROR;
411 QueryResult * result = NULL;
412 char newguid[20], chraccount[20], newpetid[20], currpetid[20], lastpetid[20];
414 // make sure the same guid doesn't already exist and is safe to use
415 bool incHighest = true;
416 if (guid != 0 && guid < objmgr.m_hiCharGuid)
418 result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE guid = '%d'", guid);
419 if (result)
421 guid = objmgr.m_hiCharGuid; // use first free if exists
422 delete result;
424 else incHighest = false;
426 else
427 guid = objmgr.m_hiCharGuid;
429 // normalize the name if specified and check if it exists
430 if (!normalizePlayerName(name))
431 name = "";
433 if (ObjectMgr::CheckPlayerName(name,true) == CHAR_NAME_SUCCESS)
435 CharacterDatabase.escape_string(name); // for safe, we use name only for sql quearies anyway
436 result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str());
437 if (result)
439 name = ""; // use the one from the dump
440 delete result;
443 else
444 name = "";
446 // name encoded or empty
448 snprintf(newguid, 20, "%d", guid);
449 snprintf(chraccount, 20, "%d", account);
450 snprintf(newpetid, 20, "%d", objmgr.GeneratePetNumber());
451 snprintf(lastpetid, 20, "%s", "");
453 std::map<uint32,uint32> items;
454 std::map<uint32,uint32> mails;
455 std::map<uint32,uint32> itemTexts;
456 char buf[32000] = "";
458 typedef std::map<uint32, uint32> PetIds; // old->new petid relation
459 typedef PetIds::value_type PetIdsPair;
460 PetIds petids;
462 CharacterDatabase.BeginTransaction();
463 while(!feof(fin))
465 if(!fgets(buf, 32000, fin))
467 if(feof(fin)) break;
468 ROLLBACK(DUMP_FILE_BROKEN);
471 std::string line; line.assign(buf);
473 // skip empty strings
474 size_t nw_pos = line.find_first_not_of(" \t\n\r\7");
475 if(nw_pos==std::string::npos)
476 continue;
478 // skip NOTE
479 if(line.substr(nw_pos,15)=="IMPORTANT NOTE:")
480 continue;
482 // add required_ check
483 if(line.substr(nw_pos,41)=="UPDATE character_db_version SET required_")
485 if(!CharacterDatabase.Execute(line.c_str()))
486 ROLLBACK(DUMP_FILE_BROKEN);
488 continue;
491 // determine table name and load type
492 std::string tn = gettablename(line);
493 if(tn.empty())
495 sLog.outError("LoadPlayerDump: Can't extract table name from line: '%s'!", line.c_str());
496 ROLLBACK(DUMP_FILE_BROKEN);
499 DumpTableType type;
500 uint8 i;
501 for(i = 0; i < DUMP_TABLE_COUNT; ++i)
503 if (tn == dumpTables[i].name)
505 type = dumpTables[i].type;
506 break;
510 if (i == DUMP_TABLE_COUNT)
512 sLog.outError("LoadPlayerDump: Unknown table: '%s'!", tn.c_str());
513 ROLLBACK(DUMP_FILE_BROKEN);
516 // change the data to server values
517 switch(type)
519 case DTT_CHAR_TABLE:
520 if(!changenth(line, 1, newguid))
521 ROLLBACK(DUMP_FILE_BROKEN);
522 break;
524 case DTT_CHARACTER: // character t.
526 if(!changenth(line, 1, newguid))
527 ROLLBACK(DUMP_FILE_BROKEN);
529 // guid, data field:guid, items
530 if(!changenth(line, 2, chraccount))
531 ROLLBACK(DUMP_FILE_BROKEN);
532 std::string vals = getnth(line, 3);
533 if(!changetoknth(vals, OBJECT_FIELD_GUID+1, newguid))
534 ROLLBACK(DUMP_FILE_BROKEN);
535 for(uint16 field = PLAYER_FIELD_INV_SLOT_HEAD; field < PLAYER_FARSIGHT; field++)
536 if(!changetokGuid(vals, field+1, items, objmgr.m_hiItemGuid, true))
537 ROLLBACK(DUMP_FILE_BROKEN);
538 if(!changenth(line, 3, vals.c_str()))
539 ROLLBACK(DUMP_FILE_BROKEN);
540 if (name == "")
542 // check if the original name already exists
543 name = getnth(line, 4);
544 CharacterDatabase.escape_string(name);
546 result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str());
547 if (result)
549 delete result;
551 if(!changenth(line, 37, "1")) // rename on login: `at_login` field 37 in raw field list
552 ROLLBACK(DUMP_FILE_BROKEN);
555 else if(!changenth(line, 4, name.c_str()))
556 ROLLBACK(DUMP_FILE_BROKEN);
558 break;
560 case DTT_INVENTORY: // character_inventory t.
562 if(!changenth(line, 1, newguid))
563 ROLLBACK(DUMP_FILE_BROKEN);
565 // bag, item
566 if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid, true))
567 ROLLBACK(DUMP_FILE_BROKEN);
568 if(!changeGuid(line, 4, items, objmgr.m_hiItemGuid))
569 ROLLBACK(DUMP_FILE_BROKEN);
570 break;
572 case DTT_ITEM: // item_instance t.
574 // item, owner, data field:item, owner guid
575 if(!changeGuid(line, 1, items, objmgr.m_hiItemGuid))
576 ROLLBACK(DUMP_FILE_BROKEN);
577 if(!changenth(line, 2, newguid))
578 ROLLBACK(DUMP_FILE_BROKEN);
579 std::string vals = getnth(line,3);
580 if(!changetokGuid(vals, OBJECT_FIELD_GUID+1, items, objmgr.m_hiItemGuid))
581 ROLLBACK(DUMP_FILE_BROKEN);
582 if(!changetoknth(vals, ITEM_FIELD_OWNER+1, newguid))
583 ROLLBACK(DUMP_FILE_BROKEN);
584 if(!changetokGuid(vals, ITEM_FIELD_ITEM_TEXT_ID+1, itemTexts, objmgr.m_ItemTextId,true))
585 ROLLBACK(DUMP_FILE_BROKEN);
586 if(!changenth(line, 3, vals.c_str()))
587 ROLLBACK(DUMP_FILE_BROKEN);
588 break;
590 case DTT_ITEM_GIFT: // character_gift
592 // guid,item_guid,
593 if(!changenth(line, 1, newguid))
594 ROLLBACK(DUMP_FILE_BROKEN);
595 if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
596 ROLLBACK(DUMP_FILE_BROKEN);
597 break;
599 case DTT_PET: // character_pet t
601 //store a map of old pet id to new inserted pet id for use by type 5 tables
602 snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
603 if(strlen(lastpetid)==0) snprintf(lastpetid, 20, "%s", currpetid);
604 if(strcmp(lastpetid,currpetid)!=0)
606 snprintf(newpetid, 20, "%d", objmgr.GeneratePetNumber());
607 snprintf(lastpetid, 20, "%s", currpetid);
610 std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
612 if(petids_iter == petids.end())
614 petids.insert(PetIdsPair(atoi(currpetid), atoi(newpetid)));
617 // item, entry, owner, ...
618 if(!changenth(line, 1, newpetid))
619 ROLLBACK(DUMP_FILE_BROKEN);
620 if(!changenth(line, 3, newguid))
621 ROLLBACK(DUMP_FILE_BROKEN);
623 break;
625 case DTT_PET_TABLE: // pet_aura, pet_spell, pet_spell_cooldown t
627 snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
629 // lookup currpetid and match to new inserted pet id
630 std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
631 if(petids_iter == petids.end()) // couldn't find new inserted id
632 ROLLBACK(DUMP_FILE_BROKEN);
634 snprintf(newpetid, 20, "%d", petids_iter->second);
636 if(!changenth(line, 1, newpetid))
637 ROLLBACK(DUMP_FILE_BROKEN);
639 break;
641 case DTT_MAIL: // mail
643 // id,messageType,stationery,mailtemplate,sender,receiver,subject,itemText
644 if(!changeGuid(line, 1, mails, objmgr.m_mailid))
645 ROLLBACK(DUMP_FILE_BROKEN);
646 if(!changenth(line, 6, newguid))
647 ROLLBACK(DUMP_FILE_BROKEN);
648 if(!changeGuid(line, 8, itemTexts, objmgr.m_ItemTextId))
649 ROLLBACK(DUMP_FILE_BROKEN);
650 break;
652 case DTT_MAIL_ITEM: // mail_items
654 // mail_id,item_guid,item_template,receiver
655 if(!changeGuid(line, 1, mails, objmgr.m_mailid))
656 ROLLBACK(DUMP_FILE_BROKEN);
657 if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
658 ROLLBACK(DUMP_FILE_BROKEN);
659 if(!changenth(line, 4, newguid))
660 ROLLBACK(DUMP_FILE_BROKEN);
661 break;
663 case DTT_ITEM_TEXT: // item_text
665 // id
666 if(!changeGuid(line, 1, itemTexts, objmgr.m_ItemTextId))
667 ROLLBACK(DUMP_FILE_BROKEN);
669 // add it to cache
670 uint32 id= atoi(getnth(line,1).c_str());
671 std::string text = getnth(line,2);
672 objmgr.AddItemText(id,text);
673 break;
675 default:
676 sLog.outError("Unknown dump table type: %u",type);
677 break;
680 if(!CharacterDatabase.Execute(line.c_str()))
681 ROLLBACK(DUMP_FILE_BROKEN);
684 CharacterDatabase.CommitTransaction();
686 objmgr.m_hiItemGuid += items.size();
687 objmgr.m_mailid += mails.size();
688 objmgr.m_ItemTextId += itemTexts.size();
690 if(incHighest)
691 ++objmgr.m_hiCharGuid;
693 fclose(fin);
695 return DUMP_SUCCESS;