[7297] Fixed profession spells sorting in trainer spell list at client.
[getmangos.git] / src / game / PlayerDump.cpp
blob7712ec0f5ae9ea96ed85a13409bbff3639f9b9a4
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 19
29 struct DumpTable
31 char const* name;
32 DumpTableType type;
35 static DumpTable dumpTables[DUMP_TABLE_COUNT] =
37 { "characters", DTT_CHARACTER },
38 { "character_queststatus", DTT_CHAR_TABLE },
39 { "character_reputation", DTT_CHAR_TABLE },
40 { "character_spell", DTT_CHAR_TABLE },
41 { "character_spell_cooldown", DTT_CHAR_TABLE },
42 { "character_action", DTT_CHAR_TABLE },
43 { "character_aura", DTT_CHAR_TABLE },
44 { "character_homebind", DTT_CHAR_TABLE },
45 { "character_ticket", DTT_CHAR_TABLE },
46 { "character_inventory", DTT_INVENTORY },
47 { "mail", DTT_MAIL },
48 { "mail_items", DTT_MAIL_ITEM },
49 { "item_instance", DTT_ITEM },
50 { "character_gifts", DTT_ITEM_GIFT },
51 { "item_text", DTT_ITEM_TEXT },
52 { "character_pet", DTT_PET },
53 { "pet_aura", DTT_PET_TABLE },
54 { "pet_spell", DTT_PET_TABLE },
55 { "pet_spell_cooldown", DTT_PET_TABLE },
58 // Low level functions
59 static bool findtoknth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e)
61 int i; s = e = 0;
62 std::string::size_type size = str.size();
63 for(i = 1; s < size && i < n; s++) if(str[s] == ' ') ++i;
64 if (i < n)
65 return false;
67 e = str.find(' ', s);
69 return e != std::string::npos;
72 std::string gettoknth(std::string &str, int n)
74 std::string::size_type s = 0, e = 0;
75 if(!findtoknth(str, n, s, e))
76 return "";
78 return str.substr(s, e-s);
81 bool findnth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e)
83 s = str.find("VALUES ('")+9;
84 if (s == std::string::npos) return false;
88 e = str.find("'",s);
89 if (e == std::string::npos) return false;
90 } while(str[e-1] == '\\');
92 for(int i = 1; i < n; i++)
96 s = e+4;
97 e = str.find("'",s);
98 if (e == std::string::npos) return false;
99 } while (str[e-1] == '\\');
101 return true;
104 std::string gettablename(std::string &str)
106 std::string::size_type s = 13;
107 std::string::size_type e = str.find(_TABLE_SIM_, s);
108 if (e == std::string::npos)
109 return "";
111 return str.substr(s, e-s);
114 bool changenth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false)
116 std::string::size_type s, e;
117 if(!findnth(str,n,s,e))
118 return false;
120 if(nonzero && str.substr(s,e-s) == "0")
121 return true; // not an error
122 if(!insert)
123 str.replace(s,e-s, with);
124 else
125 str.insert(s, with);
127 return true;
130 std::string getnth(std::string &str, int n)
132 std::string::size_type s, e;
133 if(!findnth(str,n,s,e))
134 return "";
136 return str.substr(s, e-s);
139 bool changetoknth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false)
141 std::string::size_type s = 0, e = 0;
142 if(!findtoknth(str, n, s, e))
143 return false;
144 if(nonzero && str.substr(s,e-s) == "0")
145 return true; // not an error
146 if(!insert)
147 str.replace(s, e-s, with);
148 else
149 str.insert(s, with);
151 return true;
154 uint32 registerNewGuid(uint32 oldGuid, std::map<uint32, uint32> &guidMap, uint32 hiGuid)
156 std::map<uint32, uint32>::iterator itr = guidMap.find(oldGuid);
157 if(itr != guidMap.end())
158 return itr->second;
160 uint32 newguid = hiGuid + guidMap.size();
161 guidMap[oldGuid] = newguid;
162 return newguid;
165 bool changeGuid(std::string &str, int n, std::map<uint32, uint32> &guidMap, uint32 hiGuid, bool nonzero = false)
167 char chritem[20];
168 uint32 oldGuid = atoi(getnth(str, n).c_str());
169 if (nonzero && oldGuid == 0)
170 return true; // not an error
172 uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid);
173 snprintf(chritem, 20, "%d", newGuid);
175 return changenth(str, n, chritem, false, nonzero);
178 bool changetokGuid(std::string &str, int n, std::map<uint32, uint32> &guidMap, uint32 hiGuid, bool nonzero = false)
180 char chritem[20];
181 uint32 oldGuid = atoi(gettoknth(str, n).c_str());
182 if (nonzero && oldGuid == 0)
183 return true; // not an error
185 uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid);
186 snprintf(chritem, 20, "%d", newGuid);
188 return changetoknth(str, n, chritem, false, nonzero);
191 std::string CreateDumpString(char const* tableName, QueryResult *result)
193 if(!tableName || !result) return "";
194 std::ostringstream ss;
195 ss << "INSERT INTO "<< _TABLE_SIM_ << tableName << _TABLE_SIM_ << " VALUES (";
196 Field *fields = result->Fetch();
197 for(uint32 i = 0; i < result->GetFieldCount(); i++)
199 if (i == 0) ss << "'";
200 else ss << ", '";
202 std::string s = fields[i].GetCppString();
203 CharacterDatabase.escape_string(s);
204 ss << s;
206 ss << "'";
208 ss << ");";
209 return ss.str();
212 std::string PlayerDumpWriter::GenerateWhereStr(char const* field, uint32 guid)
214 std::ostringstream wherestr;
215 wherestr << field << " = '" << guid << "'";
216 return wherestr.str();
219 std::string PlayerDumpWriter::GenerateWhereStr(char const* field, GUIDs const& guids, GUIDs::const_iterator& itr)
221 std::ostringstream wherestr;
222 wherestr << field << " IN ('";
223 for(; itr != guids.end(); ++itr)
225 wherestr << *itr;
227 if(wherestr.str().size() > MAX_QUERY_LEN - 50) // near to max query
229 ++itr;
230 break;
233 GUIDs::const_iterator itr2 = itr;
234 if(++itr2 != guids.end())
235 wherestr << "','";
237 wherestr << "')";
238 return wherestr.str();
241 void StoreGUID(QueryResult *result,uint32 field,std::set<uint32>& guids)
243 Field* fields = result->Fetch();
244 uint32 guid = fields[field].GetUInt32();
245 if(guid)
246 guids.insert(guid);
249 void StoreGUID(QueryResult *result,uint32 data,uint32 field, std::set<uint32>& guids)
251 Field* fields = result->Fetch();
252 std::string dataStr = fields[data].GetCppString();
253 uint32 guid = atoi(gettoknth(dataStr, field).c_str());
254 if(guid)
255 guids.insert(guid);
258 // Writing - High-level functions
259 void PlayerDumpWriter::DumpTable(std::string& dump, uint32 guid, char const*tableFrom, char const*tableTo, DumpTableType type)
261 GUIDs const* guids = NULL;
262 char const* fieldname = NULL;
264 switch ( type )
266 case DTT_ITEM: fieldname = "guid"; guids = &items; break;
267 case DTT_ITEM_GIFT: fieldname = "item_guid"; guids = &items; break;
268 case DTT_PET: fieldname = "owner"; break;
269 case DTT_PET_TABLE: fieldname = "guid"; guids = &pets; break;
270 case DTT_MAIL: fieldname = "receiver"; break;
271 case DTT_MAIL_ITEM: fieldname = "mail_id"; guids = &mails; break;
272 case DTT_ITEM_TEXT: fieldname = "id"; guids = &texts; break;
273 default: fieldname = "guid"; break;
276 // for guid set stop if set is empty
277 if(guids && guids->empty())
278 return; // nothing to do
280 // setup for guids case start position
281 GUIDs::const_iterator guids_itr;
282 if(guids)
283 guids_itr = guids->begin();
287 std::string wherestr;
289 if(guids) // set case, get next guids string
290 wherestr = GenerateWhereStr(fieldname,*guids,guids_itr);
291 else // not set case, get single guid string
292 wherestr = GenerateWhereStr(fieldname,guid);
294 QueryResult *result = CharacterDatabase.PQuery("SELECT * FROM %s WHERE %s", tableFrom, wherestr.c_str());
295 if(!result)
296 return;
300 // collect guids
301 switch ( type )
303 case DTT_INVENTORY:
304 StoreGUID(result,3,items); break; // item guid collection
305 case DTT_ITEM:
306 StoreGUID(result,0,ITEM_FIELD_ITEM_TEXT_ID,texts); break;
307 // item text id collection
308 case DTT_PET:
309 StoreGUID(result,0,pets); break; // pet guid collection
310 case DTT_MAIL:
311 StoreGUID(result,0,mails); // mail id collection
312 StoreGUID(result,6,texts); break; // item text id collection
313 case DTT_MAIL_ITEM:
314 StoreGUID(result,1,items); break; // item guid collection
315 default: break;
318 dump += CreateDumpString(tableTo, result);
319 dump += "\n";
321 while (result->NextRow());
323 delete result;
325 while(guids && guids_itr != guids->end()); // not set case iterate single time, set case iterate for all guids
328 std::string PlayerDumpWriter::GetDump(uint32 guid)
330 std::string dump;
331 for(int i = 0; i < DUMP_TABLE_COUNT; i++)
332 DumpTable(dump, guid, dumpTables[i].name, dumpTables[i].name, dumpTables[i].type);
334 // TODO: Add instance/group..
335 // TODO: Add a dump level option to skip some non-important tables
337 return dump;
340 DumpReturn PlayerDumpWriter::WriteDump(const std::string& file, uint32 guid)
342 FILE *fout = fopen(file.c_str(), "w");
343 if (!fout)
344 return DUMP_FILE_OPEN_ERROR;
346 std::string dump = GetDump(guid);
348 fprintf(fout,"%s\n",dump.c_str());
349 fclose(fout);
350 return DUMP_SUCCESS;
353 // Reading - High-level functions
354 #define ROLLBACK(DR) {CharacterDatabase.RollbackTransaction(); fclose(fin); return (DR);}
356 DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, std::string name, uint32 guid)
358 // check character count
360 QueryResult *result = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%d'", account);
361 uint8 charcount = 0;
362 if ( result )
364 Field *fields=result->Fetch();
365 charcount = fields[0].GetUInt8();
366 delete result;
368 if (charcount >= 10)
369 return DUMP_TOO_MANY_CHARS;
373 FILE *fin = fopen(file.c_str(), "r");
374 if(!fin)
375 return DUMP_FILE_OPEN_ERROR;
377 QueryResult * result = NULL;
378 char newguid[20], chraccount[20], newpetid[20], currpetid[20], lastpetid[20];
380 // make sure the same guid doesn't already exist and is safe to use
381 bool incHighest = true;
382 if(guid != 0 && guid < objmgr.m_hiCharGuid)
384 result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE guid = '%d'", guid);
385 if (result)
387 guid = objmgr.m_hiCharGuid; // use first free if exists
388 delete result;
390 else incHighest = false;
392 else
393 guid = objmgr.m_hiCharGuid;
395 // normalize the name if specified and check if it exists
396 if(!normalizePlayerName(name))
397 name = "";
399 if(ObjectMgr::IsValidName(name,true))
401 CharacterDatabase.escape_string(name); // for safe, we use name only for sql quearies anyway
402 result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str());
403 if (result)
405 name = ""; // use the one from the dump
406 delete result;
409 else name = "";
411 // name encoded or empty
413 snprintf(newguid, 20, "%d", guid);
414 snprintf(chraccount, 20, "%d", account);
415 snprintf(newpetid, 20, "%d", objmgr.GeneratePetNumber());
416 snprintf(lastpetid, 20, "%s", "");
418 std::map<uint32,uint32> items;
419 std::map<uint32,uint32> mails;
420 char buf[32000] = "";
422 typedef std::map<uint32, uint32> PetIds; // old->new petid relation
423 typedef PetIds::value_type PetIdsPair;
424 PetIds petids;
426 CharacterDatabase.BeginTransaction();
427 while(!feof(fin))
429 if(!fgets(buf, 32000, fin))
431 if(feof(fin)) break;
432 ROLLBACK(DUMP_FILE_BROKEN);
435 std::string line; line.assign(buf);
437 // skip empty strings
438 if(line.find_first_not_of(" \t\n\r\7")==std::string::npos)
439 continue;
441 // determine table name and load type
442 std::string tn = gettablename(line);
443 if(tn.empty())
445 sLog.outError("LoadPlayerDump: Can't extract table name from line: '%s'!", line.c_str());
446 ROLLBACK(DUMP_FILE_BROKEN);
449 DumpTableType type;
450 uint8 i;
451 for(i = 0; i < DUMP_TABLE_COUNT; i++)
453 if (tn == dumpTables[i].name)
455 type = dumpTables[i].type;
456 break;
460 if (i == DUMP_TABLE_COUNT)
462 sLog.outError("LoadPlayerDump: Unknown table: '%s'!", tn.c_str());
463 ROLLBACK(DUMP_FILE_BROKEN);
466 // change the data to server values
467 switch(type)
469 case DTT_CHAR_TABLE:
470 if(!changenth(line, 1, newguid))
471 ROLLBACK(DUMP_FILE_BROKEN);
472 break;
474 case DTT_CHARACTER: // character t.
476 if(!changenth(line, 1, newguid))
477 ROLLBACK(DUMP_FILE_BROKEN);
479 // guid, data field:guid, items
480 if(!changenth(line, 2, chraccount))
481 ROLLBACK(DUMP_FILE_BROKEN);
482 std::string vals = getnth(line, 3);
483 if(!changetoknth(vals, OBJECT_FIELD_GUID+1, newguid))
484 ROLLBACK(DUMP_FILE_BROKEN);
485 for(uint16 field = PLAYER_FIELD_INV_SLOT_HEAD; field < PLAYER_FARSIGHT; field++)
486 if(!changetokGuid(vals, field+1, items, objmgr.m_hiItemGuid, true))
487 ROLLBACK(DUMP_FILE_BROKEN);
488 if(!changenth(line, 3, vals.c_str()))
489 ROLLBACK(DUMP_FILE_BROKEN);
490 if (name == "")
492 // check if the original name already exists
493 name = getnth(line, 4);
494 CharacterDatabase.escape_string(name);
496 result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str());
497 if (result)
499 delete result;
500 // rename on login: `at_login` field 30 in raw field list
501 if(!changenth(line, 30, "1"))
502 ROLLBACK(DUMP_FILE_BROKEN);
505 else if(!changenth(line, 4, name.c_str()))
506 ROLLBACK(DUMP_FILE_BROKEN);
508 break;
510 case DTT_INVENTORY: // character_inventory t.
512 if(!changenth(line, 1, newguid))
513 ROLLBACK(DUMP_FILE_BROKEN);
515 // bag, item
516 if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid, true))
517 ROLLBACK(DUMP_FILE_BROKEN);
518 if(!changeGuid(line, 4, items, objmgr.m_hiItemGuid))
519 ROLLBACK(DUMP_FILE_BROKEN);
520 break;
522 case DTT_ITEM: // item_instance t.
524 // item, owner, data field:item, owner guid
525 if(!changeGuid(line, 1, items, objmgr.m_hiItemGuid))
526 ROLLBACK(DUMP_FILE_BROKEN);
527 if(!changenth(line, 2, newguid))
528 ROLLBACK(DUMP_FILE_BROKEN);
529 std::string vals = getnth(line,3);
530 if(!changetokGuid(vals, OBJECT_FIELD_GUID+1, items, objmgr.m_hiItemGuid))
531 ROLLBACK(DUMP_FILE_BROKEN);
532 if(!changetoknth(vals, ITEM_FIELD_OWNER+1, newguid))
533 ROLLBACK(DUMP_FILE_BROKEN);
534 if(!changenth(line, 3, vals.c_str()))
535 ROLLBACK(DUMP_FILE_BROKEN);
536 break;
538 case DTT_ITEM_GIFT: // character_gift
540 // guid,item_guid,
541 if(!changenth(line, 1, newguid))
542 ROLLBACK(DUMP_FILE_BROKEN);
543 if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
544 ROLLBACK(DUMP_FILE_BROKEN);
545 break;
547 case DTT_PET: // character_pet t
549 //store a map of old pet id to new inserted pet id for use by type 5 tables
550 snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
551 if(strlen(lastpetid)==0) snprintf(lastpetid, 20, "%s", currpetid);
552 if(strcmp(lastpetid,currpetid)!=0)
554 snprintf(newpetid, 20, "%d", objmgr.GeneratePetNumber());
555 snprintf(lastpetid, 20, "%s", currpetid);
558 std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
560 if(petids_iter == petids.end())
562 petids.insert(PetIdsPair(atoi(currpetid), atoi(newpetid)));
565 // item, entry, owner, ...
566 if(!changenth(line, 1, newpetid))
567 ROLLBACK(DUMP_FILE_BROKEN);
568 if(!changenth(line, 3, newguid))
569 ROLLBACK(DUMP_FILE_BROKEN);
571 break;
573 case DTT_PET_TABLE: // pet_aura, pet_spell, pet_spell_cooldown t
575 snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
577 // lookup currpetid and match to new inserted pet id
578 std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
579 if(petids_iter == petids.end()) // couldn't find new inserted id
580 ROLLBACK(DUMP_FILE_BROKEN);
582 snprintf(newpetid, 20, "%d", petids_iter->second);
584 if(!changenth(line, 1, newpetid))
585 ROLLBACK(DUMP_FILE_BROKEN);
587 break;
589 case DTT_MAIL: // mail
591 // id,messageType,stationery,sender,receiver
592 if(!changeGuid(line, 1, mails, objmgr.m_mailid))
593 ROLLBACK(DUMP_FILE_BROKEN);
594 if(!changenth(line, 5, newguid))
595 ROLLBACK(DUMP_FILE_BROKEN);
596 break;
598 case DTT_MAIL_ITEM: // mail_items
600 // mail_id,item_guid,item_template,receiver
601 if(!changeGuid(line, 1, mails, objmgr.m_mailid))
602 ROLLBACK(DUMP_FILE_BROKEN);
603 if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
604 ROLLBACK(DUMP_FILE_BROKEN);
605 if(!changenth(line, 4, newguid))
606 ROLLBACK(DUMP_FILE_BROKEN);
607 break;
609 default:
610 sLog.outError("Unknown dump table type: %u",type);
611 break;
614 if(!CharacterDatabase.Execute(line.c_str()))
615 ROLLBACK(DUMP_FILE_BROKEN);
618 CharacterDatabase.CommitTransaction();
620 objmgr.m_hiItemGuid += items.size();
621 objmgr.m_mailid += mails.size();
623 if(incHighest)
624 ++objmgr.m_hiCharGuid;
626 fclose(fin);
628 return DUMP_SUCCESS;