root/trunk/src/game/PlayerDump.cpp @ 198

Revision 112, 20.1 kB (checked in by yumileroy, 17 years ago)

[svn] * Merge CLI Commands with regular commands and give them level4 access. sec_console. Source mangos - thanks to ogeraisi for the amalgamated patch.
* Redid/Fixed/Added some lang strings.
* As usual remember this is a trunk rev so stability only guaranteed on northern countries of Mars and western parts of Pluto. No warranties outside the solar system, sorry :( . Check with your local government or dictator on regulations regarding export.

Original author: KingPin?
Date: 2008-10-26 13:32:42-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21#include "Common.h"
22#include "PlayerDump.h"
23#include "Database/DatabaseEnv.h"
24#include "Database/SQLStorage.h"
25#include "UpdateFields.h"
26#include "ObjectMgr.h"
27
28// Character Dump tables
29#define DUMP_TABLE_COUNT 19
30
31struct DumpTable
32{
33    char const* name;
34    DumpTableType type;
35};
36
37static DumpTable dumpTables[DUMP_TABLE_COUNT] =
38{
39    { "characters",               DTT_CHARACTER  },
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  },
58};
59
60// Low level functions
61static bool findtoknth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e)
62{
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;
68
69    e = str.find(' ', s);
70
71    return e != std::string::npos;
72}
73
74std::string gettoknth(std::string &str, int n)
75{
76    std::string::size_type s = 0, e = 0;
77    if(!findtoknth(str, n, s, e))
78        return "";
79
80    return str.substr(s, e-s);
81}
82
83bool findnth(std::string &str, int n, std::string::size_type &s, std::string::size_type &e)
84{
85    s = str.find("VALUES ('")+9;
86    if (s == std::string::npos) return false;
87
88    do
89    {
90        e = str.find("'",s);
91        if (e == std::string::npos) return false;
92    } while(str[e-1] == '\\');
93
94    for(int i = 1; i < n; i++)
95    {
96        do
97        {
98            s = e+4;
99            e = str.find("'",s);
100            if (e == std::string::npos) return false;
101        } while (str[e-1] == '\\');
102    }
103    return true;
104}
105
106std::string gettablename(std::string &str)
107{
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 "";
112
113    return str.substr(s, e-s);
114}
115
116bool changenth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false)
117{
118    std::string::size_type s, e;
119    if(!findnth(str,n,s,e))
120        return false;
121
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);
128
129    return true;
130}
131
132std::string getnth(std::string &str, int n)
133{
134    std::string::size_type s, e;
135    if(!findnth(str,n,s,e))
136        return "";
137
138    return str.substr(s, e-s);
139}
140
141bool changetoknth(std::string &str, int n, const char *with, bool insert = false, bool nonzero = false)
142{
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);
152
153    return true;
154}
155
156uint32 registerNewGuid(uint32 oldGuid, std::map<uint32, uint32> &guidMap, uint32 hiGuid)
157{
158    std::map<uint32, uint32>::iterator itr = guidMap.find(oldGuid);
159    if(itr != guidMap.end())
160        return itr->second;
161
162    uint32 newguid = hiGuid + guidMap.size();
163    guidMap[oldGuid] = newguid;
164    return newguid;
165}
166
167bool changeGuid(std::string &str, int n, std::map<uint32, uint32> &guidMap, uint32 hiGuid, bool nonzero = false)
168{
169    char chritem[20];
170    uint32 oldGuid = atoi(getnth(str, n).c_str());
171    if (nonzero && oldGuid == 0)
172        return true;                                        // not an error
173
174    uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid);
175    snprintf(chritem, 20, "%d", newGuid);
176
177    return changenth(str, n, chritem, false, nonzero);
178}
179
180bool changetokGuid(std::string &str, int n, std::map<uint32, uint32> &guidMap, uint32 hiGuid, bool nonzero = false)
181{
182    char chritem[20];
183    uint32 oldGuid = atoi(gettoknth(str, n).c_str());
184    if (nonzero && oldGuid == 0)
185        return true;                                        // not an error
186
187    uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid);
188    snprintf(chritem, 20, "%d", newGuid);
189
190    return changetoknth(str, n, chritem, false, nonzero);
191}
192
193std::string CreateDumpString(char const* tableName, QueryResult *result)
194{
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++)
200    {
201        if (i == 0) ss << "'";
202        else ss << ", '";
203
204        std::string s = fields[i].GetCppString();
205        CharacterDatabase.escape_string(s);
206        ss << s;
207
208        ss << "'";
209    }
210    ss << ");";
211    return ss.str();
212}
213
214std::string PlayerDumpWriter::GenerateWhereStr(char const* field, uint32 guid)
215{
216    std::ostringstream wherestr;
217    wherestr << field << " = '" << guid << "'";
218    return wherestr.str();
219}
220
221std::string PlayerDumpWriter::GenerateWhereStr(char const* field, GUIDs const& guids, GUIDs::const_iterator& itr)
222{
223    std::ostringstream wherestr;
224    wherestr << field << " IN ('";
225    for(; itr != guids.end(); ++itr)
226    {
227        wherestr << *itr;
228
229        if(wherestr.str().size() > MAX_QUERY_LEN - 50)      // near to max query
230        {
231            ++itr;
232            break;
233        }
234
235        GUIDs::const_iterator itr2 = itr;
236        if(++itr2 != guids.end())
237            wherestr << "','";
238    }
239    wherestr << "')";
240    return wherestr.str();
241}
242
243void StoreGUID(QueryResult *result,uint32 field,std::set<uint32>& guids)
244{
245    Field* fields = result->Fetch();
246    uint32 guid = fields[field].GetUInt32();
247    if(guid)
248        guids.insert(guid);
249}
250
251void StoreGUID(QueryResult *result,uint32 data,uint32 field, std::set<uint32>& guids)
252{
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);
258}
259
260// Writing - High-level functions
261void PlayerDumpWriter::DumpTable(std::string& dump, uint32 guid, char const*tableFrom, char const*tableTo, DumpTableType type)
262{
263    GUIDs const* guids = NULL;
264    char const* fieldname = NULL;
265
266    switch ( type )
267    {
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;
276    }
277
278    // for guid set stop if set is empty
279    if(guids && guids->empty())
280        return;                                        // nothing to do
281
282    // setup for guids case start position
283    GUIDs::const_iterator guids_itr;
284    if(guids)
285        guids_itr = guids->begin();
286
287    do
288    {
289        std::string wherestr;
290
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);
295
296        QueryResult *result = CharacterDatabase.PQuery("SELECT * FROM %s WHERE %s", tableFrom, wherestr.c_str());
297        if(!result)
298            return;
299
300        do
301        {
302            // collect guids
303            switch ( type )
304            {
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,6,texts); break;           // item text id collection
315            case DTT_MAIL_ITEM:
316                StoreGUID(result,1,items); break;           // item guid collection
317            default:                       break;
318            }
319
320            dump += CreateDumpString(tableTo, result);
321            dump += "\n";
322        }
323        while (result->NextRow());
324
325        delete result;
326    }
327    while(guids && guids_itr != guids->end());              // not set case iterate single time, set case iterate for all guids
328}
329
330std::string PlayerDumpWriter::GetDump(uint32 guid)
331{
332    std::string dump;
333    for(int i = 0; i < DUMP_TABLE_COUNT; i++)
334        DumpTable(dump, guid, dumpTables[i].name, dumpTables[i].name, dumpTables[i].type);
335
336    // TODO: Add instance/group..
337    // TODO: Add a dump level option to skip some non-important tables
338
339    return dump;
340}
341
342DumpReturn PlayerDumpWriter::WriteDump(std::string file, uint32 guid)
343{
344    FILE *fout = fopen(file.c_str(), "w");
345    if (!fout)
346                return DUMP_FILE_OPEN_ERROR;
347
348    std::string dump = GetDump(guid);
349
350    fprintf(fout,"%s\n",dump.c_str());
351    fclose(fout);
352    return DUMP_SUCCESS;
353}
354
355// Reading - High-level functions
356#define ROLLBACK(DR) {CharacterDatabase.RollbackTransaction(); fclose(fin); return (DR);}
357
358DumpReturn PlayerDumpReader::LoadDump(std::string file, uint32 account, std::string name, uint32 guid)
359{
360    // check character count
361    {
362        QueryResult *result = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%d'", account);
363        uint8 charcount = 0;
364        if ( result )
365        {
366            Field *fields=result->Fetch();
367            charcount = fields[0].GetUInt8();
368            delete result;
369
370            if (charcount >= 10)
371                return DUMP_TOO_MANY_CHARS;
372        }
373    }
374    FILE *fin = fopen(file.c_str(), "r");
375    if(!fin)
376                return DUMP_FILE_OPEN_ERROR;
377
378    QueryResult * result = NULL;
379    char newguid[20], chraccount[20], newpetid[20], currpetid[20], lastpetid[20];
380
381    // make sure the same guid doesn't already exist and is safe to use
382    bool incHighest = true;
383    if(guid != 0 && guid < objmgr.m_hiCharGuid)
384    {
385        result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE guid = '%d'", guid);
386        if (result)
387        {
388            guid = objmgr.m_hiCharGuid;                     // use first free if exists
389            delete result;
390        }
391        else incHighest = false;
392    }
393    else guid = objmgr.m_hiCharGuid;
394
395    // normalize the name if specified and check if it exists
396    if(!normalizePlayerName(name))
397        name = "";
398
399    if(ObjectMgr::IsValidName(name,true))
400    {
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)
404        {
405            name = "";                                      // use the one from the dump
406            delete result;
407        }
408    }
409    else name = "";
410
411    // name encoded or empty
412
413    snprintf(newguid, 20, "%d", guid);
414    snprintf(chraccount, 20, "%d", account);
415    snprintf(newpetid, 20, "%d", objmgr.GeneratePetNumber());
416    snprintf(lastpetid, 20, "%s", "");
417
418    std::map<uint32,uint32> items;
419    std::map<uint32,uint32> mails;
420    char buf[32000] = "";
421
422    typedef std::map<uint32, uint32> PetIds;                // old->new petid relation
423    typedef PetIds::value_type PetIdsPair;
424    PetIds petids;
425
426    CharacterDatabase.BeginTransaction();
427    while(!feof(fin))
428    {
429        if(!fgets(buf, 32000, fin))
430        {
431            if(feof(fin)) break;
432            ROLLBACK(DUMP_FILE_BROKEN);
433        }
434
435        std::string line; line.assign(buf);
436
437        // skip empty strings
438        if(line.find_first_not_of(" \t\n\r\7")==std::string::npos)
439            continue;
440
441        // determine table name and load type
442        std::string tn = gettablename(line);
443        if(tn.empty())
444        {
445            sLog.outError("LoadPlayerDump: Can't extract table name from line: '%s'!", line.c_str());
446            ROLLBACK(DUMP_FILE_BROKEN);
447        }
448
449        DumpTableType type;
450        uint8 i;
451        for(i = 0; i < DUMP_TABLE_COUNT; i++)
452        {
453            if (tn == dumpTables[i].name)
454            {
455                type = dumpTables[i].type;
456                break;
457            }
458        }
459
460        if (i == DUMP_TABLE_COUNT)
461        {
462            sLog.outError("LoadPlayerDump: Unknown table: '%s'!", tn.c_str());
463            ROLLBACK(DUMP_FILE_BROKEN);
464        }
465
466        // change the data to server values
467        switch(type)
468        {
469            case DTT_CHAR_TABLE:
470                if(!changenth(line, 1, newguid))
471                                        ROLLBACK(DUMP_FILE_BROKEN);
472                break;
473
474            case DTT_CHARACTER:                             // character t.
475            {
476                if(!changenth(line, 1, newguid))
477                                        ROLLBACK(DUMP_FILE_BROKEN);
478
479                // guid, data field:guid, items
480                if(!changenth(line, 2, chraccount))
481                                        ROLLBACK(DUMP_FILE_BROKEN);
482
483                std::string vals = getnth(line, 3);
484                if(!changetoknth(vals, OBJECT_FIELD_GUID+1, newguid))
485                                        ROLLBACK(DUMP_FILE_BROKEN);
486
487                for(uint16 field = PLAYER_FIELD_INV_SLOT_HEAD; field < PLAYER_FARSIGHT; field++)
488                    if(!changetokGuid(vals, field+1, items, objmgr.m_hiItemGuid, true))
489                                                ROLLBACK(DUMP_FILE_BROKEN);
490
491                if(!changenth(line, 3, vals.c_str()))
492                                        ROLLBACK(DUMP_FILE_BROKEN);
493
494                if (name == "")
495                {
496                    // check if the original name already exists
497                    name = getnth(line, 4);
498                    CharacterDatabase.escape_string(name);
499
500                    result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str());
501                    if (result)
502                    {
503                        delete result;
504                                                            // rename on login: `at_login` field 30 in raw field list
505                        if(!changenth(line, 30, "1"))
506                                                        ROLLBACK(DUMP_FILE_BROKEN);
507                    }
508                }
509                else if(!changenth(line, 4, name.c_str()))
510                                        ROLLBACK(DUMP_FILE_BROKEN);
511
512                break;
513            }
514            case DTT_INVENTORY:                             // character_inventory t.
515            {
516                if(!changenth(line, 1, newguid))
517                                        ROLLBACK(DUMP_FILE_BROKEN);
518
519                // bag, item
520                if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid, true))
521                                        ROLLBACK(DUMP_FILE_BROKEN);
522                                if(!changeGuid(line, 4, items, objmgr.m_hiItemGuid))
523                                        ROLLBACK(DUMP_FILE_BROKEN);
524                break;
525            }
526            case DTT_ITEM:                                  // item_instance t.
527            {
528                // item, owner, data field:item, owner guid
529                if(!changeGuid(line, 1, items, objmgr.m_hiItemGuid))
530                                        ROLLBACK(DUMP_FILE_BROKEN);
531                                if(!changenth(line, 2, newguid))
532                                        ROLLBACK(DUMP_FILE_BROKEN);
533
534                std::string vals = getnth(line,3);
535                if(!changetokGuid(vals, OBJECT_FIELD_GUID+1, items, objmgr.m_hiItemGuid))
536                                        ROLLBACK(DUMP_FILE_BROKEN);
537                                if(!changetoknth(vals, ITEM_FIELD_OWNER+1, newguid))
538                                        ROLLBACK(DUMP_FILE_BROKEN);
539                                if(!changenth(line, 3, vals.c_str()))
540                                        ROLLBACK(DUMP_FILE_BROKEN);
541                break;
542            }
543            case DTT_ITEM_GIFT:                             // character_gift
544            {
545                // guid,item_guid,
546                if(!changenth(line, 1, newguid))
547                                        ROLLBACK(DUMP_FILE_BROKEN);
548                                if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
549                                        ROLLBACK(DUMP_FILE_BROKEN);
550                break;
551            }
552            case DTT_PET:                                   // character_pet t
553            {
554                //store a map of old pet id to new inserted pet id for use by type 5 tables
555                snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
556                if(strlen(lastpetid)==0) snprintf(lastpetid, 20, "%s", currpetid);
557                if(strcmp(lastpetid,currpetid)!=0)
558                {
559                    snprintf(newpetid, 20, "%d", objmgr.GeneratePetNumber());
560                    snprintf(lastpetid, 20, "%s", currpetid);
561                }
562
563                std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
564
565                if(petids_iter == petids.end())
566                {
567                    petids.insert(PetIdsPair(atoi(currpetid), atoi(newpetid)));
568                }
569
570                // item, entry, owner, ...
571                if(!changenth(line, 1, newpetid))
572                                        ROLLBACK(DUMP_FILE_BROKEN);
573                                if(!changenth(line, 3, newguid))
574                                        ROLLBACK(DUMP_FILE_BROKEN);
575
576                break;
577            }
578            case DTT_PET_TABLE:                             // pet_aura, pet_spell, pet_spell_cooldown t
579            {
580                snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
581
582                // lookup currpetid and match to new inserted pet id
583                std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
584                if(petids_iter == petids.end())             // couldn't find new inserted id
585                                        ROLLBACK(DUMP_FILE_BROKEN);
586
587                snprintf(newpetid, 20, "%d", petids_iter->second);
588
589                if(!changenth(line, 1, newpetid))
590                                        ROLLBACK(DUMP_FILE_BROKEN);
591
592                break;
593            }
594            case DTT_MAIL:                                  // mail
595            {
596                // id,messageType,stationery,sender,receiver
597                if(!changeGuid(line, 1, mails, objmgr.m_mailid))
598                                        ROLLBACK(DUMP_FILE_BROKEN);
599                                if(!changenth(line, 5, newguid))
600                                        ROLLBACK(DUMP_FILE_BROKEN);
601                break;
602            }
603            case DTT_MAIL_ITEM:                             // mail_items
604            {
605                // mail_id,item_guid,item_template,receiver
606                if(!changeGuid(line, 1, mails, objmgr.m_mailid))
607                                        ROLLBACK(DUMP_FILE_BROKEN);
608                                if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
609                                        ROLLBACK(DUMP_FILE_BROKEN);
610                                if(!changenth(line, 4, newguid))
611                                        ROLLBACK(DUMP_FILE_BROKEN);
612                break;
613            }
614            default:
615                sLog.outError("Unknown dump table type: %u",type);
616                break;
617        }
618
619        if(!CharacterDatabase.Execute(line.c_str()))
620                        ROLLBACK(DUMP_FILE_BROKEN);
621    }
622
623    CharacterDatabase.CommitTransaction();
624
625    objmgr.m_hiItemGuid += items.size();
626    objmgr.m_mailid     += mails.size();
627
628    if(incHighest)
629        ++objmgr.m_hiCharGuid;
630
631    fclose(fin);
632
633    return DUMP_SUCCESS;
634}
Note: See TracBrowser for help on using the browser.