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

Revision 102, 19.7 kB (checked in by yumileroy, 17 years ago)

[svn] Fixed copyright notices to comply with GPL.

Original author: w12x
Date: 2008-10-23 03:29:52-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 20
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
261bool PlayerDumpWriter::DumpTable(std::string& dump, uint32 guid, char const*tableFrom, char const*tableTo, DumpTableType type)
262{
263    if (!tableFrom || !tableTo)
264        return false;
265
266    GUIDs const* guids = NULL;
267    char const* fieldname = NULL;
268
269    switch ( type )
270    {
271        case DTT_ITEM:      fieldname = "guid";      guids = &items; break;
272        case DTT_ITEM_GIFT: fieldname = "item_guid"; guids = &items; break;
273        case DTT_PET:       fieldname = "owner";                     break;
274        case DTT_PET_TABLE: fieldname = "guid";      guids = &pets;  break;
275        case DTT_MAIL:      fieldname = "receiver";                  break;
276        case DTT_MAIL_ITEM: fieldname = "mail_id";   guids = &mails; break;
277        case DTT_ITEM_TEXT: fieldname = "id";        guids = &texts; break;
278        default:            fieldname = "guid";                      break;
279    }
280
281    // for guid set stop if set is empty
282    if(guids && guids->empty())
283        return true;                                        // nothing to do
284
285    // setup for guids case start position
286    GUIDs::const_iterator guids_itr;
287    if(guids)
288        guids_itr = guids->begin();
289
290    do
291    {
292        std::string wherestr;
293
294        if(guids)                                           // set case, get next guids string
295            wherestr = GenerateWhereStr(fieldname,*guids,guids_itr);
296        else                                                // not set case, get single guid string
297            wherestr = GenerateWhereStr(fieldname,guid);
298
299        QueryResult *result = CharacterDatabase.PQuery("SELECT * FROM %s WHERE %s", tableFrom, wherestr.c_str());
300        if(!result)
301            return false;
302
303        do
304        {
305            // collect guids
306            switch ( type )
307            {
308            case DTT_INVENTORY:
309                StoreGUID(result,3,items); break;           // item guid collection
310            case DTT_ITEM:
311                StoreGUID(result,0,ITEM_FIELD_ITEM_TEXT_ID,texts); break;
312                // item text id collection
313            case DTT_PET:
314                StoreGUID(result,0,pets);  break;           // pet guid collection
315            case DTT_MAIL:
316                StoreGUID(result,0,mails);                  // mail id collection
317                StoreGUID(result,6,texts); break;           // item text id collection
318            case DTT_MAIL_ITEM:
319                StoreGUID(result,1,items); break;           // item guid collection
320            default:                       break;
321            }
322
323            dump += CreateDumpString(tableTo, result);
324            dump += "\n";
325        }
326        while (result->NextRow());
327
328        delete result;
329    }
330    while(guids && guids_itr != guids->end());              // not set case iterate single time, set case iterate for all guids
331
332    return true;
333}
334
335std::string PlayerDumpWriter::GetDump(uint32 guid)
336{
337    std::string dump;
338    for(int i = 0; i < DUMP_TABLE_COUNT; i++)
339        DumpTable(dump, guid, dumpTables[i].name, dumpTables[i].name, dumpTables[i].type);
340
341    // TODO: Add instance/group/gifts..
342    // TODO: Add a dump level option to skip some non-important tables
343
344    return dump;
345}
346
347bool PlayerDumpWriter::WriteDump(std::string file, uint32 guid)
348{
349    FILE *fout = fopen(file.c_str(), "w");
350    if (!fout) { sLog.outError("Failed to open file!\r\n"); return false; }
351
352    std::string dump = GetDump(guid);
353
354    fprintf(fout,"%s\n",dump.c_str());
355    fclose(fout);
356    return true;
357}
358
359// Reading - High-level functions
360#define ROLLBACK {CharacterDatabase.RollbackTransaction(); fclose(fin); return false;}
361
362bool PlayerDumpReader::LoadDump(std::string file, uint32 account, std::string name, uint32 guid)
363{
364    // check character count
365    {
366        QueryResult *result = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%d'", account);
367        uint8 charcount = 0;
368        if ( result )
369        {
370            Field *fields=result->Fetch();
371            charcount = fields[0].GetUInt8();
372            delete result;
373
374            if (charcount >= 10)
375            {
376                return false;
377            }
378        }
379    }
380    FILE *fin = fopen(file.c_str(), "r");
381    if(!fin) return false;
382
383    QueryResult * result = NULL;
384    char newguid[20], chraccount[20], newpetid[20], currpetid[20], lastpetid[20];
385
386    // make sure the same guid doesn't already exist and is safe to use
387    bool incHighest = true;
388    if(guid != 0 && guid < objmgr.m_hiCharGuid)
389    {
390        result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE guid = '%d'", guid);
391        if (result)
392        {
393            guid = objmgr.m_hiCharGuid;                     // use first free if exists
394            delete result;
395        }
396        else incHighest = false;
397    }
398    else guid = objmgr.m_hiCharGuid;
399
400    // normalize the name if specified and check if it exists
401    if(!normalizePlayerName(name))
402        name = "";
403
404    if(ObjectMgr::IsValidName(name,true))
405    {
406        CharacterDatabase.escape_string(name);              // for safe, we use name only for sql quearies anyway
407        result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str());
408        if (result)
409        {
410            name = "";                                      // use the one from the dump
411            delete result;
412        }
413    }
414    else name = "";
415
416    // name encoded or empty
417
418    snprintf(newguid, 20, "%d", guid);
419    snprintf(chraccount, 20, "%d", account);
420    snprintf(newpetid, 20, "%d", objmgr.GeneratePetNumber());
421    snprintf(lastpetid, 20, "%s", "");
422
423    std::map<uint32,uint32> items;
424    std::map<uint32,uint32> mails;
425    char buf[32000] = "";
426
427    typedef std::map<uint32, uint32> PetIds;                // old->new petid relation
428    typedef PetIds::value_type PetIdsPair;
429    PetIds petids;
430
431    CharacterDatabase.BeginTransaction();
432    while(!feof(fin))
433    {
434        if(!fgets(buf, 32000, fin))
435        {
436            if(feof(fin)) break;
437            sLog.outError("LoadPlayerDump: File read error!");
438            ROLLBACK;
439        }
440
441        std::string line; line.assign(buf);
442
443        // skip empty strings
444        if(line.find_first_not_of(" \t\n\r\7")==std::string::npos)
445            continue;
446
447        // determine table name and load type
448        std::string tn = gettablename(line);
449        if(tn.empty())
450        {
451            sLog.outError("LoadPlayerDump: Can't extract table name from line: '%s'!", line.c_str());
452            ROLLBACK;
453        }
454
455        DumpTableType type;
456        uint8 i;
457        for(i = 0; i < DUMP_TABLE_COUNT; i++)
458        {
459            if (tn == dumpTables[i].name)
460            {
461                type = dumpTables[i].type;
462                break;
463            }
464        }
465
466        if (i == DUMP_TABLE_COUNT)
467        {
468            sLog.outError("LoadPlayerDump: Unknown table: '%s'!", tn.c_str());
469            ROLLBACK;
470        }
471
472        // change the data to server values
473        switch(type)
474        {
475            case DTT_CHAR_TABLE:
476                if(!changenth(line, 1, newguid)) ROLLBACK;
477                break;
478
479            case DTT_CHARACTER:                             // character t.
480            {
481                if(!changenth(line, 1, newguid)) ROLLBACK;
482
483                // guid, data field:guid, items
484                if(!changenth(line, 2, chraccount)) ROLLBACK;
485                std::string vals = getnth(line, 3);
486                if(!changetoknth(vals, OBJECT_FIELD_GUID+1, newguid)) ROLLBACK;
487                for(uint16 field = PLAYER_FIELD_INV_SLOT_HEAD; field < PLAYER_FARSIGHT; field++)
488                    if(!changetokGuid(vals, field+1, items, objmgr.m_hiItemGuid, true)) ROLLBACK;
489                if(!changenth(line, 3, vals.c_str())) ROLLBACK;
490                if (name == "")
491                {
492                    // check if the original name already exists
493                    name = getnth(line, 4);
494                    CharacterDatabase.escape_string(name);
495
496                    result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str());
497                    if (result)
498                    {
499                        delete result;
500                                                            // rename on login: `at_login` field 30 in raw field list
501                        if(!changenth(line, 30, "1")) ROLLBACK;
502                    }
503                }
504                else if(!changenth(line, 4, name.c_str())) ROLLBACK;
505
506                break;
507            }
508            case DTT_INVENTORY:                             // character_inventory t.
509            {
510                if(!changenth(line, 1, newguid)) ROLLBACK;
511
512                // bag, item
513                if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid, true)) ROLLBACK;
514                if(!changeGuid(line, 4, items, objmgr.m_hiItemGuid)) ROLLBACK;
515                break;
516            }
517            case DTT_ITEM:                                  // item_instance t.
518            {
519                // item, owner, data field:item, owner guid
520                if(!changeGuid(line, 1, items, objmgr.m_hiItemGuid)) ROLLBACK;
521                if(!changenth(line, 2, newguid)) ROLLBACK;
522                std::string vals = getnth(line,3);
523                if(!changetokGuid(vals, OBJECT_FIELD_GUID+1, items, objmgr.m_hiItemGuid)) ROLLBACK;
524                if(!changetoknth(vals, ITEM_FIELD_OWNER+1, newguid)) ROLLBACK;
525                if(!changenth(line, 3, vals.c_str())) ROLLBACK;
526                break;
527            }
528            case DTT_ITEM_GIFT:                             // character_gift
529            {
530                // guid,item_guid,
531                if(!changenth(line, 1, newguid)) ROLLBACK;
532                if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid)) ROLLBACK;
533                break;
534            }
535            case DTT_PET:                                   // character_pet t
536            {
537                //store a map of old pet id to new inserted pet id for use by type 5 tables
538                snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
539                if(strlen(lastpetid)==0) snprintf(lastpetid, 20, "%s", currpetid);
540                if(strcmp(lastpetid,currpetid)!=0)
541                {
542                    snprintf(newpetid, 20, "%d", objmgr.GeneratePetNumber());
543                    snprintf(lastpetid, 20, "%s", currpetid);
544                }
545
546                std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
547
548                if(petids_iter == petids.end())
549                {
550                    petids.insert(PetIdsPair(atoi(currpetid), atoi(newpetid)));
551                }
552
553                // item, entry, owner, ...
554                if(!changenth(line, 1, newpetid)) ROLLBACK;
555                if(!changenth(line, 3, newguid)) ROLLBACK;
556
557                break;
558            }
559            case DTT_PET_TABLE:                             // pet_aura, pet_spell, pet_spell_cooldown t
560            {
561                snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
562
563                // lookup currpetid and match to new inserted pet id
564                std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
565                if(petids_iter == petids.end()) ROLLBACK;   // couldn't find new inserted id
566
567                snprintf(newpetid, 20, "%d", petids_iter->second);
568
569                if(!changenth(line, 1, newpetid)) ROLLBACK;
570
571                break;
572            }
573            case DTT_MAIL:                                  // mail
574            {
575                // id,messageType,stationery,sender,receiver
576                if(!changeGuid(line, 1, mails, objmgr.m_mailid)) ROLLBACK;
577                if(!changenth(line, 5, newguid)) ROLLBACK;
578                break;
579            }
580            case DTT_MAIL_ITEM:                             // mail_items
581            {
582                // mail_id,item_guid,item_template,receiver
583                if(!changeGuid(line, 1, mails, objmgr.m_mailid)) ROLLBACK;
584                if(!changeGuid(line, 2, items, objmgr.m_hiItemGuid)) ROLLBACK;
585                if(!changenth(line, 4, newguid)) ROLLBACK;
586                break;
587            }
588            default:
589                sLog.outError("Unknown dump table type: %u",type);
590                break;
591        }
592
593        if(!CharacterDatabase.Execute(line.c_str())) ROLLBACK;
594    }
595
596    CharacterDatabase.CommitTransaction();
597
598    objmgr.m_hiItemGuid += items.size();
599    objmgr.m_mailid     += mails.size();
600
601    if(incHighest)
602        ++objmgr.m_hiCharGuid;
603
604    fclose(fin);
605
606    return true;
607}
Note: See TracBrowser for help on using the browser.