diff options
author | gepard1984 <gepard1984@54d463be-8e91-2dee-dedb-b68131a5f0ec> | 2012-01-20 20:33:32 +0000 |
---|---|---|
committer | gepard1984 <gepard1984@54d463be-8e91-2dee-dedb-b68131a5f0ec> | 2012-01-20 20:33:32 +0000 |
commit | 44d7606656a650dc43018b5c63bb56ad1f70e77c (patch) | |
tree | a34a45286714803911fe2bf55315c611a444e605 /src/char | |
parent | a02514bc54c044f141520118ffd7e0b6ff5ecae2 (diff) | |
download | hercules-44d7606656a650dc43018b5c63bb56ad1f70e77c.tar.gz hercules-44d7606656a650dc43018b5c63bb56ad1f70e77c.tar.bz2 hercules-44d7606656a650dc43018b5c63bb56ad1f70e77c.tar.xz hercules-44d7606656a650dc43018b5c63bb56ad1f70e77c.zip |
Merged TXT removal branch back to trunk.
* TXT save engine is removed and no longer supported.
* See also tid:53926, tid:57717.
git-svn-id: https://rathena.svn.sourceforge.net/svnroot/rathena/trunk@15503 54d463be-8e91-2dee-dedb-b68131a5f0ec
Diffstat (limited to 'src/char')
-rw-r--r-- | src/char/CMakeLists.txt | 79 | ||||
-rw-r--r-- | src/char/Makefile.in | 53 | ||||
-rw-r--r-- | src/char/char.c | 3477 | ||||
-rw-r--r-- | src/char/char.h | 75 | ||||
-rw-r--r-- | src/char/int_auction.c | 494 | ||||
-rw-r--r-- | src/char/int_auction.h | 12 | ||||
-rw-r--r-- | src/char/int_guild.c | 2377 | ||||
-rw-r--r-- | src/char/int_guild.h | 40 | ||||
-rw-r--r-- | src/char/int_homun.c | 526 | ||||
-rw-r--r-- | src/char/int_homun.h | 21 | ||||
-rw-r--r-- | src/char/int_mail.c | 476 | ||||
-rw-r--r-- | src/char/int_mail.h | 16 | ||||
-rw-r--r-- | src/char/int_mercenary.c | 218 | ||||
-rw-r--r-- | src/char/int_mercenary.h | 20 | ||||
-rw-r--r-- | src/char/int_party.c | 761 | ||||
-rw-r--r-- | src/char/int_party.h | 34 | ||||
-rw-r--r-- | src/char/int_pet.c | 447 | ||||
-rw-r--r-- | src/char/int_pet.h | 14 | ||||
-rw-r--r-- | src/char/int_quest.c | 184 | ||||
-rw-r--r-- | src/char/int_quest.h | 13 | ||||
-rw-r--r-- | src/char/int_status.c | 183 | ||||
-rw-r--r-- | src/char/int_status.h | 23 | ||||
-rw-r--r-- | src/char/int_storage.c | 501 | ||||
-rw-r--r-- | src/char/int_storage.h | 24 | ||||
-rw-r--r-- | src/char/inter.c | 762 | ||||
-rw-r--r-- | src/char/inter.h | 19 |
26 files changed, 6099 insertions, 4750 deletions
diff --git a/src/char/CMakeLists.txt b/src/char/CMakeLists.txt index fa1c3f366..823939393 100644 --- a/src/char/CMakeLists.txt +++ b/src/char/CMakeLists.txt @@ -2,52 +2,57 @@ # # setup # -set( TXT_CHAR_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL "" ) +set( SQL_CHAR_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL "" ) # -# char txt +# char sql # -if( BUILD_TXT_SERVERS ) -message( STATUS "Creating target char-server" ) -set( TXT_CHAR_HEADERS - "${TXT_CHAR_SOURCE_DIR}/char.h" - "${TXT_CHAR_SOURCE_DIR}/int_guild.h" - "${TXT_CHAR_SOURCE_DIR}/int_homun.h" - "${TXT_CHAR_SOURCE_DIR}/int_party.h" - "${TXT_CHAR_SOURCE_DIR}/int_pet.h" - "${TXT_CHAR_SOURCE_DIR}/int_status.h" - "${TXT_CHAR_SOURCE_DIR}/int_storage.h" - "${TXT_CHAR_SOURCE_DIR}/inter.h" +if( BUILD_SQL_SERVERS ) +message( STATUS "Creating target char-server_sql" ) +set( SQL_CHAR_HEADERS + "${CMAKE_CURRENT_SOURCE_DIR}/char.h" + "${CMAKE_CURRENT_SOURCE_DIR}/int_auction.h" + "${CMAKE_CURRENT_SOURCE_DIR}/int_guild.h" + "${CMAKE_CURRENT_SOURCE_DIR}/int_homun.h" + "${CMAKE_CURRENT_SOURCE_DIR}/int_mail.h" + "${CMAKE_CURRENT_SOURCE_DIR}/int_mercenary.h" + "${CMAKE_CURRENT_SOURCE_DIR}/int_party.h" + "${CMAKE_CURRENT_SOURCE_DIR}/int_pet.h" + "${CMAKE_CURRENT_SOURCE_DIR}/int_quest.h" + "${CMAKE_CURRENT_SOURCE_DIR}/int_storage.h" + "${CMAKE_CURRENT_SOURCE_DIR}/inter.h" ) -set( TXT_CHAR_SOURCES - "${TXT_CHAR_SOURCE_DIR}/char.c" - "${TXT_CHAR_SOURCE_DIR}/int_guild.c" - "${TXT_CHAR_SOURCE_DIR}/int_homun.c" - "${TXT_CHAR_SOURCE_DIR}/int_party.c" - "${TXT_CHAR_SOURCE_DIR}/int_pet.c" - "${TXT_CHAR_SOURCE_DIR}/int_status.c" - "${TXT_CHAR_SOURCE_DIR}/int_storage.c" - "${TXT_CHAR_SOURCE_DIR}/inter.c" +set( SQL_CHAR_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/char.c" + "${CMAKE_CURRENT_SOURCE_DIR}/int_auction.c" + "${CMAKE_CURRENT_SOURCE_DIR}/int_guild.c" + "${CMAKE_CURRENT_SOURCE_DIR}/int_homun.c" + "${CMAKE_CURRENT_SOURCE_DIR}/int_mail.c" + "${CMAKE_CURRENT_SOURCE_DIR}/int_mercenary.c" + "${CMAKE_CURRENT_SOURCE_DIR}/int_party.c" + "${CMAKE_CURRENT_SOURCE_DIR}/int_pet.c" + "${CMAKE_CURRENT_SOURCE_DIR}/int_quest.c" + "${CMAKE_CURRENT_SOURCE_DIR}/int_storage.c" + "${CMAKE_CURRENT_SOURCE_DIR}/inter.c" ) -set( DEPENDENCIES common_base ) +set( DEPENDENCIES common_sql ) set( LIBRARIES ${GLOBAL_LIBRARIES} ) set( INCLUDE_DIRS ${GLOBAL_INCLUDE_DIRS} ) -set( DEFINITIONS "${GLOBAL_DEFINITIONS} -DTXT_ONLY" ) -set( SOURCE_FILES ${COMMON_BASE_HEADERS} ${TXT_CHAR_HEADERS} ${TXT_CHAR_SOURCES} ) -source_group( common FILES ${COMMON_BASE_HEADERS} ) -source_group( char FILES ${TXT_CHAR_HEADERS} ${TXT_CHAR_SOURCES} ) +set( DEFINITIONS "${GLOBAL_DEFINITIONS}" ) +set( SOURCE_FILES ${COMMON_BASE_HEADERS} ${COMMON_SQL_HEADERS} ${SQL_CHAR_HEADERS} ${SQL_CHAR_SOURCES} ) +source_group( common FILES ${COMMON_BASE_HEADERS} ${COMMON_SQL_HEADERS} ) +source_group( char FILES ${SQL_CHAR_HEADERS} ${SQL_CHAR_SOURCES} ) include_directories( ${INCLUDE_DIRS} ) -add_executable( char-server ${SOURCE_FILES} ) -add_dependencies( char-server ${DEPENDENCIES} ) -target_link_libraries( char-server ${LIBRARIES} ${DEPENDENCIES} ) -set_target_properties( char-server PROPERTIES COMPILE_FLAGS "${DEFINITIONS}" ) +add_executable( char-server_sql ${SOURCE_FILES} ) +add_dependencies( char-server_sql ${DEPENDENCIES} ) +target_link_libraries( char-server_sql ${LIBRARIES} ${DEPENDENCIES} ) +set_target_properties( char-server_sql PROPERTIES COMPILE_FLAGS "${DEFINITIONS}" ) if( INSTALL_COMPONENT_RUNTIME ) - cpack_add_component( Runtime_charserver_txt DESCRIPTION "char-server (txt version)" DISPLAY_NAME "char-server" GROUP Runtime ) - install( TARGETS char-server + cpack_add_component( Runtime_charserver_sql DESCRIPTION "char-server (sql version)" DISPLAY_NAME "char-server_sql" GROUP Runtime ) + install( TARGETS char-server_sql DESTINATION "." - COMPONENT Runtime_charserver_txt ) + COMPONENT Runtime_charserver_sql ) endif( INSTALL_COMPONENT_RUNTIME ) -set( TARGET_LIST ${TARGET_LIST} char-server CACHE INTERNAL "" ) -message( STATUS "Creating target char-server - done" ) -endif( BUILD_TXT_SERVERS ) +message( STATUS "Creating target char-server_sql - done" ) +endif( BUILD_SQL_SERVERS ) diff --git a/src/char/Makefile.in b/src/char/Makefile.in index 1fd54b20b..e96113f0e 100644 --- a/src/char/Makefile.in +++ b/src/char/Makefile.in @@ -14,41 +14,58 @@ MT19937AR_OBJ = ../../3rdparty/mt19937ar/mt19937ar.o MT19937AR_H = ../../3rdparty/mt19937ar/mt19937ar.h MT19937AR_INCLUDE = -I../../3rdparty/mt19937ar -CHAR_OBJ = obj_txt/char.o obj_txt/inter.o obj_txt/int_party.o obj_txt/int_guild.o \ - obj_txt/int_storage.o obj_txt/int_status.o obj_txt/int_pet.o obj_txt/int_homun.o -CHAR_H = char.h inter.h int_party.h int_guild.h int_storage.h int_status.h int_pet.h int_homun.h +COMMON_SQL_OBJ = ../common/obj_sql/sql.o +COMMON_H = ../common/sql.h + +CHAR_OBJ = obj_sql/char.o obj_sql/inter.o obj_sql/int_party.o obj_sql/int_guild.o \ + obj_sql/int_storage.o obj_sql/int_pet.o obj_sql/int_homun.o obj_sql/int_mail.o obj_sql/int_auction.o obj_sql/int_quest.o obj_sql/int_mercenary.o +CHAR_H = char.h inter.h int_party.h int_guild.h int_storage.h int_pet.h int_homun.h int_mail.h int_auction.h int_quest.h int_mercenary.h + +HAVE_MYSQL=@HAVE_MYSQL@ +ifeq ($(HAVE_MYSQL),yes) + CHAR_SERVER_SQL_DEPENDS=obj_sql $(CHAR_OBJ) $(COMMON_OBJ) $(COMMON_SQL_OBJ) $(MT19937AR_OBJ) +else + CHAR_SERVER_SQL_DEPENDS=needs_mysql +endif @SET_MAKE@ ##################################################################### -.PHONY : all char-server clean help +.PHONY : all char-server_sql clean help -all: char-server +all: char-server_sql -char-server: obj_txt $(CHAR_OBJ) $(COMMON_OBJ) $(MT19937AR_OBJ) - @CC@ @LDFLAGS@ -o ../../char-server@EXEEXT@ $(CHAR_OBJ) $(COMMON_OBJ) $(MT19937AR_OBJ) @LIBS@ +char-server_sql: $(CHAR_SERVER_SQL_DEPENDS) + @CC@ @LDFLAGS@ -o ../../char-server_sql@EXEEXT@ $(CHAR_OBJ) $(COMMON_OBJ) $(COMMON_SQL_OBJ) $(MT19937AR_OBJ) @LIBS@ @MYSQL_LIBS@ clean: - rm -rf *.o obj_txt ../../char-server@EXEEXT@ + rm -rf *.o obj_sql ../../char-server_sql@EXEEXT@ help: - @echo "possible targets are 'char-server' 'all' 'clean' 'help'" - @echo "'char-server' - char server (TXT version)" - @echo "'all' - builds all above targets" - @echo "'clean' - cleans builds and objects" - @echo "'help' - outputs this message" + @echo "possible targets are 'char-server_sql' 'all' 'clean' 'help'" + @echo "'char-server_sql' - char server (SQL version)" + @echo "'all' - builds all above targets" + @echo "'clean' - cleans builds and objects" + @echo "'help' - outputs this message" ##################################################################### -obj_txt: - -mkdir obj_txt +needs_mysql: + @echo "MySQL not found or disabled by the configure script" + @exit 1 -obj_txt/%.o: %.c $(CHAR_H) $(COMMON_H) $(MT19937AR_H) - @CC@ @CFLAGS@ $(MT19937AR_INCLUDE) -DTXT_ONLY @CPPFLAGS@ -c $(OUTPUT_OPTION) $< +obj_sql: + -mkdir obj_sql + +obj_sql/%.o: %.c $(CHAR_H) $(COMMON_H) $(COMMON_SQL_H) $(MT19937AR_H) + @CC@ @CFLAGS@ $(MT19937AR_INCLUDE) @MYSQL_CFLAGS@ @CPPFLAGS@ -c $(OUTPUT_OPTION) $< # missing object files ../common/obj_all/%.o: - @$(MAKE) -C ../common txt + @$(MAKE) -C ../common sql + +../common/obj_sql/%.o: + @$(MAKE) -C ../common sql MT19937AR_OBJ: @$(MAKE) -C ../../3rdparty/mt19937ar diff --git a/src/char/char.c b/src/char/char.c index aac469c5b..cb3007ff9 100644 --- a/src/char/char.c +++ b/src/char/char.c @@ -4,7 +4,6 @@ #include "../common/cbasetypes.h" #include "../common/core.h" #include "../common/db.h" -#include "../common/lock.h" #include "../common/malloc.h" #include "../common/mapindex.h" #include "../common/mmo.h" @@ -17,10 +16,9 @@ #include "inter.h" #include "int_guild.h" #include "int_homun.h" -#include "int_pet.h" +#include "int_mercenary.h" #include "int_party.h" #include "int_storage.h" -#include "int_status.h" #include "char.h" #include <sys/types.h> @@ -34,22 +32,43 @@ // private declarations #define CHAR_CONF_NAME "conf/char_athena.conf" #define LAN_CONF_NAME "conf/subnet_athena.conf" - -char char_txt[1024] = "save/athena.txt"; -char friends_txt[1024] = "save/friends.txt"; -char hotkeys_txt[1024] = "save/hotkeys.txt"; -char char_log_filename[1024] = "log/char.log"; +#define SQL_CONF_NAME "conf/inter_athena.conf" + +char char_db[256] = "char"; +char scdata_db[256] = "sc_data"; +char cart_db[256] = "cart_inventory"; +char inventory_db[256] = "inventory"; +char charlog_db[256] = "charlog"; +char storage_db[256] = "storage"; +char interlog_db[256] = "interlog"; +char reg_db[256] = "global_reg_value"; +char skill_db[256] = "skill"; +char memo_db[256] = "memo"; +char guild_db[256] = "guild"; +char guild_alliance_db[256] = "guild_alliance"; +char guild_castle_db[256] = "guild_castle"; +char guild_expulsion_db[256] = "guild_expulsion"; +char guild_member_db[256] = "guild_member"; +char guild_position_db[256] = "guild_position"; +char guild_skill_db[256] = "guild_skill"; +char guild_storage_db[256] = "guild_storage"; +char party_db[256] = "party"; +char pet_db[256] = "pet"; +char mail_db[256] = "mail"; // MAIL SYSTEM +char auction_db[256] = "auction"; // Auctions System +char friend_db[256] = "friends"; +char hotkey_db[256] = "hotkey"; +char quest_db[256] = "quest"; // show loading/saving messages -#ifndef TXT_SQL_CONVERT int save_log = 1; -#endif -//If your code editor is having problems syntax highlighting this file, uncomment this and RECOMMENT IT BEFORE COMPILING -//#undef TXT_SQL_CONVERT -#ifndef TXT_SQL_CONVERT +static DBMap* char_db_; // int char_id -> struct mmo_charstatus* + char db_path[1024] = "db"; +int db_use_sqldbs; + struct mmo_map_server { int fd; uint32 ip; @@ -75,12 +94,10 @@ int char_maintenance = 0; bool char_new = true; int char_new_display = 0; -int email_creation = 0; // disabled by default - bool name_ignoring_case = false; // Allow or not identical name for characters but with a different case by [Yor] int char_name_option = 0; // Option to know which letters/symbols are authorised in the name of a character (0: all, 1: only those in char_name_letters, 2: all EXCEPT those in char_name_letters) by [Yor] char unknown_char_name[NAME_LENGTH] = "Unknown"; // Name to use when the requested name cannot be determined -#define TRIM_CHARS "\032\t\x0A\x0D " //The following characters are trimmed regardless because they cause confusion and problems on the servers. [Skotlex] +#define TRIM_CHARS "\255\xA0\032\t\x0A\x0D " //The following characters are trimmed regardless because they cause confusion and problems on the servers. [Skotlex] char char_name_letters[1024] = ""; // list of letters/symbols allowed (or not) in a character name. by [Yor] int char_per_account = 0; //Maximum charas per account (default unlimited) [Sirius] @@ -107,13 +124,10 @@ struct char_session_data { int gmlevel; uint32 version; uint8 clienttype; + char new_name[NAME_LENGTH]; char birthdate[10+1]; // YYYY-MM-DD }; -int char_id_count = START_CHAR_NUM; -struct character_data *char_dat; - -int char_num, char_max; int max_connect_user = 0; int gm_allow_level = 99; int autosave_interval = DEFAULT_AUTOSAVE_INTERVAL; @@ -132,17 +146,14 @@ struct fame_list smith_fame_list[MAX_FAME_LIST]; struct fame_list chemist_fame_list[MAX_FAME_LIST]; struct fame_list taekwon_fame_list[MAX_FAME_LIST]; +// check for exit signal +// 0 is saving complete +// other is char_id +unsigned int save_flag = 0; + // Initial position (it's possible to set it in conf file) struct point start_point = { 0, 53, 111 }; -// online players by [Yor] -char online_txt_filename[1024] = "online.txt"; -char online_html_filename[1024] = "online.html"; -int online_sorting_option = 0; // sorting option to display online players in online files -int online_display_option = 1; // display options: to know which columns must be displayed -int online_refresh_html = 20; // refresh time (in sec) of the html file in the explorer -int online_gm_display_min_level = 20; // minimum GM level to display 'GM' when we want to display it - int console = 0; //----------------------------------------------------- @@ -159,6 +170,7 @@ struct auth_node { int sex; time_t expiration_time; // # of seconds 1/1/1970 (timestamp): Validity limit of the account (0 = unlimited) int gmlevel; + unsigned changing_mapservers : 1; }; static DBMap* auth_db; // int account_id -> struct auth_node* @@ -177,6 +189,7 @@ struct online_char_data { static DBMap* online_char_db; // int account_id -> struct online_char_data* static int chardb_waiting_disconnect(int tid, unsigned int tick, int id, intptr_t data); +int delete_char_sql(int char_id); static void* create_online_char_data(DBKey key, va_list args) { @@ -221,7 +234,12 @@ void set_char_charselect(int account_id) void set_char_online(int map_id, int char_id, int account_id) { struct online_char_data* character; + struct mmo_charstatus *cp; + //Update DB + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `online`='1' WHERE `char_id`='%d' LIMIT 1", char_db, char_id) ) + Sql_ShowDebug(sql_handle); + //Check to see for online conflicts character = (struct online_char_data*)idb_ensure(online_char_db, account_id, create_online_char_data); if( character->char_id != -1 && character->server > -1 && character->server != map_id ) @@ -244,6 +262,10 @@ void set_char_online(int map_id, int char_id, int account_id) character->waiting_disconnect = INVALID_TIMER; } + //Set char online in guild cache. If char is in memory, use the guild id on it, otherwise seek it. + cp = (struct mmo_charstatus*)idb_get(char_db_,char_id); + inter_guild_CharOnline(char_id, cp?cp->guild_id:-1); + //Notify login server if (login_fd > 0 && !session[login_fd]->flag.eof) { @@ -258,6 +280,22 @@ void set_char_offline(int char_id, int account_id) { struct online_char_data* character; + if ( char_id == -1 ) + { + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `online`='0' WHERE `account_id`='%d'", char_db, account_id) ) + Sql_ShowDebug(sql_handle); + } + else + { + struct mmo_charstatus* cp = (struct mmo_charstatus*)idb_get(char_db_,char_id); + inter_guild_CharOffline(char_id, cp?cp->guild_id:-1); + if (cp) + idb_remove(char_db_,char_id); + + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `online`='0' WHERE `char_id`='%d' LIMIT 1", char_db, char_id) ) + Sql_ShowDebug(sql_handle); + } + if ((character = (struct online_char_data*)idb_get(online_char_db, account_id)) != NULL) { //We don't free yet to avoid aCalloc/aFree spamming during char change. [Skotlex] if( character->server > -1 ) @@ -339,913 +377,904 @@ void set_all_offline(int id) WFIFOSET(login_fd,2); } -//------------------------------ -// Writing function of logs file -//------------------------------ -int char_log(char *fmt, ...) +void set_all_offline_sql(void) { - if(log_char) - { - FILE *logfp; - va_list ap; - time_t raw_time; - char tmpstr[2048]; - - va_start(ap, fmt); - - logfp = fopen(char_log_filename, "a"); - if (logfp) { - if (fmt[0] == '\0') // jump a line if no message - fprintf(logfp, "\n"); - else { - time(&raw_time); - strftime(tmpstr, 24, "%d-%m-%Y %H:%M:%S", localtime(&raw_time)); - sprintf(tmpstr + 19, ": %s", fmt); - vfprintf(logfp, tmpstr, ap); - } - fclose(logfp); - } - va_end(ap); - } - return 0; + //Set all players to 'OFFLINE' + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `online` = '0'", char_db) ) + Sql_ShowDebug(sql_handle); + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `online` = '0'", guild_member_db) ) + Sql_ShowDebug(sql_handle); + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `connect_member` = '0'", guild_db) ) + Sql_ShowDebug(sql_handle); } - -/// Find all characters for given session and update the session character cache. -int char_find_characters(struct char_session_data* sd) +static void* create_charstatus(DBKey key, va_list args) { - int i, found_num = 0; + struct mmo_charstatus *cp; + cp = (struct mmo_charstatus *) aCalloc(1,sizeof(struct mmo_charstatus)); + cp->char_id = key.i; + return cp; +} - for( i = 0; i < char_num; i++ ) - {// find character entries and save them - if( char_dat[i].status.account_id == sd->account_id ) - { - sd->found_char[found_num++] = i; - if( found_num >= MAX_CHARS ) - { - break; - } - } - } +int mmo_char_tosql(int char_id, struct mmo_charstatus* p) +{ + int i = 0; + int count = 0; + int diff = 0; + char save_status[128]; //For displaying save information. [Skotlex] + struct mmo_charstatus *cp; + int errors = 0; //If there are any errors while saving, "cp" will not be updated at the end. + StringBuf buf; - for( i = found_num; i < MAX_CHARS; i++ ) - {// fill remaining blanks - sd->found_char[i] = -1; - } + if (char_id!=p->char_id) return 0; - return found_num; -} + cp = (struct mmo_charstatus*)idb_ensure(char_db_, char_id, create_charstatus); + StringBuf_Init(&buf); + memset(save_status, 0, sizeof(save_status)); -/// Search character data from given session. -struct mmo_charstatus* search_session_character(struct char_session_data* sd, int char_id) -{ - int i; + //map inventory data + if( memcmp(p->inventory, cp->inventory, sizeof(p->inventory)) ) + { + if (!memitemdata_to_sql(p->inventory, MAX_INVENTORY, p->char_id, TABLE_INVENTORY)) + strcat(save_status, " inventory"); + else + errors++; + } - ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] != -1 && char_dat[sd->found_char[i]].status.char_id == char_id ); - if( i == MAX_CHARS ) + //map cart data + if( memcmp(p->cart, cp->cart, sizeof(p->cart)) ) { - return NULL; + if (!memitemdata_to_sql(p->cart, MAX_CART, p->char_id, TABLE_CART)) + strcat(save_status, " cart"); + else + errors++; } - return &char_dat[sd->found_char[i]].status; -} + //map storage data + if( memcmp(p->storage.items, cp->storage.items, sizeof(p->storage.items)) ) + { + if (!memitemdata_to_sql(p->storage.items, MAX_STORAGE, p->account_id, TABLE_STORAGE)) + strcat(save_status, " storage"); + else + errors++; + } -//Search character data from the aid/cid givem -struct mmo_charstatus* search_character(int aid, int cid) -{ - int i; - for (i = 0; i < char_num; i++) { - if (char_dat[i].status.char_id == cid && char_dat[i].status.account_id == aid) - return &char_dat[i].status; + if ( + (p->base_exp != cp->base_exp) || (p->base_level != cp->base_level) || + (p->job_level != cp->job_level) || (p->job_exp != cp->job_exp) || + (p->zeny != cp->zeny) || + (p->last_point.map != cp->last_point.map) || + (p->last_point.x != cp->last_point.x) || (p->last_point.y != cp->last_point.y) || + (p->max_hp != cp->max_hp) || (p->hp != cp->hp) || + (p->max_sp != cp->max_sp) || (p->sp != cp->sp) || + (p->status_point != cp->status_point) || (p->skill_point != cp->skill_point) || + (p->str != cp->str) || (p->agi != cp->agi) || (p->vit != cp->vit) || + (p->int_ != cp->int_) || (p->dex != cp->dex) || (p->luk != cp->luk) || + (p->option != cp->option) || + (p->party_id != cp->party_id) || (p->guild_id != cp->guild_id) || + (p->pet_id != cp->pet_id) || (p->weapon != cp->weapon) || (p->hom_id != cp->hom_id) || + (p->shield != cp->shield) || (p->head_top != cp->head_top) || + (p->head_mid != cp->head_mid) || (p->head_bottom != cp->head_bottom) || (p->delete_date != cp->delete_date) || + (p->rename != cp->rename) || (p->robe != cp->robe) + ) + { //Save status + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `base_level`='%d', `job_level`='%d'," + "`base_exp`='%u', `job_exp`='%u', `zeny`='%d'," + "`max_hp`='%d',`hp`='%d',`max_sp`='%d',`sp`='%d',`status_point`='%d',`skill_point`='%d'," + "`str`='%d',`agi`='%d',`vit`='%d',`int`='%d',`dex`='%d',`luk`='%d'," + "`option`='%d',`party_id`='%d',`guild_id`='%d',`pet_id`='%d',`homun_id`='%d'," + "`weapon`='%d',`shield`='%d',`head_top`='%d',`head_mid`='%d',`head_bottom`='%d'," + "`last_map`='%s',`last_x`='%d',`last_y`='%d',`save_map`='%s',`save_x`='%d',`save_y`='%d', `rename`='%d'," + "`delete_date`='%lu',`robe`='%d'" + " WHERE `account_id`='%d' AND `char_id` = '%d'", + char_db, p->base_level, p->job_level, + p->base_exp, p->job_exp, p->zeny, + p->max_hp, p->hp, p->max_sp, p->sp, p->status_point, p->skill_point, + p->str, p->agi, p->vit, p->int_, p->dex, p->luk, + p->option, p->party_id, p->guild_id, p->pet_id, p->hom_id, + p->weapon, p->shield, p->head_top, p->head_mid, p->head_bottom, + mapindex_id2name(p->last_point.map), p->last_point.x, p->last_point.y, + mapindex_id2name(p->save_point.map), p->save_point.x, p->save_point.y, p->rename, + (unsigned long)p->delete_date, // FIXME: platform-dependent size + p->robe, + p->account_id, p->char_id) ) + { + Sql_ShowDebug(sql_handle); + errors++; + } else + strcat(save_status, " status"); } - return NULL; -} - -struct mmo_charstatus* search_character_byname(char* character_name) -{ - int i = search_character_index(character_name); - if (i == -1) return NULL; - return &char_dat[i].status; -} -// Searches if the given character is online, and returns the fd of the -// map-server it is connected to. -int search_character_online(int aid, int cid) -{ - //Look for online character. - struct online_char_data* character; - character = (struct online_char_data*)idb_get(online_char_db, aid); - if(character && - character->char_id == cid && - character->server > -1) - return server[character->server].fd; - return -1; -} + //Values that will seldom change (to speed up saving) + if ( + (p->hair != cp->hair) || (p->hair_color != cp->hair_color) || (p->clothes_color != cp->clothes_color) || + (p->class_ != cp->class_) || + (p->partner_id != cp->partner_id) || (p->father != cp->father) || + (p->mother != cp->mother) || (p->child != cp->child) || + (p->karma != cp->karma) || (p->manner != cp->manner) || + (p->fame != cp->fame) + ) + { + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `class`='%d'," + "`hair`='%d',`hair_color`='%d',`clothes_color`='%d'," + "`partner_id`='%d', `father`='%d', `mother`='%d', `child`='%d'," + "`karma`='%d',`manner`='%d', `fame`='%d'" + " WHERE `account_id`='%d' AND `char_id` = '%d'", + char_db, p->class_, + p->hair, p->hair_color, p->clothes_color, + p->partner_id, p->father, p->mother, p->child, + p->karma, p->manner, p->fame, + p->account_id, p->char_id) ) + { + Sql_ShowDebug(sql_handle); + errors++; + } else + strcat(save_status, " status2"); + } -//---------------------------------------------- -// Search an character id -// (return character index or -1 (if not found)) -// If exact character name is not found, -// the function checks without case sensitive -// and returns index if only 1 character is found -// and similar to the searched name. -//---------------------------------------------- -int search_character_index(char* character_name) -{ - int i, quantity, index; - - quantity = 0; - index = -1; - for(i = 0; i < char_num; i++) { - // Without case sensitive check (increase the number of similar character names found) - if (stricmp(char_dat[i].status.name, character_name) == 0) { - // Strict comparison (if found, we finish the function immediatly with correct value) - if (strcmp(char_dat[i].status.name, character_name) == 0) - return i; - quantity++; - index = i; - } + /* Mercenary Owner */ + if( (p->mer_id != cp->mer_id) || + (p->arch_calls != cp->arch_calls) || (p->arch_faith != cp->arch_faith) || + (p->spear_calls != cp->spear_calls) || (p->spear_faith != cp->spear_faith) || + (p->sword_calls != cp->sword_calls) || (p->sword_faith != cp->sword_faith) ) + { + if (mercenary_owner_tosql(char_id, p)) + strcat(save_status, " mercenary"); + else + errors++; } - // Here, the exact character name is not found - // We return the found index of a similar account ONLY if there is 1 similar character - if (quantity == 1) - return index; - // Exact character name is not found and 0 or more than 1 similar characters have been found ==> we say not found - return -1; -} + //memo points + if( memcmp(p->memo_point, cp->memo_point, sizeof(p->memo_point)) ) + { + char esc_mapname[NAME_LENGTH*2+1]; -/*--------------------------------------------------- - Make a data line for friends list - --------------------------------------------------*/ -int mmo_friends_list_data_str(char *str, struct mmo_charstatus *p) -{ - int i; - char *str_p = str; - str_p += sprintf(str_p, "%d", p->char_id); + //`memo` (`memo_id`,`char_id`,`map`,`x`,`y`) + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", memo_db, p->char_id) ) + { + Sql_ShowDebug(sql_handle); + errors++; + } - for (i=0;i<MAX_FRIENDS;i++){ - if (p->friends[i].account_id > 0 && p->friends[i].char_id > 0 && p->friends[i].name[0]) - str_p += sprintf(str_p, ",%d,%d,%s", p->friends[i].account_id, p->friends[i].char_id, p->friends[i].name); + //insert here. + StringBuf_Clear(&buf); + StringBuf_Printf(&buf, "INSERT INTO `%s`(`char_id`,`map`,`x`,`y`) VALUES ", memo_db); + for( i = 0, count = 0; i < MAX_MEMOPOINTS; ++i ) + { + if( p->memo_point[i].map ) + { + if( count ) + StringBuf_AppendStr(&buf, ","); + Sql_EscapeString(sql_handle, esc_mapname, mapindex_id2name(p->memo_point[i].map)); + StringBuf_Printf(&buf, "('%d', '%s', '%d', '%d')", char_id, esc_mapname, p->memo_point[i].x, p->memo_point[i].y); + ++count; + } + } + if( count ) + { + if( SQL_ERROR == Sql_QueryStr(sql_handle, StringBuf_Value(&buf)) ) + { + Sql_ShowDebug(sql_handle); + errors++; + } + } + strcat(save_status, " memo"); } - str_p += '\0'; + //FIXME: is this neccessary? [ultramage] + for(i=0;i<MAX_SKILL;i++) + if ((p->skill[i].lv != 0) && (p->skill[i].id == 0)) + p->skill[i].id = i; // Fix skill tree - return 0; -} -/*--------------------------------------------------- - Make a data line for hotkeys list - --------------------------------------------------*/ -int mmo_hotkeys_tostr(char *str, struct mmo_charstatus *p) -{ -#ifdef HOTKEY_SAVING - int i; - char *str_p = str; - str_p += sprintf(str_p, "%d", p->char_id); - for (i=0;i<MAX_HOTKEYS;i++) - str_p += sprintf(str_p, ",%d,%d,%d", p->hotkeys[i].type, p->hotkeys[i].id, p->hotkeys[i].lv); - str_p += '\0'; -#endif - - return 0; -} - -//------------------------------------------------- -// Function to create the character line (for save) -//------------------------------------------------- -int mmo_char_tostr(char *str, struct mmo_charstatus *p, struct global_reg *reg, int reg_num) -{ - int i,j; - char *str_p = str; - - str_p += sprintf(str_p, - "%d\t%d,%d\t%s\t%d,%d,%d\t%u,%u,%d" //Up to Zeny field - "\t%d,%d,%d,%d\t%d,%d,%d,%d,%d,%d\t%d,%d" //Up to Skill Point - "\t%d,%d,%d\t%d,%d,%d,%d" //Up to hom id - "\t%d,%d,%d\t%d,%d,%d,%d,%d,%d" //Up to robe - "\t%d,%d,%d\t%d,%d,%d" //last point + save point - ",%d,%d,%d,%d,%d,%lu\t", //Family info + delete date - p->char_id, p->account_id, p->slot, p->name, // - p->class_, p->base_level, p->job_level, - p->base_exp, p->job_exp, p->zeny, - p->hp, p->max_hp, p->sp, p->max_sp, - p->str, p->agi, p->vit, p->int_, p->dex, p->luk, - p->status_point, p->skill_point, - p->option, p->karma, p->manner, // - p->party_id, p->guild_id, p->pet_id, p->hom_id, - p->hair, p->hair_color, p->clothes_color, - p->weapon, p->shield, p->head_top, p->head_mid, p->head_bottom, p->robe, - p->last_point.map, p->last_point.x, p->last_point.y, // - p->save_point.map, p->save_point.x, p->save_point.y, - p->partner_id,p->father,p->mother,p->child,p->fame, // - (unsigned long)p->delete_date); // FIXME: platform-dependent size - for(i = 0; i < MAX_MEMOPOINTS; i++) - if (p->memo_point[i].map) { - str_p += sprintf(str_p, "%d,%d,%d ", p->memo_point[i].map, p->memo_point[i].x, p->memo_point[i].y); - } - *(str_p++) = '\t'; - - for(i = 0; i < MAX_INVENTORY; i++) - if (p->inventory[i].nameid) { - str_p += sprintf(str_p,"%d,%d,%d,%d,%d,%d,%d", - p->inventory[i].id,p->inventory[i].nameid,p->inventory[i].amount,p->inventory[i].equip, - p->inventory[i].identify,p->inventory[i].refine,p->inventory[i].attribute); - for(j=0; j<MAX_SLOTS; j++) - str_p += sprintf(str_p,",%d",p->inventory[i].card[j]); - str_p += sprintf(str_p," "); - } - *(str_p++) = '\t'; - - for(i = 0; i < MAX_CART; i++) - if (p->cart[i].nameid) { - str_p += sprintf(str_p,"%d,%d,%d,%d,%d,%d,%d", - p->cart[i].id,p->cart[i].nameid,p->cart[i].amount,p->cart[i].equip, - p->cart[i].identify,p->cart[i].refine,p->cart[i].attribute); - for(j=0; j<MAX_SLOTS; j++) - str_p += sprintf(str_p,",%d",p->cart[i].card[j]); - str_p += sprintf(str_p," "); + //skills + if( memcmp(p->skill, cp->skill, sizeof(p->skill)) ) + { + //`skill` (`char_id`, `id`, `lv`) + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", skill_db, p->char_id) ) + { + Sql_ShowDebug(sql_handle); + errors++; } - *(str_p++) = '\t'; - for(i = 0; i < MAX_SKILL; i++) - if (p->skill[i].id != 0 && p->skill[i].flag != SKILL_FLAG_TEMPORARY) { - str_p += sprintf(str_p, "%d,%d ", p->skill[i].id, (p->skill[i].flag == SKILL_FLAG_PERMANENT) ? p->skill[i].lv : p->skill[i].flag - SKILL_FLAG_REPLACED_LV_0); + StringBuf_Clear(&buf); + StringBuf_Printf(&buf, "INSERT INTO `%s`(`char_id`,`id`,`lv`) VALUES ", skill_db); + //insert here. + for( i = 0, count = 0; i < MAX_SKILL; ++i ) + { + if( p->skill[i].id != 0 && p->skill[i].flag != SKILL_FLAG_TEMPORARY ) + { + if( p->skill[i].flag == SKILL_FLAG_PERMANENT && p->skill[i].lv == 0 ) + continue; + if( p->skill[i].flag != SKILL_FLAG_PERMANENT && (p->skill[i].flag - SKILL_FLAG_REPLACED_LV_0) == 0 ) + continue; + if( count ) + StringBuf_AppendStr(&buf, ","); + StringBuf_Printf(&buf, "('%d','%d','%d')", char_id, p->skill[i].id, (p->skill[i].flag == SKILL_FLAG_PERMANENT ? p->skill[i].lv : p->skill[i].flag - SKILL_FLAG_REPLACED_LV_0)); + ++count; + } + } + if( count ) + { + if( SQL_ERROR == Sql_QueryStr(sql_handle, StringBuf_Value(&buf)) ) + { + Sql_ShowDebug(sql_handle); + errors++; + } } - *(str_p++) = '\t'; - - for(i = 0; i < reg_num; i++) - if (reg[i].str[0]) - str_p += sprintf(str_p, "%s,%s ", reg[i].str, reg[i].value); - *(str_p++) = '\t'; - *str_p = '\0'; - return 0; -} -#endif //TXT_SQL_CONVERT -//------------------------------------------------------------------------- -// Function to set the character from the line (at read of characters file) -//------------------------------------------------------------------------- -int mmo_char_fromstr(char *str, struct mmo_charstatus *p, struct global_reg *reg, int *reg_num) -{ - char tmp_str[3][128]; //To avoid deleting chars with too long names. - int tmp_int[256]; - unsigned int tmp_uint[2]; //To read exp.... - int next, len, i, j; - unsigned long tmp_ulong[1]; - - // initilialise character - memset(p, '\0', sizeof(struct mmo_charstatus)); - -// Char structure of version 14797 (robe) - if (sscanf(str, "%d\t%d,%d\t%127[^\t]\t%d,%d,%d\t%u,%u,%d\t%d,%d,%d,%d\t%d,%d,%d,%d,%d,%d\t%d,%d" - "\t%d,%d,%d\t%d,%d,%d,%d\t%d,%d,%d\t%d,%d,%d,%d,%d,%d" - "\t%d,%d,%d\t%d,%d,%d,%d,%d,%d,%d,%d,%lu%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], tmp_str[0], - &tmp_int[3], &tmp_int[4], &tmp_int[5], - &tmp_uint[0], &tmp_uint[1], &tmp_int[8], - &tmp_int[9], &tmp_int[10], &tmp_int[11], &tmp_int[12], - &tmp_int[13], &tmp_int[14], &tmp_int[15], &tmp_int[16], &tmp_int[17], &tmp_int[18], - &tmp_int[19], &tmp_int[20], - &tmp_int[21], &tmp_int[22], &tmp_int[23], // - &tmp_int[24], &tmp_int[25], &tmp_int[26], &tmp_int[44], - &tmp_int[27], &tmp_int[28], &tmp_int[29], - &tmp_int[30], &tmp_int[31], &tmp_int[32], &tmp_int[33], &tmp_int[34], &tmp_int[47], - &tmp_int[45], &tmp_int[35], &tmp_int[36], - &tmp_int[46], &tmp_int[37], &tmp_int[38], &tmp_int[39], - &tmp_int[40], &tmp_int[41], &tmp_int[42], &tmp_int[43], &tmp_ulong[0], &next) != 50) - { - tmp_int[47] = 0; // robe -// Char structure of version 14700 (delete date) - if (sscanf(str, "%d\t%d,%d\t%127[^\t]\t%d,%d,%d\t%u,%u,%d\t%d,%d,%d,%d\t%d,%d,%d,%d,%d,%d\t%d,%d" - "\t%d,%d,%d\t%d,%d,%d,%d\t%d,%d,%d\t%d,%d,%d,%d,%d" - "\t%d,%d,%d\t%d,%d,%d,%d,%d,%d,%d,%d,%lu%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], tmp_str[0], - &tmp_int[3], &tmp_int[4], &tmp_int[5], - &tmp_uint[0], &tmp_uint[1], &tmp_int[8], - &tmp_int[9], &tmp_int[10], &tmp_int[11], &tmp_int[12], - &tmp_int[13], &tmp_int[14], &tmp_int[15], &tmp_int[16], &tmp_int[17], &tmp_int[18], - &tmp_int[19], &tmp_int[20], - &tmp_int[21], &tmp_int[22], &tmp_int[23], // - &tmp_int[24], &tmp_int[25], &tmp_int[26], &tmp_int[44], - &tmp_int[27], &tmp_int[28], &tmp_int[29], - &tmp_int[30], &tmp_int[31], &tmp_int[32], &tmp_int[33], &tmp_int[34], - &tmp_int[45], &tmp_int[35], &tmp_int[36], - &tmp_int[46], &tmp_int[37], &tmp_int[38], &tmp_int[39], - &tmp_int[40], &tmp_int[41], &tmp_int[42], &tmp_int[43], &tmp_ulong[0], &next) != 49) - { - tmp_ulong[0] = 0; // delete date -// Char structure of version 1500 (homun + mapindex maps) - if (sscanf(str, "%d\t%d,%d\t%127[^\t]\t%d,%d,%d\t%u,%u,%d\t%d,%d,%d,%d\t%d,%d,%d,%d,%d,%d\t%d,%d" - "\t%d,%d,%d\t%d,%d,%d,%d\t%d,%d,%d\t%d,%d,%d,%d,%d" - "\t%d,%d,%d\t%d,%d,%d,%d,%d,%d,%d,%d%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], tmp_str[0], - &tmp_int[3], &tmp_int[4], &tmp_int[5], - &tmp_uint[0], &tmp_uint[1], &tmp_int[8], - &tmp_int[9], &tmp_int[10], &tmp_int[11], &tmp_int[12], - &tmp_int[13], &tmp_int[14], &tmp_int[15], &tmp_int[16], &tmp_int[17], &tmp_int[18], - &tmp_int[19], &tmp_int[20], - &tmp_int[21], &tmp_int[22], &tmp_int[23], // - &tmp_int[24], &tmp_int[25], &tmp_int[26], &tmp_int[44], - &tmp_int[27], &tmp_int[28], &tmp_int[29], - &tmp_int[30], &tmp_int[31], &tmp_int[32], &tmp_int[33], &tmp_int[34], - &tmp_int[45], &tmp_int[35], &tmp_int[36], - &tmp_int[46], &tmp_int[37], &tmp_int[38], &tmp_int[39], - &tmp_int[40], &tmp_int[41], &tmp_int[42], &tmp_int[43], &next) != 48) - { - tmp_int[44] = 0; //Hom ID. -// Char structure of version 1488 (fame field addition) - if (sscanf(str, "%d\t%d,%d\t%127[^\t]\t%d,%d,%d\t%u,%u,%d\t%d,%d,%d,%d\t%d,%d,%d,%d,%d,%d\t%d,%d" - "\t%d,%d,%d\t%d,%d,%d\t%d,%d,%d\t%d,%d,%d,%d,%d" - "\t%127[^,],%d,%d\t%127[^,],%d,%d,%d,%d,%d,%d,%d%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], tmp_str[0], - &tmp_int[3], &tmp_int[4], &tmp_int[5], - &tmp_uint[0], &tmp_uint[1], &tmp_int[8], - &tmp_int[9], &tmp_int[10], &tmp_int[11], &tmp_int[12], - &tmp_int[13], &tmp_int[14], &tmp_int[15], &tmp_int[16], &tmp_int[17], &tmp_int[18], - &tmp_int[19], &tmp_int[20], - &tmp_int[21], &tmp_int[22], &tmp_int[23], // - &tmp_int[24], &tmp_int[25], &tmp_int[26], - &tmp_int[27], &tmp_int[28], &tmp_int[29], - &tmp_int[30], &tmp_int[31], &tmp_int[32], &tmp_int[33], &tmp_int[34], - tmp_str[1], &tmp_int[35], &tmp_int[36], - tmp_str[2], &tmp_int[37], &tmp_int[38], &tmp_int[39], - &tmp_int[40], &tmp_int[41], &tmp_int[42], &tmp_int[43], &next) != 47) - { - tmp_int[43] = 0; //Fame -// Char structure of version 1363 (family data addition) - if (sscanf(str, "%d\t%d,%d\t%127[^\t]\t%d,%d,%d\t%u,%u,%d\t%d,%d,%d,%d\t%d,%d,%d,%d,%d,%d\t%d,%d" - "\t%d,%d,%d\t%d,%d,%d\t%d,%d,%d\t%d,%d,%d,%d,%d" - "\t%127[^,],%d,%d\t%127[^,],%d,%d,%d,%d,%d,%d%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], tmp_str[0], // - &tmp_int[3], &tmp_int[4], &tmp_int[5], - &tmp_uint[0], &tmp_uint[1], &tmp_int[8], - &tmp_int[9], &tmp_int[10], &tmp_int[11], &tmp_int[12], - &tmp_int[13], &tmp_int[14], &tmp_int[15], &tmp_int[16], &tmp_int[17], &tmp_int[18], - &tmp_int[19], &tmp_int[20], - &tmp_int[21], &tmp_int[22], &tmp_int[23], // - &tmp_int[24], &tmp_int[25], &tmp_int[26], - &tmp_int[27], &tmp_int[28], &tmp_int[29], - &tmp_int[30], &tmp_int[31], &tmp_int[32], &tmp_int[33], &tmp_int[34], - tmp_str[1], &tmp_int[35], &tmp_int[36], // - tmp_str[2], &tmp_int[37], &tmp_int[38], &tmp_int[39], - &tmp_int[40], &tmp_int[41], &tmp_int[42], &next) != 46) - { - tmp_int[40] = 0; // father - tmp_int[41] = 0; // mother - tmp_int[42] = 0; // child -// Char structure version 1008 (marriage partner addition) - if (sscanf(str, "%d\t%d,%d\t%127[^\t]\t%d,%d,%d\t%u,%u,%d\t%d,%d,%d,%d\t%d,%d,%d,%d,%d,%d\t%d,%d" - "\t%d,%d,%d\t%d,%d,%d\t%d,%d,%d\t%d,%d,%d,%d,%d" - "\t%127[^,],%d,%d\t%127[^,],%d,%d,%d%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], tmp_str[0], // - &tmp_int[3], &tmp_int[4], &tmp_int[5], - &tmp_uint[0], &tmp_uint[1], &tmp_int[8], - &tmp_int[9], &tmp_int[10], &tmp_int[11], &tmp_int[12], - &tmp_int[13], &tmp_int[14], &tmp_int[15], &tmp_int[16], &tmp_int[17], &tmp_int[18], - &tmp_int[19], &tmp_int[20], - &tmp_int[21], &tmp_int[22], &tmp_int[23], // - &tmp_int[24], &tmp_int[25], &tmp_int[26], - &tmp_int[27], &tmp_int[28], &tmp_int[29], - &tmp_int[30], &tmp_int[31], &tmp_int[32], &tmp_int[33], &tmp_int[34], - tmp_str[1], &tmp_int[35], &tmp_int[36], // - tmp_str[2], &tmp_int[37], &tmp_int[38], &tmp_int[39], &next) != 43) - { - tmp_int[39] = 0; // partner id -// Char structure version 384 (pet addition) - if (sscanf(str, "%d\t%d,%d\t%127[^\t]\t%d,%d,%d\t%u,%u,%d\t%d,%d,%d,%d\t%d,%d,%d,%d,%d,%d\t%d,%d" - "\t%d,%d,%d\t%d,%d,%d\t%d,%d,%d\t%d,%d,%d,%d,%d" - "\t%127[^,],%d,%d\t%127[^,],%d,%d%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], tmp_str[0], // - &tmp_int[3], &tmp_int[4], &tmp_int[5], - &tmp_uint[0], &tmp_uint[1], &tmp_int[8], - &tmp_int[9], &tmp_int[10], &tmp_int[11], &tmp_int[12], - &tmp_int[13], &tmp_int[14], &tmp_int[15], &tmp_int[16], &tmp_int[17], &tmp_int[18], - &tmp_int[19], &tmp_int[20], - &tmp_int[21], &tmp_int[22], &tmp_int[23], // - &tmp_int[24], &tmp_int[25], &tmp_int[26], - &tmp_int[27], &tmp_int[28], &tmp_int[29], - &tmp_int[30], &tmp_int[31], &tmp_int[32], &tmp_int[33], &tmp_int[34], - tmp_str[1], &tmp_int[35], &tmp_int[36], // - tmp_str[2], &tmp_int[37], &tmp_int[38], &next) != 42) - { - tmp_int[26] = 0; // pet id -// Char structure of a version 1 (original data structure) - if (sscanf(str, "%d\t%d,%d\t%127[^\t]\t%d,%d,%d\t%u,%u,%d\t%d,%d,%d,%d\t%d,%d,%d,%d,%d,%d\t%d,%d" - "\t%d,%d,%d\t%d,%d\t%d,%d,%d\t%d,%d,%d,%d,%d" - "\t%127[^,],%d,%d\t%127[^,],%d,%d%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], tmp_str[0], // - &tmp_int[3], &tmp_int[4], &tmp_int[5], - &tmp_uint[0], &tmp_uint[1], &tmp_int[8], - &tmp_int[9], &tmp_int[10], &tmp_int[11], &tmp_int[12], - &tmp_int[13], &tmp_int[14], &tmp_int[15], &tmp_int[16], &tmp_int[17], &tmp_int[18], - &tmp_int[19], &tmp_int[20], - &tmp_int[21], &tmp_int[22], &tmp_int[23], // - &tmp_int[24], &tmp_int[25], // - &tmp_int[27], &tmp_int[28], &tmp_int[29], - &tmp_int[30], &tmp_int[31], &tmp_int[32], &tmp_int[33], &tmp_int[34], - tmp_str[1], &tmp_int[35], &tmp_int[36], // - tmp_str[2], &tmp_int[37], &tmp_int[38], &next) != 41) - { - ShowError("Char-loading: Unrecognized character data version, info lost!\n"); - ShowDebug("Character info: %s\n", str); - return 0; + strcat(save_status, " skills"); } - } // Char structure version 384 (pet addition) - } // Char structure version 1008 (marriage partner addition) - } // Char structure of version 1363 (family data addition) - } // Char structure of version 1488 (fame field addition) - //Convert save data from string to integer for older formats - tmp_int[45] = mapindex_name2id(tmp_str[1]); - tmp_int[46] = mapindex_name2id(tmp_str[2]); - } // Char structure of version 1500 (homun + mapindex maps) - } // Char structure of version 14700 (delete date) - } // Char structure of version 14797 (robe) - - safestrncpy(p->name, tmp_str[0], NAME_LENGTH); //Overflow protection [Skotlex] - p->char_id = tmp_int[0]; - p->account_id = tmp_int[1]; - p->slot = tmp_int[2]; - p->class_ = tmp_int[3]; - p->base_level = tmp_int[4]; - p->job_level = tmp_int[5]; - p->base_exp = tmp_uint[0]; - p->job_exp = tmp_uint[1]; - p->zeny = tmp_int[8]; - p->hp = tmp_int[9]; - p->max_hp = tmp_int[10]; - p->sp = tmp_int[11]; - p->max_sp = tmp_int[12]; - p->str = tmp_int[13]; - p->agi = tmp_int[14]; - p->vit = tmp_int[15]; - p->int_ = tmp_int[16]; - p->dex = tmp_int[17]; - p->luk = tmp_int[18]; - p->status_point = tmp_int[19]; - p->skill_point = tmp_int[20]; - p->option = tmp_int[21]; - p->karma = tmp_int[22]; - p->manner = tmp_int[23]; - p->party_id = tmp_int[24]; - p->guild_id = tmp_int[25]; - p->pet_id = tmp_int[26]; - p->hair = tmp_int[27]; - p->hair_color = tmp_int[28]; - p->clothes_color = tmp_int[29]; - p->weapon = tmp_int[30]; - p->shield = tmp_int[31]; - p->head_top = tmp_int[32]; - p->head_mid = tmp_int[33]; - p->head_bottom = tmp_int[34]; - p->last_point.x = tmp_int[35]; - p->last_point.y = tmp_int[36]; - p->save_point.x = tmp_int[37]; - p->save_point.y = tmp_int[38]; - p->partner_id = tmp_int[39]; - p->father = tmp_int[40]; - p->mother = tmp_int[41]; - p->child = tmp_int[42]; - p->fame = tmp_int[43]; - p->hom_id = tmp_int[44]; - p->last_point.map = tmp_int[45]; - p->save_point.map = tmp_int[46]; - p->delete_date = tmp_ulong[0]; - p->robe = tmp_int[47]; - -#ifndef TXT_SQL_CONVERT - // Some checks - for(i = 0; i < char_num; i++) { - if (char_dat[i].status.char_id == p->char_id) { - ShowError(CL_RED"mmmo_auth_init: a character has an identical id to another.\n"); - ShowError(" character id #%d -> new character not readed.\n", p->char_id); - ShowError(" Character saved in log file."CL_RESET"\n"); - return -1; - } else if (strcmp(char_dat[i].status.name, p->name) == 0) { - ShowError(CL_RED"mmmo_auth_init: a character name already exists.\n"); - ShowError(" character name '%s' -> new character not read.\n", p->name); - ShowError(" Character saved in log file."CL_RESET"\n"); - return -2; + + diff = 0; + for(i = 0; i < MAX_FRIENDS; i++){ + if(p->friends[i].char_id != cp->friends[i].char_id || + p->friends[i].account_id != cp->friends[i].account_id){ + diff = 1; + break; } } - if (strcmpi(wisp_server_name, p->name) == 0) { - ShowWarning("mmo_auth_init: ******WARNING: character name has wisp server name.\n"); - ShowWarning(" Character name '%s' = wisp server name '%s'.\n", p->name, wisp_server_name); - ShowWarning(" Character readed. Suggestion: change the wisp server name.\n"); - char_log("mmo_auth_init: ******WARNING: character name has wisp server name: Character name '%s' = wisp server name '%s'.\n", - p->name, wisp_server_name); - } -#endif //TXT_SQL_CONVERT - if (str[next] == '\n' || str[next] == '\r') - return 1; // 新規データ - - next++; - - for(i = 0; str[next] && str[next] != '\t'; i++) { - //mapindex memo format - if (sscanf(str+next, "%d,%d,%d%n", &tmp_int[2], &tmp_int[0], &tmp_int[1], &len) != 3) - { //Old string-based memo format. - if (sscanf(str+next, "%[^,],%d,%d%n", tmp_str[0], &tmp_int[0], &tmp_int[1], &len) != 3) - return -3; - tmp_int[2] = mapindex_name2id(tmp_str[0]); + if(diff == 1) + { //Save friends + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", friend_db, char_id) ) + { + Sql_ShowDebug(sql_handle); + errors++; } - if (i < MAX_MEMOPOINTS) - { //Avoid overflowing (but we must also read through all saved memos) - p->memo_point[i].x = tmp_int[0]; - p->memo_point[i].y = tmp_int[1]; - p->memo_point[i].map = tmp_int[2]; + + StringBuf_Clear(&buf); + StringBuf_Printf(&buf, "INSERT INTO `%s` (`char_id`, `friend_account`, `friend_id`) VALUES ", friend_db); + for( i = 0, count = 0; i < MAX_FRIENDS; ++i ) + { + if( p->friends[i].char_id > 0 ) + { + if( count ) + StringBuf_AppendStr(&buf, ","); + StringBuf_Printf(&buf, "('%d','%d','%d')", char_id, p->friends[i].account_id, p->friends[i].char_id); + count++; + } + } + if( count ) + { + if( SQL_ERROR == Sql_QueryStr(sql_handle, StringBuf_Value(&buf)) ) + { + Sql_ShowDebug(sql_handle); + errors++; + } } - next += len; - if (str[next] == ' ') - next++; + strcat(save_status, " friends"); } - next++; - - for(i = 0; str[next] && str[next] != '\t'; i++) { - if(sscanf(str + next, "%d,%d,%d,%d,%d,%d,%d%[0-9,-]%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], &tmp_int[3], - &tmp_int[4], &tmp_int[5], &tmp_int[6], tmp_str[0], &len) == 8) +#ifdef HOTKEY_SAVING + // hotkeys + StringBuf_Clear(&buf); + StringBuf_Printf(&buf, "REPLACE INTO `%s` (`char_id`, `hotkey`, `type`, `itemskill_id`, `skill_lvl`) VALUES ", hotkey_db); + diff = 0; + for(i = 0; i < ARRAYLENGTH(p->hotkeys); i++){ + if(memcmp(&p->hotkeys[i], &cp->hotkeys[i], sizeof(struct hotkey))) { - p->inventory[i].id = tmp_int[0]; - p->inventory[i].nameid = tmp_int[1]; - p->inventory[i].amount = tmp_int[2]; - p->inventory[i].equip = tmp_int[3]; - p->inventory[i].identify = tmp_int[4]; - p->inventory[i].refine = tmp_int[5]; - p->inventory[i].attribute = tmp_int[6]; - - for(j = 0; j < MAX_SLOTS && tmp_str[0][0] && sscanf(tmp_str[0], ",%d%[0-9,-]",&tmp_int[0], tmp_str[0]) > 0; j++) - p->inventory[i].card[j] = tmp_int[0]; - - next += len; - if (str[next] == ' ') - next++; - } else // invalid structure - return -4; + if( diff ) + StringBuf_AppendStr(&buf, ",");// not the first hotkey + StringBuf_Printf(&buf, "('%d','%u','%u','%u','%u')", char_id, (unsigned int)i, (unsigned int)p->hotkeys[i].type, p->hotkeys[i].id , (unsigned int)p->hotkeys[i].lv); + diff = 1; + } } - next++; - - for(i = 0; str[next] && str[next] != '\t'; i++) { - if(sscanf(str + next, "%d,%d,%d,%d,%d,%d,%d%[0-9,-]%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], &tmp_int[3], - &tmp_int[4], &tmp_int[5], &tmp_int[6], tmp_str[0], &len) == 8) + if(diff) { + if( SQL_ERROR == Sql_QueryStr(sql_handle, StringBuf_Value(&buf)) ) { - p->cart[i].id = tmp_int[0]; - p->cart[i].nameid = tmp_int[1]; - p->cart[i].amount = tmp_int[2]; - p->cart[i].equip = tmp_int[3]; - p->cart[i].identify = tmp_int[4]; - p->cart[i].refine = tmp_int[5]; - p->cart[i].attribute = tmp_int[6]; - - for(j = 0; j < MAX_SLOTS && tmp_str[0][0] && sscanf(tmp_str[0], ",%d%[0-9,-]",&tmp_int[0], tmp_str[0]) > 0; j++) - p->cart[i].card[j] = tmp_int[0]; - - next += len; - if (str[next] == ' ') - next++; - } else // invalid structure - return -5; + Sql_ShowDebug(sql_handle); + errors++; + } else + strcat(save_status, " hotkeys"); } +#endif + StringBuf_Destroy(&buf); + if (save_status[0]!='\0' && save_log) + ShowInfo("Saved char %d - %s:%s.\n", char_id, p->name, save_status); + if (!errors) + memcpy(cp, p, sizeof(struct mmo_charstatus)); + return 0; +} + +/// Saves an array of 'item' entries into the specified table. +int memitemdata_to_sql(const struct item items[], int max, int id, int tableswitch) +{ + StringBuf buf; + SqlStmt* stmt; + int i; + int j; + const char* tablename; + const char* selectoption; + struct item item; // temp storage variable + bool* flag; // bit array for inventory matching + bool found; + int errors = 0; + + switch (tableswitch) { + case TABLE_INVENTORY: tablename = inventory_db; selectoption = "char_id"; break; + case TABLE_CART: tablename = cart_db; selectoption = "char_id"; break; + case TABLE_STORAGE: tablename = storage_db; selectoption = "account_id"; break; + case TABLE_GUILD_STORAGE: tablename = guild_storage_db; selectoption = "guild_id"; break; + default: + ShowError("Invalid table name!\n"); + return 1; + } + - next++; + // The following code compares inventory with current database values + // and performs modification/deletion/insertion only on relevant rows. + // This approach is more complicated than a trivial delete&insert, but + // it significantly reduces cpu load on the database server. - for(i = 0; str[next] && str[next] != '\t'; i++) { - if (sscanf(str + next, "%d,%d%n", &tmp_int[0], &tmp_int[1], &len) != 2) - return -6; - p->skill[tmp_int[0]].id = tmp_int[0]; - p->skill[tmp_int[0]].lv = tmp_int[1]; - next += len; - if (str[next] == ' ') - next++; + StringBuf_Init(&buf); + StringBuf_AppendStr(&buf, "SELECT `id`, `nameid`, `amount`, `equip`, `identify`, `refine`, `attribute`, `expire_time`"); + for( j = 0; j < MAX_SLOTS; ++j ) + StringBuf_Printf(&buf, ", `card%d`", j); + StringBuf_Printf(&buf, " FROM `%s` WHERE `%s`='%d'", tablename, selectoption, id); + + stmt = SqlStmt_Malloc(sql_handle); + if( SQL_ERROR == SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf)) + || SQL_ERROR == SqlStmt_Execute(stmt) ) + { + SqlStmt_ShowDebug(stmt); + SqlStmt_Free(stmt); + StringBuf_Destroy(&buf); + return 1; } - next++; + SqlStmt_BindColumn(stmt, 0, SQLDT_INT, &item.id, 0, NULL, NULL); + SqlStmt_BindColumn(stmt, 1, SQLDT_SHORT, &item.nameid, 0, NULL, NULL); + SqlStmt_BindColumn(stmt, 2, SQLDT_SHORT, &item.amount, 0, NULL, NULL); + SqlStmt_BindColumn(stmt, 3, SQLDT_USHORT, &item.equip, 0, NULL, NULL); + SqlStmt_BindColumn(stmt, 4, SQLDT_CHAR, &item.identify, 0, NULL, NULL); + SqlStmt_BindColumn(stmt, 5, SQLDT_CHAR, &item.refine, 0, NULL, NULL); + SqlStmt_BindColumn(stmt, 6, SQLDT_CHAR, &item.attribute, 0, NULL, NULL); + SqlStmt_BindColumn(stmt, 7, SQLDT_UINT, &item.expire_time, 0, NULL, NULL); + for( j = 0; j < MAX_SLOTS; ++j ) + SqlStmt_BindColumn(stmt, 8+j, SQLDT_SHORT, &item.card[j], 0, NULL, NULL); + + // bit array indicating which inventory items have already been matched + flag = (bool*) aCallocA(max, sizeof(bool)); + + while( SQL_SUCCESS == SqlStmt_NextRow(stmt) ) + { + found = false; + // search for the presence of the item in the char's inventory + for( i = 0; i < max; ++i ) + { + // skip empty and already matched entries + if( items[i].nameid == 0 || flag[i] ) + continue; - for(i = 0; str[next] && str[next] != '\t' && str[next] != '\n' && str[next] != '\r'; i++) { // global_reg実装以前のathena.txt互換のため一応'\n'チェック - if (sscanf(str + next, "%[^,],%[^ ] %n", reg[i].str, reg[i].value, &len) != 2) { - // because some scripts are not correct, the str can be "". So, we must check that. - // If it's, we must not refuse the character, but just this REG value. - // Character line will have something like: nov_2nd_cos,9 ,9 nov_1_2_cos_c,1 (here, ,9 is not good) - if (str[next] == ',' && sscanf(str + next, ",%[^ ] %n", reg[i].value, &len) == 1) - i--; - else - return -7; + if( items[i].nameid == item.nameid + && items[i].card[0] == item.card[0] + && items[i].card[2] == item.card[2] + && items[i].card[3] == item.card[3] + ) { //They are the same item. + ARR_FIND( 0, MAX_SLOTS, j, items[i].card[j] != item.card[j] ); + if( j == MAX_SLOTS && + items[i].amount == item.amount && + items[i].equip == item.equip && + items[i].identify == item.identify && + items[i].refine == item.refine && + items[i].attribute == item.attribute && + items[i].expire_time == item.expire_time ) + ; //Do nothing. + else + { + // update all fields. + StringBuf_Clear(&buf); + StringBuf_Printf(&buf, "UPDATE `%s` SET `amount`='%d', `equip`='%d', `identify`='%d', `refine`='%d',`attribute`='%d', `expire_time`='%u'", + tablename, items[i].amount, items[i].equip, items[i].identify, items[i].refine, items[i].attribute, items[i].expire_time); + for( j = 0; j < MAX_SLOTS; ++j ) + StringBuf_Printf(&buf, ", `card%d`=%d", j, items[i].card[j]); + StringBuf_Printf(&buf, " WHERE `id`='%d' LIMIT 1", item.id); + + if( SQL_ERROR == Sql_QueryStr(sql_handle, StringBuf_Value(&buf)) ) + { + Sql_ShowDebug(sql_handle); + errors++; + } + } + + found = flag[i] = true; //Item dealt with, + break; //skip to next item in the db. + } + } + if( !found ) + {// Item not present in inventory, remove it. + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE from `%s` where `id`='%d' LIMIT 1", tablename, item.id) ) + { + Sql_ShowDebug(sql_handle); + errors++; + } } - next += len; - if (str[next] == ' ') - next++; } - *reg_num = i; + SqlStmt_Free(stmt); - return 1; -} + StringBuf_Clear(&buf); + StringBuf_Printf(&buf, "INSERT INTO `%s`(`%s`, `nameid`, `amount`, `equip`, `identify`, `refine`, `attribute`, `expire_time`", tablename, selectoption); + for( j = 0; j < MAX_SLOTS; ++j ) + StringBuf_Printf(&buf, ", `card%d`", j); + StringBuf_AppendStr(&buf, ") VALUES "); -//--------------------------------- -// Function to read friend list -//--------------------------------- -int parse_friend_txt(struct mmo_charstatus *p) -{ - char line[1024], temp[1024]; - int pos = 0, count = 0, next; - int i,len; - FILE *fp; + found = false; + // insert non-matched items into the db as new items + for( i = 0; i < max; ++i ) + { + // skip empty and already matched entries + if( items[i].nameid == 0 || flag[i] ) + continue; - // Open the file and look for the ID - fp = fopen(friends_txt, "r"); + if( found ) + StringBuf_AppendStr(&buf, ","); + else + found = true; - if(fp == NULL) - return -1; - - while(fgets(line, sizeof(line), fp)) + StringBuf_Printf(&buf, "('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%u'", + id, items[i].nameid, items[i].amount, items[i].equip, items[i].identify, items[i].refine, items[i].attribute, items[i].expire_time); + for( j = 0; j < MAX_SLOTS; ++j ) + StringBuf_Printf(&buf, ", '%d'", items[i].card[j]); + StringBuf_AppendStr(&buf, ")"); + } + + if( found && SQL_ERROR == Sql_QueryStr(sql_handle, StringBuf_Value(&buf)) ) { - if(line[0] == '/' && line[1] == '/') - continue; - if (sscanf(line, "%d%n",&i, &pos) < 1 || i != p->char_id) - continue; //Not this line... - //Read friends - len = strlen(line); - next = pos; - for (count = 0; next < len && count < MAX_FRIENDS; count++) - { //Read friends. - if (sscanf(line+next, ",%d,%d,%23[^,^\n]%n",&p->friends[count].account_id,&p->friends[count].char_id, p->friends[count].name, &pos) < 3) - { //Invalid friend? - memset(&p->friends[count], 0, sizeof(p->friends[count])); - break; - } - next+=pos; - //What IF the name contains a comma? while the next field is not a - //number, we assume it belongs to the current name. [Skotlex] - //NOTE: Of course, this will fail if someone sets their name to something like - //Bob,2005 but... meh, it's the problem of parsing a text file (encasing it in " - //won't do as quotes are also valid name chars!) - while(next < len && sscanf(line+next, ",%23[^,^\n]%n", temp, &pos) > 0) - { - if (atoi(temp)) //We read the next friend, just continue. - break; - //Append the name. - next+=pos; - i = strlen(p->friends[count].name); - if (i + strlen(temp) +1 < NAME_LENGTH) - { - p->friends[count].name[i] = ','; - strcpy(p->friends[count].name+i+1, temp); - } - } //End Guess Block - } //Friend's for. - break; //Found friends. + Sql_ShowDebug(sql_handle); + errors++; } - fclose(fp); - return count; + + StringBuf_Destroy(&buf); + aFree(flag); + + return errors; } -//--------------------------------- -// Function to read hotkey list -//--------------------------------- -int parse_hotkey_txt(struct mmo_charstatus *p) +int mmo_char_tobuf(uint8* buf, struct mmo_charstatus* p); + +//===================================================================================================== +// Loads the basic character rooster for the given account. Returns total buffer used. +int mmo_chars_fromsql(struct char_session_data* sd, uint8* buf) { -#ifdef HOTKEY_SAVING - char line[1024]; - int pos = 0, count = 0, next; - int i,len; - int type, id, lv; - FILE *fp; + SqlStmt* stmt; + struct mmo_charstatus p; + int j = 0, i; + char last_map[MAP_NAME_LENGTH_EXT]; - // Open the file and look for the ID - fp = fopen(hotkeys_txt, "r"); - if(fp == NULL) - return -1; - - while(fgets(line, sizeof(line), fp)) + stmt = SqlStmt_Malloc(sql_handle); + if( stmt == NULL ) { - if(line[0] == '/' && line[1] == '/') + SqlStmt_ShowDebug(stmt); + return 0; + } + memset(&p, 0, sizeof(p)); + + // read char data + if( SQL_ERROR == SqlStmt_Prepare(stmt, "SELECT " + "`char_id`,`char_num`,`name`,`class`,`base_level`,`job_level`,`base_exp`,`job_exp`,`zeny`," + "`str`,`agi`,`vit`,`int`,`dex`,`luk`,`max_hp`,`hp`,`max_sp`,`sp`," + "`status_point`,`skill_point`,`option`,`karma`,`manner`,`hair`,`hair_color`," + "`clothes_color`,`weapon`,`shield`,`head_top`,`head_mid`,`head_bottom`,`last_map`,`rename`,`delete_date`," + "`robe`" + " FROM `%s` WHERE `account_id`='%d' AND `char_num` < '%d'", char_db, sd->account_id, MAX_CHARS) + || SQL_ERROR == SqlStmt_Execute(stmt) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_INT, &p.char_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_UCHAR, &p.slot, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_STRING, &p.name, sizeof(p.name), NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 3, SQLDT_SHORT, &p.class_, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 4, SQLDT_UINT, &p.base_level, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 5, SQLDT_UINT, &p.job_level, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 6, SQLDT_UINT, &p.base_exp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 7, SQLDT_UINT, &p.job_exp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 8, SQLDT_INT, &p.zeny, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 9, SQLDT_SHORT, &p.str, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 10, SQLDT_SHORT, &p.agi, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 11, SQLDT_SHORT, &p.vit, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 12, SQLDT_SHORT, &p.int_, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 13, SQLDT_SHORT, &p.dex, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 14, SQLDT_SHORT, &p.luk, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 15, SQLDT_INT, &p.max_hp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 16, SQLDT_INT, &p.hp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 17, SQLDT_INT, &p.max_sp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 18, SQLDT_INT, &p.sp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 19, SQLDT_UINT, &p.status_point, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 20, SQLDT_UINT, &p.skill_point, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 21, SQLDT_UINT, &p.option, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 22, SQLDT_UCHAR, &p.karma, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 23, SQLDT_SHORT, &p.manner, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 24, SQLDT_SHORT, &p.hair, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 25, SQLDT_SHORT, &p.hair_color, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 26, SQLDT_SHORT, &p.clothes_color, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 27, SQLDT_SHORT, &p.weapon, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 28, SQLDT_SHORT, &p.shield, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 29, SQLDT_SHORT, &p.head_top, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 30, SQLDT_SHORT, &p.head_mid, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 31, SQLDT_SHORT, &p.head_bottom, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 32, SQLDT_STRING, &last_map, sizeof(last_map), NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 33, SQLDT_SHORT, &p.rename, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 34, SQLDT_UINT32, &p.delete_date, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 35, SQLDT_SHORT, &p.robe, 0, NULL, NULL) + ) + { + SqlStmt_ShowDebug(stmt); + SqlStmt_Free(stmt); + return 0; + } + for( i = 0; i < MAX_CHARS && SQL_SUCCESS == SqlStmt_NextRow(stmt); i++ ) + { + if( p.delete_date && p.delete_date < time(NULL) ) { + delete_char_sql(p.char_id); + i--; continue; - if (sscanf(line, "%d%n",&i, &pos) < 1 || i != p->char_id) - continue; //Not this line... - //Read hotkeys - len = strlen(line); - next = pos; - for (count = 0; next < len && count < MAX_HOTKEYS; count++) - { - if (sscanf(line+next, ",%d,%d,%d%n",&type,&id,&lv, &pos) < 3) - //Invalid entry? - break; - p->hotkeys[count].type = type; - p->hotkeys[count].id = id; - p->hotkeys[count].lv = lv; - next+=pos; } - break; //Found hotkeys. + p.last_point.map = mapindex_name2id(last_map); + sd->found_char[i] = p.char_id; + j += mmo_char_tobuf(WBUFP(buf, j), &p); } - fclose(fp); - return count; -#else - return 0; -#endif -} + for( ; i < MAX_CHARS; i++ ) + sd->found_char[i] = -1; + memset(sd->new_name,0,sizeof(sd->new_name)); + SqlStmt_Free(stmt); + return j; +} -#ifndef TXT_SQL_CONVERT -//--------------------------------- -// Function to read characters file -//--------------------------------- -int mmo_char_init(void) +//===================================================================================================== +int mmo_char_fromsql(int char_id, struct mmo_charstatus* p, bool load_everything) { - char line[65536]; - int ret, line_count; - FILE* fp; + int i,j; + char t_msg[128] = ""; + struct mmo_charstatus* cp; + StringBuf buf; + SqlStmt* stmt; + char last_map[MAP_NAME_LENGTH_EXT]; + char save_map[MAP_NAME_LENGTH_EXT]; + char point_map[MAP_NAME_LENGTH_EXT]; + struct point tmp_point; + struct item tmp_item; + struct s_skill tmp_skill; + struct s_friend tmp_friend; +#ifdef HOTKEY_SAVING + struct hotkey tmp_hotkey; + int hotkey_num; +#endif - char_num = 0; - char_max = 0; - char_dat = NULL; + memset(p, 0, sizeof(struct mmo_charstatus)); + + if (save_log) ShowInfo("Char load request (%d)\n", char_id); - fp = fopen(char_txt, "r"); + stmt = SqlStmt_Malloc(sql_handle); + if( stmt == NULL ) + { + SqlStmt_ShowDebug(stmt); + return 0; + } - if (fp == NULL) { - ShowError("Characters file not found: %s.\n", char_txt); - char_log("Characters file not found: %s.\n", char_txt); - char_log("Id for the next created character: %d.\n", char_id_count); + // read char data + if( SQL_ERROR == SqlStmt_Prepare(stmt, "SELECT " + "`char_id`,`account_id`,`char_num`,`name`,`class`,`base_level`,`job_level`,`base_exp`,`job_exp`,`zeny`," + "`str`,`agi`,`vit`,`int`,`dex`,`luk`,`max_hp`,`hp`,`max_sp`,`sp`," + "`status_point`,`skill_point`,`option`,`karma`,`manner`,`party_id`,`guild_id`,`pet_id`,`homun_id`,`hair`," + "`hair_color`,`clothes_color`,`weapon`,`shield`,`head_top`,`head_mid`,`head_bottom`,`last_map`,`last_x`,`last_y`," + "`save_map`,`save_x`,`save_y`,`partner_id`,`father`,`mother`,`child`,`fame`,`rename`,`delete_date`,`robe`" + " FROM `%s` WHERE `char_id`=? LIMIT 1", char_db) + || SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0) + || SQL_ERROR == SqlStmt_Execute(stmt) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_INT, &p->char_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_INT, &p->account_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_UCHAR, &p->slot, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 3, SQLDT_STRING, &p->name, sizeof(p->name), NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 4, SQLDT_SHORT, &p->class_, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 5, SQLDT_UINT, &p->base_level, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 6, SQLDT_UINT, &p->job_level, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 7, SQLDT_UINT, &p->base_exp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 8, SQLDT_UINT, &p->job_exp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 9, SQLDT_INT, &p->zeny, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 10, SQLDT_SHORT, &p->str, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 11, SQLDT_SHORT, &p->agi, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 12, SQLDT_SHORT, &p->vit, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 13, SQLDT_SHORT, &p->int_, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 14, SQLDT_SHORT, &p->dex, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 15, SQLDT_SHORT, &p->luk, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 16, SQLDT_INT, &p->max_hp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 17, SQLDT_INT, &p->hp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 18, SQLDT_INT, &p->max_sp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 19, SQLDT_INT, &p->sp, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 20, SQLDT_UINT, &p->status_point, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 21, SQLDT_UINT, &p->skill_point, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 22, SQLDT_UINT, &p->option, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 23, SQLDT_UCHAR, &p->karma, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 24, SQLDT_SHORT, &p->manner, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 25, SQLDT_INT, &p->party_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 26, SQLDT_INT, &p->guild_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 27, SQLDT_INT, &p->pet_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 28, SQLDT_INT, &p->hom_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 29, SQLDT_SHORT, &p->hair, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 30, SQLDT_SHORT, &p->hair_color, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 31, SQLDT_SHORT, &p->clothes_color, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 32, SQLDT_SHORT, &p->weapon, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 33, SQLDT_SHORT, &p->shield, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 34, SQLDT_SHORT, &p->head_top, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 35, SQLDT_SHORT, &p->head_mid, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 36, SQLDT_SHORT, &p->head_bottom, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 37, SQLDT_STRING, &last_map, sizeof(last_map), NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 38, SQLDT_SHORT, &p->last_point.x, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 39, SQLDT_SHORT, &p->last_point.y, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 40, SQLDT_STRING, &save_map, sizeof(save_map), NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 41, SQLDT_SHORT, &p->save_point.x, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 42, SQLDT_SHORT, &p->save_point.y, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 43, SQLDT_INT, &p->partner_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 44, SQLDT_INT, &p->father, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 45, SQLDT_INT, &p->mother, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 46, SQLDT_INT, &p->child, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 47, SQLDT_INT, &p->fame, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 48, SQLDT_SHORT, &p->rename, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 49, SQLDT_UINT32, &p->delete_date, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 50, SQLDT_SHORT, &p->robe, 0, NULL, NULL) + ) + { + SqlStmt_ShowDebug(stmt); + SqlStmt_Free(stmt); return 0; } + if( SQL_ERROR == SqlStmt_NextRow(stmt) ) + { + ShowError("Requested non-existant character id: %d!\n", char_id); + SqlStmt_Free(stmt); + return 0; + } + p->last_point.map = mapindex_name2id(last_map); + p->save_point.map = mapindex_name2id(save_map); - line_count = 0; - while(fgets(line, sizeof(line), fp)) + strcat(t_msg, " status"); + + if (!load_everything) // For quick selection of data when displaying the char menu { - int i, j; - line_count++; + SqlStmt_Free(stmt); + return 1; + } - if (line[0] == '/' && line[1] == '/') - continue; + //read memo data + //`memo` (`memo_id`,`char_id`,`map`,`x`,`y`) + if( SQL_ERROR == SqlStmt_Prepare(stmt, "SELECT `map`,`x`,`y` FROM `%s` WHERE `char_id`=? ORDER by `memo_id` LIMIT %d", memo_db, MAX_MEMOPOINTS) + || SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0) + || SQL_ERROR == SqlStmt_Execute(stmt) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_STRING, &point_map, sizeof(point_map), NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_SHORT, &tmp_point.x, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_SHORT, &tmp_point.y, 0, NULL, NULL) ) + SqlStmt_ShowDebug(stmt); + + for( i = 0; i < MAX_MEMOPOINTS && SQL_SUCCESS == SqlStmt_NextRow(stmt); ++i ) + { + tmp_point.map = mapindex_name2id(point_map); + memcpy(&p->memo_point[i], &tmp_point, sizeof(tmp_point)); + } + strcat(t_msg, " memo"); + + //read inventory + //`inventory` (`id`,`char_id`, `nameid`, `amount`, `equip`, `identify`, `refine`, `attribute`, `card0`, `card1`, `card2`, `card3`) + StringBuf_Init(&buf); + StringBuf_AppendStr(&buf, "SELECT `id`, `nameid`, `amount`, `equip`, `identify`, `refine`, `attribute`, `expire_time`"); + for( i = 0; i < MAX_SLOTS; ++i ) + StringBuf_Printf(&buf, ", `card%d`", i); + StringBuf_Printf(&buf, " FROM `%s` WHERE `char_id`=? LIMIT %d", inventory_db, MAX_INVENTORY); + + if( SQL_ERROR == SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf)) + || SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0) + || SQL_ERROR == SqlStmt_Execute(stmt) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_INT, &tmp_item.id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_SHORT, &tmp_item.nameid, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_SHORT, &tmp_item.amount, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 3, SQLDT_USHORT, &tmp_item.equip, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 4, SQLDT_CHAR, &tmp_item.identify, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 5, SQLDT_CHAR, &tmp_item.refine, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 6, SQLDT_CHAR, &tmp_item.attribute, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 7, SQLDT_UINT, &tmp_item.expire_time, 0, NULL, NULL) ) + SqlStmt_ShowDebug(stmt); + for( i = 0; i < MAX_SLOTS; ++i ) + if( SQL_ERROR == SqlStmt_BindColumn(stmt, 8+i, SQLDT_SHORT, &tmp_item.card[i], 0, NULL, NULL) ) + SqlStmt_ShowDebug(stmt); + + for( i = 0; i < MAX_INVENTORY && SQL_SUCCESS == SqlStmt_NextRow(stmt); ++i ) + memcpy(&p->inventory[i], &tmp_item, sizeof(tmp_item)); + + strcat(t_msg, " inventory"); + + //read cart + //`cart_inventory` (`id`,`char_id`, `nameid`, `amount`, `equip`, `identify`, `refine`, `attribute`, `card0`, `card1`, `card2`, `card3`) + StringBuf_Clear(&buf); + StringBuf_AppendStr(&buf, "SELECT `id`, `nameid`, `amount`, `equip`, `identify`, `refine`, `attribute`, `expire_time`"); + for( j = 0; j < MAX_SLOTS; ++j ) + StringBuf_Printf(&buf, ", `card%d`", j); + StringBuf_Printf(&buf, " FROM `%s` WHERE `char_id`=? LIMIT %d", cart_db, MAX_CART); + + if( SQL_ERROR == SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf)) + || SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0) + || SQL_ERROR == SqlStmt_Execute(stmt) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_INT, &tmp_item.id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_SHORT, &tmp_item.nameid, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_SHORT, &tmp_item.amount, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 3, SQLDT_USHORT, &tmp_item.equip, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 4, SQLDT_CHAR, &tmp_item.identify, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 5, SQLDT_CHAR, &tmp_item.refine, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 6, SQLDT_CHAR, &tmp_item.attribute, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 7, SQLDT_UINT, &tmp_item.expire_time, 0, NULL, NULL) ) + SqlStmt_ShowDebug(stmt); + for( i = 0; i < MAX_SLOTS; ++i ) + if( SQL_ERROR == SqlStmt_BindColumn(stmt, 8+i, SQLDT_SHORT, &tmp_item.card[i], 0, NULL, NULL) ) + SqlStmt_ShowDebug(stmt); + + for( i = 0; i < MAX_CART && SQL_SUCCESS == SqlStmt_NextRow(stmt); ++i ) + memcpy(&p->cart[i], &tmp_item, sizeof(tmp_item)); + strcat(t_msg, " cart"); + + //read storage + storage_fromsql(p->account_id, &p->storage); + strcat(t_msg, " storage"); + + //read skill + //`skill` (`char_id`, `id`, `lv`) + if( SQL_ERROR == SqlStmt_Prepare(stmt, "SELECT `id`, `lv` FROM `%s` WHERE `char_id`=? LIMIT %d", skill_db, MAX_SKILL) + || SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0) + || SQL_ERROR == SqlStmt_Execute(stmt) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_USHORT, &tmp_skill.id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_USHORT, &tmp_skill.lv, 0, NULL, NULL) ) + SqlStmt_ShowDebug(stmt); + tmp_skill.flag = SKILL_FLAG_PERMANENT; + + for( i = 0; i < MAX_SKILL && SQL_SUCCESS == SqlStmt_NextRow(stmt); ++i ) + { + if( tmp_skill.id < ARRAYLENGTH(p->skill) ) + memcpy(&p->skill[tmp_skill.id], &tmp_skill, sizeof(tmp_skill)); + else + ShowWarning("mmo_char_fromsql: ignoring invalid skill (id=%u,lv=%u) of character %s (AID=%d,CID=%d)\n", tmp_skill.id, tmp_skill.lv, p->name, p->account_id, p->char_id); + } + strcat(t_msg, " skills"); + + //read friends + //`friends` (`char_id`, `friend_account`, `friend_id`) + if( SQL_ERROR == SqlStmt_Prepare(stmt, "SELECT c.`account_id`, c.`char_id`, c.`name` FROM `%s` c LEFT JOIN `%s` f ON f.`friend_account` = c.`account_id` AND f.`friend_id` = c.`char_id` WHERE f.`char_id`=? LIMIT %d", char_db, friend_db, MAX_FRIENDS) + || SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0) + || SQL_ERROR == SqlStmt_Execute(stmt) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_INT, &tmp_friend.account_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_INT, &tmp_friend.char_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_STRING, &tmp_friend.name, sizeof(tmp_friend.name), NULL, NULL) ) + SqlStmt_ShowDebug(stmt); + + for( i = 0; i < MAX_FRIENDS && SQL_SUCCESS == SqlStmt_NextRow(stmt); ++i ) + memcpy(&p->friends[i], &tmp_friend, sizeof(tmp_friend)); + strcat(t_msg, " friends"); - j = 0; - if (sscanf(line, "%d\t%%newid%%%n", &i, &j) == 1 && j > 0) { - if (char_id_count < i) - char_id_count = i; - continue; - } +#ifdef HOTKEY_SAVING + //read hotkeys + //`hotkey` (`char_id`, `hotkey`, `type`, `itemskill_id`, `skill_lvl` + if( SQL_ERROR == SqlStmt_Prepare(stmt, "SELECT `hotkey`, `type`, `itemskill_id`, `skill_lvl` FROM `%s` WHERE `char_id`=?", hotkey_db) + || SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0) + || SQL_ERROR == SqlStmt_Execute(stmt) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_INT, &hotkey_num, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_UCHAR, &tmp_hotkey.type, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_UINT, &tmp_hotkey.id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 3, SQLDT_USHORT, &tmp_hotkey.lv, 0, NULL, NULL) ) + SqlStmt_ShowDebug(stmt); + + while( SQL_SUCCESS == SqlStmt_NextRow(stmt) ) + { + if( hotkey_num >= 0 && hotkey_num < MAX_HOTKEYS ) + memcpy(&p->hotkeys[hotkey_num], &tmp_hotkey, sizeof(tmp_hotkey)); + else + ShowWarning("mmo_char_fromsql: ignoring invalid hotkey (hotkey=%d,type=%u,id=%u,lv=%u) of character %s (AID=%d,CID=%d)\n", hotkey_num, tmp_hotkey.type, tmp_hotkey.id, tmp_hotkey.lv, p->name, p->account_id, p->char_id); + } + strcat(t_msg, " hotkeys"); +#endif - if (char_num >= char_max) { - char_max += 256; - char_dat = (struct character_data*)aRealloc(char_dat, sizeof(struct character_data) * char_max); - if (!char_dat) { - ShowFatalError("Out of memory: mmo_char_init (realloc of char_dat).\n"); - char_log("Out of memory: mmo_char_init (realloc of char_dat).\n"); - exit(EXIT_FAILURE); - } - } + /* Mercenary Owner DataBase */ + mercenary_owner_fromsql(char_id, p); + strcat(t_msg, " mercenary"); - ret = mmo_char_fromstr(line, &char_dat[char_num].status, char_dat[char_num].global, &char_dat[char_num].global_num); - // Initialize friends list - parse_friend_txt(&char_dat[char_num].status); // Grab friends for the character - // Initialize hotkey list - parse_hotkey_txt(&char_dat[char_num].status); // Grab hotkeys for the character - - if (ret > 0) { // negative value or zero for errors - if (char_dat[char_num].status.char_id >= char_id_count) - char_id_count = char_dat[char_num].status.char_id + 1; - char_num++; - } else { - ShowError("mmo_char_init: in characters file, unable to read the line #%d.\n", line_count); - ShowError(" -> Character saved in log file.\n"); - switch (ret) { - case -1: - char_log("Duplicate character id in the next character line (character not readed):\n"); - break; - case -2: - char_log("Duplicate character name in the next character line (character not readed):\n"); - break; - case -3: - char_log("Invalid memo point structure in the next character line (character not readed):\n"); - break; - case -4: - char_log("Invalid inventory item structure in the next character line (character not readed):\n"); - break; - case -5: - char_log("Invalid cart item structure in the next character line (character not readed):\n"); - break; - case -6: - char_log("Invalid skill structure in the next character line (character not readed):\n"); - break; - case -7: - char_log("Invalid register structure in the next character line (character not readed):\n"); - break; - default: // 0 - char_log("Unabled to get a character in the next line - Basic structure of line (before inventory) is incorrect (character not readed):\n"); - break; - } - char_log("%s", line); - } - } - fclose(fp); + if (save_log) ShowInfo("Loaded char (%d - %s): %s\n", char_id, p->name, t_msg); //ok. all data load successfuly! + SqlStmt_Free(stmt); + StringBuf_Destroy(&buf); - if (char_num == 0) { - ShowNotice("mmo_char_init: No character found in %s.\n", char_txt); - char_log("mmo_char_init: No character found in %s.\n", char_txt); - } else if (char_num == 1) { - ShowStatus("mmo_char_init: 1 character read in %s.\n", char_txt); - char_log("mmo_char_init: 1 character read in %s.\n", char_txt); - } else { - ShowStatus("mmo_char_init: %d characters read in %s.\n", char_num, char_txt); - char_log("mmo_char_init: %d characters read in %s.\n", char_num, char_txt); + cp = (struct mmo_charstatus*)idb_ensure(char_db_, char_id, create_charstatus); + memcpy(cp, p, sizeof(struct mmo_charstatus)); + return 1; +} + +//========================================================================================================== +int mmo_char_sql_init(void) +{ + ShowInfo("Begin Initializing.......\n"); + char_db_= idb_alloc(DB_OPT_RELEASE_DATA); + + if(char_per_account == 0){ + ShowStatus("Chars per Account: 'Unlimited'.......\n"); + }else{ + ShowStatus("Chars per Account: '%d'.......\n", char_per_account); } - char_log("Id for the next created character: %d.\n", char_id_count); + //the 'set offline' part is now in check_login_conn ... + //if the server connects to loginserver + //it will dc all off players + //and send the loginserver the new state.... + + // Force all users offline in sql when starting char-server + // (useful when servers crashs and don't clean the database) + set_all_offline_sql(); + + ShowInfo("Finished initilizing.......\n"); return 0; } -//--------------------------------------------------------- -// Function to save characters in files (speed up by [Yor]) -//--------------------------------------------------------- -void mmo_char_sync(void) +//----------------------------------- +// Function to change chararcter's names +//----------------------------------- +int rename_char_sql(struct char_session_data *sd, int char_id) { - char line[65536],f_line[1024]; - int i, j, k; - int lock; - FILE *fp,*f_fp; - CREATE_BUFFER(id, int, char_num); - - // Sorting before save (by [Yor]) - for(i = 0; i < char_num; i++) { - id[i] = i; - for(j = 0; j < i; j++) { - if ((char_dat[i].status.account_id < char_dat[id[j]].status.account_id) || - // if same account id, we sort by slot. - (char_dat[i].status.account_id == char_dat[id[j]].status.account_id && - char_dat[i].status.slot < char_dat[id[j]].status.slot)) { - for(k = i; k > j; k--) - id[k] = id[k-1]; - id[j] = i; // id[i] - break; - } - } - } + struct mmo_charstatus char_dat; + char esc_name[NAME_LENGTH*2+1]; - // Data save - fp = lock_fopen(char_txt, &lock); - if (fp == NULL) { - ShowWarning("Server cannot save characters.\n"); - char_log("WARNING: Server cannot save characters.\n"); - } else { - for(i = 0; i < char_num; i++) { - mmo_char_tostr(line, &char_dat[id[i]].status, char_dat[id[i]].global, char_dat[id[i]].global_num); // use of sorted index - fprintf(fp, "%s\n", line); - } - fprintf(fp, "%d\t%%newid%%\n", char_id_count); - lock_fclose(fp, char_txt, &lock); - } + if( sd->new_name[0] == 0 ) // Not ready for rename + return 2; + + if( !mmo_char_fromsql(char_id, &char_dat, false) ) // Only the short data is needed. + return 2; - // Friends List data save (davidsiaw) - f_fp = lock_fopen(friends_txt, &lock); - for(i = 0; i < char_num; i++) { - mmo_friends_list_data_str(f_line, &char_dat[id[i]].status); - fprintf(f_fp, "%s\n", f_line); - } + if( char_dat.rename == 0 ) + return 1; - lock_fclose(f_fp, friends_txt, &lock); + Sql_EscapeStringLen(sql_handle, esc_name, sd->new_name, strnlen(sd->new_name, NAME_LENGTH)); -#ifdef HOTKEY_SAVING - // Hotkey List data save (Skotlex) - f_fp = lock_fopen(hotkeys_txt, &lock); - for(i = 0; i < char_num; i++) { - mmo_hotkeys_tostr(f_line, &char_dat[id[i]].status); - fprintf(f_fp, "%s\n", f_line); + // check if the char exist + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT 1 FROM `%s` WHERE `name` LIKE '%s' LIMIT 1", char_db, esc_name) ) + { + Sql_ShowDebug(sql_handle); + return 4; } - lock_fclose(f_fp, hotkeys_txt, &lock); -#endif + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `name` = '%s', `rename` = '%d' WHERE `char_id` = '%d'", char_db, esc_name, --char_dat.rename, char_id) ) + { + Sql_ShowDebug(sql_handle); + return 3; + } - DELETE_BUFFER(id); + // Change character's name into guild_db. + if( char_dat.guild_id ) + inter_guild_charname_changed(char_dat.guild_id, sd->account_id, char_id, sd->new_name); - return; -} + safestrncpy(char_dat.name, sd->new_name, NAME_LENGTH); + memset(sd->new_name,0,sizeof(sd->new_name)); + + // log change + if( log_char ) + { + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` (`time`, `char_msg`,`account_id`,`char_num`,`name`,`str`,`agi`,`vit`,`int`,`dex`,`luk`,`hair`,`hair_color`)" + "VALUES (NOW(), '%s', '%d', '%d', '%s', '0', '0', '0', '0', '0', '0', '0', '0')", + charlog_db, "change char name", sd->account_id, char_dat.slot, esc_name) ) + Sql_ShowDebug(sql_handle); + } -//---------------------------------------------------- -// Function to save (in a periodic way) datas in files -//---------------------------------------------------- -int mmo_char_sync_timer(int tid, unsigned int tick, int id, intptr_t data) -{ - if (save_log) - ShowInfo("Saving all files...\n"); - mmo_char_sync(); - inter_save(); return 0; } -int check_char_name(char * name) +int check_char_name(char * name, char * esc_name) { int i; // check length of character name if( name[0] == '\0' ) return -2; // empty character name - + /** + * The client does not allow you to create names with less than 4 characters, however, + * the use of WPE can bypass this, and this fixes the exploit. + **/ + if( strlen( name ) < 4 ) + return -2; // check content of character name if( remove_control_chars(name) ) return -2; // control chars in name @@ -1267,17 +1296,18 @@ int check_char_name(char * name) if( strchr(char_name_letters, name[i]) != NULL ) return -2; } - - // check name (already in use?) - if( name_ignoring_case ) - { - ARR_FIND( 0, char_num, i, strncmp(char_dat[i].status.name, name, NAME_LENGTH) == 0 ); - } - else - { - ARR_FIND( 0, char_num, i, strncmpi(char_dat[i].status.name, name, NAME_LENGTH) == 0 ); + if( name_ignoring_case ) { + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT 1 FROM `%s` WHERE BINARY `name` = '%s' LIMIT 1", char_db, esc_name) ) { + Sql_ShowDebug(sql_handle); + return -2; + } + } else { + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT 1 FROM `%s` WHERE `name` = '%s' LIMIT 1", char_db, esc_name) ) { + Sql_ShowDebug(sql_handle); + return -2; + } } - if( i < char_num ) + if( Sql_NumRows(sql_handle) > 0 ) return -1; // name already exists return 0; @@ -1286,15 +1316,17 @@ int check_char_name(char * name) //----------------------------------- // Function to create a new character //----------------------------------- -int make_new_char(struct char_session_data* sd, char* name_, int str, int agi, int vit, int int_, int dex, int luk, int slot, int hair_color, int hair_style) +int make_new_char_sql(struct char_session_data* sd, char* name_, int str, int agi, int vit, int int_, int dex, int luk, int slot, int hair_color, int hair_style) { char name[NAME_LENGTH]; - int i, flag; - + char esc_name[NAME_LENGTH*2+1]; + int char_id, flag; + safestrncpy(name, name_, NAME_LENGTH); normalize_name(name,TRIM_CHARS); + Sql_EscapeStringLen(sql_handle, esc_name, name, strnlen(name, NAME_LENGTH)); - flag = check_char_name(name); + flag = check_char_name(name,esc_name); if( flag < 0 ) return flag; @@ -1307,471 +1339,226 @@ int make_new_char(struct char_session_data* sd, char* name_, int str, int agi, i // check the number of already existing chars in this account if( char_per_account != 0 ) { - ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] == -1 ); - - if( i >= char_per_account ) + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT 1 FROM `%s` WHERE `account_id` = '%d'", char_db, sd->account_id) ) + Sql_ShowDebug(sql_handle); + if( Sql_NumRows(sql_handle) >= char_per_account ) return -2; // character account limit exceeded } // check char slot - ARR_FIND( 0, char_num, i, char_dat[i].status.account_id == sd->account_id && char_dat[i].status.slot == slot ); - if( i < char_num ) + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT 1 FROM `%s` WHERE `account_id` = '%d' AND `char_num` = '%d' LIMIT 1", char_db, sd->account_id, slot) ) + Sql_ShowDebug(sql_handle); + if( Sql_NumRows(sql_handle) > 0 ) return -2; // slot already in use - if (char_num >= char_max) { - char_max += 256; - RECREATE(char_dat, struct character_data, char_max); - if (!char_dat) { - ShowFatalError("Out of memory: make_new_char (realloc of char_dat).\n"); - char_log("Out of memory: make_new_char (realloc of char_dat).\n"); - exit(EXIT_FAILURE); - } + // validation success, log result + if (log_char) { + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` (`time`, `char_msg`,`account_id`,`char_num`,`name`,`str`,`agi`,`vit`,`int`,`dex`,`luk`,`hair`,`hair_color`)" + "VALUES (NOW(), '%s', '%d', '%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')", + charlog_db, "make new char", sd->account_id, slot, esc_name, str, agi, vit, int_, dex, luk, hair_style, hair_color) ) + Sql_ShowDebug(sql_handle); } - // validation success, log result - char_log("make new char: account: %d, slot %d, name: %s, stats: %d/%d/%d/%d/%d/%d, hair: %d, hair color: %d.\n", - sd->account_id, slot, name, str, agi, vit, int_, dex, luk, hair_style, hair_color); - - i = char_num; - memset(&char_dat[i], 0, sizeof(struct character_data)); - - char_dat[i].status.char_id = char_id_count++; - char_dat[i].status.account_id = sd->account_id; - char_dat[i].status.slot = slot; - safestrncpy(char_dat[i].status.name,name,NAME_LENGTH); - char_dat[i].status.class_ = 0; - char_dat[i].status.base_level = 1; - char_dat[i].status.job_level = 1; - char_dat[i].status.base_exp = 0; - char_dat[i].status.job_exp = 0; - char_dat[i].status.zeny = start_zeny; - char_dat[i].status.str = str; - char_dat[i].status.agi = agi; - char_dat[i].status.vit = vit; - char_dat[i].status.int_ = int_; - char_dat[i].status.dex = dex; - char_dat[i].status.luk = luk; - char_dat[i].status.max_hp = 40 * (100 + char_dat[i].status.vit) / 100; - char_dat[i].status.max_sp = 11 * (100 + char_dat[i].status.int_) / 100; - char_dat[i].status.hp = char_dat[i].status.max_hp; - char_dat[i].status.sp = char_dat[i].status.max_sp; - char_dat[i].status.status_point = 0; - char_dat[i].status.skill_point = 0; - char_dat[i].status.option = 0; - char_dat[i].status.karma = 0; - char_dat[i].status.manner = 0; - char_dat[i].status.party_id = 0; - char_dat[i].status.guild_id = 0; - char_dat[i].status.hair = hair_style; - char_dat[i].status.hair_color = hair_color; - char_dat[i].status.clothes_color = 0; - char_dat[i].status.inventory[0].nameid = start_weapon; // Knife - char_dat[i].status.inventory[0].amount = 1; - char_dat[i].status.inventory[0].identify = 1; - char_dat[i].status.inventory[1].nameid = start_armor; // Cotton Shirt - char_dat[i].status.inventory[1].amount = 1; - char_dat[i].status.inventory[1].identify = 1; - char_dat[i].status.weapon = 0; // W_FIST - char_dat[i].status.shield = 0; - char_dat[i].status.head_top = 0; - char_dat[i].status.head_mid = 0; - char_dat[i].status.head_bottom = 0; - memcpy(&char_dat[i].status.last_point, &start_point, sizeof(start_point)); - memcpy(&char_dat[i].status.save_point, &start_point, sizeof(start_point)); - char_num++; - - ShowInfo("Created char: account: %d, char: %d, slot: %d, name: %s\n", sd->account_id, i, slot, name); - mmo_char_sync(); - return i; + //Insert the new char entry to the database + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` (`account_id`, `char_num`, `name`, `zeny`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `max_hp`, `hp`," + "`max_sp`, `sp`, `hair`, `hair_color`, `last_map`, `last_x`, `last_y`, `save_map`, `save_x`, `save_y`) VALUES (" + "'%d', '%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d','%d', '%d','%d', '%d', '%s', '%d', '%d', '%s', '%d', '%d')", + char_db, sd->account_id , slot, esc_name, start_zeny, str, agi, vit, int_, dex, luk, + (40 * (100 + vit)/100) , (40 * (100 + vit)/100 ), (11 * (100 + int_)/100), (11 * (100 + int_)/100), hair_style, hair_color, + mapindex_id2name(start_point.map), start_point.x, start_point.y, mapindex_id2name(start_point.map), start_point.x, start_point.y) ) + { + Sql_ShowDebug(sql_handle); + return -2; //No, stop the procedure! + } + //Retrieve the newly auto-generated char id + char_id = (int)Sql_LastInsertId(sql_handle); + //Give the char the default items + if (start_weapon > 0) { //add Start Weapon (Knife?) + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` (`char_id`,`nameid`, `amount`, `identify`) VALUES ('%d', '%d', '%d', '%d')", inventory_db, char_id, start_weapon, 1, 1) ) + Sql_ShowDebug(sql_handle); + } + if (start_armor > 0) { //Add default armor (cotton shirt?) + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` (`char_id`,`nameid`, `amount`, `identify`) VALUES ('%d', '%d', '%d', '%d')", inventory_db, char_id, start_armor, 1, 1) ) + Sql_ShowDebug(sql_handle); + } + + ShowInfo("Created char: account: %d, char: %d, slot: %d, name: %s\n", sd->account_id, char_id, slot, name); + return char_id; } -//---------------------------------------------------- -// This function return the name of the job (by [Yor]) -//---------------------------------------------------- -char * job_name(int class_) +/*----------------------------------------------------------------------------------------------------------*/ +/* Divorce Players */ +/*----------------------------------------------------------------------------------------------------------*/ +int divorce_char_sql(int partner_id1, int partner_id2) { - switch (class_) { - case JOB_NOVICE: return "Novice"; - case JOB_SWORDMAN: return "Swordsman"; - case JOB_MAGE: return "Mage"; - case JOB_ARCHER: return "Archer"; - case JOB_ACOLYTE: return "Acolyte"; - case JOB_MERCHANT: return "Merchant"; - case JOB_THIEF: return "Thief"; - case JOB_KNIGHT: return "Knight"; - case JOB_PRIEST: return "Priest"; - case JOB_WIZARD: return "Wizard"; - case JOB_BLACKSMITH: return "Blacksmith"; - case JOB_HUNTER: return "Hunter"; - case JOB_ASSASSIN: return "Assassin"; - case JOB_KNIGHT2: return "Peco-Knight"; - case JOB_CRUSADER: return "Crusader"; - case JOB_MONK: return "Monk"; - case JOB_SAGE: return "Sage"; - case JOB_ROGUE: return "Rogue"; - case JOB_ALCHEMIST: return "Alchemist"; - case JOB_BARD: return "Bard"; - case JOB_DANCER: return "Dancer"; - case JOB_CRUSADER2: return "Peco-Crusader"; - case JOB_WEDDING: return "Wedding"; - case JOB_SUPER_NOVICE: return "Super Novice"; - case JOB_GUNSLINGER: return "Gunslinger"; - case JOB_NINJA: return "Ninja"; - case JOB_XMAS: return "Christmas"; - case JOB_NOVICE_HIGH: return "Novice High"; - case JOB_SWORDMAN_HIGH: return "Swordsman High"; - case JOB_MAGE_HIGH: return "Mage High"; - case JOB_ARCHER_HIGH: return "Archer High"; - case JOB_ACOLYTE_HIGH: return "Acolyte High"; - case JOB_MERCHANT_HIGH: return "Merchant High"; - case JOB_THIEF_HIGH: return "Thief High"; - case JOB_LORD_KNIGHT: return "Lord Knight"; - case JOB_HIGH_PRIEST: return "High Priest"; - case JOB_HIGH_WIZARD: return "High Wizard"; - case JOB_WHITESMITH: return "Whitesmith"; - case JOB_SNIPER: return "Sniper"; - case JOB_ASSASSIN_CROSS: return "Assassin Cross"; - case JOB_LORD_KNIGHT2: return "Peko Knight"; - case JOB_PALADIN: return "Paladin"; - case JOB_CHAMPION: return "Champion"; - case JOB_PROFESSOR: return "Professor"; - case JOB_STALKER: return "Stalker"; - case JOB_CREATOR: return "Creator"; - case JOB_CLOWN: return "Clown"; - case JOB_GYPSY: return "Gypsy"; - case JOB_PALADIN2: return "Peko Paladin"; - case JOB_BABY: return "Baby Novice"; - case JOB_BABY_SWORDMAN: return "Baby Swordsman"; - case JOB_BABY_MAGE: return "Baby Mage"; - case JOB_BABY_ARCHER: return "Baby Archer"; - case JOB_BABY_ACOLYTE: return "Baby Acolyte"; - case JOB_BABY_MERCHANT: return "Baby Merchant"; - case JOB_BABY_THIEF: return "Baby Thief"; - case JOB_BABY_KNIGHT: return "Baby Knight"; - case JOB_BABY_PRIEST: return "Baby Priest"; - case JOB_BABY_WIZARD: return "Baby Wizard"; - case JOB_BABY_BLACKSMITH: return "Baby Blacksmith"; - case JOB_BABY_HUNTER: return "Baby Hunter"; - case JOB_BABY_ASSASSIN: return "Baby Assassin"; - case JOB_BABY_KNIGHT2: return "Baby Peco Knight"; - case JOB_BABY_CRUSADER: return "Baby Crusader"; - case JOB_BABY_MONK: return "Baby Monk"; - case JOB_BABY_SAGE: return "Baby Sage"; - case JOB_BABY_ROGUE: return "Baby Rogue"; - case JOB_BABY_ALCHEMIST: return "Baby Alchemist"; - case JOB_BABY_BARD: return "Baby Bard"; - case JOB_BABY_DANCER: return "Baby Dancer"; - case JOB_BABY_CRUSADER2: return "Baby Peco Crusader"; - case JOB_SUPER_BABY: return "Super Baby"; - case JOB_TAEKWON: return "Taekwon"; - case JOB_STAR_GLADIATOR: return "Star Gladiator"; - case JOB_STAR_GLADIATOR2: return "Flying Star Gladiator"; - case JOB_SOUL_LINKER: return "Soul Linker"; - } - return "Unknown Job"; + unsigned char buf[64]; + + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `partner_id`='0' WHERE `char_id`='%d' OR `char_id`='%d' LIMIT 2", char_db, partner_id1, partner_id2) ) + Sql_ShowDebug(sql_handle); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE (`nameid`='%d' OR `nameid`='%d') AND (`char_id`='%d' OR `char_id`='%d') LIMIT 2", inventory_db, WEDDING_RING_M, WEDDING_RING_F, partner_id1, partner_id2) ) + Sql_ShowDebug(sql_handle); + + WBUFW(buf,0) = 0x2b12; + WBUFL(buf,2) = partner_id1; + WBUFL(buf,6) = partner_id2; + mapif_sendall(buf,10); + + return 0; } -static int create_online_files_sub(DBKey key, void* data, va_list va) +/*----------------------------------------------------------------------------------------------------------*/ +/* Delete char - davidsiaw */ +/*----------------------------------------------------------------------------------------------------------*/ +/* Returns 0 if successful + * Returns < 0 for error + */ +int delete_char_sql(int char_id) { - struct online_char_data *character; - int* players; - int *id; - int j,k,l; - character = (struct online_char_data*) data; - players = va_arg(va, int*); - id = va_arg(va, int*); - - // check if map-server is online - if (character->server == -1 || character->char_id == -1) { //Character not currently online. + char name[NAME_LENGTH]; + char esc_name[NAME_LENGTH*2+1]; //Name needs be escaped. + int account_id, party_id, guild_id, hom_id, base_level, partner_id, father_id, mother_id; + char* data; + size_t len; + + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `name`,`account_id`,`party_id`,`guild_id`,`base_level`,`homun_id`,`partner_id`,`father`,`mother` FROM `%s` WHERE `char_id`='%d'", char_db, char_id) ) + Sql_ShowDebug(sql_handle); + + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + { + ShowError("delete_char_sql: Unable to fetch character data, deletion aborted.\n"); + Sql_FreeResult(sql_handle); return -1; } - - j = character->server; - if (server[j].fd < 0) { - server[j].users = 0; - return -1; + + Sql_GetData(sql_handle, 0, &data, &len); safestrncpy(name, data, NAME_LENGTH); + Sql_GetData(sql_handle, 1, &data, NULL); account_id = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); party_id = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); guild_id = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); base_level = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); hom_id = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); partner_id = atoi(data); + Sql_GetData(sql_handle, 7, &data, NULL); father_id = atoi(data); + Sql_GetData(sql_handle, 8, &data, NULL); mother_id = atoi(data); + + Sql_EscapeStringLen(sql_handle, esc_name, name, min(len, NAME_LENGTH)); + Sql_FreeResult(sql_handle); + + //check for config char del condition [Lupus] + // TODO: Move this out to packet processing (0x68/0x1fb). + if( ( char_del_level > 0 && base_level >= char_del_level ) + || ( char_del_level < 0 && base_level <= -char_del_level ) + ) { + ShowInfo("Char deletion aborted: %s, BaseLevel: %i\n", name, base_level); + return -1; } - // search position of character in char_dat and sort online characters. - for(j = 0; j < char_num; j++) { - if (char_dat[j].status.char_id != character->char_id) - continue; - id[*players] = j; - // use sorting option - switch (online_sorting_option) { - case 1: // by name (without case sensitive) - for(k = 0; k < *players; k++) - if (stricmp(char_dat[j].status.name, char_dat[id[k]].status.name) < 0 || - // if same name, we sort with case sensitive. - (stricmp(char_dat[j].status.name, char_dat[id[k]].status.name) == 0 && - strcmp(char_dat[j].status.name, char_dat[id[k]].status.name) < 0)) { - for(l = *players; l > k; l--) - id[l] = id[l-1]; - id[k] = j; // id[*players] - break; - } - break; - case 2: // by zeny - for(k = 0; k < *players; k++) - if (char_dat[j].status.zeny < char_dat[id[k]].status.zeny || - // if same number of zenys, we sort by name. - (char_dat[j].status.zeny == char_dat[id[k]].status.zeny && - stricmp(char_dat[j].status.name, char_dat[id[k]].status.name) < 0)) { - for(l = *players; l > k; l--) - id[l] = id[l-1]; - id[k] = j; // id[*players] - break; - } - break; - case 3: // by base level - for(k = 0; k < *players; k++) - if (char_dat[j].status.base_level < char_dat[id[k]].status.base_level || - // if same base level, we sort by base exp. - (char_dat[j].status.base_level == char_dat[id[k]].status.base_level && - char_dat[j].status.base_exp < char_dat[id[k]].status.base_exp)) { - for(l = *players; l > k; l--) - id[l] = id[l-1]; - id[k] = j; // id[*players] - break; - } - break; - case 4: // by job (and job level) - for(k = 0; k < *players; k++) - if (char_dat[j].status.class_ < char_dat[id[k]].status.class_ || - // if same job, we sort by job level. - (char_dat[j].status.class_ == char_dat[id[k]].status.class_ && - char_dat[j].status.job_level < char_dat[id[k]].status.job_level) || - // if same job and job level, we sort by job exp. - (char_dat[j].status.class_ == char_dat[id[k]].status.class_ && - char_dat[j].status.job_level == char_dat[id[k]].status.job_level && - char_dat[j].status.job_exp < char_dat[id[k]].status.job_exp)) { - for(l = *players; l > k; l--) - id[l] = id[l-1]; - id[k] = j; // id[*players] - break; - } - break; - case 5: // by location map name - { - const char *map1, *map2; - map1 = mapindex_id2name(char_dat[j].status.last_point.map); - - for(k = 0; k < *players; k++) { - map2 = mapindex_id2name(char_dat[id[k]].status.last_point.map); - if (!map1 || !map2 || //Avoid sorting if either one failed to resolve. - stricmp(map1, map2) < 0 || - // if same map name, we sort by name. - (stricmp(map1, map2) == 0 && - stricmp(char_dat[j].status.name, char_dat[id[k]].status.name) < 0)) { - for(l = *players; l > k; l--) - id[l] = id[l-1]; - id[k] = j; // id[*players] - break; - } - } - } - break; - default: // 0 or invalid value: no sorting - break; - } - (*players)++; - break; + + /* Divorce [Wizputer] */ + if( partner_id ) + divorce_char_sql(char_id, partner_id); + + /* De-addopt [Zephyrus] */ + if( father_id || mother_id ) + { // Char is Baby + unsigned char buf[64]; + + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `child`='0' WHERE `char_id`='%d' OR `char_id`='%d'", char_db, father_id, mother_id) ) + Sql_ShowDebug(sql_handle); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `id` = '410'AND (`char_id`='%d' OR `char_id`='%d')", skill_db, father_id, mother_id) ) + Sql_ShowDebug(sql_handle); + + WBUFW(buf,0) = 0x2b25; + WBUFL(buf,2) = father_id; + WBUFL(buf,6) = mother_id; + WBUFL(buf,10) = char_id; // Baby + mapif_sendall(buf,14); } - return 0; -} -//------------------------------------------------------------- -// Function to create the online files (txt and html). by [Yor] -//------------------------------------------------------------- -void create_online_files(void) -{ - unsigned int k, j; // for loop with strlen comparing - int i, l; // for loops - int players; // count the number of players - FILE *fp; // for the txt file - FILE *fp2; // for the html file - char temp[256]; // to prepare what we must display - time_t time_server; // for number of seconds - struct tm *datetime; // variable for time in structure ->tm_mday, ->tm_sec, ... - int id[4096]; - - if (online_display_option == 0) // we display nothing, so return - return; - // Get number of online players, id of each online players, and verify if a server is offline - players = 0; - online_char_db->foreach(online_char_db, create_online_files_sub, &players, &id); - - // write files - fp = fopen(online_txt_filename, "w"); - if (fp != NULL) { - fp2 = fopen(online_html_filename, "w"); - if (fp2 != NULL) { - // get time - time(&time_server); // get time in seconds since 1/1/1970 - datetime = localtime(&time_server); // convert seconds in structure - strftime(temp, sizeof(temp), "%d %b %Y %X", datetime); // like sprintf, but only for date/time (05 dec 2003 15:12:52) - // write heading - fprintf(fp2, "<HTML>\n"); - fprintf(fp2, " <META http-equiv=\"Refresh\" content=\"%d\">\n", online_refresh_html); // update on client explorer every x seconds - fprintf(fp2, " <HEAD>\n"); - fprintf(fp2, " <TITLE>Online Players on %s</TITLE>\n", server_name); - fprintf(fp2, " </HEAD>\n"); - fprintf(fp2, " <BODY>\n"); - fprintf(fp2, " <H3>Online Players on %s (%s):</H3>\n", server_name, temp); - fprintf(fp, "Online Players on %s (%s):\n", server_name, temp); - fprintf(fp, "\n"); - - for (i = 0; i < players; i++) { - // if it's the first player - if (i == 0) { - j = 0; // count the number of characters for the txt version and to set the separate line - fprintf(fp2, " <table border=\"1\" cellspacing=\"1\">\n"); - fprintf(fp2, " <tr>\n"); - if ((online_display_option & 1) || (online_display_option & 64)) { - fprintf(fp2, " <td><b>Name</b></td>\n"); - if (online_display_option & 64) { - fprintf(fp, "Name "); // 30 - j += 30; - } else { - fprintf(fp, "Name "); // 25 - j += 25; - } - } - if ((online_display_option & 6) == 6) { - fprintf(fp2, " <td><b>Job (levels)</b></td>\n"); - fprintf(fp, "Job Levels "); // 27 - j += 27; - } else if (online_display_option & 2) { - fprintf(fp2, " <td><b>Job</b></td>\n"); - fprintf(fp, "Job "); // 19 - j += 19; - } else if (online_display_option & 4) { - fprintf(fp2, " <td><b>Levels</b></td>\n"); - fprintf(fp, " Levels "); // 8 - j += 8; - } - if (online_display_option & 24) { // 8 or 16 - fprintf(fp2, " <td><b>Location</b></td>\n"); - if (online_display_option & 16) { - fprintf(fp, "Location ( x , y ) "); // 23 - j += 23; - } else { - fprintf(fp, "Location "); // 13 - j += 13; - } - } - if (online_display_option & 32) { - fprintf(fp2, " <td ALIGN=CENTER><b>zenys</b></td>\n"); - fprintf(fp, " Zenys "); // 16 - j += 16; - } - fprintf(fp2, " </tr>\n"); - fprintf(fp, "\n"); - for (k = 0; k < j; k++) - fprintf(fp, "-"); - fprintf(fp, "\n"); - } - fprintf(fp2, " <tr>\n"); - // get id of the character (more speed) - j = id[i]; - // displaying the character name - if ((online_display_option & 1) || (online_display_option & 64)) { // without/with 'GM' display - safestrncpy(temp, char_dat[j].status.name, sizeof(temp)); - //l = isGM(char_dat[j].status.account_id); - l = 0; //FIXME: how to get the gm level? - if (online_display_option & 64) { - if (l >= online_gm_display_min_level) - fprintf(fp, "%-24s (GM) ", temp); - else - fprintf(fp, "%-24s ", temp); - } else - fprintf(fp, "%-24s ", temp); - // name of the character in the html (no < >, because that create problem in html code) - fprintf(fp2, " <td>"); - if ((online_display_option & 64) && l >= online_gm_display_min_level) - fprintf(fp2, "<b>"); - for (k = 0; k < strlen(temp); k++) { - switch(temp[k]) { - case '<': // < - fprintf(fp2, "<"); - break; - case '>': // > - fprintf(fp2, ">"); - break; - default: - fprintf(fp2, "%c", temp[k]); - break; - }; - } - if ((online_display_option & 64) && l >= online_gm_display_min_level) - fprintf(fp2, "</b> (GM)"); - fprintf(fp2, "</td>\n"); - } - // displaying of the job - if (online_display_option & 6) { - char * jobname = job_name(char_dat[j].status.class_); - if ((online_display_option & 6) == 6) { - fprintf(fp2, " <td>%s %d/%d</td>\n", jobname, char_dat[j].status.base_level, char_dat[j].status.job_level); - fprintf(fp, "%-18s %3d/%3d ", jobname, char_dat[j].status.base_level, char_dat[j].status.job_level); - } else if (online_display_option & 2) { - fprintf(fp2, " <td>%s</td>\n", jobname); - fprintf(fp, "%-18s ", jobname); - } else if (online_display_option & 4) { - fprintf(fp2, " <td>%d/%d</td>\n", char_dat[j].status.base_level, char_dat[j].status.job_level); - fprintf(fp, "%3d/%3d ", char_dat[j].status.base_level, char_dat[j].status.job_level); - } - } - // displaying of the map - if (online_display_option & 24) { // 8 or 16 - // prepare map name - safestrncpy(temp, mapindex_id2name(char_dat[j].status.last_point.map), sizeof(temp)); - // write map name - if (online_display_option & 16) { // map-name AND coordinates - fprintf(fp2, " <td>%s (%d, %d)</td>\n", temp, char_dat[j].status.last_point.x, char_dat[j].status.last_point.y); - fprintf(fp, "%-12s (%3d,%3d) ", temp, char_dat[j].status.last_point.x, char_dat[j].status.last_point.y); - } else { - fprintf(fp2, " <td>%s</td>\n", temp); - fprintf(fp, "%-12s ", temp); - } - } - // displaying nimber of zenys - if (online_display_option & 32) { - // write number of zenys - if (char_dat[j].status.zeny == 0) { // if no zeny - fprintf(fp2, " <td ALIGN=RIGHT>no zeny</td>\n"); - fprintf(fp, " no zeny "); - } else { - fprintf(fp2, " <td ALIGN=RIGHT>%d z</td>\n", char_dat[j].status.zeny); - fprintf(fp, "%13d z ", char_dat[j].status.zeny); - } - } - fprintf(fp, "\n"); - fprintf(fp2, " </tr>\n"); - } - // If we display at least 1 player - if (players > 0) { - fprintf(fp2, " </table>\n"); - fprintf(fp, "\n"); - } + //Make the character leave the party [Skotlex] + if (party_id) + inter_party_leave(party_id, account_id, char_id); - // Displaying number of online players - if (players == 0) { - fprintf(fp2, " <p>No user is online.</p>\n"); - fprintf(fp, "No user is online.\n"); - } else if (players == 1) { - fprintf(fp2, " <p>%d user is online.</p>\n", players); - fprintf(fp, "%d user is online.\n", players); - } else { - fprintf(fp2, " <p>%d users are online.</p>\n", players); - fprintf(fp, "%d users are online.\n", players); - } - fprintf(fp2, " </BODY>\n"); - fprintf(fp2, "</HTML>\n"); - fclose(fp2); - } - fclose(fp); + /* delete char's pet */ + //Delete the hatched pet if you have one... + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d' AND `incuvate` = '0'", pet_db, char_id) ) + Sql_ShowDebug(sql_handle); + + //Delete all pets that are stored in eggs (inventory + cart) + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` USING `%s` JOIN `%s` ON `pet_id` = `card1`|`card2`<<16 WHERE `%s`.char_id = '%d' AND card0 = -256", pet_db, pet_db, inventory_db, inventory_db, char_id) ) + Sql_ShowDebug(sql_handle); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` USING `%s` JOIN `%s` ON `pet_id` = `card1`|`card2`<<16 WHERE `%s`.char_id = '%d' AND card0 = -256", pet_db, pet_db, cart_db, cart_db, char_id) ) + Sql_ShowDebug(sql_handle); + + /* remove homunculus */ + if( hom_id ) + mapif_homunculus_delete(hom_id); + + /* remove mercenary data */ + mercenary_owner_delete(char_id); + + /* delete char's friends list */ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id` = '%d'", friend_db, char_id) ) + Sql_ShowDebug(sql_handle); + + /* delete char from other's friend list */ + //NOTE: Won't this cause problems for people who are already online? [Skotlex] + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `friend_id` = '%d'", friend_db, char_id) ) + Sql_ShowDebug(sql_handle); + +#ifdef HOTKEY_SAVING + /* delete hotkeys */ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", hotkey_db, char_id) ) + Sql_ShowDebug(sql_handle); +#endif + + /* delete inventory */ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", inventory_db, char_id) ) + Sql_ShowDebug(sql_handle); + + /* delete cart inventory */ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", cart_db, char_id) ) + Sql_ShowDebug(sql_handle); + + /* delete memo areas */ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", memo_db, char_id) ) + Sql_ShowDebug(sql_handle); + + /* delete character registry */ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `type`=3 AND `char_id`='%d'", reg_db, char_id) ) + Sql_ShowDebug(sql_handle); + + /* delete skills */ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", skill_db, char_id) ) + Sql_ShowDebug(sql_handle); + +#ifdef ENABLE_SC_SAVING + /* status changes */ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id` = '%d' AND `char_id`='%d'", scdata_db, account_id, char_id) ) + Sql_ShowDebug(sql_handle); +#endif + + if (log_char) { + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s`(`time`, `account_id`,`char_num`,`char_msg`,`name`) VALUES (NOW(), '%d', '%d', 'Deleted char (CID %d)', '%s')", + charlog_db, account_id, 0, char_id, esc_name) ) + Sql_ShowDebug(sql_handle); } - return; + /* delete character */ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", char_db, char_id) ) + Sql_ShowDebug(sql_handle); + + /* No need as we used inter_guild_leave [Skotlex] + // Also delete info from guildtables. + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d'", guild_member_db, char_id) ) + Sql_ShowDebug(sql_handle); + */ + + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `guild_id` FROM `%s` WHERE `char_id` = '%d'", guild_db, char_id) ) + Sql_ShowDebug(sql_handle); + else if( Sql_NumRows(sql_handle) > 0 ) + mapif_parse_BreakGuild(0,guild_id); + else if( guild_id ) + inter_guild_leave(guild_id, account_id, char_id);// Leave your guild. + return 0; } //--------------------------------------------------------------------- @@ -1828,7 +1615,10 @@ int mmo_char_tobuf(uint8* buffer, struct mmo_charstatus* p) WBUFW(buf,50) = DEFAULT_WALK_SPEED; // p->speed; WBUFW(buf,52) = p->class_; WBUFW(buf,54) = p->hair; - WBUFW(buf,56) = p->option&0x20 ? 0 : p->weapon; //When the weapon is sent and your option is riding, the client crashes on login!? + + //When the weapon is sent and your option is riding, the client crashes on login!? + WBUFW(buf,56) = p->option&(0x20|0x80000|0x100000|0x200000|0x400000|0x800000|0x1000000|0x2000000|0x4000000|0x8000000) ? 0 : p->weapon; + WBUFW(buf,58) = p->base_level; WBUFW(buf,60) = min(p->skill_point, INT16_MAX); WBUFW(buf,62) = p->head_bottom; @@ -1861,14 +1651,17 @@ int mmo_char_tobuf(uint8* buffer, struct mmo_charstatus* p) WBUFL(buf,128) = p->robe; offset += 4; #endif -#if PACKETVER >= 20110928 - WBUFL(buf,132) = 0; // change slot feature (0 = disabled, otherwise enabled) - offset += 4; -#endif -#if PACKETVER >= 20111025 - WBUFL(buf,136) = 0; // unknown purpose (0 = disabled, otherwise displays "Add-Ons" sidebar) - offset += 4; +#if PACKETVER != 20111116 //2011-11-16 wants 136, ask gravity. + #if PACKETVER >= 20110928 + WBUFL(buf,132) = 0; // change slot feature (0 = disabled, otherwise enabled) + offset += 4; + #endif + #if PACKETVER >= 20111025 + WBUFL(buf,136) = 0; // unknown purpose (0 = disabled, otherwise displays "Add-Ons" sidebar) + offset += 4; + #endif #endif + return 106+offset; } @@ -1877,15 +1670,16 @@ int mmo_char_tobuf(uint8* buffer, struct mmo_charstatus* p) //---------------------------------------- int mmo_char_send006b(int fd, struct char_session_data* sd) { - int i, j, found_num, offset = 0; + int j, offset = 0; #if PACKETVER >= 20100413 offset += 3; #endif - found_num = char_find_characters(sd); + if (save_log) + ShowInfo("Loading Char Data ("CL_BOLD"%d"CL_RESET")\n",sd->account_id); j = 24 + offset; // offset - WFIFOHEAD(fd,j + found_num*MAX_CHAR_BUF); + WFIFOHEAD(fd,j + MAX_CHARS*MAX_CHAR_BUF); WFIFOW(fd,0) = 0x6b; #if PACKETVER >= 20100413 WFIFOB(fd,4) = MAX_CHARS; // Max slots. @@ -1893,80 +1687,75 @@ int mmo_char_send006b(int fd, struct char_session_data* sd) WFIFOB(fd,6) = MAX_CHARS; // Premium slots. #endif memset(WFIFOP(fd,4 + offset), 0, 20); // unknown bytes - for(i = 0; i < found_num; i++) - j += mmo_char_tobuf(WFIFOP(fd,j), &char_dat[sd->found_char[i]].status); + j+=mmo_chars_fromsql(sd, WFIFOP(fd,j)); WFIFOW(fd,2) = j; // packet len WFIFOSET(fd,j); return 0; } -// 離婚(char削除時に使用) -int char_divorce(struct mmo_charstatus *cs) +int char_married(int pl1, int pl2) { - if (cs == NULL) - return 0; + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `partner_id` FROM `%s` WHERE `char_id` = '%d'", char_db, pl1) ) + Sql_ShowDebug(sql_handle); + else if( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + char* data; - if (cs->partner_id > 0){ - int i, j; - for(i = 0; i < char_num; i++) { - if (char_dat[i].status.char_id == cs->partner_id && char_dat[i].status.partner_id == cs->char_id) { - cs->partner_id = 0; - char_dat[i].status.partner_id = 0; - for(j = 0; j < MAX_INVENTORY; j++) - { - if (char_dat[i].status.inventory[j].nameid == WEDDING_RING_M || char_dat[i].status.inventory[j].nameid == WEDDING_RING_F) - memset(&char_dat[i].status.inventory[j], 0, sizeof(char_dat[i].status.inventory[0])); - if (cs->inventory[j].nameid == WEDDING_RING_M || cs->inventory[j].nameid == WEDDING_RING_F) - memset(&cs->inventory[j], 0, sizeof(cs->inventory[0])); - } - return 0; - } + Sql_GetData(sql_handle, 0, &data, NULL); + if( pl2 == atoi(data) ) + { + Sql_FreeResult(sql_handle); + return 1; } } + Sql_FreeResult(sql_handle); return 0; } -int char_married(int pl1, int pl2) -{ - return (char_dat[pl1].status.char_id == char_dat[pl2].status.partner_id && char_dat[pl2].status.char_id == char_dat[pl1].status.partner_id); -} - int char_child(int parent_id, int child_id) { - return (char_dat[parent_id].status.child == char_dat[child_id].status.char_id && - ((char_dat[parent_id].status.char_id == char_dat[child_id].status.father) || - (char_dat[parent_id].status.char_id == char_dat[child_id].status.mother))); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `child` FROM `%s` WHERE `char_id` = '%d'", char_db, parent_id) ) + Sql_ShowDebug(sql_handle); + else if( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + char* data; + + Sql_GetData(sql_handle, 0, &data, NULL); + if( child_id == atoi(data) ) + { + Sql_FreeResult(sql_handle); + return 1; + } + } + Sql_FreeResult(sql_handle); + return 0; } int char_family(int cid1, int cid2, int cid3) { - int i, idx1 = -1, idx2 =-1;//, idx3 =-1; - for(i = 0; i < char_num && (idx1 == -1 || idx2 == -1/* || idx3 == 1*/); i++) - { - if (char_dat[i].status.char_id == cid1) - idx1 = i; - if (char_dat[i].status.char_id == cid2) - idx2 = i; -// if (char_dat[i].status.char_id == cid2) -// idx3 = i; + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `char_id`,`partner_id`,`child` FROM `%s` WHERE `char_id` IN ('%d','%d','%d')", char_db, cid1, cid2, cid3) ) + Sql_ShowDebug(sql_handle); + else while( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + int charid; + int partnerid; + int childid; + char* data; + + Sql_GetData(sql_handle, 0, &data, NULL); charid = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); partnerid = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); childid = atoi(data); + + if( (cid1 == charid && ((cid2 == partnerid && cid3 == childid ) || (cid2 == childid && cid3 == partnerid))) || + (cid1 == partnerid && ((cid2 == charid && cid3 == childid ) || (cid2 == childid && cid3 == charid ))) || + (cid1 == childid && ((cid2 == charid && cid3 == partnerid) || (cid2 == partnerid && cid3 == charid ))) ) + { + Sql_FreeResult(sql_handle); + return childid; + } } - if (idx1 == -1 || idx2 == -1/* || idx3 == -1*/) - return 0; //Some character not found?? - - //Unless the dbs are corrupted, these 3 checks should suffice, even though - //we could do a lot more checks and force cross-reference integrity. - if(char_dat[idx1].status.partner_id == cid2 && - char_dat[idx1].status.child == cid3) - return cid3; //cid1/cid2 parents. cid3 child. - - if(char_dat[idx1].status.partner_id == cid3 && - char_dat[idx1].status.child == cid2) - return cid2; //cid1/cid3 parents. cid2 child. - - if(char_dat[idx2].status.partner_id == cid3 && - char_dat[idx2].status.child == cid1) - return cid1; //cid2/cid3 parents. cid1 child. + Sql_FreeResult(sql_handle); return 0; } @@ -1984,45 +1773,6 @@ void disconnect_player(int account_id) set_eof(i); } -// キャラ削除に伴うデータ削除 -static int char_delete(struct mmo_charstatus *cs) -{ - int j; - - // ペット削除 - if (cs->pet_id) - inter_pet_delete(cs->pet_id); - if (cs->hom_id) - inter_homun_delete(cs->hom_id); - for (j = 0; j < MAX_INVENTORY; j++) - if (cs->inventory[j].card[0] == (short)0xff00) - inter_pet_delete(MakeDWord(cs->inventory[j].card[1],cs->inventory[j].card[2])); - for (j = 0; j < MAX_CART; j++) - if (cs->cart[j].card[0] == (short)0xff00) - inter_pet_delete( MakeDWord(cs->cart[j].card[1],cs->cart[j].card[2]) ); - // ギルド脱退 - if (cs->guild_id) - inter_guild_leave(cs->guild_id, cs->account_id, cs->char_id); - // パーティー脱退 - if (cs->party_id) - inter_party_leave(cs->party_id, cs->account_id, cs->char_id); - // 離婚 - if (cs->partner_id){ - // 離婚情報をmapに通知 - unsigned char buf[10]; - WBUFW(buf,0) = 0x2b12; - WBUFL(buf,2) = cs->char_id; - WBUFL(buf,6) = cs->partner_id; - mapif_sendall(buf,10); - // 離婚 - char_divorce(cs); - } -#ifdef ENABLE_SC_SAVING - status_delete_scdata(cs->account_id, cs->char_id); -#endif - return 0; -} - static void char_auth_ok(int fd, struct char_session_data *sd) { struct online_char_data* character; @@ -2085,6 +1835,7 @@ void loginif_reset(void) /// Checks the conditions for the server to stop. +/// Releases the cookie when all characters are saved. /// If all the conditions are met, it stops the core loop. void loginif_check_shutdown(void) { @@ -2107,7 +1858,7 @@ void loginif_on_ready(void) int i; loginif_check_shutdown(); - + //Send online accounts to login server. send_accounts_tologin(INVALID_TIMER, gettick(), 0, 0); @@ -2122,7 +1873,7 @@ int parse_fromlogin(int fd) { struct char_session_data* sd = NULL; int i; - + // only process data from the login-server if( fd != login_fd ) { @@ -2157,7 +1908,7 @@ int parse_fromlogin(int fd) //printf("connect login server error : %d\n", RFIFOB(fd,2)); ShowError("Can not connect to login-server.\n"); ShowError("The server communication passwords (default s1/p1) are probably invalid.\n"); - ShowError("Also, please make sure your accounts file (default: accounts.txt) has the correct communication username/passwords and the gender of the account is S.\n"); + ShowError("Also, please make sure your login db has the correct communication username/passwords and the gender of the account is S.\n"); ShowError("The communication passwords are set in map_athena.conf and char_athena.conf\n"); set_eof(fd); return 0; @@ -2213,22 +1964,21 @@ int parse_fromlogin(int fd) ARR_FIND( 0, fd_max, i, session[i] && (sd = (struct char_session_data*)session[i]->session_data) && sd->auth && sd->account_id == RFIFOL(fd,2) ); if( i < fd_max ) { + int server_id; memcpy(sd->email, RFIFOP(fd,6), 40); sd->expiration_time = (time_t)RFIFOL(fd,46); sd->gmlevel = RFIFOB(fd,50); safestrncpy(sd->birthdate, (const char*)RFIFOP(fd,51), sizeof(sd->birthdate)); - + ARR_FIND( 0, ARRAYLENGTH(server), server_id, server[server_id].fd > 0 && server[server_id].map[0] ); // continued from char_auth_ok... - if( max_connect_user && count_users() >= max_connect_user && sd->gmlevel < gm_allow_level ) - { + if( server_id == ARRAYLENGTH(server) || //server not online, bugreport:2359 + ( max_connect_user && count_users() >= max_connect_user && sd->gmlevel < gm_allow_level ) ) { // refuse connection (over populated) WFIFOHEAD(i,3); WFIFOW(i,0) = 0x6c; WFIFOW(i,2) = 0; WFIFOSET(i,3); - } - else - { + } else { // send characters to player mmo_char_send006b(i, sd); #if PACKETVER >= 20110309 @@ -2258,7 +2008,6 @@ int parse_fromlogin(int fd) if (RFIFOREST(fd) < 7) return 0; { - int j; unsigned char buf[7]; int acc = RFIFOL(fd,2); @@ -2267,57 +2016,65 @@ int parse_fromlogin(int fd) if( acc > 0 ) {// TODO: Is this even possible? + int char_id[MAX_CHARS]; + int class_[MAX_CHARS]; + int guild_id[MAX_CHARS]; + int num; + char* data; + struct auth_node* node = (struct auth_node*)idb_get(auth_db, acc); if( node != NULL ) node->sex = sex; - ARR_FIND( 0, char_num, i, char_dat[i].status.account_id == acc ); - if( i < char_num ) + // get characters + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `char_id`,`class`,`guild_id` FROM `%s` WHERE `account_id` = '%d'", char_db, acc) ) + Sql_ShowDebug(sql_handle); + for( i = 0; i < MAX_CHARS && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + Sql_GetData(sql_handle, 0, &data, NULL); char_id[i] = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); class_[i] = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); guild_id[i] = atoi(data); + } + num = i; + for( i = 0; i < num; ++i ) { - int jobclass = char_dat[i].status.class_; - char_dat[i].status.sex = sex; - if (jobclass == JOB_BARD || jobclass == JOB_DANCER || - jobclass == JOB_CLOWN || jobclass == JOB_GYPSY || - jobclass == JOB_BABY_BARD || jobclass == JOB_BABY_DANCER) { + if( class_[i] == JOB_BARD || class_[i] == JOB_DANCER || + class_[i] == JOB_CLOWN || class_[i] == JOB_GYPSY || + class_[i] == JOB_BABY_BARD || class_[i] == JOB_BABY_DANCER || + class_[i] == JOB_WANDERER || class_[i] == JOB_WANDERER_T || + class_[i] == JOB_MINSTREL || class_[i] == JOB_MINSTREL_T ) + { // job modification - if (jobclass == JOB_BARD || jobclass == JOB_DANCER) { - char_dat[i].status.class_ = (sex) ? JOB_BARD : JOB_DANCER; - } else if (jobclass == JOB_CLOWN || jobclass == JOB_GYPSY) { - char_dat[i].status.class_ = (sex) ? JOB_CLOWN : JOB_GYPSY; - } else if (jobclass == JOB_BABY_BARD || jobclass == JOB_BABY_DANCER) { - char_dat[i].status.class_ = (sex) ? JOB_BABY_BARD : JOB_BABY_DANCER; - } - // remove specifical skills of classes 19, 4020 and 4042 - for(j = 315; j <= 322; j++) { - if (char_dat[i].status.skill[j].id > 0 && char_dat[i].status.skill[j].flag == SKILL_FLAG_PERMANENT) { - char_dat[i].status.skill_point += char_dat[i].status.skill[j].lv; - char_dat[i].status.skill[j].id = 0; - char_dat[i].status.skill[j].lv = 0; - } - } - // remove specifical skills of classes 20, 4021 and 4043 - for(j = 323; j <= 330; j++) { - if (char_dat[i].status.skill[j].id > 0 && char_dat[i].status.skill[j].flag == SKILL_FLAG_PERMANENT) { - char_dat[i].status.skill_point += char_dat[i].status.skill[j].lv; - char_dat[i].status.skill[j].id = 0; - char_dat[i].status.skill[j].lv = 0; - } - } + if( class_[i] == JOB_BARD || class_[i] == JOB_DANCER ) + class_[i] = (sex ? JOB_BARD : JOB_DANCER); + else if( class_[i] == JOB_CLOWN || class_[i] == JOB_GYPSY ) + class_[i] = (sex ? JOB_CLOWN : JOB_GYPSY); + else if( class_[i] == JOB_BABY_BARD || class_[i] == JOB_BABY_DANCER ) + class_[i] = (sex ? JOB_BABY_BARD : JOB_BABY_DANCER); + else if( class_[i] == JOB_MINSTREL || class_[i] == JOB_WANDERER ) + class_[i] = (sex ? JOB_MINSTREL : JOB_WANDERER); + else if( class_[i] == JOB_MINSTREL_T || class_[i] == JOB_WANDERER_T ) + class_[i] = (sex ? JOB_MINSTREL_T : JOB_WANDERER_T); + // remove specifical skills of classes 19,20 4020,4021 and 4042,4043 + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `skill_point` = `skill_point` +" + " (SELECT SUM(lv) FROM `%s` WHERE `char_id` = '%d' AND `id` >= '315' AND `id` <= '330' AND `lv` > '0')" + " WHERE `char_id` = '%d'", + char_db, skill_db, char_id[i], char_id[i]) ) + Sql_ShowDebug(sql_handle); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id` = '%d' AND `id` >= '315' AND `id` <= '330'", skill_db, char_id[i]) ) + Sql_ShowDebug(sql_handle); } // to avoid any problem with equipment and invalid sex, equipment is unequiped. - for (j = 0; j < MAX_INVENTORY; j++) { - if (char_dat[i].status.inventory[j].nameid && char_dat[i].status.inventory[j].equip) - char_dat[i].status.inventory[j].equip = 0; - } - char_dat[i].status.weapon = 0; - char_dat[i].status.shield = 0; - char_dat[i].status.head_top = 0; - char_dat[i].status.head_mid = 0; - char_dat[i].status.head_bottom = 0; - - if (char_dat[i].status.guild_id) //If there is a guild, update the guild_member data [Skotlex] - inter_guild_sex_changed(char_dat[i].status.guild_id, acc, char_dat[i].status.char_id, sex); + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `equip` = '0' WHERE `char_id` = '%d'", inventory_db, char_id[i]) ) + Sql_ShowDebug(sql_handle); + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `class`='%d', `weapon`='0', `shield`='0', `head_top`='0', `head_mid`='0', `head_bottom`='0' WHERE `char_id`='%d'", char_db, class_[i], char_id[i]) ) + Sql_ShowDebug(sql_handle); + + if( guild_id[i] )// If there is a guild, update the guild_member data [Skotlex] + inter_guild_sex_changed(guild_id[i], acc, char_id[i], sex); } + Sql_FreeResult(sql_handle); + // disconnect player if online on char-server disconnect_player(acc); } @@ -2495,124 +2252,62 @@ int save_accreg2(unsigned char* buf, int len) return 0; } -//Receive Registry information for a character. -int char_parse_Registry(int account_id, int char_id, unsigned char *buf, int buf_len) -{ - int i,j,p,len; - for (i = 0; i < char_num; i++) { - if (char_dat[i].status.account_id == account_id && char_dat[i].status.char_id == char_id) - break; - } - if(i >= char_num) //Character not found? - return 1; - for(j=0,p=0;j<GLOBAL_REG_NUM && p<buf_len;j++){ - sscanf((char*)WBUFP(buf,p), "%31c%n",char_dat[i].global[j].str,&len); - char_dat[i].global[j].str[len]='\0'; - p +=len+1; //+1 to skip the '\0' between strings. - sscanf((char*)WBUFP(buf,p), "%255c%n",char_dat[i].global[j].value,&len); - char_dat[i].global[j].value[len]='\0'; - p +=len+1; - } - char_dat[i].global_num = j; - return 0; -} - -//Reply to map server with acc reg values. -int char_account_reg_reply(int fd,int account_id,int char_id) -{ - int i,j,p; - WFIFOHEAD(fd, GLOBAL_REG_NUM*288 + 13); - WFIFOW(fd,0)=0x3804; - WFIFOL(fd,4)=account_id; - WFIFOL(fd,8)=char_id; - WFIFOB(fd,12)=3; //Type 3: char acc reg. - for (i = 0;i < char_num; i++) { - if (char_dat[i].status.account_id == account_id && char_dat[i].status.char_id == char_id) - break; - } - if(i >= char_num){ //Character not found? Sent empty packet. - WFIFOW(fd,2)=13; - }else{ - for (p=13,j = 0; j < char_dat[i].global_num; j++) { - if (char_dat[i].global[j].str[0]) { - p+= sprintf((char*)WFIFOP(fd,p), "%s", char_dat[i].global[j].str)+1; //We add 1 to consider the '\0' in place. - p+= sprintf((char*)WFIFOP(fd,p), "%s", char_dat[i].global[j].value)+1; - } - } - WFIFOW(fd,2)=p; - } - WFIFOSET(fd,WFIFOW(fd,2)); - return 0; -} - void char_read_fame_list(void) { - int i, j, k; - struct fame_list fame_item; - CREATE_BUFFER(id, int, char_num); - - for(i = 0; i < char_num; i++) { - id[i] = i; - for(j = 0; j < i; j++) { - if (char_dat[i].status.fame > char_dat[id[j]].status.fame) { - for(k = i; k > j; k--) - id[k] = id[k-1]; - id[j] = i; // id[i] - break; - } - } - } + int i; + char* data; + size_t len; // Empty ranking lists memset(smith_fame_list, 0, sizeof(smith_fame_list)); memset(chemist_fame_list, 0, sizeof(chemist_fame_list)); memset(taekwon_fame_list, 0, sizeof(taekwon_fame_list)); // Build Blacksmith ranking list - for (i = 0, j = 0; i < char_num && j < fame_list_size_smith; i++) { - if (char_dat[id[i]].status.fame && ( - char_dat[id[i]].status.class_ == JOB_BLACKSMITH || - char_dat[id[i]].status.class_ == JOB_WHITESMITH || - char_dat[id[i]].status.class_ == JOB_BABY_BLACKSMITH)) - { - fame_item.id = char_dat[id[i]].status.char_id; - fame_item.fame = char_dat[id[i]].status.fame; - safestrncpy(fame_item.name, char_dat[id[i]].status.name, NAME_LENGTH); - - memcpy(&smith_fame_list[j],&fame_item,sizeof(struct fame_list)); - j++; - } + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `char_id`,`fame`,`name` FROM `%s` WHERE `fame`>0 AND (`class`='%d' OR `class`='%d' OR `class`='%d') ORDER BY `fame` DESC LIMIT 0,%d", char_db, JOB_BLACKSMITH, JOB_WHITESMITH, JOB_BABY_BLACKSMITH, fame_list_size_smith) ) + Sql_ShowDebug(sql_handle); + for( i = 0; i < fame_list_size_smith && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + // char_id + Sql_GetData(sql_handle, 0, &data, NULL); + smith_fame_list[i].id = atoi(data); + // fame + Sql_GetData(sql_handle, 1, &data, &len); + smith_fame_list[i].fame = atoi(data); + // name + Sql_GetData(sql_handle, 2, &data, &len); + memcpy(smith_fame_list[i].name, data, min(len, NAME_LENGTH)); } // Build Alchemist ranking list - for (i = 0, j = 0; i < char_num && j < fame_list_size_chemist; i++) { - if (char_dat[id[i]].status.fame && ( - char_dat[id[i]].status.class_ == JOB_ALCHEMIST || - char_dat[id[i]].status.class_ == JOB_CREATOR || - char_dat[id[i]].status.class_ == JOB_BABY_ALCHEMIST)) - { - fame_item.id = char_dat[id[i]].status.char_id; - fame_item.fame = char_dat[id[i]].status.fame; - safestrncpy(fame_item.name, char_dat[id[i]].status.name, NAME_LENGTH); - - memcpy(&chemist_fame_list[j],&fame_item,sizeof(struct fame_list)); - - j++; - } + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `char_id`,`fame`,`name` FROM `%s` WHERE `fame`>0 AND (`class`='%d' OR `class`='%d' OR `class`='%d') ORDER BY `fame` DESC LIMIT 0,%d", char_db, JOB_ALCHEMIST, JOB_CREATOR, JOB_BABY_ALCHEMIST, fame_list_size_chemist) ) + Sql_ShowDebug(sql_handle); + for( i = 0; i < fame_list_size_chemist && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + // char_id + Sql_GetData(sql_handle, 0, &data, NULL); + chemist_fame_list[i].id = atoi(data); + // fame + Sql_GetData(sql_handle, 1, &data, &len); + chemist_fame_list[i].fame = atoi(data); + // name + Sql_GetData(sql_handle, 2, &data, &len); + memcpy(chemist_fame_list[i].name, data, min(len, NAME_LENGTH)); } // Build Taekwon ranking list - for (i = 0, j = 0; i < char_num && j < fame_list_size_taekwon; i++) { - if (char_dat[id[i]].status.fame && - char_dat[id[i]].status.class_ == JOB_TAEKWON) - { - fame_item.id = char_dat[id[i]].status.char_id; - fame_item.fame = char_dat[id[i]].status.fame; - safestrncpy(fame_item.name, char_dat[id[i]].status.name, NAME_LENGTH); - - memcpy(&taekwon_fame_list[j],&fame_item,sizeof(struct fame_list)); - - j++; - } + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `char_id`,`fame`,`name` FROM `%s` WHERE `fame`>0 AND (`class`='%d') ORDER BY `fame` DESC LIMIT 0,%d", char_db, JOB_TAEKWON, fame_list_size_taekwon) ) + Sql_ShowDebug(sql_handle); + for( i = 0; i < fame_list_size_taekwon && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + // char_id + Sql_GetData(sql_handle, 0, &data, NULL); + taekwon_fame_list[i].id = atoi(data); + // fame + Sql_GetData(sql_handle, 1, &data, &len); + taekwon_fame_list[i].fame = atoi(data); + // name + Sql_GetData(sql_handle, 2, &data, &len); + memcpy(taekwon_fame_list[i].name, data, min(len, NAME_LENGTH)); } - DELETE_BUFFER(id); + Sql_FreeResult(sql_handle); } // Send map-servers the fame ranking lists @@ -2666,12 +2361,15 @@ void char_update_fame_list(int type, int index, int fame) //Returns 1 on found, 0 on not found (buffer is filled with Unknown char name) int char_loadName(int char_id, char* name) { - int j; + char* data; + size_t len; - ARR_FIND( 0, char_num, j, char_dat[j].status.char_id == char_id ); - if( j < char_num ) + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `name` FROM `%s` WHERE `char_id`='%d'", char_db, char_id) ) + Sql_ShowDebug(sql_handle); + else if( SQL_SUCCESS == Sql_NextRow(sql_handle) ) { - safestrncpy(name, char_dat[j].status.name, NAME_LENGTH); + Sql_GetData(sql_handle, 0, &data, &len); + safestrncpy(name, data, NAME_LENGTH); return 1; } else @@ -2721,8 +2419,9 @@ void mapif_server_reset(int id) WBUFW(buf,2) = j * 4 + 10; mapif_sendallwos(fd, buf, WBUFW(buf,2)); } + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `ragsrvinfo` WHERE `index`='%d'", server[id].fd) ) + Sql_ShowDebug(sql_handle); online_char_db->foreach(online_char_db,char_db_setoffline,id); //Tag relevant chars as 'in disconnected' server. - create_online_files(); mapif_server_destroy(id); mapif_server_init(id); } @@ -2775,9 +2474,7 @@ int parse_frommap(int fd) ShowStatus("Map-Server %d connected: %d maps, from IP %d.%d.%d.%d port %d.\n", id, j, CONVIP(server[id].ip), server[id].port); ShowStatus("Map-server %d loading complete.\n", id); - char_log("Map-Server %d connected: %d maps, from IP %d.%d.%d.%d port %d. Map-server %d loading complete.\n", - id, j, CONVIP(server[id].ip), server[id].port, id); - + // send name for wisp to player WFIFOHEAD(fd, 3 + NAME_LENGTH); WFIFOW(fd,0) = 0x2afb; @@ -2792,7 +2489,6 @@ int parse_frommap(int fd) int x; if (j == 0) { ShowWarning("Map-server %d has NO maps.\n", id); - char_log("WARNING: Map-server %d has NO maps.\n", id); } else { // Transmitting maps information to the other map-servers WBUFW(buf,0) = 0x2b04; @@ -2829,23 +2525,48 @@ int parse_frommap(int fd) { #ifdef ENABLE_SC_SAVING int aid, cid; - struct scdata *data; aid = RFIFOL(fd,2); cid = RFIFOL(fd,6); - data = status_search_scdata(aid, cid); - if (data->count > 0) - { //Deliver status change data. - WFIFOHEAD(fd,14 + data->count*sizeof(struct status_change_data)); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT type, tick, val1, val2, val3, val4 from `%s` WHERE `account_id` = '%d' AND `char_id`='%d'", + scdata_db, aid, cid) ) + { + Sql_ShowDebug(sql_handle); + break; + } + if( Sql_NumRows(sql_handle) > 0 ) + { + struct status_change_data scdata; + int count; + char* data; + + WFIFOHEAD(fd,14+50*sizeof(struct status_change_data)); WFIFOW(fd,0) = 0x2b1d; - WFIFOW(fd,2) = 14 + data->count*sizeof(struct status_change_data); WFIFOL(fd,4) = aid; WFIFOL(fd,8) = cid; - WFIFOW(fd,12) = data->count; - for (i = 0; i < data->count; i++) - memcpy(WFIFOP(fd,14+i*sizeof(struct status_change_data)), &data->data[i], sizeof(struct status_change_data)); - WFIFOSET(fd, WFIFOW(fd,2)); - status_delete_scdata(aid, cid); //Data sent, so it needs be discarded now. + for( count = 0; count < 50 && SQL_SUCCESS == Sql_NextRow(sql_handle); ++count ) + { + Sql_GetData(sql_handle, 0, &data, NULL); scdata.type = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); scdata.tick = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); scdata.val1 = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); scdata.val2 = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); scdata.val3 = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); scdata.val4 = atoi(data); + memcpy(WFIFOP(fd, 14+count*sizeof(struct status_change_data)), &scdata, sizeof(struct status_change_data)); + } + if (count >= 50) + ShowWarning("Too many status changes for %d:%d, some of them were not loaded.\n", aid, cid); + if (count > 0) + { + WFIFOW(fd,2) = 14 + count*sizeof(struct status_change_data); + WFIFOW(fd,12) = count; + WFIFOSET(fd,WFIFOW(fd,2)); + + //Clear the data once loaded. + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id` = '%d' AND `char_id`='%d'", scdata_db, aid, cid) ) + Sql_ShowDebug(sql_handle); + } } + Sql_FreeResult(sql_handle); #endif RFIFOSKIP(fd, 10); } @@ -2894,7 +2615,7 @@ int parse_frommap(int fd) return 0; { int aid = RFIFOL(fd,4), cid = RFIFOL(fd,8), size = RFIFOW(fd,2); - struct mmo_charstatus* cs; + struct online_char_data* character; if (size - 13 != sizeof(struct mmo_charstatus)) { @@ -2902,10 +2623,17 @@ int parse_frommap(int fd) RFIFOSKIP(fd,size); break; } - if( ( cs = search_character(aid, cid) ) != NULL ) + //Check account only if this ain't final save. Final-save goes through because of the char-map reconnect + if (RFIFOB(fd,12) || ( + (character = (struct online_char_data*)idb_get(online_char_db, aid)) != NULL && + character->char_id == cid)) { - memcpy(cs, RFIFOP(fd,13), sizeof(struct mmo_charstatus)); - storage_save(cs->account_id, &cs->storage); + struct mmo_charstatus char_dat; + memcpy(&char_dat, RFIFOP(fd,13), sizeof(struct mmo_charstatus)); + mmo_char_tosql(cid, &char_dat); + } else { //This may be valid on char-server reconnection, when re-sending characters that already logged off. + ShowError("parse_from_map (save-char): Received data for non-existant/offline character (%d:%d).\n", aid, cid); + set_char_online(id, cid, aid); } if (RFIFOB(fd,12)) @@ -2932,7 +2660,7 @@ int parse_frommap(int fd) uint32 login_id2 = RFIFOL(fd,10); uint32 ip = RFIFOL(fd,14); RFIFOSKIP(fd,18); - + if( runflag != CHARSERVER_ST_RUNNING ) { WFIFOHEAD(fd,7); @@ -2968,19 +2696,25 @@ int parse_frommap(int fd) break; case 0x2b05: // request "change map server" - if (RFIFOREST(fd) < 35) + if (RFIFOREST(fd) < 39) return 0; { int map_id, map_fd = -1; struct online_char_data* data; struct mmo_charstatus* char_data; + struct mmo_charstatus char_dat; map_id = search_mapserver(RFIFOW(fd,18), ntohl(RFIFOL(fd,24)), ntohs(RFIFOW(fd,28))); //Locate mapserver by ip and port. if (map_id >= 0) map_fd = server[map_id].fd; - - char_data = search_character(RFIFOL(fd,2), RFIFOL(fd,14)); - + //Char should just had been saved before this packet, so this should be safe. [Skotlex] + char_data = (struct mmo_charstatus*)uidb_get(char_db_,RFIFOL(fd,14)); + if (char_data == NULL) + { //Really shouldn't happen. + mmo_char_fromsql(RFIFOL(fd,14), &char_dat, true); + char_data = (struct mmo_charstatus*)uidb_get(char_db_,RFIFOL(fd,14)); + } + if( runflag == CHARSERVER_ST_RUNNING && session_isActive(map_fd) && char_data ) @@ -3000,8 +2734,10 @@ int parse_frommap(int fd) node->login_id1 = RFIFOL(fd,6); node->login_id2 = RFIFOL(fd,10); node->sex = RFIFOB(fd,30); - node->expiration_time = 0; // FIXME + node->expiration_time = 0; // FIXME (this thing isn't really supported we could as well purge it instead of fixing) node->ip = ntohl(RFIFOL(fd,31)); + node->gmlevel = RFIFOL(fd,35); + node->changing_mapservers = 1; idb_put(auth_db, RFIFOL(fd,2), node); data = (struct online_char_data*)idb_ensure(online_char_db, RFIFOL(fd,2), create_online_char_data); @@ -3024,6 +2760,22 @@ int parse_frommap(int fd) } break; + case 0x2b07: // Remove RFIFOL(fd,6) (friend_id) from RFIFOL(fd,2) (char_id) friend list [Ind] + if (RFIFOREST(fd) < 10) + return 0; + { + int char_id, friend_id; + char_id = RFIFOL(fd,2); + friend_id = RFIFOL(fd,6); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id`='%d' AND `friend_id`='%d' LIMIT 1", + friend_db, char_id, friend_id) ) { + Sql_ShowDebug(sql_handle); + break; + } + RFIFOSKIP(fd,10); + } + break; + case 0x2b08: // char name request if (RFIFOREST(fd) < 6) return 0; @@ -3054,7 +2806,7 @@ int parse_frommap(int fd) return 0; { int result = 0; // 0-login-server request done, 1-player not found, 2-gm level too low, 3-login-server offline - char character_name[NAME_LENGTH]; + char esc_name[NAME_LENGTH*2+1]; int acc = RFIFOL(fd,2); // account_id of who ask (-1 if server itself made this request) const char* name = (char*)RFIFOP(fd,6); // name of the target character @@ -3067,19 +2819,26 @@ int parse_frommap(int fd) short second = RFIFOW(fd,42); RFIFOSKIP(fd,44); - safestrncpy(character_name, name, NAME_LENGTH); - i = search_character_index(character_name); - if( i < 0 ) + Sql_EscapeStringLen(sql_handle, esc_name, name, strnlen(name, NAME_LENGTH)); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id`,`name` FROM `%s` WHERE `name` = '%s'", char_db, esc_name) ) + Sql_ShowDebug(sql_handle); + else + if( Sql_NumRows(sql_handle) == 0 ) { result = 1; // 1-player not found } else + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + Sql_ShowDebug(sql_handle); + //FIXME: set proper result value? + else { char name[NAME_LENGTH]; int account_id; + char* data; - account_id = char_dat[i].status.account_id; - safestrncpy(name, char_dat[i].status.name, NAME_LENGTH); + Sql_GetData(sql_handle, 0, &data, NULL); account_id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); safestrncpy(name, data, sizeof(name)); if( login_fd <= 0 ) result = 3; // 3-login-server offline @@ -3130,6 +2889,8 @@ int parse_frommap(int fd) } } + Sql_FreeResult(sql_handle); + // send answer if a player ask, not if the server ask if( acc != -1 && type != 5) { // Don't send answer for changesex WFIFOHEAD(fd,34); @@ -3196,11 +2957,28 @@ int parse_frommap(int fd) } break; + // Divorce chars + case 0x2b11: + if( RFIFOREST(fd) < 10 ) + return 0; + + divorce_char_sql(RFIFOL(fd,2), RFIFOL(fd,6)); + RFIFOSKIP(fd,10); + break; + case 0x2b16: // Receive rates [Wizputer] if( RFIFOREST(fd) < 14 ) return 0; - // Txt doesn't need this packet, so just skip it + { + char esc_server_name[sizeof(server_name)*2+1]; + + Sql_EscapeString(sql_handle, esc_server_name, server_name); + + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `ragsrvinfo` SET `index`='%d',`name`='%s',`exp`='%d',`jexp`='%d',`drop`='%d'", + fd, esc_server_name, RFIFOL(fd,2), RFIFOL(fd,6), RFIFOL(fd,10)) ) + Sql_ShowDebug(sql_handle); RFIFOSKIP(fd,14); + } break; case 0x2b17: // Character disconnected set online 0 [Wizputer] @@ -3236,20 +3014,31 @@ int parse_frommap(int fd) { #ifdef ENABLE_SC_SAVING int count, aid, cid; - struct scdata *data; aid = RFIFOL(fd, 4); cid = RFIFOL(fd, 8); count = RFIFOW(fd, 12); - data = status_search_scdata(aid, cid); - if (data->count != count) + if( count > 0 ) { - data->count = count; - data->data = (struct status_change_data*)aRealloc(data->data, count*sizeof(struct status_change_data)); + struct status_change_data data; + StringBuf buf; + int i; + + StringBuf_Init(&buf); + StringBuf_Printf(&buf, "INSERT INTO `%s` (`account_id`, `char_id`, `type`, `tick`, `val1`, `val2`, `val3`, `val4`) VALUES ", scdata_db); + for( i = 0; i < count; ++i ) + { + memcpy (&data, RFIFOP(fd, 14+i*sizeof(struct status_change_data)), sizeof(struct status_change_data)); + if( i > 0 ) + StringBuf_AppendStr(&buf, ", "); + StringBuf_Printf(&buf, "('%d','%d','%hu','%d','%d','%d','%d','%d')", aid, cid, + data.type, data.tick, data.val1, data.val2, data.val3, data.val4); + } + if( SQL_ERROR == Sql_QueryStr(sql_handle, StringBuf_Value(&buf)) ) + Sql_ShowDebug(sql_handle); + StringBuf_Destroy(&buf); } - for (i = 0; i < count; i++) - memcpy (&data->data[i], RFIFOP(fd, 14+i*sizeof(struct status_change_data)), sizeof(struct status_change_data)); #endif RFIFOSKIP(fd, RFIFOW(fd, 2)); } @@ -3274,6 +3063,7 @@ int parse_frommap(int fd) uint32 ip; struct auth_node* node; struct mmo_charstatus* cd; + struct mmo_charstatus char_dat; account_id = RFIFOL(fd,2); char_id = RFIFOL(fd,6); @@ -3283,10 +3073,15 @@ int parse_frommap(int fd) RFIFOSKIP(fd,19); node = (struct auth_node*)idb_get(auth_db, account_id); - cd = search_character(account_id, char_id); + cd = (struct mmo_charstatus*)uidb_get(char_db_,char_id); + if( cd == NULL ) + { //Really shouldn't happen. + mmo_char_fromsql(char_id, &char_dat, true); + cd = (struct mmo_charstatus*)uidb_get(char_db_,char_id); + } if( runflag == CHARSERVER_ST_RUNNING && cd != NULL && - node != NULL && + node != NULL && node->account_id == account_id && node->char_id == char_id && node->login_id1 == login_id1 && @@ -3295,16 +3090,16 @@ int parse_frommap(int fd) {// auth ok cd->sex = sex; - WFIFOHEAD(fd,24 + sizeof(struct mmo_charstatus)); + WFIFOHEAD(fd,25 + sizeof(struct mmo_charstatus)); WFIFOW(fd,0) = 0x2afd; - WFIFOW(fd,2) = 24 + sizeof(struct mmo_charstatus); + WFIFOW(fd,2) = 25 + sizeof(struct mmo_charstatus); WFIFOL(fd,4) = account_id; WFIFOL(fd,8) = node->login_id1; WFIFOL(fd,12) = node->login_id2; WFIFOL(fd,16) = (uint32)node->expiration_time; // FIXME: will wrap to negative after "19-Jan-2038, 03:14:07 AM GMT" WFIFOL(fd,20) = node->gmlevel; - storage_load(cd->account_id, &cd->storage); //FIXME: storage is used as a temp buffer here - memcpy(WFIFOP(fd,24), cd, sizeof(struct mmo_charstatus)); + WFIFOB(fd,24) = node->changing_mapservers; + memcpy(WFIFOP(fd,25), cd, sizeof(struct mmo_charstatus)); WFIFOSET(fd, WFIFOW(fd,2)); // only use the auth once and mark user online @@ -3460,18 +3255,31 @@ void char_delete2_cancel_ack(int fd, int char_id, uint32 result) static void char_delete2_req(int fd, struct char_session_data* sd) {// CH: <0827>.W <char id>.L - int char_id; - struct mmo_charstatus* cs; + int char_id, i, guild_id, party_id; + char* data; + time_t delete_date; char_id = RFIFOL(fd,2); - if( ( cs = search_session_character(sd, char_id) ) == NULL ) + ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] == char_id ); + if( i == MAX_CHARS ) {// character not found char_delete2_ack(fd, char_id, 3, 0); return; } - if( cs->delete_date ) + if( SQL_SUCCESS != Sql_Query(sql_handle, "SELECT `guild_id`,`party_id`,`delete_date` FROM `%s` WHERE `char_id`='%d'", char_db, char_id) || SQL_SUCCESS != Sql_NextRow(sql_handle) ) + { + Sql_ShowDebug(sql_handle); + char_delete2_ack(fd, char_id, 3, 0); + return; + } + + Sql_GetData(sql_handle, 0, &data, NULL); guild_id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); party_id = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); delete_date = strtoul(data, NULL, 10); + + if( delete_date ) {// character already queued for deletion char_delete2_ack(fd, char_id, 0, 0); return; @@ -3481,13 +3289,13 @@ static void char_delete2_req(int fd, struct char_session_data* sd) // Aegis imposes these checks probably to avoid dead member // entries in guilds/parties, otherwise they are not required. // TODO: Figure out how these are enforced during waiting. - if( cs->guild_id ) + if( guild_id ) {// character in guild char_delete2_ack(fd, char_id, 4, 0); return; } - if( cs->party_id ) + if( party_id ) {// character in party char_delete2_ack(fd, char_id, 5, 0); return; @@ -3495,17 +3303,26 @@ static void char_delete2_req(int fd, struct char_session_data* sd) */ // success - cs->delete_date = time(NULL)+char_del_delay; + delete_date = time(NULL)+char_del_delay; - char_delete2_ack(fd, char_id, 1, cs->delete_date); + if( SQL_SUCCESS != Sql_Query(sql_handle, "UPDATE `%s` SET `delete_date`='%lu' WHERE `char_id`='%d'", char_db, (unsigned long)delete_date, char_id) ) + { + Sql_ShowDebug(sql_handle); + char_delete2_ack(fd, char_id, 3, 0); + return; + } + + char_delete2_ack(fd, char_id, 1, delete_date); } static void char_delete2_accept(int fd, struct char_session_data* sd) {// CH: <0829>.W <char id>.L <birth date:YYMMDD>.6B char birthdate[8+1]; - int char_id, i; - struct mmo_charstatus* cs; + int char_id, i, k; + unsigned int base_level; + char* data; + time_t delete_date; char_id = RFIFOL(fd,2); @@ -3522,15 +3339,24 @@ static void char_delete2_accept(int fd, struct char_session_data* sd) birthdate[7] = RFIFOB(fd,11); birthdate[8] = 0; - ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] != -1 && char_dat[sd->found_char[i]].status.char_id == char_id ); + ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] == char_id ); if( i == MAX_CHARS ) {// character not found char_delete2_accept_ack(fd, char_id, 3); return; } - cs = &char_dat[sd->found_char[i]].status; - if( !cs->delete_date || cs->delete_date>time(NULL) ) + if( SQL_SUCCESS != Sql_Query(sql_handle, "SELECT `base_level`,`delete_date` FROM `%s` WHERE `char_id`='%d'", char_db, char_id) || SQL_SUCCESS != Sql_NextRow(sql_handle) ) + {// data error + Sql_ShowDebug(sql_handle); + char_delete2_accept_ack(fd, char_id, 3); + return; + } + + Sql_GetData(sql_handle, 0, &data, NULL); base_level = (unsigned int)strtoul(data, NULL, 10); + Sql_GetData(sql_handle, 1, &data, NULL); delete_date = strtoul(data, NULL, 10); + + if( !delete_date || delete_date>time(NULL) ) {// not queued or delay not yet passed char_delete2_accept_ack(fd, char_id, 4); return; @@ -3542,49 +3368,25 @@ static void char_delete2_accept(int fd, struct char_session_data* sd) return; } - if( ( char_del_level > 0 && cs->base_level >= (unsigned int)char_del_level ) || ( char_del_level < 0 && cs->base_level <= (unsigned int)(-char_del_level) ) ) + if( ( char_del_level > 0 && base_level >= (unsigned int)char_del_level ) || ( char_del_level < 0 && base_level <= (unsigned int)(-char_del_level) ) ) {// character level config restriction char_delete2_accept_ack(fd, char_id, 2); return; } // success - char_delete(cs); - - // drop character entry - if( --char_num > 0 && sd->found_char[i] != char_num ) + if( delete_char_sql(char_id) < 0 ) { - int s, c; - - // move the last entry to the place of the deleted character - memcpy(&char_dat[sd->found_char[i]], &char_dat[char_num], sizeof(struct mmo_charstatus)); - - // scan currently online accounts, if the moved character - // entry requires an update of the cached character list - for( s = 0; s < fd_max; s++ ) - { - struct char_session_data* osd; - - if( session[s] && ( osd = (struct char_session_data*)session[s]->session_data ) != NULL && osd->account_id == char_dat[char_num].status.account_id ) - { - for( c = 0; c < MAX_CHARS; c++ ) - { - if( osd->found_char[c] == char_num ) - { - osd->found_char[c] = sd->found_char[i]; - break; - } - } - break; - } - } - - // wipe the last entry - memset(&char_dat[char_num], 0, sizeof(struct mmo_charstatus)); + char_delete2_accept_ack(fd, char_id, 3); + return; } // refresh character list cache - char_find_characters(sd); + for(k = i; k < MAX_CHARS-1; k++) + { + sd->found_char[k] = sd->found_char[k+1]; + } + sd->found_char[MAX_CHARS-1] = -1; char_delete2_accept_ack(fd, char_id, 1); } @@ -3592,12 +3394,12 @@ static void char_delete2_accept(int fd, struct char_session_data* sd) static void char_delete2_cancel(int fd, struct char_session_data* sd) {// CH: <082b>.W <char id>.L - int char_id; - struct mmo_charstatus* cs; + int char_id, i; char_id = RFIFOL(fd,2); - if( ( cs = search_session_character(sd, char_id) ) == NULL ) + ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] == char_id ); + if( i == MAX_CHARS ) {// character not found char_delete2_cancel_ack(fd, char_id, 2); return; @@ -3606,7 +3408,12 @@ static void char_delete2_cancel(int fd, struct char_session_data* sd) // there is no need to check, whether or not the character was // queued for deletion, as the client prints an error message by // itself, if it was not the case (@see char_delete2_cancel_ack) - cs->delete_date = 0; + if( SQL_SUCCESS != Sql_Query(sql_handle, "UPDATE `%s` SET `delete_date`='0' WHERE `char_id`='%d'", char_db, char_id) ) + { + Sql_ShowDebug(sql_handle); + char_delete2_cancel_ack(fd, char_id, 2); + return; + } char_delete2_cancel_ack(fd, char_id, 1); } @@ -3732,37 +3539,46 @@ int parse_char(int fd) case 0x66: FIFOSD_CHECK(3); { + struct mmo_charstatus char_dat; struct mmo_charstatus *cd; + char* data; + int char_id; uint32 subnet_map_ip; struct auth_node* node; int slot = RFIFOB(fd,2); RFIFOSKIP(fd,3); - // if we activated email creation and email is default email - if (email_creation != 0 && strcmp(sd->email, "a@a.com") == 0 && login_fd > 0) { // to modify an e-mail, login-server must be online - WFIFOHEAD(fd,3); - WFIFOW(fd,0) = 0x70; - WFIFOB(fd,2) = 0; // 00 = Incorrect Email address - WFIFOSET(fd,3); - break; - } - // otherwise, load the character - ARR_FIND( 0, MAX_CHARS, ch, sd->found_char[ch] >= 0 && char_dat[sd->found_char[ch]].status.slot == slot ); - if (ch == MAX_CHARS) + if ( SQL_SUCCESS != Sql_Query(sql_handle, "SELECT `char_id` FROM `%s` WHERE `account_id`='%d' AND `char_num`='%d'", char_db, sd->account_id, slot) + || SQL_SUCCESS != Sql_NextRow(sql_handle) + || SQL_SUCCESS != Sql_GetData(sql_handle, 0, &data, NULL) ) { //Not found?? May be forged packet. + Sql_ShowDebug(sql_handle); + Sql_FreeResult(sql_handle); WFIFOHEAD(fd,3); WFIFOW(fd,0) = 0x6c; WFIFOB(fd,2) = 0; // rejected from server WFIFOSET(fd,3); break; } - cd = &char_dat[sd->found_char[ch]].status; - char_log("Character Selected, Account ID: %d, Character Slot: %d, Character Name: %s.\n", sd->account_id, slot, cd->name); + char_id = atoi(data); + Sql_FreeResult(sql_handle); + mmo_char_fromsql(char_id, &char_dat, true); + + //Have to switch over to the DB instance otherwise data won't propagate [Kevin] + cd = (struct mmo_charstatus *)idb_get(char_db_, char_id); cd->sex = sd->sex; - ShowInfo("Selected char: (Account %d: %d - %s)\n", sd->account_id, slot, cd->name); + if (log_char) { + char esc_name[NAME_LENGTH*2+1]; + + Sql_EscapeStringLen(sql_handle, esc_name, char_dat.name, strnlen(char_dat.name, NAME_LENGTH)); + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s`(`time`, `account_id`,`char_num`,`name`) VALUES (NOW(), '%d', '%d', '%s')", + charlog_db, sd->account_id, slot, esc_name) ) + Sql_ShowDebug(sql_handle); + } + ShowInfo("Selected char: (Account %d: %d - %s)\n", sd->account_id, slot, char_dat.name); // searching map server i = search_mapserver(cd->last_point.map, -1, -1); @@ -3846,6 +3662,9 @@ int parse_char(int fd) node->gmlevel = sd->gmlevel; node->ip = ipl; idb_put(auth_db, sd->account_id, node); + + set_char_online(-2,node->char_id,sd->account_id); + } break; @@ -3857,7 +3676,7 @@ int parse_char(int fd) if( !char_new ) //turn character creation on/off [Kevin] i = -2; else - i = make_new_char(sd, (char*)RFIFOP(fd,2),RFIFOB(fd,26),RFIFOB(fd,27),RFIFOB(fd,28),RFIFOB(fd,29),RFIFOB(fd,30),RFIFOB(fd,31),RFIFOB(fd,32),RFIFOW(fd,33),RFIFOW(fd,35)); + i = make_new_char_sql(sd, (char*)RFIFOP(fd,2),RFIFOB(fd,26),RFIFOB(fd,27),RFIFOB(fd,28),RFIFOB(fd,29),RFIFOB(fd,30),RFIFOB(fd,31),RFIFOB(fd,32),RFIFOW(fd,33),RFIFOW(fd,35)); //'Charname already exists' (-1), 'Char creation denied' (-2) and 'You are underaged' (-3) if (i < 0) @@ -3874,17 +3693,20 @@ int parse_char(int fd) else { int len; + // retrieve data + struct mmo_charstatus char_dat; + mmo_char_fromsql(i, &char_dat, false); //Only the short data is needed. // send to player WFIFOHEAD(fd,2+MAX_CHAR_BUF); WFIFOW(fd,0) = 0x6d; - len = 2 + mmo_char_tobuf(WFIFOP(fd,2), &char_dat[i].status); + len = 2 + mmo_char_tobuf(WFIFOP(fd,2), &char_dat); WFIFOSET(fd,len); // add new entry to the chars list ARR_FIND( 0, MAX_CHARS, ch, sd->found_char[ch] == -1 ); if( ch < MAX_CHARS ) - sd->found_char[ch] = i; // position of the new char in the char_dat[] array + sd->found_char[ch] = i; // the char_id of the new char } RFIFOSKIP(fd,37); @@ -3898,56 +3720,17 @@ int parse_char(int fd) if (cmd == 0x1fb) FIFOSD_CHECK(56); { int cid = RFIFOL(fd,2); - struct mmo_charstatus* cs = NULL; ShowInfo(CL_RED"Request Char Deletion: "CL_GREEN"%d (%d)"CL_RESET"\n", sd->account_id, cid); memcpy(email, RFIFOP(fd,6), 40); - RFIFOSKIP(fd,( cmd == 0x68 ) ? 46 : 56); - - if (e_mail_check(email) == 0) - safestrncpy(email, "a@a.com", sizeof(email)); // default e-mail - - // BEGIN HACK: "change email using the char deletion 'confirm email' menu" - // if we activated email creation and email is default email - if (email_creation != 0 && strcmp(sd->email, "a@a.com") == 0 && login_fd > 0) { // to modify an e-mail, login-server must be online - // if sended email is incorrect e-mail - if (strcmp(email, "a@a.com") == 0) { - WFIFOHEAD(fd,3); - WFIFOW(fd,0) = 0x70; - WFIFOB(fd,2) = 0; // 00 = Incorrect Email address - WFIFOSET(fd,3); - break; - } - // we change the packet to set it like selection. - ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] != -1 && char_dat[sd->found_char[i]].status.char_id == cid ); - if( i < MAX_CHARS ) - { - // we save new e-mail - memcpy(sd->email, email, 40); - // we send new e-mail to login-server ('online' login-server is checked before) - WFIFOHEAD(login_fd,46); - WFIFOW(login_fd,0) = 0x2715; - WFIFOL(login_fd,2) = sd->account_id; - memcpy(WFIFOP(login_fd, 6), email, 40); - WFIFOSET(login_fd,46); - - // change value to put new packet (char selection) - RFIFOSKIP(fd,-3); //FIXME: Will this work? Messing with the received buffer is ugly anyway... - RFIFOW(fd,0) = 0x66; - RFIFOB(fd,2) = char_dat[sd->found_char[i]].status.slot; - // not send packet, it's modify of actual packet - } else { - WFIFOHEAD(fd,3); - WFIFOW(fd,0) = 0x70; - WFIFOB(fd,2) = 0; // 00 = Incorrect Email address - WFIFOSET(fd,3); - } - break; - } - // END HACK - - // otherwise, we delete the character - if (strcmpi(email, sd->email) != 0) { // if it's an invalid email + RFIFOSKIP(fd,( cmd == 0x68) ? 46 : 56); + + // Check if e-mail is correct + if(strcmpi(email, sd->email) && //email does not matches and + ( + strcmp("a@a.com", sd->email) || //it is not default email, or + (strcmp("a@a.com", email) && strcmp("", email)) //email sent does not matches default + )) { //Fail WFIFOHEAD(fd,3); WFIFOW(fd,0) = 0x70; WFIFOB(fd,2) = 0; // 00 = Incorrect Email address @@ -3956,7 +3739,7 @@ int parse_char(int fd) } // check if this char exists - ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] != -1 && char_dat[sd->found_char[i]].status.char_id == cid ); + ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] == cid ); if( i == MAX_CHARS ) { // Such a character does not exist in the account WFIFOHEAD(fd,3); @@ -3966,45 +3749,22 @@ int parse_char(int fd) break; } - // deletion process - cs = &char_dat[sd->found_char[i]].status; - - //check for config char del condition [Lupus] - if( ( char_del_level > 0 && cs->base_level >= (unsigned int)char_del_level ) || ( char_del_level < 0 && cs->base_level <= (unsigned int)(-char_del_level) ) ) - { - WFIFOHEAD(fd,3); - WFIFOW(fd,0) = 0x70; - WFIFOB(fd,2) = 1; // This character cannot be deleted. - WFIFOSET(fd,3); - break; - } - - char_delete(cs); - if (sd->found_char[i] != char_num - 1) { - int j, k; - struct char_session_data *sd2; - memcpy(&char_dat[sd->found_char[i]], &char_dat[char_num-1], sizeof(struct mmo_charstatus)); - // Correct moved character reference in the character's owner - for (j = 0; j < fd_max; j++) { - if (session[j] && (sd2 = (struct char_session_data*)session[j]->session_data) && - sd2->account_id == char_dat[char_num-1].status.account_id) { - for (k = 0; k < MAX_CHARS; k++) { - if (sd2->found_char[k] == char_num-1) { - sd2->found_char[k] = sd->found_char[i]; - break; - } - } - break; - } - } - } - char_num--; - // remove char from list and compact it for(ch = i; ch < MAX_CHARS-1; ch++) sd->found_char[ch] = sd->found_char[ch+1]; sd->found_char[MAX_CHARS-1] = -1; - + + /* Delete character */ + if(delete_char_sql(cid)<0){ + //can't delete the char + //either SQL error or can't delete by some CONFIG conditions + //del fail + WFIFOHEAD(fd,3); + WFIFOW(fd, 0) = 0x70; + WFIFOB(fd, 2) = 0; + WFIFOSET(fd, 3); + break; + } /* Char successfully deleted.*/ WFIFOHEAD(fd,2); WFIFOW(fd,0) = 0x6f; @@ -4025,8 +3785,32 @@ int parse_char(int fd) case 0x28d: FIFOSD_CHECK(34); { - //not implemented + int i, aid = RFIFOL(fd,2), cid =RFIFOL(fd,6); + char name[NAME_LENGTH]; + char esc_name[NAME_LENGTH*2+1]; + safestrncpy(name, (char *)RFIFOP(fd,10), NAME_LENGTH); RFIFOSKIP(fd,34); + + if( aid != sd->account_id ) + break; + ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] == cid ); + if( i == MAX_CHARS ) + break; + + normalize_name(name,TRIM_CHARS); + Sql_EscapeStringLen(sql_handle, esc_name, name, strnlen(name, NAME_LENGTH)); + if( !check_char_name(name,esc_name) ) + { + i = 1; + safestrncpy(sd->new_name, name, NAME_LENGTH); + } + else + i = 0; + + WFIFOHEAD(fd, 4); + WFIFOW(fd,0) = 0x28e; + WFIFOW(fd,2) = i; + WFIFOSET(fd,4); } break; //Confirm change name. @@ -4039,8 +3823,19 @@ int parse_char(int fd) // 4: Another user is using this character name, so please select another one. FIFOSD_CHECK(6); { - //not implemented + int i; + int cid = RFIFOL(fd,2); RFIFOSKIP(fd,6); + + ARR_FIND( 0, MAX_CHARS, i, sd->found_char[i] == cid ); + if( i == MAX_CHARS ) + break; + i = rename_char_sql(sd, cid); + + WFIFOHEAD(fd, 4); + WFIFOW(fd,0) = 0x290; + WFIFOW(fd,2) = i; + WFIFOSET(fd,4); } break; @@ -4237,9 +4032,6 @@ int broadcast_user_count(int tid, unsigned int tick, int id, intptr_t data) WBUFL(buf,2) = users; mapif_sendall(buf,6); - // refresh online files (txt and html) - create_online_files(); - return 0; } @@ -4409,9 +4201,86 @@ int char_lan_config_read(const char *lancfgName) fclose(fp); return 0; } -#endif //TXT_SQL_CONVERT -int char_config_read(const char *cfgName) +void sql_config_read(const char* cfgName) +{ + char line[1024], w1[1024], w2[1024]; + FILE* fp; + + ShowInfo("Reading file %s...\n", cfgName); + + if ((fp = fopen(cfgName, "r")) == NULL) { + ShowError("file not found: %s\n", cfgName); + return; + } + + while(fgets(line, sizeof(line), fp)) + { + if(line[0] == '/' && line[1] == '/') + continue; + + if (sscanf(line, "%[^:]: %[^\r\n]", w1, w2) != 2) + continue; + + if(!strcmpi(w1,"char_db")) + safestrncpy(char_db, w2, sizeof(char_db)); + else if(!strcmpi(w1,"scdata_db")) + safestrncpy(scdata_db, w2, sizeof(scdata_db)); + else if(!strcmpi(w1,"cart_db")) + safestrncpy(cart_db, w2, sizeof(cart_db)); + else if(!strcmpi(w1,"inventory_db")) + safestrncpy(inventory_db, w2, sizeof(inventory_db)); + else if(!strcmpi(w1,"charlog_db")) + safestrncpy(charlog_db, w2, sizeof(charlog_db)); + else if(!strcmpi(w1,"storage_db")) + safestrncpy(storage_db, w2, sizeof(storage_db)); + else if(!strcmpi(w1,"reg_db")) + safestrncpy(reg_db, w2, sizeof(reg_db)); + else if(!strcmpi(w1,"skill_db")) + safestrncpy(skill_db, w2, sizeof(skill_db)); + else if(!strcmpi(w1,"interlog_db")) + safestrncpy(interlog_db, w2, sizeof(interlog_db)); + else if(!strcmpi(w1,"memo_db")) + safestrncpy(memo_db, w2, sizeof(memo_db)); + else if(!strcmpi(w1,"guild_db")) + safestrncpy(guild_db, w2, sizeof(guild_db)); + else if(!strcmpi(w1,"guild_alliance_db")) + safestrncpy(guild_alliance_db, w2, sizeof(guild_alliance_db)); + else if(!strcmpi(w1,"guild_castle_db")) + safestrncpy(guild_castle_db, w2, sizeof(guild_castle_db)); + else if(!strcmpi(w1,"guild_expulsion_db")) + safestrncpy(guild_expulsion_db, w2, sizeof(guild_expulsion_db)); + else if(!strcmpi(w1,"guild_member_db")) + safestrncpy(guild_member_db, w2, sizeof(guild_member_db)); + else if(!strcmpi(w1,"guild_skill_db")) + safestrncpy(guild_skill_db, w2, sizeof(guild_skill_db)); + else if(!strcmpi(w1,"guild_position_db")) + safestrncpy(guild_position_db, w2, sizeof(guild_position_db)); + else if(!strcmpi(w1,"guild_storage_db")) + safestrncpy(guild_storage_db, w2, sizeof(guild_storage_db)); + else if(!strcmpi(w1,"party_db")) + safestrncpy(party_db, w2, sizeof(party_db)); + else if(!strcmpi(w1,"pet_db")) + safestrncpy(pet_db, w2, sizeof(pet_db)); + else if(!strcmpi(w1,"mail_db")) + safestrncpy(mail_db, w2, sizeof(mail_db)); + else if(!strcmpi(w1,"auction_db")) + safestrncpy(auction_db, w2, sizeof(auction_db)); + else if(!strcmpi(w1,"friend_db")) + safestrncpy(friend_db, w2, sizeof(friend_db)); + else if(!strcmpi(w1,"hotkey_db")) + safestrncpy(hotkey_db, w2, sizeof(hotkey_db)); + else if(!strcmpi(w1,"quest_db")) + safestrncpy(quest_db,w2,sizeof(quest_db)); + //support the import command, just like any other config + else if(!strcmpi(w1,"import")) + sql_config_read(w2); + } + fclose(fp); + ShowInfo("Done reading %s.\n", cfgName); +} + +int char_config_read(const char* cfgName) { char line[1024], w1[1024], w2[1024]; FILE* fp = fopen(cfgName, "r"); @@ -4437,7 +4306,6 @@ int char_config_read(const char *cfgName) } else if(strcmpi(w1,"console_silent")==0){ ShowInfo("Console Silent Setting: %d\n", atoi(w2)); msg_silent = atoi(w2); -#ifndef TXT_SQL_CONVERT } else if(strcmpi(w1,"stdout_with_ansisequence")==0){ stdout_with_ansisequence = config_switch(w2); } else if (strcmpi(w1, "userid") == 0) { @@ -4482,18 +4350,6 @@ int char_config_read(const char *cfgName) char_new = (bool)atoi(w2); } else if (strcmpi(w1, "char_new_display") == 0) { char_new_display = atoi(w2); - } else if (strcmpi(w1, "email_creation") == 0) { - email_creation = config_switch(w2); - } else if (strcmpi(w1, "scdata_txt") == 0) { //By Skotlex - safestrncpy(scdata_txt, w2, sizeof(scdata_txt)); -#endif - } else if (strcmpi(w1, "char_txt") == 0) { - safestrncpy(char_txt, w2, sizeof(char_txt)); - } else if (strcmpi(w1, "friends_txt") == 0) { //By davidsiaw - safestrncpy(friends_txt, w2, sizeof(friends_txt)); - } else if (strcmpi(w1, "hotkeys_txt") == 0) { //By davidsiaw - safestrncpy(hotkeys_txt, w2, sizeof(hotkeys_txt)); -#ifndef TXT_SQL_CONVERT } else if (strcmpi(w1, "max_connect_user") == 0) { max_connect_user = atoi(w2); if (max_connect_user < 0) @@ -4535,8 +4391,6 @@ int char_config_read(const char *cfgName) } else if (strcmpi(w1, "unknown_char_name") == 0) { safestrncpy(unknown_char_name, w2, sizeof(unknown_char_name)); unknown_char_name[NAME_LENGTH-1] = '\0'; - } else if (strcmpi(w1, "char_log_filename") == 0) { - safestrncpy(char_log_filename, w2, sizeof(char_log_filename)); } else if (strcmpi(w1, "name_ignoring_case") == 0) { name_ignoring_case = (bool)config_switch(w2); } else if (strcmpi(w1, "char_name_option") == 0) { @@ -4549,23 +4403,6 @@ int char_config_read(const char *cfgName) char_del_level = atoi(w2); } else if (strcmpi(w1, "char_del_delay") == 0) { char_del_delay = atoi(w2); -// online files options - } else if (strcmpi(w1, "online_txt_filename") == 0) { - safestrncpy(online_txt_filename, w2, sizeof(online_txt_filename)); - } else if (strcmpi(w1, "online_html_filename") == 0) { - safestrncpy(online_html_filename, w2, sizeof(online_html_filename)); - } else if (strcmpi(w1, "online_sorting_option") == 0) { - online_sorting_option = atoi(w2); - } else if (strcmpi(w1, "online_display_option") == 0) { - online_display_option = atoi(w2); - } else if (strcmpi(w1, "online_gm_display_min_level") == 0) { // minimum GM level to display 'GM' when we want to display it - online_gm_display_min_level = atoi(w2); - if (online_gm_display_min_level < 5) // send online file every 5 seconds to player is enough - online_gm_display_min_level = 5; - } else if (strcmpi(w1, "online_refresh_html") == 0) { - online_refresh_html = atoi(w2); - if (online_refresh_html < 1) - online_refresh_html = 1; } else if(strcmpi(w1,"db_path")==0) { safestrncpy(db_path, w2, sizeof(db_path)); } else if (strcmpi(w1, "console") == 0) { @@ -4590,7 +4427,6 @@ int char_config_read(const char *cfgName) } } else if (strcmpi(w1, "guild_exp_rate") == 0) { guild_exp_rate = atoi(w2); -#endif //TXT_SQL_CONVERT } else if (strcmpi(w1, "import") == 0) { char_config_read(w2); } @@ -4601,41 +4437,36 @@ int char_config_read(const char *cfgName) return 0; } -#ifndef TXT_SQL_CONVERT void do_final(void) { ShowStatus("Terminating...\n"); - mmo_char_sync(); - inter_save(); set_all_offline(-1); + set_all_offline_sql(); + + inter_final(); + flush_fifos(); do_final_mapif(); do_final_loginif(); - // write online players files with no player - online_char_db->clear(online_char_db, NULL); - create_online_files(); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `ragsrvinfo`") ) + Sql_ShowDebug(sql_handle); + char_db_->destroy(char_db_, NULL); online_char_db->destroy(online_char_db, NULL); auth_db->destroy(auth_db, NULL); - - if(char_dat) aFree(char_dat); - + if( char_fd != -1 ) { do_close(char_fd); char_fd = -1; } -#ifdef ENABLE_SC_SAVING - status_final(); -#endif - inter_final(); + Sql_Free(sql_handle); mapindex_final(); - char_log("----End of char-server (normal end with closing of all files).\n"); ShowStatus("Finished.\n"); } @@ -4679,28 +4510,24 @@ int do_init(int argc, char **argv) char_config_read((argc < 2) ? CHAR_CONF_NAME : argv[1]); char_lan_config_read((argc > 3) ? argv[3] : LAN_CONF_NAME); + sql_config_read(SQL_CONF_NAME); if (strcmp(userid, "s1")==0 && strcmp(passwd, "p1")==0) { ShowError("Using the default user/password s1/p1 is NOT RECOMMENDED.\n"); - ShowNotice("Please edit your save/account.txt file to create a proper inter-server user/password (gender 'S')\n"); + ShowNotice("Please edit your 'login' table to create a proper inter-server user/password (gender 'S')\n"); ShowNotice("And then change the user/password to use in conf/char_athena.conf (or conf/import/char_conf.txt)\n"); } ShowInfo("Finished reading the char-server configuration.\n"); - // a newline in the log... - char_log(""); - char_log("The char-server starting...\n"); - + inter_init_sql((argc > 2) ? argv[2] : inter_cfgName); // inter server テハア篳ュ + ShowInfo("Finished reading the inter-server configuration.\n"); + ShowInfo("Initializing char server.\n"); auth_db = idb_alloc(DB_OPT_RELEASE_DATA); online_char_db = idb_alloc(DB_OPT_RELEASE_DATA); - mmo_char_init(); + mmo_char_sql_init(); char_read_fame_list(); //Read fame lists. -#ifdef ENABLE_SC_SAVING - status_init(); -#endif - inter_init_txt((argc > 2) ? argv[2] : inter_cfgName); // inter server 初期化 ShowInfo("char server initialized.\n"); if ((naddr_ != 0) && (!login_ip || !char_ip)) @@ -4736,18 +4563,32 @@ int do_init(int argc, char **argv) add_timer_func_list(online_data_cleanup, "online_data_cleanup"); add_timer_interval(gettick() + 1000, online_data_cleanup, 0, 0, 600 * 1000); - // periodic flush of all saved data to disk - add_timer_func_list(mmo_char_sync_timer, "mmo_char_sync_timer"); - add_timer_interval(gettick() + 1000, mmo_char_sync_timer, 0, 0, autosave_interval); - if( console ) { //##TODO invoke a CONSOLE_START plugin event } + //Cleaning the tables for NULL entrys @ startup [Sirius] + //Chardb clean + ShowInfo("Cleaning the '%s' table...\n", char_db); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id` = '0'", char_db) ) + Sql_ShowDebug(sql_handle); + + //guilddb clean + ShowInfo("Cleaning the '%s' table...\n", guild_db); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_lv` = '0' AND `max_member` = '0' AND `exp` = '0' AND `next_exp` = '0' AND `average_lv` = '0'", guild_db) ) + Sql_ShowDebug(sql_handle); + + //guildmemberdb clean + ShowInfo("Cleaning the '%s' table...\n", guild_member_db); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '0' AND `account_id` = '0' AND `char_id` = '0'", guild_member_db) ) + Sql_ShowDebug(sql_handle); + + ShowInfo("End of char server initilization function.\n"); + set_defaultparse(parse_char); + ShowInfo("open port %d.....\n",char_port); char_fd = make_listen_bind(bind_ip, char_port); - char_log("The char-server is ready (Server is listening on the port %d).\n", char_port); ShowStatus("The char-server is "CL_GREEN"ready"CL_RESET" (Server is listening on the port %d).\n\n", char_port); if( runflag != CORE_ST_STOP ) @@ -4758,5 +4599,3 @@ int do_init(int argc, char **argv) return 0; } - -#endif //TXT_SQL_CONVERT diff --git a/src/char/char.h b/src/char/char.h index bb1a530f0..73c2f9f72 100644 --- a/src/char/char.h +++ b/src/char/char.h @@ -1,62 +1,81 @@ // Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder -#ifndef _CHAR_H_ -#define _CHAR_H_ +#ifndef _CHAR_SQL_H_ +#define _CHAR_SQL_H_ #include "../common/core.h" // CORE_ST_LAST -#include "../common/mmo.h" -#ifndef TXT_SQL_CONVERT enum E_CHARSERVER_ST { CHARSERVER_ST_RUNNING = CORE_ST_LAST, CHARSERVER_ST_SHUTDOWN, CHARSERVER_ST_LAST }; -#endif + +struct mmo_charstatus; #define MAX_MAP_SERVERS 30 #define DEFAULT_AUTOSAVE_INTERVAL 300*1000 -struct character_data { - struct mmo_charstatus status; - int global_num; - struct global_reg global[GLOBAL_REG_NUM]; +enum { + TABLE_INVENTORY, + TABLE_CART, + TABLE_STORAGE, + TABLE_GUILD_STORAGE, }; -struct mmo_charstatus* search_character(int aid, int cid); -struct mmo_charstatus* search_character_byname(char* character_name); -int search_character_index(char* character_name); -char* search_character_name(int index); -int search_character_online(int aid, int cid); +int memitemdata_to_sql(const struct item items[], int max, int id, int tableswitch); -int mapif_sendall(unsigned char *buf, unsigned int len); -int mapif_sendallwos(int fd,unsigned char *buf, unsigned int len); -int mapif_send(int fd,unsigned char *buf, unsigned int len); +int mapif_sendall(unsigned char *buf,unsigned int len); +int mapif_sendallwos(int fd,unsigned char *buf,unsigned int len); +int mapif_send(int fd,unsigned char *buf,unsigned int len); int char_married(int pl1,int pl2); int char_child(int parent_id, int child_id); -int char_family(int cid1, int cid2, int cid3); - -int char_log(char *fmt, ...); +int char_family(int pl1,int pl2,int pl3); int request_accreg2(int account_id, int char_id); -int char_parse_Registry(int account_id, int char_id, unsigned char *buf, int len); -int save_accreg2(unsigned char *buf, int len); -int char_account_reg_reply(int fd,int account_id,int char_id); +int save_accreg2(unsigned char* buf, int len); extern int char_name_option; extern char char_name_letters[]; +extern bool char_gm_read; extern int autosave_interval; +extern int save_log; extern char db_path[]; +extern char char_db[256]; +extern char scdata_db[256]; +extern char cart_db[256]; +extern char inventory_db[256]; +extern char charlog_db[256]; +extern char storage_db[256]; +extern char interlog_db[256]; +extern char reg_db[256]; +extern char skill_db[256]; +extern char memo_db[256]; +extern char guild_db[256]; +extern char guild_alliance_db[256]; +extern char guild_castle_db[256]; +extern char guild_expulsion_db[256]; +extern char guild_member_db[256]; +extern char guild_position_db[256]; +extern char guild_skill_db[256]; +extern char guild_storage_db[256]; +extern char party_db[256]; +extern char pet_db[256]; +extern char mail_db[256]; +extern char auction_db[256]; +extern char quest_db[256]; + +extern int db_use_sqldbs; // added for sql item_db read for char server [Valaris] + extern int guild_exp_rate; extern int log_inter; + //Exported for use in the TXT-SQL converter. -extern char char_txt[]; -int char_config_read(const char *cfgName); -int mmo_char_fromstr(char *str, struct mmo_charstatus *p, struct global_reg *reg, int *reg_num); -int parse_friend_txt(struct mmo_charstatus *p); +int mmo_char_tosql(int char_id, struct mmo_charstatus *p); +void sql_config_read(const char *cfgName); -#endif /* _CHAR_H_ */ +#endif /* _CHAR_SQL_H_ */ diff --git a/src/char/int_auction.c b/src/char/int_auction.c new file mode 100644 index 000000000..04e321062 --- /dev/null +++ b/src/char/int_auction.c @@ -0,0 +1,494 @@ +// Copyright (c) Athena Dev Teams - Licensed under GNU GPL +// For more information, see LICENCE in the main folder + +#include "../common/mmo.h" +#include "../common/malloc.h" +#include "../common/db.h" +#include "../common/showmsg.h" +#include "../common/socket.h" +#include "../common/strlib.h" +#include "../common/sql.h" +#include "../common/timer.h" +#include "char.h" +#include "inter.h" +#include "int_mail.h" +#include "int_auction.h" + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +static DBMap* auction_db_ = NULL; // int auction_id -> struct auction_data* + +void auction_delete(struct auction_data *auction); +static int auction_end_timer(int tid, unsigned int tick, int id, intptr_t data); + +static int auction_count(int char_id, bool buy) +{ + int i = 0; + struct auction_data *auction; + DBIterator* iter; + DBKey key; + + iter = auction_db_->iterator(auction_db_); + for( auction = (struct auction_data*)iter->first(iter,&key); iter->exists(iter); auction = (struct auction_data*)iter->next(iter,&key) ) + { + if( (buy && auction->buyer_id == char_id) || (!buy && auction->seller_id == char_id) ) + i++; + } + iter->destroy(iter); + + return i; +} + +void auction_save(struct auction_data *auction) +{ + int j; + StringBuf buf; + SqlStmt* stmt; + + if( !auction ) + return; + + StringBuf_Init(&buf); + StringBuf_Printf(&buf, "UPDATE `%s` SET `seller_id` = '%d', `seller_name` = ?, `buyer_id` = '%d', `buyer_name` = ?, `price` = '%d', `buynow` = '%d', `hours` = '%d', `timestamp` = '%lu', `nameid` = '%d', `item_name` = ?, `type` = '%d', `refine` = '%d', `attribute` = '%d'", + auction_db, auction->seller_id, auction->buyer_id, auction->price, auction->buynow, auction->hours, (unsigned long)auction->timestamp, auction->item.nameid, auction->type, auction->item.refine, auction->item.attribute); + for( j = 0; j < MAX_SLOTS; j++ ) + StringBuf_Printf(&buf, ", `card%d` = '%d'", j, auction->item.card[j]); + StringBuf_Printf(&buf, " WHERE `auction_id` = '%d'", auction->auction_id); + + stmt = SqlStmt_Malloc(sql_handle); + if( SQL_SUCCESS != SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, auction->seller_name, strnlen(auction->seller_name, NAME_LENGTH)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, auction->buyer_name, strnlen(auction->buyer_name, NAME_LENGTH)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 2, SQLDT_STRING, auction->item_name, strnlen(auction->item_name, ITEM_NAME_LENGTH)) + || SQL_SUCCESS != SqlStmt_Execute(stmt) ) + { + SqlStmt_ShowDebug(stmt); + } + + SqlStmt_Free(stmt); + StringBuf_Destroy(&buf); +} + +unsigned int auction_create(struct auction_data *auction) +{ + int j; + StringBuf buf; + SqlStmt* stmt; + + if( !auction ) + return false; + + auction->timestamp = time(NULL) + (auction->hours * 3600); + + StringBuf_Init(&buf); + StringBuf_Printf(&buf, "INSERT INTO `%s` (`seller_id`,`seller_name`,`buyer_id`,`buyer_name`,`price`,`buynow`,`hours`,`timestamp`,`nameid`,`item_name`,`type`,`refine`,`attribute`", auction_db); + for( j = 0; j < MAX_SLOTS; j++ ) + StringBuf_Printf(&buf, ",`card%d`", j); + StringBuf_Printf(&buf, ") VALUES ('%d',?,'%d',?,'%d','%d','%d','%lu','%d',?,'%d','%d','%d'", + auction->seller_id, auction->buyer_id, auction->price, auction->buynow, auction->hours, (unsigned long)auction->timestamp, auction->item.nameid, auction->type, auction->item.refine, auction->item.attribute); + for( j = 0; j < MAX_SLOTS; j++ ) + StringBuf_Printf(&buf, ",'%d'", auction->item.card[j]); + StringBuf_AppendStr(&buf, ")"); + + stmt = SqlStmt_Malloc(sql_handle); + if( SQL_SUCCESS != SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, auction->seller_name, strnlen(auction->seller_name, NAME_LENGTH)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, auction->buyer_name, strnlen(auction->buyer_name, NAME_LENGTH)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 2, SQLDT_STRING, auction->item_name, strnlen(auction->item_name, ITEM_NAME_LENGTH)) + || SQL_SUCCESS != SqlStmt_Execute(stmt) ) + { + SqlStmt_ShowDebug(stmt); + auction->auction_id = 0; + } + else + { + struct auction_data *auction_; + unsigned int tick = auction->hours * 3600000; + + auction->item.amount = 1; + auction->item.identify = 1; + auction->item.expire_time = 0; + + auction->auction_id = (unsigned int)SqlStmt_LastInsertId(stmt); + auction->auction_end_timer = add_timer( gettick() + tick , auction_end_timer, auction->auction_id, 0); + ShowInfo("New Auction %u | time left %u ms | By %s.\n", auction->auction_id, tick, auction->seller_name); + + CREATE(auction_, struct auction_data, 1); + memcpy(auction_, auction, sizeof(struct auction_data)); + idb_put(auction_db_, auction_->auction_id, auction_); + } + + SqlStmt_Free(stmt); + StringBuf_Destroy(&buf); + + return auction->auction_id; +} + +static void mapif_Auction_message(int char_id, unsigned char result) +{ + unsigned char buf[74]; + + WBUFW(buf,0) = 0x3854; + WBUFL(buf,2) = char_id; + WBUFL(buf,6) = result; + mapif_sendall(buf,7); +} + +static int auction_end_timer(int tid, unsigned int tick, int id, intptr_t data) +{ + struct auction_data *auction; + if( (auction = (struct auction_data *)idb_get(auction_db_, id)) != NULL ) + { + if( auction->buyer_id ) + { + mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "Thanks, you won the auction!.", 0, &auction->item); + mapif_Auction_message(auction->buyer_id, 6); // You have won the auction + mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Payment for your auction!.", auction->price, NULL); + } + else + mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "No buyers have been found for your auction.", 0, &auction->item); + + ShowInfo("Auction End: id %u.\n", auction->auction_id); + + auction->auction_end_timer = INVALID_TIMER; + auction_delete(auction); + } + + return 0; +} + +void auction_delete(struct auction_data *auction) +{ + unsigned int auction_id = auction->auction_id; + + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `auction_id` = '%d'", auction_db, auction_id) ) + Sql_ShowDebug(sql_handle); + + if( auction->auction_end_timer != INVALID_TIMER ) + delete_timer(auction->auction_end_timer, auction_end_timer); + + idb_remove(auction_db_, auction_id); +} + +void inter_auctions_fromsql(void) +{ + int i; + struct auction_data *auction; + struct item *item; + char *data; + StringBuf buf; + unsigned int tick = gettick(), endtick; + time_t now = time(NULL); + + StringBuf_Init(&buf); + StringBuf_AppendStr(&buf, "SELECT `auction_id`,`seller_id`,`seller_name`,`buyer_id`,`buyer_name`," + "`price`,`buynow`,`hours`,`timestamp`,`nameid`,`item_name`,`type`,`refine`,`attribute`"); + for( i = 0; i < MAX_SLOTS; i++ ) + StringBuf_Printf(&buf, ",`card%d`", i); + StringBuf_Printf(&buf, " FROM `%s` ORDER BY `auction_id` DESC", auction_db); + + if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) ) + Sql_ShowDebug(sql_handle); + + StringBuf_Destroy(&buf); + + while( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + CREATE(auction, struct auction_data, 1); + Sql_GetData(sql_handle, 0, &data, NULL); auction->auction_id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); auction->seller_id = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); safestrncpy(auction->seller_name, data, NAME_LENGTH); + Sql_GetData(sql_handle, 3, &data, NULL); auction->buyer_id = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); safestrncpy(auction->buyer_name, data, NAME_LENGTH); + Sql_GetData(sql_handle, 5, &data, NULL); auction->price = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); auction->buynow = atoi(data); + Sql_GetData(sql_handle, 7, &data, NULL); auction->hours = atoi(data); + Sql_GetData(sql_handle, 8, &data, NULL); auction->timestamp = atoi(data); + + item = &auction->item; + Sql_GetData(sql_handle, 9, &data, NULL); item->nameid = atoi(data); + Sql_GetData(sql_handle,10, &data, NULL); safestrncpy(auction->item_name, data, ITEM_NAME_LENGTH); + Sql_GetData(sql_handle,11, &data, NULL); auction->type = atoi(data); + + Sql_GetData(sql_handle,12, &data, NULL); item->refine = atoi(data); + Sql_GetData(sql_handle,13, &data, NULL); item->attribute = atoi(data); + + item->identify = 1; + item->amount = 1; + item->expire_time = 0; + + for( i = 0; i < MAX_SLOTS; i++ ) + { + Sql_GetData(sql_handle, 14 + i, &data, NULL); + item->card[i] = atoi(data); + } + + if( auction->timestamp > now ) + endtick = ((unsigned int)(auction->timestamp - now) * 1000) + tick; + else + endtick = tick + 10000; // 10 Second's to process ended auctions + + auction->auction_end_timer = add_timer(endtick, auction_end_timer, auction->auction_id, 0); + idb_put(auction_db_, auction->auction_id, auction); + } + + Sql_FreeResult(sql_handle); +} + +static void mapif_Auction_sendlist(int fd, int char_id, short count, short pages, unsigned char *buf) +{ + int len = (sizeof(struct auction_data) * count) + 12; + + WFIFOHEAD(fd, len); + WFIFOW(fd,0) = 0x3850; + WFIFOW(fd,2) = len; + WFIFOL(fd,4) = char_id; + WFIFOW(fd,8) = count; + WFIFOW(fd,10) = pages; + memcpy(WFIFOP(fd,12), buf, len - 12); + WFIFOSET(fd,len); +} + +static void mapif_parse_Auction_requestlist(int fd) +{ + char searchtext[NAME_LENGTH]; + int char_id = RFIFOL(fd,4), len = sizeof(struct auction_data); + int price = RFIFOL(fd,10); + short type = RFIFOW(fd,8), page = max(1,RFIFOW(fd,14)); + unsigned char buf[5 * sizeof(struct auction_data)]; + DBIterator* iter; + DBKey key; + struct auction_data *auction; + short i = 0, j = 0, pages = 1; + + memcpy(searchtext, RFIFOP(fd,16), NAME_LENGTH); + + iter = auction_db_->iterator(auction_db_); + for( auction = (struct auction_data*)iter->first(iter,&key); iter->exists(iter); auction = (struct auction_data*)iter->next(iter,&key) ) + { + if( (type == 0 && auction->type != IT_ARMOR && auction->type != IT_PETARMOR) || + (type == 1 && auction->type != IT_WEAPON) || + (type == 2 && auction->type != IT_CARD) || + (type == 3 && auction->type != IT_ETC) || + (type == 4 && !strstr(auction->item_name, searchtext)) || + (type == 5 && auction->price > price) || + (type == 6 && auction->seller_id != char_id) || + (type == 7 && auction->buyer_id != char_id) ) + continue; + + i++; + if( i > 5 ) + { // Counting Pages of Total Results (5 Results per Page) + pages++; + i = 1; // First Result of This Page + } + + if( page != pages ) + continue; // This is not the requested Page + + memcpy(WBUFP(buf, j * len), auction, len); + j++; // Found Results + } + iter->destroy(iter); + + mapif_Auction_sendlist(fd, char_id, j, pages, buf); +} + +static void mapif_Auction_register(int fd, struct auction_data *auction) +{ + int len = sizeof(struct auction_data) + 4; + + WFIFOHEAD(fd,len); + WFIFOW(fd,0) = 0x3851; + WFIFOW(fd,2) = len; + memcpy(WFIFOP(fd,4), auction, sizeof(struct auction_data)); + WFIFOSET(fd,len); +} + +static void mapif_parse_Auction_register(int fd) +{ + struct auction_data auction; + if( RFIFOW(fd,2) != sizeof(struct auction_data) + 4 ) + return; + + memcpy(&auction, RFIFOP(fd,4), sizeof(struct auction_data)); + if( auction_count(auction.seller_id, false) < 5 ) + auction.auction_id = auction_create(&auction); + + mapif_Auction_register(fd, &auction); +} + +static void mapif_Auction_cancel(int fd, int char_id, unsigned char result) +{ + WFIFOHEAD(fd,7); + WFIFOW(fd,0) = 0x3852; + WFIFOL(fd,2) = char_id; + WFIFOB(fd,6) = result; + WFIFOSET(fd,7); +} + +static void mapif_parse_Auction_cancel(int fd) +{ + int char_id = RFIFOL(fd,2), auction_id = RFIFOL(fd,6); + struct auction_data *auction; + + if( (auction = (struct auction_data *)idb_get(auction_db_, auction_id)) == NULL ) + { + mapif_Auction_cancel(fd, char_id, 1); // Bid Number is Incorrect + return; + } + + if( auction->seller_id != char_id ) + { + mapif_Auction_cancel(fd, char_id, 2); // You cannot end the auction + return; + } + + if( auction->buyer_id > 0 ) + { + mapif_Auction_cancel(fd, char_id, 3); // An auction with at least one bidder cannot be canceled + return; + } + + mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Auction canceled.", 0, &auction->item); + auction_delete(auction); + + mapif_Auction_cancel(fd, char_id, 0); // The auction has been canceled +} + +static void mapif_Auction_close(int fd, int char_id, unsigned char result) +{ + WFIFOHEAD(fd,7); + WFIFOW(fd,0) = 0x3853; + WFIFOL(fd,2) = char_id; + WFIFOB(fd,6) = result; + WFIFOSET(fd,7); +} + +static void mapif_parse_Auction_close(int fd) +{ + int char_id = RFIFOL(fd,2), auction_id = RFIFOL(fd,6); + struct auction_data *auction; + + if( (auction = (struct auction_data *)idb_get(auction_db_, auction_id)) == NULL ) + { + mapif_Auction_close(fd, char_id, 2); // Bid Number is Incorrect + return; + } + + if( auction->seller_id != char_id ) + { + mapif_Auction_close(fd, char_id, 1); // You cannot end the auction + return; + } + + if( auction->buyer_id == 0 ) + { + mapif_Auction_close(fd, char_id, 1); // You cannot end the auction + return; + } + + // Send Money to Seller + mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Auction closed.", auction->price, NULL); + // Send Item to Buyer + mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "Auction winner.", 0, &auction->item); + mapif_Auction_message(auction->buyer_id, 6); // You have won the auction + auction_delete(auction); + + mapif_Auction_close(fd, char_id, 0); // You have ended the auction +} + +static void mapif_Auction_bid(int fd, int char_id, int bid, unsigned char result) +{ + WFIFOHEAD(fd,11); + WFIFOW(fd,0) = 0x3855; + WFIFOL(fd,2) = char_id; + WFIFOL(fd,6) = bid; // To Return Zeny + WFIFOB(fd,10) = result; + WFIFOSET(fd,11); +} + +static void mapif_parse_Auction_bid(int fd) +{ + int char_id = RFIFOL(fd,4), bid = RFIFOL(fd,12); + unsigned int auction_id = RFIFOL(fd,8); + struct auction_data *auction; + + if( (auction = (struct auction_data *)idb_get(auction_db_, auction_id)) == NULL || auction->price >= bid || auction->seller_id == char_id ) + { + mapif_Auction_bid(fd, char_id, bid, 0); // You have failed to bid in the auction + return; + } + + if( auction_count(char_id, true) > 4 && bid < auction->buynow && auction->buyer_id != char_id ) + { + mapif_Auction_bid(fd, char_id, bid, 9); // You cannot place more than 5 bids at a time + return; + } + + if( auction->buyer_id > 0 ) + { // Send Money back to the previous Buyer + if( auction->buyer_id != char_id ) + { + mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "Someone has placed a higher bid.", auction->price, NULL); + mapif_Auction_message(auction->buyer_id, 7); // You have failed to win the auction + } + else + mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "You have placed a higher bid.", auction->price, NULL); + } + + auction->buyer_id = char_id; + safestrncpy(auction->buyer_name, (char*)RFIFOP(fd,16), NAME_LENGTH); + auction->price = bid; + + if( bid >= auction->buynow ) + { // Automatic won the auction + mapif_Auction_bid(fd, char_id, bid - auction->buynow, 1); // You have successfully bid in the auction + + mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "You have won the auction.", 0, &auction->item); + mapif_Auction_message(char_id, 6); // You have won the auction + mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Payment for your auction!.", auction->buynow, NULL); + + auction_delete(auction); + return; + } + + auction_save(auction); + + mapif_Auction_bid(fd, char_id, 0, 1); // You have successfully bid in the auction +} + +/*========================================== + * Packets From Map Server + *------------------------------------------*/ +int inter_auction_parse_frommap(int fd) +{ + switch(RFIFOW(fd,0)) + { + case 0x3050: mapif_parse_Auction_requestlist(fd); break; + case 0x3051: mapif_parse_Auction_register(fd); break; + case 0x3052: mapif_parse_Auction_cancel(fd); break; + case 0x3053: mapif_parse_Auction_close(fd); break; + case 0x3055: mapif_parse_Auction_bid(fd); break; + default: + return 0; + } + return 1; +} + +int inter_auction_sql_init(void) +{ + auction_db_ = idb_alloc(DB_OPT_RELEASE_DATA); + inter_auctions_fromsql(); + + return 0; +} + +void inter_auction_sql_final(void) +{ + auction_db_->destroy(auction_db_,NULL); + + return; +} diff --git a/src/char/int_auction.h b/src/char/int_auction.h new file mode 100644 index 000000000..bf26b152c --- /dev/null +++ b/src/char/int_auction.h @@ -0,0 +1,12 @@ +// Copyright (c) Athena Dev Teams - Licensed under GNU GPL +// For more information, see LICENCE in the main folder + +#ifndef _INT_AUCTION_SQL_H_ +#define _INT_AUCTION_SQL_H_ + +int inter_auction_parse_frommap(int fd); + +int inter_auction_sql_init(void); +void inter_auction_sql_final(void); + +#endif /* _INT_AUCTION_SQL_H_ */ diff --git a/src/char/int_guild.c b/src/char/int_guild.c index 31cceeff0..2ce6d6141 100644 --- a/src/char/int_guild.c +++ b/src/char/int_guild.c @@ -6,381 +6,634 @@ #include "../common/malloc.h" #include "../common/socket.h" #include "../common/db.h" -#include "../common/lock.h" #include "../common/showmsg.h" #include "../common/strlib.h" +#include "../common/timer.h" #include "char.h" #include "inter.h" -#include "int_storage.h" #include "int_guild.h" #include <string.h> #include <stdio.h> #include <stdlib.h> -char guild_txt[1024] = "save/guild.txt"; -char castle_txt[1024] = "save/castle.txt"; +#define GS_MEMBER_UNMODIFIED 0x00 +#define GS_MEMBER_MODIFIED 0x01 +#define GS_MEMBER_NEW 0x02 -#ifndef TXT_SQL_CONVERT -static DBMap* guild_db; // int guild_id -> struct guild* -static DBMap* castle_db; // int castle_id -> struct guild_castle* +#define GS_POSITION_UNMODIFIED 0x00 +#define GS_POSITION_MODIFIED 0x01 -static int guild_newid = 10000; +// LSB = 0 => Alliance, LSB = 1 => Opposition +#define GUILD_ALLIANCE_TYPE_MASK 0x01 +#define GUILD_ALLIANCE_REMOVE 0x08 + +static const char dataToHex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + +//Guild cache +static DBMap* guild_db_; // int guild_id -> struct guild* + +struct guild_castle castles[MAX_GUILDCASTLE]; static unsigned int guild_exp[100]; -int mapif_guild_broken(int guild_id, int flag); +int mapif_parse_GuildLeave(int fd,int guild_id,int account_id,int char_id,int flag,const char *mes); +int mapif_guild_broken(int guild_id,int flag); static bool guild_check_empty(struct guild *g); int guild_calcinfo(struct guild *g); -int mapif_guild_basicinfochanged(int guild_id, int type, const void *data, int len); -int mapif_guild_info(int fd, struct guild *g); -int guild_break_sub(DBKey key, void *data, va_list ap); +int mapif_guild_basicinfochanged(int guild_id,int type,const void *data,int len); +int mapif_guild_info(int fd,struct guild *g); +int guild_break_sub(int key,void *data,va_list ap); +int inter_guild_tosql(struct guild *g,int flag); -/// serializes the guild data structure into the provided string -int inter_guild_tostr(char* str, struct guild* g) +static int guild_save_timer(int tid, unsigned int tick, int id, intptr_t data) { - int i, c, len; + static int last_id = 0; //To know in which guild we were. + int state = 0; //0: Have not reached last guild. 1: Reached last guild, ready for save. 2: Some guild saved, don't do further saving. + DBIterator* iter; + DBKey key; + struct guild* g; - // save guild base info - len = sprintf(str, "%d\t%s\t%s\t%d,%d,%"PRIu64",%d,%d\t%s#\t%s#\t", - g->guild_id, g->name, g->master, g->guild_lv, g->max_member, g->exp, g->skill_point, 0, g->mes1, g->mes2); + if( last_id == 0 ) //Save the first guild in the list. + state = 1; - // save guild member info - for(i = 0; i < g->max_member; i++) + iter = guild_db_->iterator(guild_db_); + for( g = (struct guild*)iter->first(iter,&key); iter->exists(iter); g = (struct guild*)iter->next(iter,&key) ) { - struct guild_member *m = &g->member[i]; - len += sprintf(str + len, "%d,%d,%d,%d,%d,%d,%d,%"PRIu64",%d,%d\t%s\t", - m->account_id, m->char_id, - m->hair, m->hair_color, m->gender, - m->class_, m->lv, m->exp, m->exp_payper, m->position, - ((m->account_id > 0) ? m->name : "-")); - } - - // save guild position info - for(i = 0; i < MAX_GUILDPOSITION; i++) { - struct guild_position *p = &g->position[i]; - len += sprintf(str + len, "%d,%d\t%s#\t", p->mode, p->exp_mode, p->name); - } + if( state == 0 && g->guild_id == last_id ) + state++; //Save next guild in the list. + else + if( state == 1 && g->save_flag&GS_MASK ) + { + inter_guild_tosql(g, g->save_flag&GS_MASK); + g->save_flag &= ~GS_MASK; - // save guild emblem - len += sprintf(str + len, "%d,%d,", g->emblem_len, g->emblem_id); - for(i = 0; i < g->emblem_len; i++) { - len += sprintf(str + len, "%02x", (unsigned char)(g->emblem_data[i])); - } - len += sprintf(str + len, "$\t"); + //Some guild saved. + last_id = g->guild_id; + state++; + } - // save guild alliance info - c = 0; - for(i = 0; i < MAX_GUILDALLIANCE; i++) - if (g->alliance[i].guild_id > 0) - c++; - len += sprintf(str + len, "%d\t", c); - for(i = 0; i < MAX_GUILDALLIANCE; i++) { - struct guild_alliance *a = &g->alliance[i]; - if (a->guild_id > 0) - len += sprintf(str + len, "%d,%d\t%s\t", a->guild_id, a->opposition, a->name); + if( g->save_flag == GS_REMOVE ) + {// Nothing to save, guild is ready for removal. + if (save_log) + ShowInfo("Guild Unloaded (%d - %s)\n", g->guild_id, g->name); + db_remove(guild_db_, key); + } } + iter->destroy(iter); - // save guild expulsion info - c = 0; - for(i = 0; i < MAX_GUILDEXPULSION; i++) - if (g->expulsion[i].account_id > 0) - c++; - len += sprintf(str + len, "%d\t", c); - for(i = 0; i < MAX_GUILDEXPULSION; i++) { - struct guild_expulsion *e = &g->expulsion[i]; - if (e->account_id > 0) - len += sprintf(str + len, "%d,%d,%d,%d\t%s\t%s\t%s#\t", - e->account_id, 0, 0, 0, e->name, "#", e->mes ); - } + if( state != 2 ) //Reached the end of the guild db without saving. + last_id = 0; //Reset guild saved, return to beginning. - // save guild skill info - for(i = 0; i < MAX_GUILDSKILL; i++) { - len += sprintf(str + len, "%d,%d ", g->skill[i].id, g->skill[i].lv); - } - len += sprintf(str + len, "\t"); + state = guild_db_->size(guild_db_); + if( state < 1 ) state = 1; //Calculate the time slot for the next save. + add_timer(tick + autosave_interval/state, guild_save_timer, 0, 0); + return 0; +} +int inter_guild_removemember_tosql(int account_id, int char_id) +{ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE from `%s` where `account_id` = '%d' and `char_id` = '%d'", guild_member_db, account_id, char_id) ) + Sql_ShowDebug(sql_handle); + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `guild_id` = '0' WHERE `char_id` = '%d'", char_db, char_id) ) + Sql_ShowDebug(sql_handle); return 0; } -#endif //TXT_SQL_CONVERT -/// parses the guild data string into a guild data structure -int inter_guild_fromstr(char* str, struct guild* g) +// Save guild into sql +int inter_guild_tosql(struct guild *g,int flag) { - int i, c; - char *pstr; - - memset(g, 0, sizeof(struct guild)); - - {// load guild base info - int guildid; - char name[256]; // only 24 used - char master[256]; // only 24 used - int guildlv; - int max_member; - uint64 exp; - int skpoint; - char mes1[256]; // only 60 used - char mes2[256]; // only 120 used - int len; - - if( sscanf(str, "%d\t%[^\t]\t%[^\t]\t%d,%d,%"SCNu64",%d,%*d\t%[^\t]\t%[^\t]\t%n", - &guildid, name, master, &guildlv, &max_member, &exp, &skpoint, mes1, mes2, &len) < 9 ) - return 1; - - // remove '#' - mes1[strlen(mes1)-1] = '\0'; - mes2[strlen(mes2)-1] = '\0'; - - g->guild_id = guildid; - g->guild_lv = guildlv; - g->max_member = max_member; - g->exp = exp; - g->skill_point = skpoint; - safestrncpy(g->name, name, sizeof(g->name)); - safestrncpy(g->master, master, sizeof(g->master)); - safestrncpy(g->mes1, mes1, sizeof(g->mes1)); - safestrncpy(g->mes2, mes2, sizeof(g->mes2)); - - str+= len; - } - - {// load guild member info - int accountid; - int charid; - int hair, hair_color, gender; - int class_, lv; - uint64 exp; - int exp_payper; - int position; - char name[256]; // only 24 used - int len; - int i; + // Table guild (GS_BASIC_MASK) + // GS_EMBLEM `emblem_len`,`emblem_id`,`emblem_data` + // GS_CONNECT `connect_member`,`average_lv` + // GS_MES `mes1`,`mes2` + // GS_LEVEL `guild_lv`,`max_member`,`exp`,`next_exp`,`skill_point` + // GS_BASIC `name`,`master`,`char_id` + + // GS_MEMBER `guild_member` (`guild_id`,`account_id`,`char_id`,`hair`,`hair_color`,`gender`,`class`,`lv`,`exp`,`exp_payper`,`online`,`position`,`name`) + // GS_POSITION `guild_position` (`guild_id`,`position`,`name`,`mode`,`exp_mode`) + // GS_ALLIANCE `guild_alliance` (`guild_id`,`opposition`,`alliance_id`,`name`) + // GS_EXPULSION `guild_expulsion` (`guild_id`,`account_id`,`name`,`mes`) + // GS_SKILL `guild_skill` (`guild_id`,`id`,`lv`) + + // temporary storage for str convertion. They must be twice the size of the + // original string to ensure no overflows will occur. [Skotlex] + char t_info[256]; + char esc_name[NAME_LENGTH*2+1]; + char esc_master[NAME_LENGTH*2+1]; + char new_guild = 0; + int i=0; + + if (g->guild_id<=0 && g->guild_id != -1) return 0; + +#ifdef NOISY + ShowInfo("Save guild request ("CL_BOLD"%d"CL_RESET" - flag 0x%x).",g->guild_id, flag); +#endif + + Sql_EscapeStringLen(sql_handle, esc_name, g->name, strnlen(g->name, NAME_LENGTH)); + Sql_EscapeStringLen(sql_handle, esc_master, g->master, strnlen(g->master, NAME_LENGTH)); + *t_info = '\0'; + + // Insert a new guild the guild + if (flag&GS_BASIC && g->guild_id == -1) + { + strcat(t_info, " guild_create"); - for( i = 0; i < g->max_member; i++ ) + // Create a new guild + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` " + "(`name`,`master`,`guild_lv`,`max_member`,`average_lv`,`char_id`) " + "VALUES ('%s', '%s', '%d', '%d', '%d', '%d')", + guild_db, esc_name, esc_master, g->guild_lv, g->max_member, g->average_lv, g->member[0].char_id) ) + { + Sql_ShowDebug(sql_handle); + if (g->guild_id == -1) + return 0; //Failed to create guild! + } + else { - struct guild_member* m = &g->member[i]; - if (sscanf(str, "%d,%d,%d,%d,%d,%d,%d,%"SCNu64",%d,%d\t%[^\t]\t%n", - &accountid, &charid, &hair, &hair_color, &gender, - &class_, &lv, &exp, &exp_payper, &position, - name, &len) < 11) - return 1; - - m->account_id = accountid; - m->char_id = charid; - m->hair = hair; - m->hair_color = hair_color; - m->gender = gender; - m->class_ = class_; - m->lv = lv; - m->exp = exp; - m->exp_payper = exp_payper; - m->position = position; - safestrncpy(m->name, name, NAME_LENGTH); - - str+= len; + g->guild_id = (int)Sql_LastInsertId(sql_handle); + new_guild = 1; } } - {// load guild position info - int mode, exp_mode; - char name[256]; // only 24 used - int len; - int i = 0; - int j; + // If we need an update on an existing guild or more update on the new guild + if (((flag & GS_BASIC_MASK) && !new_guild) || ((flag & (GS_BASIC_MASK & ~GS_BASIC)) && new_guild)) + { + StringBuf buf; + bool add_comma = false; - while (sscanf(str, "%d,%d%n", &mode, &exp_mode, &j) == 2 && str[j] == '\t') + StringBuf_Init(&buf); + StringBuf_Printf(&buf, "UPDATE `%s` SET ", guild_db); + + if (flag & GS_EMBLEM) { - struct guild_position *p = &g->position[i]; - if (sscanf(str, "%d,%d\t%[^\t]\t%n", &mode, &exp_mode, name, &len) < 3) - return 1; + char emblem_data[sizeof(g->emblem_data)*2+1]; + char* pData = emblem_data; + + strcat(t_info, " emblem"); + // Convert emblem_data to hex + //TODO: why not use binary directly? [ultramage] + for(i=0; i<g->emblem_len; i++){ + *pData++ = dataToHex[(g->emblem_data[i] >> 4) & 0x0F]; + *pData++ = dataToHex[g->emblem_data[i] & 0x0F]; + } + *pData = 0; + StringBuf_Printf(&buf, "`emblem_len`=%d, `emblem_id`=%d, `emblem_data`='%s'", g->emblem_len, g->emblem_id, emblem_data); + add_comma = true; + } + if (flag & GS_BASIC) + { + strcat(t_info, " basic"); + if( add_comma ) + StringBuf_AppendStr(&buf, ", "); + else + add_comma = true; + StringBuf_Printf(&buf, "`name`='%s', `master`='%s', `char_id`=%d", esc_name, esc_master, g->member[0].char_id); + } + if (flag & GS_CONNECT) + { + strcat(t_info, " connect"); + if( add_comma ) + StringBuf_AppendStr(&buf, ", "); + else + add_comma = true; + StringBuf_Printf(&buf, "`connect_member`=%d, `average_lv`=%d", g->connect_member, g->average_lv); + } + if (flag & GS_MES) + { + char esc_mes1[sizeof(g->mes1)*2+1]; + char esc_mes2[sizeof(g->mes2)*2+1]; - p->mode = mode; - p->exp_mode = exp_mode; - name[strlen(name)-1] = 0; - safestrncpy(p->name, name, NAME_LENGTH); + strcat(t_info, " mes"); + if( add_comma ) + StringBuf_AppendStr(&buf, ", "); + else + add_comma = true; + Sql_EscapeStringLen(sql_handle, esc_mes1, g->mes1, strnlen(g->mes1, sizeof(g->mes1))); + Sql_EscapeStringLen(sql_handle, esc_mes2, g->mes2, strnlen(g->mes2, sizeof(g->mes2))); + StringBuf_Printf(&buf, "`mes1`='%s', `mes2`='%s'", esc_mes1, esc_mes2); + } + if (flag & GS_LEVEL) + { + strcat(t_info, " level"); + if( add_comma ) + StringBuf_AppendStr(&buf, ", "); + else + add_comma = true; + StringBuf_Printf(&buf, "`guild_lv`=%d, `skill_point`=%d, `exp`=%"PRIu64", `next_exp`=%u, `max_member`=%d", g->guild_lv, g->skill_point, g->exp, g->next_exp, g->max_member); + } + StringBuf_Printf(&buf, " WHERE `guild_id`=%d", g->guild_id); + if( SQL_ERROR == Sql_Query(sql_handle, "%s", StringBuf_Value(&buf)) ) + Sql_ShowDebug(sql_handle); + StringBuf_Destroy(&buf); + } - i++; - str+= len; + if (flag&GS_MEMBER) + { + struct guild_member *m; + + strcat(t_info, " members"); + // Update only needed players + for(i=0;i<g->max_member;i++){ + m = &g->member[i]; + if (!m->modified) + continue; + if(m->account_id) { + //Since nothing references guild member table as foreign keys, it's safe to use REPLACE INTO + Sql_EscapeStringLen(sql_handle, esc_name, m->name, strnlen(m->name, NAME_LENGTH)); + if( SQL_ERROR == Sql_Query(sql_handle, "REPLACE INTO `%s` (`guild_id`,`account_id`,`char_id`,`hair`,`hair_color`,`gender`,`class`,`lv`,`exp`,`exp_payper`,`online`,`position`,`name`) " + "VALUES ('%d','%d','%d','%d','%d','%d','%d','%d','%"PRIu64"','%d','%d','%d','%s')", + guild_member_db, g->guild_id, m->account_id, m->char_id, + m->hair, m->hair_color, m->gender, + m->class_, m->lv, m->exp, m->exp_payper, m->online, m->position, esc_name) ) + Sql_ShowDebug(sql_handle); + if (m->modified & GS_MEMBER_NEW) + { + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `guild_id` = '%d' WHERE `char_id` = '%d'", + char_db, g->guild_id, m->char_id) ) + Sql_ShowDebug(sql_handle); + } + m->modified = GS_MEMBER_UNMODIFIED; + } } } - {// load guild emblem - int emblemlen; - int emblemid; - char emblem[4096]; - int len; - - emblemid = 0; - if( sscanf(str, "%d,%d,%[^\t]\t%n", &emblemlen, &emblemid, emblem, &len) < 3 ) - if( sscanf(str, "%d,%[^\t]\t%n", &emblemlen, emblem, &len) < 2 ) //! pre-svn format - return 1; - - g->emblem_len = emblemlen; - g->emblem_id = emblemid; - for(i = 0, pstr = emblem; i < g->emblem_len; i++, pstr += 2) { - int c1 = pstr[0], c2 = pstr[1], x1 = 0, x2 = 0; - if (c1 >= '0' && c1 <= '9') x1 = c1 - '0'; - if (c1 >= 'a' && c1 <= 'f') x1 = c1 - 'a' + 10; - if (c1 >= 'A' && c1 <= 'F') x1 = c1 - 'A' + 10; - if (c2 >= '0' && c2 <= '9') x2 = c2 - '0'; - if (c2 >= 'a' && c2 <= 'f') x2 = c2 - 'a' + 10; - if (c2 >= 'A' && c2 <= 'F') x2 = c2 - 'A' + 10; - g->emblem_data[i] = (x1<<4) | x2; + if (flag&GS_POSITION){ + strcat(t_info, " positions"); + //printf("- Insert guild %d to guild_position\n",g->guild_id); + for(i=0;i<MAX_GUILDPOSITION;i++){ + struct guild_position *p = &g->position[i]; + if (!p->modified) + continue; + Sql_EscapeStringLen(sql_handle, esc_name, p->name, strnlen(p->name, NAME_LENGTH)); + if( SQL_ERROR == Sql_Query(sql_handle, "REPLACE INTO `%s` (`guild_id`,`position`,`name`,`mode`,`exp_mode`) VALUES ('%d','%d','%s','%d','%d')", + guild_position_db, g->guild_id, i, esc_name, p->mode, p->exp_mode) ) + Sql_ShowDebug(sql_handle); + p->modified = GS_POSITION_UNMODIFIED; } + } - str+= len; + if (flag&GS_ALLIANCE) + { + // Delete current alliances + // NOTE: no need to do it on both sides since both guilds in memory had + // their info changed, not to mention this would also mess up oppositions! + // [Skotlex] + //if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id`='%d' OR `alliance_id`='%d'", guild_alliance_db, g->guild_id, g->guild_id) ) + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id`='%d'", guild_alliance_db, g->guild_id) ) + { + Sql_ShowDebug(sql_handle); + } + else + { + //printf("- Insert guild %d to guild_alliance\n",g->guild_id); + for(i=0;i<MAX_GUILDALLIANCE;i++) + { + struct guild_alliance *a=&g->alliance[i]; + if(a->guild_id>0) + { + Sql_EscapeStringLen(sql_handle, esc_name, a->name, strnlen(a->name, NAME_LENGTH)); + if( SQL_ERROR == Sql_Query(sql_handle, "REPLACE INTO `%s` (`guild_id`,`opposition`,`alliance_id`,`name`) " + "VALUES ('%d','%d','%d','%s')", + guild_alliance_db, g->guild_id, a->opposition, a->guild_id, esc_name) ) + Sql_ShowDebug(sql_handle); + } + } + } } - {// load guild alliance info - int guildid; - int opposition; - char name[256]; // only 24 used - int len; + if (flag&GS_EXPULSION){ + strcat(t_info, " expulsions"); + //printf("- Insert guild %d to guild_expulsion\n",g->guild_id); + for(i=0;i<MAX_GUILDEXPULSION;i++){ + struct guild_expulsion *e=&g->expulsion[i]; + if(e->account_id>0){ + char esc_mes[sizeof(e->mes)*2+1]; + + Sql_EscapeStringLen(sql_handle, esc_name, e->name, strnlen(e->name, NAME_LENGTH)); + Sql_EscapeStringLen(sql_handle, esc_mes, e->mes, strnlen(e->mes, sizeof(e->mes))); + if( SQL_ERROR == Sql_Query(sql_handle, "REPLACE INTO `%s` (`guild_id`,`account_id`,`name`,`mes`) " + "VALUES ('%d','%d','%s','%s')", guild_expulsion_db, g->guild_id, e->account_id, esc_name, esc_mes) ) + Sql_ShowDebug(sql_handle); + } + } + } - if (sscanf(str, "%d\t%n", &c, &len) < 1) - return 1; - str+= len; + if (flag&GS_SKILL){ + strcat(t_info, " skills"); + //printf("- Insert guild %d to guild_skill\n",g->guild_id); + for(i=0;i<MAX_GUILDSKILL;i++){ + if (g->skill[i].id>0 && g->skill[i].lv>0){ + if( SQL_ERROR == Sql_Query(sql_handle, "REPLACE INTO `%s` (`guild_id`,`id`,`lv`) VALUES ('%d','%d','%d')", + guild_skill_db, g->guild_id, g->skill[i].id, g->skill[i].lv) ) + Sql_ShowDebug(sql_handle); + } + } + } - for(i = 0; i < c; i++) - { - struct guild_alliance* a = &g->alliance[i]; - if (sscanf(str, "%d,%d\t%[^\t]\t%n", &guildid, &opposition, name, &len) < 3) - return 1; + if (save_log) + ShowInfo("Saved guild (%d - %s):%s\n",g->guild_id,g->name,t_info); + return 1; +} - a->guild_id = guildid; - a->opposition = opposition; - safestrncpy(a->name, name, NAME_LENGTH); +// Read guild from sql +struct guild * inter_guild_fromsql(int guild_id) +{ + struct guild *g; + char* data; + size_t len; + char* p; + int i; - str+= len; - } + if( guild_id <= 0 ) + return NULL; + + g = (struct guild*)idb_get(guild_db_, guild_id); + if( g ) + return g; + +#ifdef NOISY + ShowInfo("Guild load request (%d)...\n", guild_id); +#endif + + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT g.`name`,c.`name`,g.`guild_lv`,g.`connect_member`,g.`max_member`,g.`average_lv`,g.`exp`,g.`next_exp`,g.`skill_point`,g.`mes1`,g.`mes2`,g.`emblem_len`,g.`emblem_id`,g.`emblem_data` " + "FROM `%s` g LEFT JOIN `%s` c ON c.`char_id` = g.`char_id` WHERE g.`guild_id`='%d'", guild_db, char_db, guild_id) ) + { + Sql_ShowDebug(sql_handle); + return NULL; } - {// load guild expulsion info - int accountid; - char name[256]; // only 24 used - char message[256]; // only 40 used - int len; - int i; + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + return NULL;// Guild does not exists. - if (sscanf(str, "%d\t%n", &c, &len) < 1) - return 1; - str+= len; + CREATE(g, struct guild, 1); - for(i = 0; i < c; i++) - { - struct guild_expulsion *e = &g->expulsion[i]; - if (sscanf(str, "%d,%*d,%*d,%*d\t%[^\t]\t%*[^\t]\t%[^\t]\t%n", &accountid, name, message, &len) < 3) - return 1; + g->guild_id = guild_id; + Sql_GetData(sql_handle, 0, &data, &len); memcpy(g->name, data, min(len, NAME_LENGTH)); + Sql_GetData(sql_handle, 1, &data, &len); memcpy(g->master, data, min(len, NAME_LENGTH)); + Sql_GetData(sql_handle, 2, &data, NULL); g->guild_lv = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); g->connect_member = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); g->max_member = atoi(data); + if( g->max_member > MAX_GUILD ) + { // Fix reduction of MAX_GUILD [PoW] + ShowWarning("Guild %d:%s specifies higher capacity (%d) than MAX_GUILD (%d)\n", guild_id, g->name, g->max_member, MAX_GUILD); + g->max_member = MAX_GUILD; + } + Sql_GetData(sql_handle, 5, &data, NULL); g->average_lv = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); g->exp = strtoull(data, NULL, 10); + Sql_GetData(sql_handle, 7, &data, NULL); g->next_exp = (unsigned int)strtoul(data, NULL, 10); + Sql_GetData(sql_handle, 8, &data, NULL); g->skill_point = atoi(data); + Sql_GetData(sql_handle, 9, &data, &len); memcpy(g->mes1, data, min(len, sizeof(g->mes1))); + Sql_GetData(sql_handle, 10, &data, &len); memcpy(g->mes2, data, min(len, sizeof(g->mes2))); + Sql_GetData(sql_handle, 11, &data, &len); g->emblem_len = atoi(data); + Sql_GetData(sql_handle, 12, &data, &len); g->emblem_id = atoi(data); + Sql_GetData(sql_handle, 13, &data, &len); + // convert emblem data from hexadecimal to binary + //TODO: why not store it in the db as binary directly? [ultramage] + for( i = 0, p = g->emblem_data; i < g->emblem_len; ++i, ++p ) + { + if( *data >= '0' && *data <= '9' ) + *p = *data - '0'; + else if( *data >= 'a' && *data <= 'f' ) + *p = *data - 'a' + 10; + else if( *data >= 'A' && *data <= 'F' ) + *p = *data - 'A' + 10; + *p <<= 4; + ++data; + + if( *data >= '0' && *data <= '9' ) + *p |= *data - '0'; + else if( *data >= 'a' && *data <= 'f' ) + *p |= *data - 'a' + 10; + else if( *data >= 'A' && *data <= 'F' ) + *p |= *data - 'A' + 10; + ++data; + } - e->account_id = accountid; - safestrncpy(e->name, name, sizeof(e->name)); - message[strlen(message)-1] = 0; // remove '#' - safestrncpy(e->mes, message, sizeof(e->mes)); + // load guild member info + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id`,`char_id`,`hair`,`hair_color`,`gender`,`class`,`lv`,`exp`,`exp_payper`,`online`,`position`,`name` " + "FROM `%s` WHERE `guild_id`='%d' ORDER BY `position`", guild_member_db, guild_id) ) + { + Sql_ShowDebug(sql_handle); + aFree(g); + return NULL; + } + for( i = 0; i < g->max_member && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + struct guild_member* m = &g->member[i]; + + Sql_GetData(sql_handle, 0, &data, NULL); m->account_id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); m->char_id = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); m->hair = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); m->hair_color = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); m->gender = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); m->class_ = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); m->lv = atoi(data); + Sql_GetData(sql_handle, 7, &data, NULL); m->exp = strtoull(data, NULL, 10); + Sql_GetData(sql_handle, 8, &data, NULL); m->exp_payper = (unsigned int)atoi(data); + Sql_GetData(sql_handle, 9, &data, NULL); m->online = atoi(data); + Sql_GetData(sql_handle, 10, &data, NULL); m->position = atoi(data); + if( m->position >= MAX_GUILDPOSITION ) // Fix reduction of MAX_GUILDPOSITION [PoW] + m->position = MAX_GUILDPOSITION - 1; + Sql_GetData(sql_handle, 11, &data, &len); memcpy(m->name, data, min(len, NAME_LENGTH)); + m->modified = GS_MEMBER_UNMODIFIED; + } - str+= len; - } + //printf("- Read guild_position %d from sql \n",guild_id); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `position`,`name`,`mode`,`exp_mode` FROM `%s` WHERE `guild_id`='%d'", guild_position_db, guild_id) ) + { + Sql_ShowDebug(sql_handle); + aFree(g); + return NULL; + } + while( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + int position; + struct guild_position* p; + + Sql_GetData(sql_handle, 0, &data, NULL); position = atoi(data); + if( position < 0 || position >= MAX_GUILDPOSITION ) + continue;// invalid position + p = &g->position[position]; + Sql_GetData(sql_handle, 1, &data, &len); memcpy(p->name, data, min(len, NAME_LENGTH)); + Sql_GetData(sql_handle, 2, &data, NULL); p->mode = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); p->exp_mode = atoi(data); + p->modified = GS_POSITION_UNMODIFIED; } - {// load guild skill info - int skillid; - int skilllv; - int len; - int i; + //printf("- Read guild_alliance %d from sql \n",guild_id); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `opposition`,`alliance_id`,`name` FROM `%s` WHERE `guild_id`='%d'", guild_alliance_db, guild_id) ) + { + Sql_ShowDebug(sql_handle); + aFree(g); + return NULL; + } + for( i = 0; i < MAX_GUILDALLIANCE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + struct guild_alliance* a = &g->alliance[i]; - for(i = 0; i < MAX_GUILDSKILL; i++) - { - if (sscanf(str, "%d,%d %n", &skillid, &skilllv, &len) < 2) - break; - g->skill[i].id = skillid; - g->skill[i].lv = skilllv; + Sql_GetData(sql_handle, 0, &data, NULL); a->opposition = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); a->guild_id = atoi(data); + Sql_GetData(sql_handle, 2, &data, &len); memcpy(a->name, data, min(len, NAME_LENGTH)); + } - str+= len; - } - str = strchr(str, '\t'); + //printf("- Read guild_expulsion %d from sql \n",guild_id); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id`,`name`,`mes` FROM `%s` WHERE `guild_id`='%d'", guild_expulsion_db, guild_id) ) + { + Sql_ShowDebug(sql_handle); + aFree(g); + return NULL; } + for( i = 0; i < MAX_GUILDEXPULSION && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + struct guild_expulsion *e = &g->expulsion[i]; - return 0; -} + Sql_GetData(sql_handle, 0, &data, NULL); e->account_id = atoi(data); + Sql_GetData(sql_handle, 1, &data, &len); memcpy(e->name, data, min(len, NAME_LENGTH)); + Sql_GetData(sql_handle, 2, &data, &len); memcpy(e->mes, data, min(len, sizeof(e->mes))); + } -#ifndef TXT_SQL_CONVERT -// ギルド城データの文字列への変換 -int inter_guildcastle_tostr(char *str, struct guild_castle *gc) -{ - int len; + //printf("- Read guild_skill %d from sql \n",guild_id); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `id`,`lv` FROM `%s` WHERE `guild_id`='%d' ORDER BY `id`", guild_skill_db, guild_id) ) + { + Sql_ShowDebug(sql_handle); + aFree(g); + return NULL; + } - len = sprintf(str, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", - gc->castle_id, gc->guild_id, gc->economy, gc->defense, gc->triggerE, - gc->triggerD, gc->nextTime, gc->payTime, gc->createTime, gc->visibleC, - gc->guardian[0].visible, gc->guardian[1].visible, gc->guardian[2].visible, gc->guardian[3].visible, - gc->guardian[4].visible, gc->guardian[5].visible, gc->guardian[6].visible, gc->guardian[7].visible); + for(i = 0; i < MAX_GUILDSKILL; i++) + { //Skill IDs must always be initialized. [Skotlex] + g->skill[i].id = i + GD_SKILLBASE; + } + + while( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + int id; + Sql_GetData(sql_handle, 0, &data, NULL); id = atoi(data) - GD_SKILLBASE; + if( id < 0 && id >= MAX_GUILDSKILL ) + continue;// invalid guild skill + Sql_GetData(sql_handle, 1, &data, NULL); g->skill[id].lv = atoi(data); + } + Sql_FreeResult(sql_handle); + + idb_put(guild_db_, guild_id, g); //Add to cache + g->save_flag |= GS_REMOVE; //But set it to be removed, in case it is not needed for long. + + if (save_log) + ShowInfo("Guild loaded (%d - %s)\n", guild_id, g->name); + return g; +} + +int inter_guildcastle_tosql(struct guild_castle *gc) +{ + // `guild_castle` (`castle_id`, `guild_id`, `economy`, `defense`, `triggerE`, `triggerD`, `nextTime`, `payTime`, `createTime`, `visibleC`, `visibleG0`, `visibleG1`, `visibleG2`, `visibleG3`, `visibleG4`, `visibleG5`, `visibleG6`, `visibleG7`) + + if (gc==NULL) return 0; + #ifdef GUILD_DEBUG +ShowDebug("Save guild_castle (%d)\n", gc->castle_id); + #endif + +// sql_query("DELETE FROM `%s` WHERE `castle_id`='%d'",guild_castle_db, gc->castle_id); + if( SQL_ERROR == Sql_Query(sql_handle, "REPLACE INTO `%s` " + "(`castle_id`, `guild_id`, `economy`, `defense`, `triggerE`, `triggerD`, `nextTime`, `payTime`, `createTime`," + "`visibleC`, `visibleG0`, `visibleG1`, `visibleG2`, `visibleG3`, `visibleG4`, `visibleG5`, `visibleG6`, `visibleG7`)" + "VALUES ('%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d')", + guild_castle_db, gc->castle_id, gc->guild_id, gc->economy, gc->defense, gc->triggerE, gc->triggerD, gc->nextTime, gc->payTime, gc->createTime, gc->visibleC, + gc->guardian[0].visible, gc->guardian[1].visible, gc->guardian[2].visible, gc->guardian[3].visible, gc->guardian[4].visible, gc->guardian[5].visible, gc->guardian[6].visible, gc->guardian[7].visible) ) + Sql_ShowDebug(sql_handle); + + memcpy(&castles[gc->castle_id],gc,sizeof(struct guild_castle)); return 0; } -#endif ///TXT_SQL_CONVERT -// ギルド城データの文字列からの変換 -int inter_guildcastle_fromstr(char *str, struct guild_castle *gc) +// Read guild_castle from sql +int inter_guildcastle_fromsql(int castle_id,struct guild_castle *gc) { - int castleid, guildid, economy, defense, triggerE, triggerD, nextTime, payTime, createTime, visibleC; - int guardian[8]; - int dummy; - - memset(gc, 0, sizeof(struct guild_castle)); - // structure of guild castle with the guardian hp included - if( sscanf(str, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", - &castleid, &guildid, &economy, &defense, &triggerE, &triggerD, &nextTime, &payTime, &createTime, &visibleC, - &guardian[0], &guardian[1], &guardian[2], &guardian[3], &guardian[4], &guardian[5], &guardian[6], &guardian[7], - &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy) != 26 ) - // structure of guild castle without the hps (current one) - if( sscanf(str, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", - &castleid, &guildid, &economy, &defense, &triggerE, &triggerD, &nextTime, &payTime, &createTime, &visibleC, - &guardian[0], &guardian[1], &guardian[2], &guardian[3], &guardian[4], &guardian[5], &guardian[6], &guardian[7]) != 18 ) + static int castles_init=0; + char* data; + + if (gc==NULL) return 0; + if (castle_id==-1) return 0; + + if(!castles_init) + { + int i; + for(i=0;i<MAX_GUILDCASTLE;i++) + castles[i].castle_id=-1; + castles_init = 1; + } + + if(castles[castle_id].castle_id == castle_id) + { + memcpy(gc,&castles[castle_id],sizeof(struct guild_castle)); return 1; + } + + memset(gc,0,sizeof(struct guild_castle)); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `castle_id`, `guild_id`, `economy`, `defense`, `triggerE`, `triggerD`, `nextTime`, `payTime`, `createTime`, " + "`visibleC`, `visibleG0`, `visibleG1`, `visibleG2`, `visibleG3`, `visibleG4`, `visibleG5`, `visibleG6`, `visibleG7`" + " FROM `%s` WHERE `castle_id`='%d'", guild_castle_db, castle_id) ) + { + Sql_ShowDebug(sql_handle); + return 0; + } + // ARU: This needs to be set even if there are no SQL results + gc->castle_id=castle_id; + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + { + Sql_FreeResult(sql_handle); + return 1; //Assume empty castle. + } - gc->castle_id = castleid; - gc->guild_id = guildid; - gc->economy = economy; - gc->defense = defense; - gc->triggerE = triggerE; - gc->triggerD = triggerD; - gc->nextTime = nextTime; - gc->payTime = payTime; - gc->createTime = createTime; - gc->visibleC = visibleC; - gc->guardian[0].visible = guardian[0]; - gc->guardian[1].visible = guardian[1]; - gc->guardian[2].visible = guardian[2]; - gc->guardian[3].visible = guardian[3]; - gc->guardian[4].visible = guardian[4]; - gc->guardian[5].visible = guardian[5]; - gc->guardian[6].visible = guardian[6]; - gc->guardian[7].visible = guardian[7]; + Sql_GetData(sql_handle, 1, &data, NULL); gc->guild_id = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); gc->economy = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); gc->defense = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); gc->triggerE = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); gc->triggerD = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); gc->nextTime = atoi(data); + Sql_GetData(sql_handle, 7, &data, NULL); gc->payTime = atoi(data); + Sql_GetData(sql_handle, 8, &data, NULL); gc->createTime = atoi(data); + Sql_GetData(sql_handle, 9, &data, NULL); gc->visibleC = atoi(data); + Sql_GetData(sql_handle, 10, &data, NULL); gc->guardian[0].visible = atoi(data); + Sql_GetData(sql_handle, 11, &data, NULL); gc->guardian[1].visible = atoi(data); + Sql_GetData(sql_handle, 12, &data, NULL); gc->guardian[2].visible = atoi(data); + Sql_GetData(sql_handle, 13, &data, NULL); gc->guardian[3].visible = atoi(data); + Sql_GetData(sql_handle, 14, &data, NULL); gc->guardian[4].visible = atoi(data); + Sql_GetData(sql_handle, 15, &data, NULL); gc->guardian[5].visible = atoi(data); + Sql_GetData(sql_handle, 16, &data, NULL); gc->guardian[6].visible = atoi(data); + Sql_GetData(sql_handle, 17, &data, NULL); gc->guardian[7].visible = atoi(data); + + Sql_FreeResult(sql_handle); + memcpy(&castles[castle_id],gc,sizeof(struct guild_castle)); + + if( save_log ) + ShowInfo("Loaded Castle %d (guild %d)\n", castle_id, gc->guild_id); - return 0; + return 1; } -#ifndef TXT_SQL_CONVERT -// ギルド関連データベース読み込み -int inter_guild_readdb(void) + +// Read exp_guild.txt +int inter_guild_ReadEXP(void) { int i; FILE *fp; char line[1024]; - char path[1024]; - - sprintf(path, "%s%s", db_path, "/exp_guild.txt"); - fp = fopen(path, "r"); - if (fp == NULL) { - ShowError("can't read db/exp_guild.txt\n"); + for (i=0;i<100;i++) guild_exp[i]=0; + //this is going to be discussed, temp fix + sprintf(line, "%s/pre-re/exp_guild.txt", db_path); + fp=fopen(line,"r"); + if(fp==NULL){ + ShowError("can't read %s\n", line); return 1; } - i = 0; + i=0; while(fgets(line, sizeof(line), fp) && i < 100) { - if (line[0] == '/' && line[1] == '/') + if(line[0]=='/' && line[1]=='/') continue; - guild_exp[i] = (unsigned int)atof(line); + guild_exp[i]=(unsigned int)atof(line); i++; } fclose(fp); @@ -388,171 +641,172 @@ int inter_guild_readdb(void) return 0; } -// ギルドデータの読み込み -int inter_guild_init() -{ - char line[16384]; - struct guild *g; - struct guild_castle *gc; - FILE *fp; - int i, j, c = 0; - inter_guild_readdb(); - - guild_db = idb_alloc(DB_OPT_RELEASE_DATA); - castle_db = idb_alloc(DB_OPT_RELEASE_DATA); - - if ((fp = fopen(guild_txt,"r")) == NULL) - return 1; - while(fgets(line, sizeof(line), fp)) - { - j = 0; - if (sscanf(line, "%d\t%%newid%%\n%n", &i, &j) == 1 && j > 0 && guild_newid <= i) { - guild_newid = i; - continue; +int inter_guild_CharOnline(int char_id, int guild_id) +{ + struct guild *g; + int i; + + if (guild_id == -1) { + //Get guild_id from the database + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT guild_id FROM `%s` WHERE char_id='%d'", char_db, char_id) ) + { + Sql_ShowDebug(sql_handle); + return 0; } - g = (struct guild *) aCalloc(sizeof(struct guild), 1); - if(g == NULL){ - ShowFatalError("int_guild: out of memory!\n"); - exit(EXIT_FAILURE); + if( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + char* data; + + Sql_GetData(sql_handle, 0, &data, NULL); + guild_id = atoi(data); } -// memset(g, 0, sizeof(struct guild)); not needed... - if (inter_guild_fromstr(line, g) == 0 && g->guild_id > 0) { - if (g->guild_id >= guild_newid) - guild_newid = g->guild_id + 1; - idb_put(guild_db, g->guild_id, g); - guild_check_empty(g); - guild_calcinfo(g); - } else { - ShowError("int_guild: broken data [%s] line %d\n", guild_txt, c); - aFree(g); + else + { + guild_id = 0; } - c++; + Sql_FreeResult(sql_handle); + } + if (guild_id == 0) + return 0; //No guild... + + g = inter_guild_fromsql(guild_id); + if(!g) { + ShowError("Character %d's guild %d not found!\n", char_id, guild_id); + return 0; } - fclose(fp); - c = 0;//カウンタ初期化 + //Member has logged in before saving, tell saver not to delete + if(g->save_flag & GS_REMOVE) + g->save_flag &= ~GS_REMOVE; - if ((fp = fopen(castle_txt, "r")) == NULL) { - return 1; + //Set member online + ARR_FIND( 0, g->max_member, i, g->member[i].char_id == char_id ); + if( i < g->max_member ) + { + g->member[i].online = 1; + g->member[i].modified = GS_MEMBER_MODIFIED; } - while(fgets(line, sizeof(line), fp)) + return 1; +} + +int inter_guild_CharOffline(int char_id, int guild_id) +{ + struct guild *g=NULL; + int online_count, i; + + if (guild_id == -1) { - gc = (struct guild_castle *) aCalloc(sizeof(struct guild_castle), 1); - if(gc == NULL){ - ShowFatalError("int_guild: out of memory!\n"); - exit(EXIT_FAILURE); - } -// memset(gc, 0, sizeof(struct guild_castle)); No need... - if (inter_guildcastle_fromstr(line, gc) == 0) { - idb_put(castle_db, gc->castle_id, gc); - } else { - ShowError("int_guild: broken data [%s] line %d\n", castle_txt, c); - aFree(gc); + //Get guild_id from the database + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT guild_id FROM `%s` WHERE char_id='%d'", char_db, char_id) ) + { + Sql_ShowDebug(sql_handle); + return 0; } - c++; - } - fclose(fp); + if( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + char* data; - if (!c) { - ShowStatus(" %s - making Default Data...\n", castle_txt); - //デフォルトデータを作成 - for(i = 0; i < MAX_GUILDCASTLE; i++) { - gc = (struct guild_castle *) aCalloc(sizeof(struct guild_castle), 1); - if (gc == NULL) { - ShowFatalError("int_guild: out of memory!\n"); - exit(EXIT_FAILURE); - } - gc->castle_id = i; - idb_put(castle_db, gc->castle_id, gc); + Sql_GetData(sql_handle, 0, &data, NULL); + guild_id = atoi(data); + } + else + { + guild_id = 0; } - ShowStatus(" %s - making done\n",castle_txt); + Sql_FreeResult(sql_handle); + } + if (guild_id == 0) + return 0; //No guild... + + //Character has a guild, set character offline and check if they were the only member online + g = inter_guild_fromsql(guild_id); + if (g == NULL) //Guild not found? return 0; + + //Set member offline + ARR_FIND( 0, g->max_member, i, g->member[i].char_id == char_id ); + if( i < g->max_member ) + { + g->member[i].online = 0; + g->member[i].modified = GS_MEMBER_MODIFIED; } - return 0; -} + online_count = 0; + for( i = 0; i < g->max_member; i++ ) + if( g->member[i].online ) + online_count++; -void inter_guild_final() -{ - castle_db->destroy(castle_db, NULL); - guild_db->destroy(guild_db, NULL); - return; + // Remove guild from memory if no players online + if( online_count == 0 ) + g->save_flag |= GS_REMOVE; + + return 1; } -struct guild *inter_guild_search(int guild_id) +// Initialize guild sql +int inter_guild_sql_init(void) { - return (struct guild*)idb_get(guild_db, guild_id); + //Initialize the guild cache + guild_db_= idb_alloc(DB_OPT_RELEASE_DATA); + + //Read exp file + inter_guild_ReadEXP(); + + add_timer_func_list(guild_save_timer, "guild_save_timer"); + add_timer(gettick() + 10000, guild_save_timer, 0, 0); + return 0; } -// ギルドデータのセーブ -int inter_guild_save() +static int guild_db_final(DBKey key, void *data, va_list ap) { - FILE *fp; - int lock; - DBIterator* iter; - struct guild* g; - struct guild_castle* gc; - - // save guild data - if ((fp = lock_fopen(guild_txt, &lock)) == NULL) { - ShowError("int_guild: can't write [%s] !!! data is lost !!!\n", guild_txt); + struct guild *g = (struct guild*)data; + if (g->save_flag&GS_MASK) { + inter_guild_tosql(g, g->save_flag&GS_MASK); return 1; } - - iter = guild_db->iterator(guild_db); - for( g = (struct guild*)iter->first(iter,NULL); iter->exists(iter); g = (struct guild*)iter->next(iter,NULL) ) - { - char line[16384]; - inter_guild_tostr(line, g); - fprintf(fp, "%s\n", line); - } - iter->destroy(iter); - -// fprintf(fp, "%d\t%%newid%%\n", guild_newid); - lock_fclose(fp, guild_txt, &lock); - - // save castle data - if ((fp = lock_fopen(castle_txt,&lock)) == NULL) { - ShowError("int_guild: can't write [%s] !!! data is lost !!!\n", castle_txt); - return 1; - } - - iter = castle_db->iterator(castle_db); - for( gc = (struct guild_castle*)iter->first(iter,NULL); iter->exists(iter); gc = (struct guild_castle*)iter->next(iter,NULL) ) - { - char line[16384]; - inter_guildcastle_tostr(line, gc); - fprintf(fp, "%s\n", line); - } - iter->destroy(iter); - - lock_fclose(fp, castle_txt, &lock); - return 0; } -// ギルド名検索 -struct guild* search_guildname(char *str) +void inter_guild_sql_final(void) { - DBIterator* iter; - struct guild* g; + guild_db_->destroy(guild_db_, guild_db_final); + return; +} - iter = guild_db->iterator(guild_db); - for( g = (struct guild*)iter->first(iter,NULL); iter->exists(iter); g = (struct guild*)iter->next(iter,NULL) ) +// Get guild_id by its name. Returns 0 if not found, -1 on error. +int search_guildname(char *str) +{ + int guild_id; + char esc_name[NAME_LENGTH*2+1]; + + Sql_EscapeStringLen(sql_handle, esc_name, str, safestrnlen(str, NAME_LENGTH)); + //Lookup guilds with the same name + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT guild_id FROM `%s` WHERE name='%s'", guild_db, esc_name) ) { - if (strcmpi(g->name, str) == 0) - break; + Sql_ShowDebug(sql_handle); + return -1; } - iter->destroy(iter); - return g; + if( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + char* data; + + Sql_GetData(sql_handle, 0, &data, NULL); + guild_id = atoi(data); + } + else + { + guild_id = 0; + } + Sql_FreeResult(sql_handle); + return guild_id; } -// ギルドが空かどうかチェック +// Check if guild is empty static bool guild_check_empty(struct guild *g) { int i; @@ -560,11 +814,8 @@ static bool guild_check_empty(struct guild *g) if( i < g->max_member) return false; // not empty - // 誰もいないので解散 - guild_db->foreach(guild_db, guild_break_sub, g->guild_id); - inter_guild_storage_delete(g->guild_id); - mapif_guild_broken(g->guild_id, 0); - idb_remove(guild_db, g->guild_id); + //Let the calling function handle the guild removal in case they need + //to do something else with it before freeing the data. [Skotlex] return true; } @@ -572,79 +823,80 @@ unsigned int guild_nextexp(int level) { if (level == 0) return 1; - if (level > 0 && level < 100) + if (level < 100 && level > 0) // Change by hack return guild_exp[level-1]; return 0; } -// ギルドスキルがあるか確認 -int guild_checkskill(struct guild *g, int id) +int guild_checkskill(struct guild *g,int id) { int idx = id - GD_SKILLBASE; - if(idx < 0 || idx >= MAX_GUILDSKILL) - return 0; return g->skill[idx].lv; } -// ギルドの情報の再計算 int guild_calcinfo(struct guild *g) { - int i, c; + int i,c; unsigned int nextexp; - struct guild before = *g; - - // スキルIDの設定 - for(i = 0; i < MAX_GUILDSKILL; i++) - g->skill[i].id=i+GD_SKILLBASE; + struct guild before = *g; // Save guild current values - // ギルドレベル - if (g->guild_lv <= 0) + if(g->guild_lv<=0) g->guild_lv = 1; nextexp = guild_nextexp(g->guild_lv); - if (nextexp > 0) { - while(g->exp >= nextexp && nextexp > 0) { //fixed guild exp overflow [Kevin] - g->exp -= nextexp; - g->guild_lv++; - g->skill_point++; - nextexp = guild_nextexp(g->guild_lv); - } + + // Consume guild exp and increase guild level + while(g->exp >= nextexp && nextexp > 0){ //fixed guild exp overflow [Kevin] + g->exp-=nextexp; + g->guild_lv++; + g->skill_point++; + nextexp = guild_nextexp(g->guild_lv); } - // ギルドの次の経験値 - g->next_exp = guild_nextexp(g->guild_lv); + // Save next exp step + g->next_exp = nextexp; - // メンバ上限(ギルド拡張適用) - g->max_member = 16 + guild_checkskill(g, GD_EXTENSION) * 6; //Guild Extention skill - currently adds 6 to max per skill lv. + // Set the max number of members, Guild Extention skill - currently adds 6 to max per skill lv. + g->max_member = 16 + guild_checkskill(g, GD_EXTENSION) * 6; if(g->max_member > MAX_GUILD) { ShowError("Guild %d:%s has capacity for too many guild members (%d), max supported is %d\n", g->guild_id, g->name, g->max_member, MAX_GUILD); g->max_member = MAX_GUILD; } + + // Compute the guild average level level + g->average_lv=0; + g->connect_member=0; + for(i=c=0;i<g->max_member;i++) + { + if(g->member[i].account_id>0) + { + if (g->member[i].lv >= 0) + { + g->average_lv+=g->member[i].lv; + c++; + } + else + { + ShowWarning("Guild %d:%s, member %d:%s has an invalid level %d\n", g->guild_id, g->name, g->member[i].char_id, g->member[i].name, g->member[i].lv); + } - // 平均レベルとオンライン人数 - g->average_lv = 0; - g->connect_member = 0; - c = 0; - for(i = 0; i < g->max_member; i++) { - if (g->member[i].account_id > 0) { - g->average_lv += g->member[i].lv; - c++; - if (g->member[i].online > 0) + if(g->member[i].online) g->connect_member++; } } - if(c) g->average_lv /= c; + if(c) + g->average_lv /= c; - // 全データを送る必要がありそう - if (g->max_member != before.max_member || - g->guild_lv != before.guild_lv || - g->skill_point != before.skill_point) { - mapif_guild_info(-1, g); + // Check if guild stats has change + if(g->max_member != before.max_member || g->guild_lv != before.guild_lv || g->skill_point != before.skill_point ) + { + g->save_flag |= GS_LEVEL; + mapif_guild_info(-1,g); return 1; } @@ -652,238 +904,219 @@ int guild_calcinfo(struct guild *g) } //------------------------------------------------------------------- -// map serverへの通信 +// Packet sent to map server -// ギルド作成可否 -int mapif_guild_created(int fd, int account_id, struct guild *g) +int mapif_guild_created(int fd,int account_id,struct guild *g) { WFIFOHEAD(fd, 10); - WFIFOW(fd,0) = 0x3830; - WFIFOL(fd,2) = account_id; - if (g != NULL) { - WFIFOL(fd,6) = g->guild_id; - ShowInfo("Created Guild (%d %s)\n", g->guild_id, g->name); - }else{ - WFIFOL(fd,6) = 0; - } + WFIFOW(fd,0)=0x3830; + WFIFOL(fd,2)=account_id; + if(g != NULL) + { + WFIFOL(fd,6)=g->guild_id; + ShowInfo("int_guild: Guild created (%d - %s)\n",g->guild_id,g->name); + } else + WFIFOL(fd,6)=0; + WFIFOSET(fd,10); return 0; } -// ギルド情報見つからず -int mapif_guild_noinfo(int fd, int guild_id) +// Guild not found +int mapif_guild_noinfo(int fd,int guild_id) { - WFIFOHEAD(fd, 8); - WFIFOW(fd,0) = 0x3831; - WFIFOW(fd,2) = 8; - WFIFOL(fd,4) = guild_id; - WFIFOSET(fd,8); - ShowNotice("int_guild: info not found %d\n", guild_id); - + unsigned char buf[12]; + WBUFW(buf,0)=0x3831; + WBUFW(buf,2)=8; + WBUFL(buf,4)=guild_id; + ShowWarning("int_guild: info not found %d\n",guild_id); + if(fd<0) + mapif_sendall(buf,8); + else + mapif_send(fd,buf,8); return 0; } -// ギルド情報まとめ送り -int mapif_guild_info(int fd, struct guild *g) +// Send guild info +int mapif_guild_info(int fd,struct guild *g) { unsigned char buf[8+sizeof(struct guild)]; - - WBUFW(buf,0) = 0x3831; - memcpy(buf + 4, g, sizeof(struct guild)); - WBUFW(buf,2) = 4 + sizeof(struct guild); - if (fd < 0) - mapif_sendall(buf, WBUFW(buf,2)); + WBUFW(buf,0)=0x3831; + WBUFW(buf,2)=4+sizeof(struct guild); + memcpy(buf+4,g,sizeof(struct guild)); + if(fd<0) + mapif_sendall(buf,WBUFW(buf,2)); else - mapif_send(fd, buf, WBUFW(buf,2)); - + mapif_send(fd,buf,WBUFW(buf,2)); return 0; } -// メンバ追加可否 -int mapif_guild_memberadded(int fd, int guild_id, int account_id, int char_id, int flag) +// ACK member add +int mapif_guild_memberadded(int fd,int guild_id,int account_id,int char_id,int flag) { WFIFOHEAD(fd, 15); - WFIFOW(fd,0) = 0x3832; - WFIFOL(fd,2) = guild_id; - WFIFOL(fd,6) = account_id; - WFIFOL(fd,10) = char_id; - WFIFOB(fd,14) = flag; - WFIFOSET(fd, 15); - + WFIFOW(fd,0)=0x3832; + WFIFOL(fd,2)=guild_id; + WFIFOL(fd,6)=account_id; + WFIFOL(fd,10)=char_id; + WFIFOB(fd,14)=flag; + WFIFOSET(fd,15); return 0; } -// 脱退/追放通知 -int mapif_guild_withdraw(int guild_id, int account_id, int char_id, int flag, const char *name, const char *mes) +// ACK member leave +int mapif_guild_withdraw(int guild_id,int account_id,int char_id,int flag, const char *name, const char *mes) { - unsigned char buf[79]; - - WBUFW(buf, 0) = 0x3834; - WBUFL(buf, 2) = guild_id; - WBUFL(buf, 6) = account_id; - WBUFL(buf,10) = char_id; - WBUFB(buf,14) = flag; - memcpy(WBUFP(buf,15), mes, 40); - memcpy(WBUFP(buf,55), name, NAME_LENGTH); - mapif_sendall(buf, 55+NAME_LENGTH); -// mapif_sendall(buf, 79); - ShowInfo("Character left guild (Guild %d, %d - %s: %s)\n", guild_id, account_id, name, mes); - + unsigned char buf[55+NAME_LENGTH]; + WBUFW(buf, 0)=0x3834; + WBUFL(buf, 2)=guild_id; + WBUFL(buf, 6)=account_id; + WBUFL(buf,10)=char_id; + WBUFB(buf,14)=flag; + memcpy(WBUFP(buf,15),mes,40); + memcpy(WBUFP(buf,55),name,NAME_LENGTH); + mapif_sendall(buf,55+NAME_LENGTH); + ShowInfo("int_guild: guild withdraw (%d - %d: %s - %s)\n",guild_id,account_id,name,mes); return 0; } -// オンライン状態とLv更新通知 -int mapif_guild_memberinfoshort(struct guild *g, int idx) +// Send short member's info +int mapif_guild_memberinfoshort(struct guild *g,int idx) { unsigned char buf[19]; - - WBUFW(buf, 0) = 0x3835; - WBUFL(buf, 2) = g->guild_id; - WBUFL(buf, 6) = g->member[idx].account_id; - WBUFL(buf,10) = g->member[idx].char_id; - WBUFB(buf,14) = (unsigned char)g->member[idx].online; - WBUFW(buf,15) = g->member[idx].lv; - WBUFW(buf,17) = g->member[idx].class_; - mapif_sendall(buf, 19); + WBUFW(buf, 0)=0x3835; + WBUFL(buf, 2)=g->guild_id; + WBUFL(buf, 6)=g->member[idx].account_id; + WBUFL(buf,10)=g->member[idx].char_id; + WBUFB(buf,14)=(unsigned char)g->member[idx].online; + WBUFW(buf,15)=g->member[idx].lv; + WBUFW(buf,17)=g->member[idx].class_; + mapif_sendall(buf,19); return 0; } -// 解散通知 -int mapif_guild_broken(int guild_id, int flag) +// Send guild broken +int mapif_guild_broken(int guild_id,int flag) { unsigned char buf[7]; - - WBUFW(buf,0) = 0x3836; - WBUFL(buf,2) = guild_id; - WBUFB(buf,6) = flag; - mapif_sendall(buf, 7); - ShowInfo("Guild Break (%d)\n", guild_id); - + WBUFW(buf,0)=0x3836; + WBUFL(buf,2)=guild_id; + WBUFB(buf,6)=flag; + mapif_sendall(buf,7); + ShowInfo("int_guild: Guild broken (%d)\n",guild_id); return 0; } -// ギルド内発言 -int mapif_guild_message(int guild_id, int account_id, char *mes, int len, int sfd) +// Send guild message +int mapif_guild_message(int guild_id,int account_id,char *mes,int len, int sfd) { - unsigned char buf[2048]; - - WBUFW(buf,0) = 0x3837; - WBUFW(buf,2) = len + 12; - WBUFL(buf,4) = guild_id; - WBUFL(buf,8) = account_id; - memcpy(WBUFP(buf,12), mes, len); - mapif_sendallwos(sfd, buf, len + 12); - + unsigned char buf[512]; + if (len > 500) + len = 500; + WBUFW(buf,0)=0x3837; + WBUFW(buf,2)=len+12; + WBUFL(buf,4)=guild_id; + WBUFL(buf,8)=account_id; + memcpy(WBUFP(buf,12),mes,len); + mapif_sendallwos(sfd, buf,len+12); return 0; } -// ギルド基本情報変更通知 -int mapif_guild_basicinfochanged(int guild_id, int type, const void *data, int len) +// Send basic info +int mapif_guild_basicinfochanged(int guild_id,int type,const void *data,int len) { unsigned char buf[2048]; - - WBUFW(buf,0) = 0x3839; - WBUFW(buf,2) = len+10; - WBUFL(buf,4) = guild_id; - WBUFW(buf,8) = type; + if (len > 2038) + len = 2038; + WBUFW(buf, 0)=0x3839; + WBUFW(buf, 2)=len+10; + WBUFL(buf, 4)=guild_id; + WBUFW(buf, 8)=type; memcpy(WBUFP(buf,10),data,len); mapif_sendall(buf,len+10); return 0; } -// ギルドメンバ情報変更通知 -int mapif_guild_memberinfochanged(int guild_id, int account_id, int char_id, int type, const void *data, int len) +// Send member info +int mapif_guild_memberinfochanged(int guild_id,int account_id,int char_id, int type,const void *data,int len) { - unsigned char buf[4096]; - - WBUFW(buf, 0) = 0x383a; - WBUFW(buf, 2) = len + 18; - WBUFL(buf, 4) = guild_id; - WBUFL(buf, 8) = account_id; - WBUFL(buf,12) = char_id; - WBUFW(buf,16) = type; - memcpy(WBUFP(buf,18), data, len); + unsigned char buf[2048]; + if (len > 2030) + len = 2030; + WBUFW(buf, 0)=0x383a; + WBUFW(buf, 2)=len+18; + WBUFL(buf, 4)=guild_id; + WBUFL(buf, 8)=account_id; + WBUFL(buf,12)=char_id; + WBUFW(buf,16)=type; + memcpy(WBUFP(buf,18),data,len); mapif_sendall(buf,len+18); - return 0; } -// ギルドスキルアップ通知 -int mapif_guild_skillupack(int guild_id, int skill_num, int account_id) +// ACK guild skill up +int mapif_guild_skillupack(int guild_id,int skill_num,int account_id) { unsigned char buf[14]; - - WBUFW(buf, 0) = 0x383c; - WBUFL(buf, 2) = guild_id; - WBUFL(buf, 6) = skill_num; - WBUFL(buf,10) = account_id; - mapif_sendall(buf, 14); - + WBUFW(buf, 0)=0x383c; + WBUFL(buf, 2)=guild_id; + WBUFL(buf, 6)=skill_num; + WBUFL(buf,10)=account_id; + mapif_sendall(buf,14); return 0; } -// ギルド同盟/敵対通知 -int mapif_guild_alliance(int guild_id1, int guild_id2, int account_id1, int account_id2, int flag, const char *name1, const char *name2) +// ACK guild alliance +int mapif_guild_alliance(int guild_id1,int guild_id2,int account_id1,int account_id2,int flag,const char *name1,const char *name2) { - unsigned char buf[67]; - - WBUFW(buf, 0) = 0x383d; - WBUFL(buf, 2) = guild_id1; - WBUFL(buf, 6) = guild_id2; - WBUFL(buf,10) = account_id1; - WBUFL(buf,14) = account_id2; - WBUFB(buf,18) = flag; - memcpy(WBUFP(buf,19), name1, NAME_LENGTH); - memcpy(WBUFP(buf,19+NAME_LENGTH), name2, NAME_LENGTH); + unsigned char buf[19+2*NAME_LENGTH]; + WBUFW(buf, 0)=0x383d; + WBUFL(buf, 2)=guild_id1; + WBUFL(buf, 6)=guild_id2; + WBUFL(buf,10)=account_id1; + WBUFL(buf,14)=account_id2; + WBUFB(buf,18)=flag; + memcpy(WBUFP(buf,19),name1,NAME_LENGTH); + memcpy(WBUFP(buf,19+NAME_LENGTH),name2,NAME_LENGTH); mapif_sendall(buf,19+2*NAME_LENGTH); -/* - memcpy(WBUFP(buf,43), name2, NAME_LENGTH); - mapif_sendall(buf, 67); -*/ return 0; } -// ギルド役職変更通知 -int mapif_guild_position(struct guild *g, int idx) +// Send a guild position desc +int mapif_guild_position(struct guild *g,int idx) { - unsigned char buf[2048]; - - WBUFW(buf,0) = 0x383b; - WBUFW(buf,2) = sizeof(struct guild_position) + 12; - WBUFL(buf,4) = g->guild_id; - WBUFL(buf,8) = idx; - memcpy(WBUFP(buf,12), &g->position[idx], sizeof(struct guild_position)); - mapif_sendall(buf, WBUFW(buf,2)); - + unsigned char buf[12 + sizeof(struct guild_position)]; + WBUFW(buf,0)=0x383b; + WBUFW(buf,2)=sizeof(struct guild_position)+12; + WBUFL(buf,4)=g->guild_id; + WBUFL(buf,8)=idx; + memcpy(WBUFP(buf,12),&g->position[idx],sizeof(struct guild_position)); + mapif_sendall(buf,WBUFW(buf,2)); return 0; } -// ギルド告知変更通知 +// Send the guild notice int mapif_guild_notice(struct guild *g) { - unsigned char buf[186]; - - WBUFW(buf,0) = 0x383e; - WBUFL(buf,2) = g->guild_id; - memcpy(WBUFP(buf,6), g->mes1, MAX_GUILDMES1); - memcpy(WBUFP(buf,66), g->mes2, MAX_GUILDMES2); - mapif_sendall(buf, 186); - + unsigned char buf[256]; + WBUFW(buf,0)=0x383e; + WBUFL(buf,2)=g->guild_id; + memcpy(WBUFP(buf,6),g->mes1,MAX_GUILDMES1); + memcpy(WBUFP(buf,66),g->mes2,MAX_GUILDMES2); + mapif_sendall(buf,186); return 0; } -// ギルドエンブレム変更通知 +// Send emblem data int mapif_guild_emblem(struct guild *g) { - unsigned char buf[2048]; - - WBUFW(buf,0) = 0x383f; - WBUFW(buf,2) = g->emblem_len + 12; - WBUFL(buf,4) = g->guild_id; - WBUFL(buf,8) = g->emblem_id; - memcpy(WBUFP(buf,12), g->emblem_data, g->emblem_len); - mapif_sendall(buf, WBUFW(buf,2)); - + unsigned char buf[12 + sizeof(g->emblem_data)]; + WBUFW(buf,0)=0x383f; + WBUFW(buf,2)=g->emblem_len+12; + WBUFL(buf,4)=g->guild_id; + WBUFL(buf,8)=g->emblem_id; + memcpy(WBUFP(buf,12),g->emblem_data,g->emblem_len); + mapif_sendall(buf,WBUFW(buf,2)); return 0; } @@ -898,76 +1131,94 @@ int mapif_guild_master_changed(struct guild *g, int aid, int cid) return 0; } -int mapif_guild_castle_dataload(int castle_id, int index, int value) +int mapif_guild_castle_dataload(int castle_id,int index,int value) { unsigned char buf[9]; - - WBUFW(buf,0) = 0x3840; - WBUFW(buf,2) = castle_id; - WBUFB(buf,4) = index; - WBUFL(buf,5) = value; + WBUFW(buf, 0)=0x3840; + WBUFW(buf, 2)=castle_id; + WBUFB(buf, 4)=index; + WBUFL(buf, 5)=value; mapif_sendall(buf,9); - return 0; } -int mapif_guild_castle_datasave(int castle_id, int index, int value) +int mapif_guild_castle_datasave(int castle_id,int index,int value) { unsigned char buf[9]; - - WBUFW(buf,0) = 0x3841; - WBUFW(buf,2) = castle_id; - WBUFB(buf,4) = index; - WBUFL(buf,5) = value; + WBUFW(buf, 0)=0x3841; + WBUFW(buf, 2)=castle_id; + WBUFB(buf, 4)=index; + WBUFL(buf, 5)=value; mapif_sendall(buf,9); - return 0; } int mapif_guild_castle_alldataload(int fd) { - DBIterator* iter; - struct guild_castle* gc; - int len = 4; + struct guild_castle s_gc; + struct guild_castle* gc = &s_gc; + int i; + int len; + char* data; WFIFOHEAD(fd, 4 + MAX_GUILDCASTLE*sizeof(struct guild_castle)); - WFIFOW(fd,0) = 0x3842; - iter = castle_db->iterator(castle_db); - for( gc = (struct guild_castle*)iter->first(iter,NULL); iter->exists(iter); gc = (struct guild_castle*)iter->next(iter,NULL) ) + WFIFOW(fd, 0) = 0x3842; + if( SQL_ERROR == Sql_Query(sql_handle, + "SELECT `castle_id`, `guild_id`, `economy`, `defense`, `triggerE`, `triggerD`, `nextTime`, `payTime`, `createTime`," + " `visibleC`, `visibleG0`, `visibleG1`, `visibleG2`, `visibleG3`, `visibleG4`, `visibleG5`, `visibleG6`, `visibleG7`" + " FROM `%s` ORDER BY `castle_id`", guild_castle_db) ) + Sql_ShowDebug(sql_handle); + for( i = 0, len = 4; i < MAX_GUILDCASTLE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) { - memcpy(WFIFOP(fd,len), gc, sizeof(struct guild_castle)); + memset(gc, 0, sizeof(struct guild_castle)); + + Sql_GetData(sql_handle, 0, &data, NULL); gc->castle_id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); gc->guild_id = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); gc->economy = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); gc->defense = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); gc->triggerE = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); gc->triggerD = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); gc->nextTime = atoi(data); + Sql_GetData(sql_handle, 7, &data, NULL); gc->payTime = atoi(data); + Sql_GetData(sql_handle, 8, &data, NULL); gc->createTime = atoi(data); + Sql_GetData(sql_handle, 9, &data, NULL); gc->visibleC = atoi(data); + Sql_GetData(sql_handle, 10, &data, NULL); gc->guardian[0].visible = atoi(data); + Sql_GetData(sql_handle, 11, &data, NULL); gc->guardian[1].visible = atoi(data); + Sql_GetData(sql_handle, 12, &data, NULL); gc->guardian[2].visible = atoi(data); + Sql_GetData(sql_handle, 13, &data, NULL); gc->guardian[3].visible = atoi(data); + Sql_GetData(sql_handle, 14, &data, NULL); gc->guardian[4].visible = atoi(data); + Sql_GetData(sql_handle, 15, &data, NULL); gc->guardian[5].visible = atoi(data); + Sql_GetData(sql_handle, 16, &data, NULL); gc->guardian[6].visible = atoi(data); + Sql_GetData(sql_handle, 17, &data, NULL); gc->guardian[7].visible = atoi(data); + + memcpy(WFIFOP(fd, len), gc, sizeof(struct guild_castle)); len += sizeof(struct guild_castle); } - iter->destroy(iter); - WFIFOW(fd,2) = len; + Sql_FreeResult(sql_handle); + WFIFOW(fd, 2) = len; WFIFOSET(fd, len); - + return 0; } + //------------------------------------------------------------------- -// map serverからの通信 +// Packet received from map server + // ギルド作成要求 -int mapif_parse_CreateGuild(int fd, int account_id, char *name, struct guild_member *master) +int mapif_parse_CreateGuild(int fd,int account_id,char *name,struct guild_member *master) { struct guild *g; - int i; - - for(i = 0; i < NAME_LENGTH && name[i]; i++) { - if (!(name[i] & 0xe0) || name[i] == 0x7f) { - ShowInfo("Create Guild: illegal guild name [%s]\n", name); - mapif_guild_created(fd, account_id, NULL); - return 0; - } - } - - if ((g = search_guildname(name)) != NULL) { - ShowInfo("Create Guild: same name guild exists [%s]\n", name); - mapif_guild_created(fd, account_id, NULL); + int i=0; +#ifdef NOISY + ShowInfo("Creating Guild (%s)\n", name); +#endif + if(search_guildname(name) != 0){ + ShowInfo("int_guild: guild with same name exists [%s]\n",name); + mapif_guild_created(fd,account_id,NULL); return 0; } - // Check Authorised letters/symbols in the name of the character if (char_name_option == 1) { // only letters/symbols in char_name_letters are authorised for (i = 0; i < NAME_LENGTH && name[i]; i++) @@ -983,81 +1234,104 @@ int mapif_parse_CreateGuild(int fd, int account_id, char *name, struct guild_mem } } - g = (struct guild *) aCalloc(sizeof(struct guild), 1); - if (g == NULL) { - ShowFatalError("int_guild: CreateGuild: out of memory !\n"); - mapif_guild_created(fd, account_id, NULL); - exit(EXIT_FAILURE); - } -// memset(g, 0, sizeof(struct guild)); Meh... - g->guild_id = guild_newid++; - memcpy(g->name, name, NAME_LENGTH); - memcpy(g->master, master->name, NAME_LENGTH); - memcpy(&g->member[0], master, sizeof(struct guild_member)); - - g->position[0].mode = 0x11; - strcpy(g->position[ 0].name, "GuildMaster"); - strcpy(g->position[MAX_GUILDPOSITION-1].name, "Newbie"); - for(i = 1; i < MAX_GUILDPOSITION-1; i++) - sprintf(g->position[i].name, "Position %d", i + 1); - - // ここでギルド情報計算が必要と思われる - g->max_member = 16; - g->average_lv = master->lv; - g->connect_member = 1; - for(i = 0; i < MAX_GUILDSKILL; i++) - g->skill[i].id=i + GD_SKILLBASE; + g = (struct guild *)aMalloc(sizeof(struct guild)); + memset(g,0,sizeof(struct guild)); + + memcpy(g->name,name,NAME_LENGTH); + memcpy(g->master,master->name,NAME_LENGTH); + memcpy(&g->member[0],master,sizeof(struct guild_member)); + g->member[0].modified = GS_MEMBER_MODIFIED; + + // Set default positions + g->position[0].mode=0x11; + strcpy(g->position[0].name,"GuildMaster"); + strcpy(g->position[MAX_GUILDPOSITION-1].name,"Newbie"); + g->position[0].modified = g->position[MAX_GUILDPOSITION-1].modified = GS_POSITION_MODIFIED; + for(i=1;i<MAX_GUILDPOSITION-1;i++) { + sprintf(g->position[i].name,"Position %d",i+1); + g->position[i].modified = GS_POSITION_MODIFIED; + } - idb_put(guild_db, g->guild_id, g); + // Initialize guild property + g->max_member=16; + g->average_lv=master->lv; + g->connect_member=1; - mapif_guild_created(fd, account_id, g); - mapif_guild_info(fd, g); + for(i=0;i<MAX_GUILDSKILL;i++) + g->skill[i].id=i + GD_SKILLBASE; + g->guild_id= -1; //Request to create guild. + + // Create the guild + if (!inter_guild_tosql(g,GS_BASIC|GS_POSITION|GS_SKILL)) { + //Failed to Create guild.... + ShowError("Failed to create Guild %s (Guild Master: %s)\n", g->name, g->master); + mapif_guild_created(fd,account_id,NULL); + aFree(g); + return 0; + } + ShowInfo("Created Guild %d - %s (Guild Master: %s)\n", g->guild_id, g->name, g->master); + + //Add to cache + idb_put(guild_db_, g->guild_id, g); + + // Report to client + mapif_guild_created(fd,account_id,g); + mapif_guild_info(fd,g); if(log_inter) inter_log("guild %s (id=%d) created by master %s (id=%d)\n", - name, g->guild_id, master->name, master->account_id); + name, g->guild_id, master->name, master->account_id ); return 0; } -// ギルド情報要求 -int mapif_parse_GuildInfo(int fd, int guild_id) +// Return guild info to client +int mapif_parse_GuildInfo(int fd,int guild_id) { - struct guild *g; - - g = (struct guild*)idb_get(guild_db, guild_id); - if (g != NULL){ - guild_calcinfo(g); - mapif_guild_info(fd, g); - } else - mapif_guild_noinfo(fd, guild_id); - + struct guild * g = inter_guild_fromsql(guild_id); //We use this because on start-up the info of castle-owned guilds is requied. [Skotlex] + if(g) + { + if (!guild_calcinfo(g)) + mapif_guild_info(fd,g); + } + else + mapif_guild_noinfo(fd,guild_id); // Failed to load info return 0; } -// ギルドメンバ追加要求 -int mapif_parse_GuildAddMember(int fd, int guild_id, struct guild_member *m) +// Add member to guild +int mapif_parse_GuildAddMember(int fd,int guild_id,struct guild_member *m) { - struct guild *g; + struct guild * g; int i; - g = (struct guild*)idb_get(guild_db, guild_id); - if (g == NULL) { - mapif_guild_memberadded(fd, guild_id, m->account_id, m->char_id, 1); + g = inter_guild_fromsql(guild_id); + if(g==NULL){ + // Failed to add + mapif_guild_memberadded(fd,guild_id,m->account_id,m->char_id,1); return 0; } - ARR_FIND( 0, g->max_member, i, g->member[i].account_id == 0 ); - if( i < g->max_member ) + // Find an empty slot + for(i=0;i<g->max_member;i++) { - memcpy(&g->member[i], m, sizeof(struct guild_member)); - mapif_guild_memberadded(fd, guild_id, m->account_id, m->char_id, 0); - guild_calcinfo(g); - mapif_guild_info(-1, g); + if(g->member[i].account_id==0) + { + memcpy(&g->member[i],m,sizeof(struct guild_member)); + g->member[i].modified = (GS_MEMBER_NEW | GS_MEMBER_MODIFIED); + mapif_guild_memberadded(fd,guild_id,m->account_id,m->char_id,0); + if (!guild_calcinfo(g)) //Send members if it was not invoked. + mapif_guild_info(-1,g); + + g->save_flag |= GS_MEMBER; + if (g->save_flag&GS_REMOVE) + g->save_flag&=~GS_REMOVE; + return 0; + } } - else - mapif_guild_memberadded(fd, guild_id, m->account_id, m->char_id, 1); + // Failed to add + mapif_guild_memberadded(fd,guild_id,m->account_id,m->char_id,1); return 0; } @@ -1066,10 +1340,13 @@ int mapif_parse_GuildLeave(int fd, int guild_id, int account_id, int char_id, in { int i, j; - struct guild* g = (struct guild*)idb_get(guild_db, guild_id); + struct guild* g = inter_guild_fromsql(guild_id); if( g == NULL ) { - //TODO + // Unknown guild, just update the player + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `guild_id`='0' WHERE `account_id`='%d' AND `char_id`='%d'", char_db, account_id, char_id) ) + Sql_ShowDebug(sql_handle); + // mapif_guild_withdraw(guild_id,account_id,char_id,flag,g->member[i].name,mes); return 0; } @@ -1082,13 +1359,15 @@ int mapif_parse_GuildLeave(int fd, int guild_id, int account_id, int char_id, in } if( flag ) - { // 追放の場合追放リストに入れる + { // Write expulsion reason + // Find an empty slot ARR_FIND( 0, MAX_GUILDEXPULSION, j, g->expulsion[j].account_id == 0 ); - if (j == MAX_GUILDEXPULSION) - { // 一杯なので古いのを消す - for(j = 0; j < MAX_GUILDEXPULSION - 1; j++) + if( j == MAX_GUILDEXPULSION ) + { + // Expulsion list is full, flush the oldest one + for( j = 0; j < MAX_GUILDEXPULSION - 1; j++ ) g->expulsion[j] = g->expulsion[j+1]; - j = MAX_GUILDEXPULSION - 1; + j = MAX_GUILDEXPULSION-1; } // Save the expulsion entry g->expulsion[j].account_id = account_id; @@ -1096,41 +1375,54 @@ int mapif_parse_GuildLeave(int fd, int guild_id, int account_id, int char_id, in safestrncpy(g->expulsion[j].mes, mes, 40); } - mapif_guild_withdraw(guild_id, account_id, char_id, flag, g->member[i].name, mes); + mapif_guild_withdraw(guild_id,account_id,char_id,flag,g->member[i].name,mes); + inter_guild_removemember_tosql(g->member[i].account_id,g->member[i].char_id); - memset(&g->member[i], 0, sizeof(struct guild_member)); + memset(&g->member[i],0,sizeof(struct guild_member)); - if (guild_check_empty(g) == 0) - mapif_guild_info(-1,g);// まだ人がいるのでデータ送信 + if( guild_check_empty(g) ) + mapif_parse_BreakGuild(-1,guild_id); //Break the guild. + else { + //Update member info. + if (!guild_calcinfo(g)) + mapif_guild_info(fd,g); + g->save_flag |= GS_EXPULSION; + } return 0; } -// オンライン/Lv更新 -int mapif_parse_GuildChangeMemberInfoShort(int fd, int guild_id, int account_id, int char_id, int online, int lv, int class_) +// Change member info +int mapif_parse_GuildChangeMemberInfoShort(int fd,int guild_id,int account_id,int char_id,int online,int lv,int class_) { - struct guild *g; - int i, sum, c; + // Could speed up by manipulating only guild_member + struct guild * g; + int i,sum,c; + int prev_count, prev_alv; - g = (struct guild*)idb_get(guild_db, guild_id); - if (g == NULL) + g = inter_guild_fromsql(guild_id); + if(g==NULL) return 0; - + ARR_FIND( 0, g->max_member, i, g->member[i].account_id == account_id && g->member[i].char_id == char_id ); if( i < g->max_member ) { - g->member[i].online = online; - g->member[i].lv = lv; - g->member[i].class_ = class_; - mapif_guild_memberinfoshort(g, i); + g->member[i].online = online; + g->member[i].lv = lv; + g->member[i].class_ = class_; + g->member[i].modified = GS_MEMBER_MODIFIED; + mapif_guild_memberinfoshort(g,i); } + prev_count = g->connect_member; + prev_alv = g->average_lv; + g->average_lv = 0; g->connect_member = 0; - c = 0; // member count - sum = 0; // total sum of base levels + c = 0; + sum = 0; - for(i = 0; i < g->max_member; i++) + for( i = 0; i < g->max_member; i++ ) { if( g->member[i].account_id > 0 ) { @@ -1142,198 +1434,287 @@ int mapif_parse_GuildChangeMemberInfoShort(int fd, int guild_id, int account_id, } if( c ) // this check should always succeed... + { g->average_lv = sum / c; - - //FIXME: how about sending a mapif_guild_info() update to the mapserver? [ultramage] - + if( g->connect_member != prev_count || g->average_lv != prev_alv ) + g->save_flag |= GS_CONNECT; + if( g->save_flag & GS_REMOVE ) + g->save_flag &= ~GS_REMOVE; + } + g->save_flag |= GS_MEMBER; //Update guild member data return 0; } -// ギルド解散処理用(同盟/敵対を解除) -int guild_break_sub(DBKey key, void *data, va_list ap) +// BreakGuild +int mapif_parse_BreakGuild(int fd,int guild_id) { - struct guild *g = (struct guild *)data; - int guild_id = va_arg(ap, int); - int i; + struct guild * g; + + g = inter_guild_fromsql(guild_id); + if(g==NULL) + return 0; - for(i = 0; i < MAX_GUILDALLIANCE; i++) { - if (g->alliance[i].guild_id == guild_id) - g->alliance[i].guild_id = 0; - } - return 0; -} + // Delete guild from sql + //printf("- Delete guild %d from guild\n",guild_id); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_db, guild_id) ) + Sql_ShowDebug(sql_handle); -// ギルド解散要求 -int mapif_parse_BreakGuild(int fd, int guild_id) -{ - struct guild *g; + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_member_db, guild_id) ) + Sql_ShowDebug(sql_handle); - g = (struct guild*)idb_get(guild_db, guild_id); - if(g == NULL) - return 0; + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_castle_db, guild_id) ) + Sql_ShowDebug(sql_handle); + + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_storage_db, guild_id) ) + Sql_ShowDebug(sql_handle); + + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d' OR `alliance_id` = '%d'", guild_alliance_db, guild_id, guild_id) ) + Sql_ShowDebug(sql_handle); - guild_db->foreach(guild_db, guild_break_sub, guild_id); - inter_guild_storage_delete(guild_id); - mapif_guild_broken(guild_id, 0); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_position_db, guild_id) ) + Sql_ShowDebug(sql_handle); + + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_skill_db, guild_id) ) + Sql_ShowDebug(sql_handle); + + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id` = '%d'", guild_expulsion_db, guild_id) ) + Sql_ShowDebug(sql_handle); + + //printf("- Update guild %d of char\n",guild_id); + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `guild_id`='0' WHERE `guild_id`='%d'", char_db, guild_id) ) + Sql_ShowDebug(sql_handle); + + mapif_guild_broken(guild_id,0); if(log_inter) - inter_log("guild %s (id=%d) broken\n", g->name, guild_id); + inter_log("guild %s (id=%d) broken\n",g->name,guild_id); - idb_remove(guild_db, guild_id); + //Remove the guild from memory. [Skotlex] + idb_remove(guild_db_, guild_id); return 0; } -// ギルドメッセージ送信 -int mapif_parse_GuildMessage(int fd, int guild_id, int account_id, char *mes, int len) +// Forward Guild message to others map servers +int mapif_parse_GuildMessage(int fd,int guild_id,int account_id,char *mes,int len) { - return mapif_guild_message(guild_id, account_id, mes, len, fd); + return mapif_guild_message(guild_id,account_id,mes,len, fd); } -// ギルド基本データ変更要求 -int mapif_parse_GuildBasicInfoChange(int fd, int guild_id, int type, const char *data, int len) +// Modification of the guild +int mapif_parse_GuildBasicInfoChange(int fd,int guild_id,int type,const char *data,int len) { - struct guild *g; - short dw = *((short *)data); - - g = (struct guild*)idb_get(guild_db, guild_id); - if (g == NULL) + struct guild * g; + short dw=*((short *)data); + g = inter_guild_fromsql(guild_id); + if(g==NULL) return 0; - switch(type) { - case GBI_GUILDLV: - if (dw > 0 && g->guild_lv + dw <= 50) { - g->guild_lv+=dw; - g->skill_point+=dw; - } else if (dw < 0 && g->guild_lv + dw >= 1) - g->guild_lv += dw; - mapif_guild_info(-1, g); - return 0; - default: - ShowError("int_guild: GuildBasicInfoChange: Unknown type %d\n", type); - break; + switch(type) + { + case GBI_GUILDLV: + if(dw>0 && g->guild_lv+dw<=50) + { + g->guild_lv+=dw; + g->skill_point+=dw; + } + else if(dw<0 && g->guild_lv+dw>=1) + g->guild_lv+=dw; + mapif_guild_info(-1,g); + g->save_flag |= GS_LEVEL; + return 0; + default: + ShowError("int_guild: GuildBasicInfoChange: Unknown type %d\n",type); + break; } - mapif_guild_basicinfochanged(guild_id, type, data, len); - + mapif_guild_basicinfochanged(guild_id,type,data,len); return 0; } -// ギルドメンバデータ変更要求 -int mapif_parse_GuildMemberInfoChange(int fd, int guild_id, int account_id, int char_id, int type, const char *data, int len) +// Modification of the guild +int mapif_parse_GuildMemberInfoChange(int fd,int guild_id,int account_id,int char_id,int type,const char *data,int len) { + // Could make some improvement in speed, because only change guild_member int i; - struct guild *g; + struct guild * g; - g = (struct guild*)idb_get(guild_db, guild_id); - if(g == NULL) + g = inter_guild_fromsql(guild_id); + if(g==NULL) return 0; - for(i = 0; i < g->max_member; i++) - if (g->member[i].account_id == account_id && g->member[i].char_id == char_id) - break; - if (i == g->max_member) { - ShowWarning("int_guild: GuildMemberChange: Not found %d,%d in %d[%s]\n", account_id, char_id, guild_id, g->name); + // Search the member + for(i=0;i<g->max_member;i++) + if( g->member[i].account_id==account_id && + g->member[i].char_id==char_id ) + break; + + // Not Found + if(i==g->max_member){ + ShowWarning("int_guild: GuildMemberChange: Not found %d,%d in guild (%d - %s)\n", + account_id,char_id,guild_id,g->name); return 0; } - switch(type) { - case GMI_POSITION: // 役職 - g->member[i].position = *((short *)data); - mapif_guild_memberinfochanged(guild_id, account_id, char_id, type, data, len); - break; - case GMI_EXP: // EXP + + switch(type) { - uint64 exp, old_exp=g->member[i].exp; - g->member[i].exp=*((uint64 *)data); - if (g->member[i].exp > old_exp) + case GMI_POSITION: + { + g->member[i].position=*((short *)data); + g->member[i].modified = GS_MEMBER_MODIFIED; + mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); + g->save_flag |= GS_MEMBER; + break; + } + case GMI_EXP: + { // EXP + uint64 exp, old_exp=g->member[i].exp; + g->member[i].exp=*((uint64 *)data); + g->member[i].modified = GS_MEMBER_MODIFIED; + if (g->member[i].exp > old_exp) + { + exp = g->member[i].exp - old_exp; + + // Compute gained exp + if (guild_exp_rate != 100) + exp = exp*guild_exp_rate/100; + + // Update guild exp + if (exp > UINT64_MAX - g->exp) + g->exp = UINT64_MAX; + else + g->exp+=exp; + + guild_calcinfo(g); + mapif_guild_basicinfochanged(guild_id,GBI_EXP,&g->exp,sizeof(g->exp)); + g->save_flag |= GS_LEVEL; + } + mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); + g->save_flag |= GS_MEMBER; + break; + } + case GMI_HAIR: { - exp = g->member[i].exp - old_exp; - if (guild_exp_rate != 100) - exp = exp*guild_exp_rate/100; - if (exp > UINT64_MAX - g->exp) - g->exp = UINT64_MAX; - else - g->exp+=exp; - guild_calcinfo(g); - mapif_guild_basicinfochanged(guild_id,GBI_EXP,&g->exp,sizeof(g->exp)); + g->member[i].hair=*((short *)data); + g->member[i].modified = GS_MEMBER_MODIFIED; + mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); + g->save_flag |= GS_MEMBER; //Save new data. + break; } - mapif_guild_memberinfochanged(guild_id, account_id, char_id, type, data, len); - break; - } - case GMI_HAIR: - { - g->member[i].hair=*((short *)data); - mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); - break; - } - case GMI_HAIR_COLOR: - { - g->member[i].hair_color=*((short *)data); - mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); - break; + case GMI_HAIR_COLOR: + { + g->member[i].hair_color=*((short *)data); + g->member[i].modified = GS_MEMBER_MODIFIED; + mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); + g->save_flag |= GS_MEMBER; //Save new data. + break; + } + case GMI_GENDER: + { + g->member[i].gender=*((short *)data); + g->member[i].modified = GS_MEMBER_MODIFIED; + mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); + g->save_flag |= GS_MEMBER; //Save new data. + break; + } + case GMI_CLASS: + { + g->member[i].class_=*((short *)data); + g->member[i].modified = GS_MEMBER_MODIFIED; + mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); + g->save_flag |= GS_MEMBER; //Save new data. + break; + } + case GMI_LEVEL: + { + g->member[i].lv=*((short *)data); + g->member[i].modified = GS_MEMBER_MODIFIED; + mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); + g->save_flag |= GS_MEMBER; //Save new data. + break; + } + default: + ShowError("int_guild: GuildMemberInfoChange: Unknown type %d\n",type); + break; } - case GMI_GENDER: + return 0; +} + +int inter_guild_sex_changed(int guild_id,int account_id,int char_id, short gender) +{ + return mapif_parse_GuildMemberInfoChange(0, guild_id, account_id, char_id, GMI_GENDER, (const char*)&gender, sizeof(gender)); +} + +int inter_guild_charname_changed(int guild_id,int account_id, int char_id, char *name) +{ + struct guild *g; + int i, flag = 0; + + g = inter_guild_fromsql(guild_id); + if( g == NULL ) { - g->member[i].gender=*((short *)data); - mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); - break; + ShowError("inter_guild_charrenamed: Can't find guild %d.\n", guild_id); + return 0; } - case GMI_CLASS: + + ARR_FIND(0, g->max_member, i, g->member[i].char_id == char_id); + if( i == g->max_member ) { - g->member[i].class_=*((short *)data); - mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); - break; + ShowError("inter_guild_charrenamed: Can't find character %d in the guild\n", char_id); + return 0; } - case GMI_LEVEL: + + if( !strcmp(g->member[i].name, g->master) ) { - g->member[i].lv=*((short *)data); - mapif_guild_memberinfochanged(guild_id,account_id,char_id,type,data,len); - break; + safestrncpy(g->master, name, NAME_LENGTH); + flag |= GS_BASIC; } + safestrncpy(g->member[i].name, name, NAME_LENGTH); + g->member[i].modified = GS_MEMBER_MODIFIED; + flag |= GS_MEMBER; - default: - ShowError("int_guild: GuildMemberInfoChange: Unknown type %d\n", type); - break; - } + if( !inter_guild_tosql(g, flag) ) + return 0; + mapif_guild_info(-1,g); + return 0; } -int inter_guild_sex_changed(int guild_id,int account_id,int char_id, short gender) +// Change a position desc +int mapif_parse_GuildPosition(int fd,int guild_id,int idx,struct guild_position *p) { - return mapif_parse_GuildMemberInfoChange(0, guild_id, account_id, char_id, GMI_GENDER, (const char*)&gender, sizeof(gender)); -} + // Could make some improvement in speed, because only change guild_position + struct guild * g; -// ギルド役職名変更要求 -int mapif_parse_GuildPosition(int fd, int guild_id, int idx, struct guild_position *p) -{ - struct guild *g = (struct guild*)idb_get(guild_db, guild_id); - - if (g == NULL || idx < 0 || idx >= MAX_GUILDPOSITION) { + g = inter_guild_fromsql(guild_id); + if(g==NULL || idx<0 || idx>=MAX_GUILDPOSITION) return 0; - } - memcpy(&g->position[idx], p, sizeof(struct guild_position)); - mapif_guild_position(g, idx); - ShowInfo("int_guild: position [%d] changed\n", idx); + memcpy(&g->position[idx],p,sizeof(struct guild_position)); + mapif_guild_position(g,idx); + g->position[idx].modified = GS_POSITION_MODIFIED; + g->save_flag |= GS_POSITION; // Change guild_position return 0; } -// ギルドスキルアップ要求 -int mapif_parse_GuildSkillUp(int fd, int guild_id, int skill_num, int account_id, int max) +// Guild Skill UP +int mapif_parse_GuildSkillUp(int fd,int guild_id,int skill_num,int account_id,int max) { - struct guild *g = (struct guild*)idb_get(guild_db, guild_id); + struct guild * g; int idx = skill_num - GD_SKILLBASE; - if (g == NULL || idx < 0 || idx >= MAX_GUILDSKILL) + g = inter_guild_fromsql(guild_id); + if(g == NULL || idx < 0 || idx >= MAX_GUILDSKILL) return 0; - if (g->skill_point > 0 && g->skill[idx].id > 0 && g->skill[idx].lv < max) { + if(g->skill_point>0 && g->skill[idx].id>0 && g->skill[idx].lv<max ) + { g->skill[idx].lv++; g->skill_point--; - if (guild_calcinfo(g) == 0) - mapif_guild_info(-1, g); - mapif_guild_skillupack(guild_id, skill_num, account_id); + if (!guild_calcinfo(g)) + mapif_guild_info(-1,g); + mapif_guild_skillupack(guild_id,skill_num,account_id); + g->save_flag |= (GS_LEVEL|GS_SKILL); // Change guild & guild_skill } - return 0; } @@ -1342,106 +1723,119 @@ static int mapif_parse_GuildDeleteAlliance(struct guild *g, int guild_id, int ac { int i; char name[NAME_LENGTH]; - for(i=0;i<MAX_GUILDALLIANCE;i++) - if(g->alliance[i].guild_id == guild_id) - { - strcpy(name, g->alliance[i].name); - g->alliance[i].guild_id=0; - break; - } - if (i == MAX_GUILDALLIANCE) + + ARR_FIND( 0, MAX_GUILDALLIANCE, i, g->alliance[i].guild_id == guild_id ); + if( i == MAX_GUILDALLIANCE ) return -1; + + strcpy(name, g->alliance[i].name); + g->alliance[i].guild_id=0; mapif_guild_alliance(g->guild_id,guild_id,account_id1,account_id2,flag,g->name,name); + g->save_flag |= GS_ALLIANCE; return 0; } -// ギルド同盟要求 -int mapif_parse_GuildAlliance(int fd, int guild_id1, int guild_id2, int account_id1, int account_id2, int flag) +// Alliance modification +int mapif_parse_GuildAlliance(int fd,int guild_id1,int guild_id2,int account_id1,int account_id2,int flag) { + // Could speed up struct guild *g[2]; - int j, i; - - g[0] = (struct guild*)idb_get(guild_db, guild_id1); - g[1] = (struct guild*)idb_get(guild_db, guild_id2); - - if(g[0] && g[1]==NULL && (flag&0x8)) //Requested to remove an alliance with a not found guild. - return mapif_parse_GuildDeleteAlliance(g[0], guild_id2, - account_id1, account_id2, flag); //Try to do a manual removal of said guild. - - if (g[0] == NULL || g[1] == NULL) + int j,i; + g[0] = inter_guild_fromsql(guild_id1); + g[1] = inter_guild_fromsql(guild_id2); + + if(g[0] && g[1]==NULL && (flag & GUILD_ALLIANCE_REMOVE)) //Requested to remove an alliance with a not found guild. + return mapif_parse_GuildDeleteAlliance(g[0], guild_id2, account_id1, account_id2, flag); //Try to do a manual removal of said guild. + + if(g[0]==NULL || g[1]==NULL) return 0; - if (!(flag & 0x8)) { - for(i = 0; i < 2 - (flag & 1); i++) { - for(j = 0; j < MAX_GUILDALLIANCE; j++) - if (g[i]->alliance[j].guild_id == 0) { - g[i]->alliance[j].guild_id = g[1-i]->guild_id; - memcpy(g[i]->alliance[j].name, g[1-i]->name, NAME_LENGTH); - g[i]->alliance[j].opposition = flag & 1; - break; - } + if(flag&GUILD_ALLIANCE_REMOVE) + { + // Remove alliance/opposition, in case of alliance, remove on both side + for(i=0;i<2-(flag&GUILD_ALLIANCE_TYPE_MASK);i++) + { + ARR_FIND( 0, MAX_GUILDALLIANCE, j, g[i]->alliance[j].guild_id == g[1-i]->guild_id && g[i]->alliance[j].opposition == (flag&GUILD_ALLIANCE_TYPE_MASK) ); + if( j < MAX_GUILDALLIANCE ) + g[i]->alliance[j].guild_id = 0; } - } else { // 関係解消 - for(i = 0; i < 2 - (flag & 1); i++) { - for(j = 0; j < MAX_GUILDALLIANCE; j++) - if (g[i]->alliance[j].guild_id == g[1-i]->guild_id && g[i]->alliance[j].opposition == (flag & 1)) { - g[i]->alliance[j].guild_id = 0; - break; - } + } + else + { + // Add alliance, in case of alliance, add on both side + for(i=0;i<2-(flag&GUILD_ALLIANCE_TYPE_MASK);i++) + { + // Search an empty slot + ARR_FIND( 0, MAX_GUILDALLIANCE, j, g[i]->alliance[j].guild_id == 0 ); + if( j < MAX_GUILDALLIANCE ) + { + g[i]->alliance[j].guild_id=g[1-i]->guild_id; + memcpy(g[i]->alliance[j].name,g[1-i]->name,NAME_LENGTH); + // Set alliance type + g[i]->alliance[j].opposition = flag&GUILD_ALLIANCE_TYPE_MASK; + } } } - mapif_guild_alliance(guild_id1, guild_id2, account_id1, account_id2, flag, g[0]->name, g[1]->name); + // Send on all map the new alliance/opposition + mapif_guild_alliance(guild_id1,guild_id2,account_id1,account_id2,flag,g[0]->name,g[1]->name); + + // Mark the two guild to be saved + g[0]->save_flag |= GS_ALLIANCE; + g[1]->save_flag |= GS_ALLIANCE; return 0; } -// ギルド告知変更要求 -int mapif_parse_GuildNotice(int fd, int guild_id, const char *mes1, const char *mes2) +// Change guild message +int mapif_parse_GuildNotice(int fd,int guild_id,const char *mes1,const char *mes2) { struct guild *g; - g = (struct guild*)idb_get(guild_db, guild_id); - if (g == NULL) + g = inter_guild_fromsql(guild_id); + if(g==NULL) return 0; - memcpy(g->mes1, mes1, MAX_GUILDMES1); - memcpy(g->mes2, mes2, MAX_GUILDMES2); + memcpy(g->mes1,mes1,MAX_GUILDMES1); + memcpy(g->mes2,mes2,MAX_GUILDMES2); + g->save_flag |= GS_MES; //Change mes of guild return mapif_guild_notice(g); } -// ギルドエンブレム変更要求 -int mapif_parse_GuildEmblem(int fd, int len, int guild_id, int dummy, const char *data) +int mapif_parse_GuildEmblem(int fd,int len,int guild_id,int dummy,const char *data) { - struct guild *g; + struct guild * g; - g = (struct guild*)idb_get(guild_db, guild_id); - if (g == NULL) + g = inter_guild_fromsql(guild_id); + if(g==NULL) return 0; - memcpy(g->emblem_data, data, len); - g->emblem_len = len; - g->emblem_id++; + if (len > sizeof(g->emblem_data)) + len = sizeof(g->emblem_data); + + memcpy(g->emblem_data,data,len); + g->emblem_len=len; + g->emblem_id++; + g->save_flag |= GS_EMBLEM; //Change guild return mapif_guild_emblem(g); } -int mapif_parse_GuildCastleDataLoad(int fd, int castle_id, int index) +int mapif_parse_GuildCastleDataLoad(int fd,int castle_id,int index) { - struct guild_castle *gc = (struct guild_castle*)idb_get(castle_db, castle_id); - - if (gc == NULL) { - return mapif_guild_castle_dataload(castle_id, 0, 0); - } - switch(index) { - case 1: return mapif_guild_castle_dataload(gc->castle_id, index, gc->guild_id); - case 2: return mapif_guild_castle_dataload(gc->castle_id, index, gc->economy); - case 3: return mapif_guild_castle_dataload(gc->castle_id, index, gc->defense); - case 4: return mapif_guild_castle_dataload(gc->castle_id, index, gc->triggerE); - case 5: return mapif_guild_castle_dataload(gc->castle_id, index, gc->triggerD); - case 6: return mapif_guild_castle_dataload(gc->castle_id, index, gc->nextTime); - case 7: return mapif_guild_castle_dataload(gc->castle_id, index, gc->payTime); - case 8: return mapif_guild_castle_dataload(gc->castle_id, index, gc->createTime); - case 9: return mapif_guild_castle_dataload(gc->castle_id, index, gc->visibleC); + struct guild_castle gc; + if (!inter_guildcastle_fromsql(castle_id, &gc)) { + return mapif_guild_castle_dataload(castle_id,0,0); + } + switch(index){ + case 1: return mapif_guild_castle_dataload(gc.castle_id,index,gc.guild_id); break; + case 2: return mapif_guild_castle_dataload(gc.castle_id,index,gc.economy); break; + case 3: return mapif_guild_castle_dataload(gc.castle_id,index,gc.defense); break; + case 4: return mapif_guild_castle_dataload(gc.castle_id,index,gc.triggerE); break; + case 5: return mapif_guild_castle_dataload(gc.castle_id,index,gc.triggerD); break; + case 6: return mapif_guild_castle_dataload(gc.castle_id,index,gc.nextTime); break; + case 7: return mapif_guild_castle_dataload(gc.castle_id,index,gc.payTime); break; + case 8: return mapif_guild_castle_dataload(gc.castle_id,index,gc.createTime); break; + case 9: return mapif_guild_castle_dataload(gc.castle_id,index,gc.visibleC); break; case 10: case 11: case 12: @@ -1450,45 +1844,42 @@ int mapif_parse_GuildCastleDataLoad(int fd, int castle_id, int index) case 15: case 16: case 17: - return mapif_guild_castle_dataload(gc->castle_id, index, gc->guardian[index-10].visible); + return mapif_guild_castle_dataload(gc.castle_id,index,gc.guardian[index-10].visible); break; default: ShowError("mapif_parse_GuildCastleDataLoad ERROR!! (Not found index=%d)\n", index); return 0; } - - return 0; } -int mapif_parse_GuildCastleDataSave(int fd, int castle_id, int index, int value) +int mapif_parse_GuildCastleDataSave(int fd,int castle_id,int index,int value) { - struct guild_castle *gc = (struct guild_castle*)idb_get(castle_db, castle_id); - - if (gc == NULL) - return mapif_guild_castle_datasave(castle_id, index, value); + struct guild_castle gc; + if(!inter_guildcastle_fromsql(castle_id, &gc)) + return mapif_guild_castle_datasave(castle_id,index,value); - switch(index) { + switch(index){ case 1: - if (gc->guild_id != value) { - int gid = (value) ? value : gc->guild_id; - struct guild *g = (struct guild*)idb_get(guild_db, gid); + if( gc.guild_id!=value ){ + int gid=(value)?value:gc.guild_id; + struct guild *g = (struct guild*)idb_get(guild_db_, gid); if(log_inter) inter_log("guild %s (id=%d) %s castle id=%d\n", - (g) ? g->name : "??", gid, (value) ? "occupy" : "abandon", castle_id); + (g)?g->name:"??" ,gid, (value)?"occupy":"abandon", castle_id); } - gc->guild_id = value; - if(gc->guild_id == 0) { + gc.guild_id = value; + if(gc.guild_id == 0) { //Delete guardians. - memset(&gc->guardian, 0, sizeof(gc->guardian)); + memset(&gc.guardian, 0, sizeof(gc.guardian)); } break; - case 2: gc->economy = value; break; - case 3: gc->defense = value; break; - case 4: gc->triggerE = value; break; - case 5: gc->triggerD = value; break; - case 6: gc->nextTime = value; break; - case 7: gc->payTime = value; break; - case 8: gc->createTime = value; break; - case 9: gc->visibleC = value; break; + case 2: gc.economy = value; break; + case 3: gc.defense = value; break; + case 4: gc.triggerE = value; break; + case 5: gc.triggerD = value; break; + case 6: gc.nextTime = value; break; + case 7: gc.payTime = value; break; + case 8: gc.createTime = value; break; + case 9: gc.visibleC = value; break; case 10: case 11: case 12: @@ -1497,38 +1888,50 @@ int mapif_parse_GuildCastleDataSave(int fd, int castle_id, int index, int value) case 15: case 16: case 17: - gc->guardian[index-10].visible = value; break; + gc.guardian[index-10].visible = value; break; default: ShowError("mapif_parse_GuildCastleDataSave ERROR!! (Not found index=%d)\n", index); return 0; } - - return mapif_guild_castle_datasave(gc->castle_id, index, value); + inter_guildcastle_tosql(&gc); + mapif_guild_castle_datasave(gc.castle_id,index,value); + return 0; } int mapif_parse_GuildMasterChange(int fd, int guild_id, const char* name, int len) { - struct guild *g = (struct guild*)idb_get(guild_db, guild_id); + struct guild * g; struct guild_member gm; int pos; - if(g==NULL || g->guild_id<=0 || len > NAME_LENGTH) + g = inter_guild_fromsql(guild_id); + + if(g==NULL || len > NAME_LENGTH) return 0; + // Find member (name) for (pos = 0; pos < g->max_member && strncmp(g->member[pos].name, name, len); pos++); if (pos == g->max_member) return 0; //Character not found?? + // Switch current and old GM memcpy(&gm, &g->member[pos], sizeof (struct guild_member)); memcpy(&g->member[pos], &g->member[0], sizeof(struct guild_member)); memcpy(&g->member[0], &gm, sizeof(struct guild_member)); + // Switch positions g->member[pos].position = g->member[0].position; + g->member[pos].modified = GS_MEMBER_MODIFIED; g->member[0].position = 0; //Position 0: guild Master. - safestrncpy(g->master, name, NAME_LENGTH); + g->member[0].modified = GS_MEMBER_MODIFIED; + + strncpy(g->master, name, len); + if (len < NAME_LENGTH) + g->master[len] = '\0'; - ShowInfo("int_guild: Guildmaster Changed to %s (Guild %d - %s)\n",name, guild_id, g->name); + ShowInfo("int_guild: Guildmaster Changed to %s (Guild %d - %s)\n",g->master, guild_id, g->name); + g->save_flag |= (GS_BASIC|GS_MEMBER); //Save main data and member data. return mapif_guild_master_changed(g, g->member[0].account_id, g->member[0].char_id); } @@ -1541,23 +1944,23 @@ int inter_guild_parse_frommap(int fd) { RFIFOHEAD(fd); switch(RFIFOW(fd,0)) { - case 0x3030: mapif_parse_CreateGuild(fd, RFIFOL(fd,4), (char*)RFIFOP(fd,8), (struct guild_member *)RFIFOP(fd,32)); break; - case 0x3031: mapif_parse_GuildInfo(fd, RFIFOL(fd,2)); break; - case 0x3032: mapif_parse_GuildAddMember(fd, RFIFOL(fd,4), (struct guild_member *)RFIFOP(fd,8)); break; + case 0x3030: mapif_parse_CreateGuild(fd,RFIFOL(fd,4),(char*)RFIFOP(fd,8),(struct guild_member *)RFIFOP(fd,32)); break; + case 0x3031: mapif_parse_GuildInfo(fd,RFIFOL(fd,2)); break; + case 0x3032: mapif_parse_GuildAddMember(fd,RFIFOL(fd,4),(struct guild_member *)RFIFOP(fd,8)); break; case 0x3033: mapif_parse_GuildMasterChange(fd,RFIFOL(fd,4),(const char*)RFIFOP(fd,8),RFIFOW(fd,2)-8); break; - case 0x3034: mapif_parse_GuildLeave(fd, RFIFOL(fd,2), RFIFOL(fd,6), RFIFOL(fd,10), RFIFOB(fd,14), (const char*)RFIFOP(fd,15)); break; - case 0x3035: mapif_parse_GuildChangeMemberInfoShort(fd, RFIFOL(fd,2), RFIFOL(fd,6), RFIFOL(fd,10), RFIFOB(fd,14), RFIFOW(fd,15), RFIFOW(fd,17)); break; - case 0x3036: mapif_parse_BreakGuild(fd, RFIFOL(fd,2)); break; - case 0x3037: mapif_parse_GuildMessage(fd, RFIFOL(fd,4), RFIFOL(fd,8), (char*)RFIFOP(fd,12), RFIFOW(fd,2)-12); break; - case 0x3039: mapif_parse_GuildBasicInfoChange(fd, RFIFOL(fd,4), RFIFOW(fd,8), (const char*)RFIFOP(fd,10), RFIFOW(fd,2)-10); break; - case 0x303A: mapif_parse_GuildMemberInfoChange(fd, RFIFOL(fd,4), RFIFOL(fd,8), RFIFOL(fd,12), RFIFOW(fd,16), (const char*)RFIFOP(fd,18), RFIFOW(fd,2)-18); break; - case 0x303B: mapif_parse_GuildPosition(fd, RFIFOL(fd,4), RFIFOL(fd,8), (struct guild_position *)RFIFOP(fd,12)); break; - case 0x303C: mapif_parse_GuildSkillUp(fd, RFIFOL(fd,2), RFIFOL(fd,6), RFIFOL(fd,10), RFIFOL(fd,14)); break; - case 0x303D: mapif_parse_GuildAlliance(fd, RFIFOL(fd,2), RFIFOL(fd,6), RFIFOL(fd,10), RFIFOL(fd,14), RFIFOB(fd,18)); break; - case 0x303E: mapif_parse_GuildNotice(fd, RFIFOL(fd,2), (const char*)RFIFOP(fd,6), (const char*)RFIFOP(fd,66)); break; - case 0x303F: mapif_parse_GuildEmblem(fd, RFIFOW(fd,2)-12, RFIFOL(fd,4), RFIFOL(fd,8), (const char*)RFIFOP(fd,12)); break; - case 0x3040: mapif_parse_GuildCastleDataLoad(fd, RFIFOW(fd,2), RFIFOB(fd,4)); break; - case 0x3041: mapif_parse_GuildCastleDataSave(fd, RFIFOW(fd,2), RFIFOB(fd,4), RFIFOL(fd,5)); break; + case 0x3034: mapif_parse_GuildLeave(fd,RFIFOL(fd,2),RFIFOL(fd,6),RFIFOL(fd,10),RFIFOB(fd,14),(const char*)RFIFOP(fd,15)); break; + case 0x3035: mapif_parse_GuildChangeMemberInfoShort(fd,RFIFOL(fd,2),RFIFOL(fd,6),RFIFOL(fd,10),RFIFOB(fd,14),RFIFOW(fd,15),RFIFOW(fd,17)); break; + case 0x3036: mapif_parse_BreakGuild(fd,RFIFOL(fd,2)); break; + case 0x3037: mapif_parse_GuildMessage(fd,RFIFOL(fd,4),RFIFOL(fd,8),(char*)RFIFOP(fd,12),RFIFOW(fd,2)-12); break; + case 0x3039: mapif_parse_GuildBasicInfoChange(fd,RFIFOL(fd,4),RFIFOW(fd,8),(const char*)RFIFOP(fd,10),RFIFOW(fd,2)-10); break; + case 0x303A: mapif_parse_GuildMemberInfoChange(fd,RFIFOL(fd,4),RFIFOL(fd,8),RFIFOL(fd,12),RFIFOW(fd,16),(const char*)RFIFOP(fd,18),RFIFOW(fd,2)-18); break; + case 0x303B: mapif_parse_GuildPosition(fd,RFIFOL(fd,4),RFIFOL(fd,8),(struct guild_position *)RFIFOP(fd,12)); break; + case 0x303C: mapif_parse_GuildSkillUp(fd,RFIFOL(fd,2),RFIFOL(fd,6),RFIFOL(fd,10),RFIFOL(fd,14)); break; + case 0x303D: mapif_parse_GuildAlliance(fd,RFIFOL(fd,2),RFIFOL(fd,6),RFIFOL(fd,10),RFIFOL(fd,14),RFIFOB(fd,18)); break; + case 0x303E: mapif_parse_GuildNotice(fd,RFIFOL(fd,2),(const char*)RFIFOP(fd,6),(const char*)RFIFOP(fd,66)); break; + case 0x303F: mapif_parse_GuildEmblem(fd,RFIFOW(fd,2)-12,RFIFOL(fd,4),RFIFOL(fd,8),(const char*)RFIFOP(fd,12)); break; + case 0x3040: mapif_parse_GuildCastleDataLoad(fd,RFIFOW(fd,2),RFIFOB(fd,4)); break; + case 0x3041: mapif_parse_GuildCastleDataSave(fd,RFIFOW(fd,2),RFIFOB(fd,4),RFIFOL(fd,5)); break; default: return 0; @@ -1577,4 +1980,8 @@ int inter_guild_leave(int guild_id, int account_id, int char_id) { return mapif_parse_GuildLeave(-1, guild_id, account_id, char_id, 0, "** Character Deleted **"); } -#endif //TXT_SQL_CONVERT + +int inter_guild_broken(int guild_id) +{ + return mapif_guild_broken(guild_id, 0); +} diff --git a/src/char/int_guild.h b/src/char/int_guild.h index 0be6c50d9..4577357f3 100644 --- a/src/char/int_guild.h +++ b/src/char/int_guild.h @@ -1,26 +1,40 @@ // Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder -#ifndef _INT_GUILD_H_ -#define _INT_GUILD_H_ +#ifndef _INT_GUILD_SQL_H_ +#define _INT_GUILD_SQL_H_ + +#define GS_BASIC 0x0001 +#define GS_MEMBER 0x0002 +#define GS_POSITION 0x0004 +#define GS_ALLIANCE 0x0008 +#define GS_EXPULSION 0x0010 +#define GS_SKILL 0x0020 +#define GS_EMBLEM 0x0040 +#define GS_CONNECT 0x0080 +#define GS_LEVEL 0x0100 +#define GS_MES 0x0200 +#define GS_MASK 0x03FF +#define GS_BASIC_MASK (GS_BASIC | GS_EMBLEM | GS_CONNECT | GS_LEVEL | GS_MES) +#define GS_REMOVE 0x8000 struct guild; struct guild_castle; -int inter_guild_init(void); -void inter_guild_final(void); -int inter_guild_save(void); int inter_guild_parse_frommap(int fd); -struct guild *inter_guild_search(int guild_id); +int inter_guild_sql_init(void); +void inter_guild_sql_final(void); int inter_guild_mapif_init(int fd); int inter_guild_leave(int guild_id,int account_id,int char_id); +int mapif_parse_BreakGuild(int fd,int guild_id); +int inter_guild_broken(int guild_id); int inter_guild_sex_changed(int guild_id,int account_id,int char_id, short gender); +int inter_guild_charname_changed(int guild_id,int account_id, int char_id, char *name); +int inter_guild_CharOnline(int char_id, int guild_id); +int inter_guild_CharOffline(int char_id, int guild_id); -extern char guild_txt[1024]; -extern char castle_txt[1024]; - -//For the TXT->SQL converter -int inter_guild_fromstr(char *str, struct guild *g); -int inter_guildcastle_fromstr(char *str, struct guild_castle *gc); +//For the TXT->SQL converter. +int inter_guild_tosql(struct guild *g,int flag); +int inter_guildcastle_tosql(struct guild_castle *gc); -#endif /* _INT_GUILD_H_ */ +#endif /* _INT_GUILD_SQL_H_ */ diff --git a/src/char/int_homun.c b/src/char/int_homun.c index ec22499d0..d5a928e59 100644 --- a/src/char/int_homun.c +++ b/src/char/int_homun.c @@ -3,363 +3,311 @@ #include "../common/mmo.h" #include "../common/malloc.h" -#include "../common/socket.h" -#include "../common/db.h" -#include "../common/lock.h" +#include "../common/strlib.h" #include "../common/showmsg.h" +#include "../common/socket.h" +#include "../common/utils.h" +#include "../common/sql.h" #include "char.h" #include "inter.h" -#include "int_homun.h" #include <stdio.h> #include <stdlib.h> #include <string.h> -char homun_txt[1024]="save/homun.txt"; -static DBMap* homun_db; // int hom_id -> struct s_homunculus* -static int homun_newid = 100; - -int inter_homun_tostr(char *str,struct s_homunculus *p) +int inter_homunculus_sql_init(void) { - int i; - - str+=sprintf(str,"%d,%d\t%s\t%d,%d,%d,%d,%d," - "%u,%d,%d,%d," - "%u,%d,%d," - "%d,%d,%d,%d,%d,%d\t", - p->hom_id, p->class_, p->name, - p->char_id, p->hp, p->max_hp, p->sp, p->max_sp, - p->intimacy, p->hunger, p->skillpts, p->level, - p->exp, p->rename_flag, p->vaporize, - p->str, p->agi, p->vit, p->int_, p->dex, p->luk); - - for (i = 0; i < MAX_HOMUNSKILL; i++) - { - if (p->hskill[i].id && p->hskill[i].flag == SKILL_FLAG_PERMANENT) - str+=sprintf(str,"%d,%d,", p->hskill[i].id, p->hskill[i].lv); - } - return 0; } - -int inter_homun_fromstr(char *str,struct s_homunculus *p) -{ - int i, next, len; - int tmp_int[25]; - unsigned int tmp_uint[5]; - char tmp_str[256]; - - memset(p,0,sizeof(struct s_homunculus)); - - i=sscanf(str,"%d,%d\t%127[^\t]\t%d,%d,%d,%d,%d," - "%u,%d,%d,%d," - "%u,%d,%d," - "%d,%d,%d,%d,%d,%d\t%n", - &tmp_int[0],&tmp_int[1],tmp_str, - &tmp_int[2],&tmp_int[3],&tmp_int[4],&tmp_int[5],&tmp_int[6], - &tmp_uint[0],&tmp_int[7],&tmp_int[8],&tmp_int[9], - &tmp_uint[1],&tmp_int[10],&tmp_int[11], - &tmp_int[12],&tmp_int[13],&tmp_int[14],&tmp_int[15],&tmp_int[16],&tmp_int[17], - &next); - - if(i!=21) - return 1; - - p->hom_id = tmp_int[0]; - p->class_ = tmp_int[1]; - memcpy(p->name, tmp_str, NAME_LENGTH); - - p->char_id = tmp_int[2]; - p->hp = tmp_int[3]; - p->max_hp = tmp_int[4]; - p->sp = tmp_int[5]; - p->max_sp = tmp_int[6]; - - p->intimacy = tmp_uint[0]; - p->hunger = tmp_int[7]; - p->skillpts = tmp_int[8]; - p->level = tmp_int[9]; - - p->exp = tmp_uint[1]; - p->rename_flag = tmp_int[10]; - p->vaporize = tmp_int[11]; - - p->str = tmp_int[12]; - p->agi = tmp_int[13]; - p->vit = tmp_int[14]; - p->int_= tmp_int[15]; - p->dex = tmp_int[16]; - p->luk = tmp_int[17]; - - //Read skills. - while(str[next] && str[next] != '\n' && str[next] != '\r') { - if (sscanf(str+next, "%d,%d,%n", &tmp_int[0], &tmp_int[1], &len) != 2) - return 2; - - if (tmp_int[0] >= HM_SKILLBASE && tmp_int[0] < HM_SKILLBASE+MAX_HOMUNSKILL) - { - i = tmp_int[0] - HM_SKILLBASE; - p->hskill[i].id = tmp_int[0]; - p->hskill[i].lv = tmp_int[1]; - } else - ShowError("Read Homun: Unsupported Skill ID %d for homunculus (Homun ID=%d)\n", tmp_int[0], p->hom_id); - next += len; - if (str[next] == ' ') - next++; - } - return 0; -} - -int inter_homun_init() +void inter_homunculus_sql_final(void) { - char line[8192]; - struct s_homunculus *p; - FILE *fp; - int c=0; - - homun_db= idb_alloc(DB_OPT_RELEASE_DATA); - - if( (fp=fopen(homun_txt,"r"))==NULL ) - return 1; - while(fgets(line, sizeof(line), fp)) - { - p = (struct s_homunculus*)aCalloc(sizeof(struct s_homunculus), 1); - if(p==NULL){ - ShowFatalError("int_homun: out of memory!\n"); - exit(EXIT_FAILURE); - } - if(inter_homun_fromstr(line,p)==0 && p->hom_id>0){ - if( p->hom_id >= homun_newid) - homun_newid=p->hom_id+1; - idb_put(homun_db,p->hom_id,p); - }else{ - ShowError("int_homun: broken data [%s] line %d\n",homun_txt,c); - aFree(p); - } - c++; - } - fclose(fp); - return 0; -} - -void inter_homun_final() -{ - homun_db->destroy(homun_db, NULL); return; } -int inter_homun_save_sub(DBKey key,void *data,va_list ap) -{ - char line[8192]; - FILE *fp; - inter_homun_tostr(line,(struct s_homunculus *)data); - fp=va_arg(ap,FILE *); - fprintf(fp,"%s\n",line); - return 0; -} - -int inter_homun_save() -{ - FILE *fp; - int lock; - if( (fp=lock_fopen(homun_txt,&lock))==NULL ){ - ShowError("int_homun: can't write [%s] !!! data is lost !!!\n",homun_txt); - return 1; - } - homun_db->foreach(homun_db,inter_homun_save_sub,fp); - lock_fclose(fp,homun_txt,&lock); - return 0; -} - -int inter_homun_delete(int hom_id) -{ - struct s_homunculus *p; - p = (struct s_homunculus*)idb_get(homun_db,hom_id); - if( p == NULL) - return 0; - idb_remove(homun_db,hom_id); - ShowInfo("Deleted homun (hom_id: %d)\n",hom_id); - return 1; -} - -int mapif_homun_created(int fd,int account_id, struct s_homunculus *p) +static void mapif_homunculus_created(int fd, int account_id, struct s_homunculus *sh, unsigned char flag) { WFIFOHEAD(fd, sizeof(struct s_homunculus)+9); - WFIFOW(fd, 0) =0x3890; + WFIFOW(fd,0) = 0x3890; WFIFOW(fd,2) = sizeof(struct s_homunculus)+9; WFIFOL(fd,4) = account_id; - WFIFOB(fd,8)= p->hom_id?1:0; - memcpy(WFIFOP(fd,9), p, sizeof(struct s_homunculus)); + WFIFOB(fd,8)= flag; + memcpy(WFIFOP(fd,9),sh,sizeof(struct s_homunculus)); WFIFOSET(fd, WFIFOW(fd,2)); - return 0; } -int mapif_homun_info(int fd,int account_id,struct s_homunculus *p) +static void mapif_homunculus_deleted(int fd, int flag) +{ + WFIFOHEAD(fd, 3); + WFIFOW(fd, 0) = 0x3893; + WFIFOB(fd,2) = flag; //Flag 1 = success + WFIFOSET(fd, 3); +} + +static void mapif_homunculus_loaded(int fd, int account_id, struct s_homunculus *hd) { WFIFOHEAD(fd, sizeof(struct s_homunculus)+9); WFIFOW(fd,0) = 0x3891; WFIFOW(fd,2) = sizeof(struct s_homunculus)+9; WFIFOL(fd,4) = account_id; - WFIFOB(fd,8) = 1; // account loaded with success - - memcpy(WFIFOP(fd,9), p, sizeof(struct s_homunculus)); - WFIFOSET(fd,WFIFOW(fd,2)); - return 0; -} - -int mapif_homun_noinfo(int fd,int account_id) -{ - WFIFOHEAD(fd,sizeof(struct s_homunculus) + 9); - WFIFOW(fd,0)=0x3891; - WFIFOW(fd,2)=sizeof(struct s_homunculus) + 9; - WFIFOL(fd,4)=account_id; - WFIFOB(fd,8)=0; - memset(WFIFOP(fd,9),0,sizeof(struct s_homunculus)); - WFIFOSET(fd,WFIFOW(fd,2)); - - return 0; + if( hd != NULL ) + { + WFIFOB(fd,8) = 1; // success + memcpy(WFIFOP(fd,9), hd, sizeof(struct s_homunculus)); + } + else + { + WFIFOB(fd,8) = 0; // not found. + memset(WFIFOP(fd,9), 0, sizeof(struct s_homunculus)); + } + WFIFOSET(fd, sizeof(struct s_homunculus)+9); } -int mapif_save_homun_ack(int fd,int account_id,int flag) +static void mapif_homunculus_saved(int fd, int account_id, bool flag) { WFIFOHEAD(fd, 7); - WFIFOW(fd,0)=0x3892; - WFIFOL(fd,2)=account_id; - WFIFOB(fd,6)=flag; - WFIFOSET(fd,7); - return 0; + WFIFOW(fd,0) = 0x3892; + WFIFOL(fd,2) = account_id; + WFIFOB(fd,6) = flag; // 1:success, 0:failure + WFIFOSET(fd, 7); } -int mapif_delete_homun_ack(int fd,int flag) +static void mapif_homunculus_renamed(int fd, int account_id, int char_id, unsigned char flag, char* name) { - WFIFOHEAD(fd, 3); - WFIFOW(fd,0)=0x3893; - WFIFOB(fd,2)=flag; - WFIFOSET(fd,3); - return 0; -} - -int mapif_rename_homun_ack(int fd, int account_id, int char_id, int flag, char *name){ WFIFOHEAD(fd, NAME_LENGTH+12); - WFIFOW(fd, 0) =0x3894; - WFIFOL(fd, 2) =account_id; - WFIFOL(fd, 6) =char_id; - WFIFOB(fd, 10) =flag; - memcpy(WFIFOP(fd, 11), name, NAME_LENGTH); + WFIFOW(fd, 0) = 0x3894; + WFIFOL(fd, 2) = account_id; + WFIFOL(fd, 6) = char_id; + WFIFOB(fd,10) = flag; + safestrncpy((char*)WFIFOP(fd,11), name, NAME_LENGTH); WFIFOSET(fd, NAME_LENGTH+12); - - return 0; } -int mapif_create_homun(int fd) +bool mapif_homunculus_save(struct s_homunculus* hd) { - struct s_homunculus *p; - p= (struct s_homunculus *) aCalloc(sizeof(struct s_homunculus), 1); - if(p==NULL){ - ShowFatalError("int_homun: out of memory !\n"); - //Sending the received data will pass hom_id == 0 <- fail. - mapif_homun_created(fd,RFIFOL(fd,4),(struct s_homunculus*)RFIFOP(fd,8)); - return 0; + bool flag = true; + char esc_name[NAME_LENGTH*2+1]; + + Sql_EscapeStringLen(sql_handle, esc_name, hd->name, strnlen(hd->name, NAME_LENGTH)); + + if( hd->hom_id == 0 ) + {// new homunculus + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `homunculus` " + "(`char_id`, `class`,`name`,`level`,`exp`,`intimacy`,`hunger`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `hp`,`max_hp`,`sp`,`max_sp`,`skill_point`, `rename_flag`, `vaporize`) " + "VALUES ('%d', '%d', '%s', '%d', '%u', '%u', '%d', '%d', %d, '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')", + hd->char_id, hd->class_, esc_name, hd->level, hd->exp, hd->intimacy, hd->hunger, hd->str, hd->agi, hd->vit, hd->int_, hd->dex, hd->luk, + hd->hp, hd->max_hp, hd->sp, hd->max_sp, hd->skillpts, hd->rename_flag, hd->vaporize) ) + { + Sql_ShowDebug(sql_handle); + flag = false; + } + else + { + hd->hom_id = (int)Sql_LastInsertId(sql_handle); + } } - memcpy(p, RFIFOP(fd,8), sizeof(struct s_homunculus)); - p->hom_id = homun_newid++; //New ID - idb_put(homun_db,p->hom_id,p); - mapif_homun_created(fd,RFIFOL(fd,4),p); - return 0; + else + { + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `homunculus` SET `char_id`='%d', `class`='%d',`name`='%s',`level`='%d',`exp`='%u',`intimacy`='%u',`hunger`='%d', `str`='%d', `agi`='%d', `vit`='%d', `int`='%d', `dex`='%d', `luk`='%d', `hp`='%d',`max_hp`='%d',`sp`='%d',`max_sp`='%d',`skill_point`='%d', `rename_flag`='%d', `vaporize`='%d' WHERE `homun_id`='%d'", + hd->char_id, hd->class_, esc_name, hd->level, hd->exp, hd->intimacy, hd->hunger, hd->str, hd->agi, hd->vit, hd->int_, hd->dex, hd->luk, + hd->hp, hd->max_hp, hd->sp, hd->max_sp, hd->skillpts, hd->rename_flag, hd->vaporize, hd->hom_id) ) + { + Sql_ShowDebug(sql_handle); + flag = false; + } + else + { + SqlStmt* stmt; + int i; + + stmt = SqlStmt_Malloc(sql_handle); + if( SQL_ERROR == SqlStmt_Prepare(stmt, "REPLACE INTO `skill_homunculus` (`homun_id`, `id`, `lv`) VALUES (%d, ?, ?)", hd->hom_id) ) + SqlStmt_ShowDebug(stmt); + for( i = 0; i < MAX_HOMUNSKILL; ++i ) + { + if( hd->hskill[i].id > 0 && hd->hskill[i].lv != 0 ) + { + SqlStmt_BindParam(stmt, 0, SQLDT_USHORT, &hd->hskill[i].id, 0); + SqlStmt_BindParam(stmt, 1, SQLDT_USHORT, &hd->hskill[i].lv, 0); + if( SQL_ERROR == SqlStmt_Execute(stmt) ) + { + SqlStmt_ShowDebug(stmt); + SqlStmt_Free(stmt); + flag = false; + break; + } + } + } + SqlStmt_Free(stmt); + } + } + + return flag; } -int mapif_load_homun(int fd) + + +// Load an homunculus +bool mapif_homunculus_load(int homun_id, struct s_homunculus* hd) { - struct s_homunculus *p; - int account_id; - account_id = RFIFOL(fd,2); - - p = (struct s_homunculus*)idb_get(homun_db,RFIFOL(fd,6)); - if(p==NULL) { - mapif_homun_noinfo(fd,account_id); - return 0; + int i; + char* data; + size_t len; + + memset(hd, 0, sizeof(*hd)); + + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `homun_id`,`char_id`,`class`,`name`,`level`,`exp`,`intimacy`,`hunger`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `hp`,`max_hp`,`sp`,`max_sp`,`skill_point`,`rename_flag`, `vaporize` FROM `homunculus` WHERE `homun_id`='%u'", homun_id) ) + { + Sql_ShowDebug(sql_handle); + return false; } - mapif_homun_info(fd,account_id,p); - return 0; -} -static void* create_homun(DBKey key, va_list args) { - struct s_homunculus *p; - p=(struct s_homunculus *)aCalloc(sizeof(struct s_homunculus),1); - p->hom_id = key.i; - return p; -} -int mapif_save_homun(int fd,int account_id,struct s_homunculus *data) -{ - struct s_homunculus *p; - int hom_id; - - if (data->hom_id == 0) - data->hom_id = homun_newid++; - hom_id = data->hom_id; - p = (struct s_homunculus*)idb_ensure(homun_db,hom_id,create_homun); - memcpy(p,data,sizeof(struct s_homunculus)); - mapif_save_homun_ack(fd,account_id,1); - return 0; + if( !Sql_NumRows(sql_handle) ) + { //No homunculus found. + Sql_FreeResult(sql_handle); + return false; + } + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + { + Sql_ShowDebug(sql_handle); + Sql_FreeResult(sql_handle); + return false; + } + + hd->hom_id = homun_id; + Sql_GetData(sql_handle, 1, &data, NULL); hd->char_id = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); hd->class_ = atoi(data); + Sql_GetData(sql_handle, 3, &data, &len); safestrncpy(hd->name, data, sizeof(hd->name)); + Sql_GetData(sql_handle, 4, &data, NULL); hd->level = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); hd->exp = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); hd->intimacy = (unsigned int)strtoul(data, NULL, 10); + Sql_GetData(sql_handle, 7, &data, NULL); hd->hunger = atoi(data); + Sql_GetData(sql_handle, 8, &data, NULL); hd->str = atoi(data); + Sql_GetData(sql_handle, 9, &data, NULL); hd->agi = atoi(data); + Sql_GetData(sql_handle, 10, &data, NULL); hd->vit = atoi(data); + Sql_GetData(sql_handle, 11, &data, NULL); hd->int_ = atoi(data); + Sql_GetData(sql_handle, 12, &data, NULL); hd->dex = atoi(data); + Sql_GetData(sql_handle, 13, &data, NULL); hd->luk = atoi(data); + Sql_GetData(sql_handle, 14, &data, NULL); hd->hp = atoi(data); + Sql_GetData(sql_handle, 15, &data, NULL); hd->max_hp = atoi(data); + Sql_GetData(sql_handle, 16, &data, NULL); hd->sp = atoi(data); + Sql_GetData(sql_handle, 17, &data, NULL); hd->max_sp = atoi(data); + Sql_GetData(sql_handle, 18, &data, NULL); hd->skillpts = atoi(data); + Sql_GetData(sql_handle, 19, &data, NULL); hd->rename_flag = atoi(data); + Sql_GetData(sql_handle, 20, &data, NULL); hd->vaporize = atoi(data); + Sql_FreeResult(sql_handle); + + hd->intimacy = cap_value(hd->intimacy, 0, 100000); + hd->hunger = cap_value(hd->hunger, 0, 100); + + // Load Homunculus Skill + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `id`,`lv` FROM `skill_homunculus` WHERE `homun_id`=%d", homun_id) ) + { + Sql_ShowDebug(sql_handle); + return false; + } + while( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + // id + Sql_GetData(sql_handle, 0, &data, NULL); + i = atoi(data); + if( i < HM_SKILLBASE || i >= HM_SKILLBASE + MAX_HOMUNSKILL ) + continue;// invalid skill id + i = i - HM_SKILLBASE; + hd->hskill[i].id = (unsigned short)atoi(data); + + // lv + Sql_GetData(sql_handle, 1, &data, NULL); + hd->hskill[i].lv = (unsigned char)atoi(data); + } + Sql_FreeResult(sql_handle); + + if( save_log ) + ShowInfo("Homunculus loaded (%d - %s).\n", hd->hom_id, hd->name); + + return true; } -int mapif_delete_homun(int fd,int hom_id) +bool mapif_homunculus_delete(int homun_id) { - mapif_delete_homun_ack(fd,inter_homun_delete(hom_id)); - return 0; + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `homunculus` WHERE `homun_id` = '%u'", homun_id) + || SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `skill_homunculus` WHERE `homun_id` = '%u'", homun_id) + ) { + Sql_ShowDebug(sql_handle); + return false; + } + return true; } -int mapif_rename_homun(int fd, int account_id, int char_id, char *name){ +bool mapif_homunculus_rename(char *name) +{ int i; // Check Authorised letters/symbols in the name of the homun - if (char_name_option == 1) { // only letters/symbols in char_name_letters are authorised - for (i = 0; i < NAME_LENGTH && name[i]; i++) - if (strchr(char_name_letters, name[i]) == NULL) { - mapif_rename_homun_ack(fd, account_id, char_id, 0, name); - return 0; - } - } else if (char_name_option == 2) { // letters/symbols in char_name_letters are forbidden - for (i = 0; i < NAME_LENGTH && name[i]; i++) - if (strchr(char_name_letters, name[i]) != NULL) { - mapif_rename_homun_ack(fd, account_id, char_id, 0, name); - return 0; - } + if( char_name_option == 1 ) + {// only letters/symbols in char_name_letters are authorised + for( i = 0; i < NAME_LENGTH && name[i]; i++ ) + if( strchr(char_name_letters, name[i]) == NULL ) + return false; + } else + if( char_name_option == 2 ) + {// letters/symbols in char_name_letters are forbidden + for( i = 0; i < NAME_LENGTH && name[i]; i++ ) + if( strchr(char_name_letters, name[i]) != NULL ) + return false; } - mapif_rename_homun_ack(fd, account_id, char_id, 1, name); - return 0; + return true; } -int mapif_parse_SaveHomun(int fd) + +static void mapif_parse_homunculus_create(int fd, int len, int account_id, struct s_homunculus* phd) { - mapif_save_homun(fd,RFIFOL(fd,4),(struct s_homunculus *)RFIFOP(fd,8)); - return 0; + bool result = mapif_homunculus_save(phd); + mapif_homunculus_created(fd, account_id, phd, result); } -int mapif_parse_DeleteHomun(int fd) +static void mapif_parse_homunculus_delete(int fd, int homun_id) { - mapif_delete_homun(fd,RFIFOL(fd,2)); - return 0; + bool result = mapif_homunculus_delete(homun_id); + mapif_homunculus_deleted(fd, result); } -int mapif_parse_RenameHomun(int fd) +static void mapif_parse_homunculus_load(int fd, int account_id, int homun_id) { - mapif_rename_homun(fd, RFIFOL(fd, 2), RFIFOL(fd, 6), (char*)RFIFOP(fd, 10)); - return 0; + struct s_homunculus hd; + bool result = mapif_homunculus_load(homun_id, &hd); + mapif_homunculus_loaded(fd, account_id, ( result ? &hd : NULL )); +} + +static void mapif_parse_homunculus_save(int fd, int len, int account_id, struct s_homunculus* phd) +{ + bool result = mapif_homunculus_save(phd); + mapif_homunculus_saved(fd, account_id, result); +} + +static void mapif_parse_homunculus_rename(int fd, int account_id, int char_id, char* name) +{ + bool result = mapif_homunculus_rename(name); + mapif_homunculus_renamed(fd, account_id, char_id, result, name); } -int inter_homun_parse_frommap(int fd) +/*========================================== + * Inter Packets + *------------------------------------------*/ +int inter_homunculus_parse_frommap(int fd) { - switch(RFIFOW(fd,0)){ - case 0x3090: mapif_create_homun(fd); break; - case 0x3091: mapif_load_homun(fd); break; - case 0x3092: mapif_parse_SaveHomun(fd); break; - case 0x3093: mapif_parse_DeleteHomun(fd); break; - case 0x3094: mapif_parse_RenameHomun(fd); break; - default: - return 0; + unsigned short cmd = RFIFOW(fd,0); + + switch( cmd ) + { + case 0x3090: mapif_parse_homunculus_create(fd, (int)RFIFOW(fd,2), (int)RFIFOL(fd,4), (struct s_homunculus*)RFIFOP(fd,8)); break; + case 0x3091: mapif_parse_homunculus_load (fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6)); break; + case 0x3092: mapif_parse_homunculus_save (fd, (int)RFIFOW(fd,2), (int)RFIFOL(fd,4), (struct s_homunculus*)RFIFOP(fd,8)); break; + case 0x3093: mapif_parse_homunculus_delete(fd, (int)RFIFOL(fd,2)); break; + case 0x3094: mapif_parse_homunculus_rename(fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6), (char*)RFIFOP(fd,10)); break; + default: + return 0; } return 1; } diff --git a/src/char/int_homun.h b/src/char/int_homun.h index 1858ed4ba..1c0d76269 100644 --- a/src/char/int_homun.h +++ b/src/char/int_homun.h @@ -1,15 +1,18 @@ // Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder -#ifndef _INT_HOMUN_H_ -#define _INT_HOMUN_H_ +#ifndef _INT_HOMUN_SQL_H_ +#define _INT_HOMUN_SQL_H_ -int inter_homun_init(void); -void inter_homun_final(void); -int inter_homun_save(void); -int inter_homun_delete(int homun_id); -int inter_homun_parse_frommap(int fd); +struct s_homunculus; -extern char homun_txt[1024]; +int inter_homunculus_sql_init(void); +void inter_homunculus_sql_final(void); +int inter_homunculus_parse_frommap(int fd); -#endif /* _INT_HOMUN_H_ */ +bool mapif_homunculus_save(struct s_homunculus* hd); +bool mapif_homunculus_load(int homun_id, struct s_homunculus* hd); +bool mapif_homunculus_delete(int homun_id); +bool mapif_homunculus_rename(char *name); + +#endif /* _INT_HOMUN_SQL_H_ */ diff --git a/src/char/int_mail.c b/src/char/int_mail.c new file mode 100644 index 000000000..b19b732c7 --- /dev/null +++ b/src/char/int_mail.c @@ -0,0 +1,476 @@ +// Copyright (c) Athena Dev Teams - Licensed under GNU GPL +// For more information, see LICENCE in the main folder + +#include "../common/mmo.h" +#include "../common/malloc.h" +#include "../common/showmsg.h" +#include "../common/socket.h" +#include "../common/strlib.h" +#include "../common/sql.h" +#include "../common/timer.h" +#include "char.h" +#include "inter.h" + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +static int mail_fromsql(int char_id, struct mail_data* md) +{ + int i, j; + struct mail_message *msg; + struct item *item; + char *data; + StringBuf buf; + + memset(md, 0, sizeof(struct mail_data)); + md->amount = 0; + md->full = false; + + StringBuf_Init(&buf); + StringBuf_AppendStr(&buf, "SELECT `id`,`send_name`,`send_id`,`dest_name`,`dest_id`,`title`,`message`,`time`,`status`," + "`zeny`,`amount`,`nameid`,`refine`,`attribute`,`identify`"); + for (i = 0; i < MAX_SLOTS; i++) + StringBuf_Printf(&buf, ",`card%d`", i); + + // I keep the `status` < 3 just in case someone forget to apply the sqlfix + StringBuf_Printf(&buf, " FROM `%s` WHERE `dest_id`='%d' AND `status` < 3 ORDER BY `id` LIMIT %d", + mail_db, char_id, MAIL_MAX_INBOX + 1); + + if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) ) + Sql_ShowDebug(sql_handle); + + StringBuf_Destroy(&buf); + + for (i = 0; i < MAIL_MAX_INBOX && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + msg = &md->msg[i]; + Sql_GetData(sql_handle, 0, &data, NULL); msg->id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); safestrncpy(msg->send_name, data, NAME_LENGTH); + Sql_GetData(sql_handle, 2, &data, NULL); msg->send_id = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); safestrncpy(msg->dest_name, data, NAME_LENGTH); + Sql_GetData(sql_handle, 4, &data, NULL); msg->dest_id = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); safestrncpy(msg->title, data, MAIL_TITLE_LENGTH); + Sql_GetData(sql_handle, 6, &data, NULL); safestrncpy(msg->body, data, MAIL_BODY_LENGTH); + Sql_GetData(sql_handle, 7, &data, NULL); msg->timestamp = atoi(data); + Sql_GetData(sql_handle, 8, &data, NULL); msg->status = (mail_status)atoi(data); + Sql_GetData(sql_handle, 9, &data, NULL); msg->zeny = atoi(data); + item = &msg->item; + Sql_GetData(sql_handle,10, &data, NULL); item->amount = (short)atoi(data); + Sql_GetData(sql_handle,11, &data, NULL); item->nameid = atoi(data); + Sql_GetData(sql_handle,12, &data, NULL); item->refine = atoi(data); + Sql_GetData(sql_handle,13, &data, NULL); item->attribute = atoi(data); + Sql_GetData(sql_handle,14, &data, NULL); item->identify = atoi(data); + item->expire_time = 0; + + for (j = 0; j < MAX_SLOTS; j++) + { + Sql_GetData(sql_handle, 15 + j, &data, NULL); + item->card[j] = atoi(data); + } + } + + md->full = ( Sql_NumRows(sql_handle) > MAIL_MAX_INBOX ); + + md->amount = i; + Sql_FreeResult(sql_handle); + + md->unchecked = 0; + md->unread = 0; + for (i = 0; i < md->amount; i++) + { + msg = &md->msg[i]; + if( msg->status == MAIL_NEW ) + { + if ( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `status` = '%d' WHERE `id` = '%d'", mail_db, MAIL_UNREAD, msg->id) ) + Sql_ShowDebug(sql_handle); + + msg->status = MAIL_UNREAD; + md->unchecked++; + } + else if ( msg->status == MAIL_UNREAD ) + md->unread++; + } + + ShowInfo("mail load complete from DB - id: %d (total: %d)\n", char_id, md->amount); + return 1; +} + +/// Stores a single message in the database. +/// Returns the message's ID if successful (or 0 if it fails). +int mail_savemessage(struct mail_message* msg) +{ + StringBuf buf; + SqlStmt* stmt; + int j; + + // build message save query + StringBuf_Init(&buf); + StringBuf_Printf(&buf, "INSERT INTO `%s` (`send_name`, `send_id`, `dest_name`, `dest_id`, `title`, `message`, `time`, `status`, `zeny`, `amount`, `nameid`, `refine`, `attribute`, `identify`", mail_db); + for (j = 0; j < MAX_SLOTS; j++) + StringBuf_Printf(&buf, ", `card%d`", j); + StringBuf_Printf(&buf, ") VALUES (?, '%d', ?, '%d', ?, ?, '%lu', '%d', '%d', '%d', '%d', '%d', '%d', '%d'", + msg->send_id, msg->dest_id, (unsigned long)msg->timestamp, msg->status, msg->zeny, msg->item.amount, msg->item.nameid, msg->item.refine, msg->item.attribute, msg->item.identify); + for (j = 0; j < MAX_SLOTS; j++) + StringBuf_Printf(&buf, ", '%d'", msg->item.card[j]); + StringBuf_AppendStr(&buf, ")"); + + // prepare and execute query + stmt = SqlStmt_Malloc(sql_handle); + if( SQL_SUCCESS != SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, msg->send_name, strnlen(msg->send_name, NAME_LENGTH)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, msg->dest_name, strnlen(msg->dest_name, NAME_LENGTH)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 2, SQLDT_STRING, msg->title, strnlen(msg->title, MAIL_TITLE_LENGTH)) + || SQL_SUCCESS != SqlStmt_BindParam(stmt, 3, SQLDT_STRING, msg->body, strnlen(msg->body, MAIL_BODY_LENGTH)) + || SQL_SUCCESS != SqlStmt_Execute(stmt) ) + { + SqlStmt_ShowDebug(stmt); + msg->id = 0; + } else + msg->id = (int)SqlStmt_LastInsertId(stmt); + + SqlStmt_Free(stmt); + StringBuf_Destroy(&buf); + + return msg->id; +} + +/// Retrieves a single message from the database. +/// Returns true if the operation succeeds (or false if it fails). +static bool mail_loadmessage(int mail_id, struct mail_message* msg) +{ + int j; + StringBuf buf; + + StringBuf_Init(&buf); + StringBuf_AppendStr(&buf, "SELECT `id`,`send_name`,`send_id`,`dest_name`,`dest_id`,`title`,`message`,`time`,`status`," + "`zeny`,`amount`,`nameid`,`refine`,`attribute`,`identify`"); + for( j = 0; j < MAX_SLOTS; j++ ) + StringBuf_Printf(&buf, ",`card%d`", j); + StringBuf_Printf(&buf, " FROM `%s` WHERE `id` = '%d'", mail_db, mail_id); + + if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) + || SQL_SUCCESS != Sql_NextRow(sql_handle) ) + { + Sql_ShowDebug(sql_handle); + Sql_FreeResult(sql_handle); + StringBuf_Destroy(&buf); + return false; + } + else + { + char* data; + + Sql_GetData(sql_handle, 0, &data, NULL); msg->id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); safestrncpy(msg->send_name, data, NAME_LENGTH); + Sql_GetData(sql_handle, 2, &data, NULL); msg->send_id = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); safestrncpy(msg->dest_name, data, NAME_LENGTH); + Sql_GetData(sql_handle, 4, &data, NULL); msg->dest_id = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); safestrncpy(msg->title, data, MAIL_TITLE_LENGTH); + Sql_GetData(sql_handle, 6, &data, NULL); safestrncpy(msg->body, data, MAIL_BODY_LENGTH); + Sql_GetData(sql_handle, 7, &data, NULL); msg->timestamp = atoi(data); + Sql_GetData(sql_handle, 8, &data, NULL); msg->status = (mail_status)atoi(data); + Sql_GetData(sql_handle, 9, &data, NULL); msg->zeny = atoi(data); + Sql_GetData(sql_handle,10, &data, NULL); msg->item.amount = (short)atoi(data); + Sql_GetData(sql_handle,11, &data, NULL); msg->item.nameid = atoi(data); + Sql_GetData(sql_handle,12, &data, NULL); msg->item.refine = atoi(data); + Sql_GetData(sql_handle,13, &data, NULL); msg->item.attribute = atoi(data); + Sql_GetData(sql_handle,14, &data, NULL); msg->item.identify = atoi(data); + msg->item.expire_time = 0; + + for( j = 0; j < MAX_SLOTS; j++ ) + { + Sql_GetData(sql_handle,15 + j, &data, NULL); + msg->item.card[j] = atoi(data); + } + } + + StringBuf_Destroy(&buf); + Sql_FreeResult(sql_handle); + + return true; +} + +/*========================================== + * Client Inbox Request + *------------------------------------------*/ +static void mapif_Mail_sendinbox(int fd, int char_id, unsigned char flag) +{ + struct mail_data md; + mail_fromsql(char_id, &md); + + //FIXME: dumping the whole structure like this is unsafe [ultramage] + WFIFOHEAD(fd, sizeof(md) + 9); + WFIFOW(fd,0) = 0x3848; + WFIFOW(fd,2) = sizeof(md) + 9; + WFIFOL(fd,4) = char_id; + WFIFOB(fd,8) = flag; + memcpy(WFIFOP(fd,9),&md,sizeof(md)); + WFIFOSET(fd,WFIFOW(fd,2)); +} + +static void mapif_parse_Mail_requestinbox(int fd) +{ + mapif_Mail_sendinbox(fd, RFIFOL(fd,2), RFIFOB(fd,6)); +} + +/*========================================== + * Mark mail as 'Read' + *------------------------------------------*/ +static void mapif_parse_Mail_read(int fd) +{ + int mail_id = RFIFOL(fd,2); + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `status` = '%d' WHERE `id` = '%d'", mail_db, MAIL_READ, mail_id) ) + Sql_ShowDebug(sql_handle); +} + +/*========================================== + * Client Attachment Request + *------------------------------------------*/ +static bool mail_DeleteAttach(int mail_id) +{ + StringBuf buf; + int i; + + StringBuf_Init(&buf); + StringBuf_Printf(&buf, "UPDATE `%s` SET `zeny` = '0', `nameid` = '0', `amount` = '0', `refine` = '0', `attribute` = '0', `identify` = '0'", mail_db); + for (i = 0; i < MAX_SLOTS; i++) + StringBuf_Printf(&buf, ", `card%d` = '0'", i); + StringBuf_Printf(&buf, " WHERE `id` = '%d'", mail_id); + + if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) ) + { + Sql_ShowDebug(sql_handle); + StringBuf_Destroy(&buf); + + return false; + } + + StringBuf_Destroy(&buf); + return true; +} + +static void mapif_Mail_getattach(int fd, int char_id, int mail_id) +{ + struct mail_message msg; + + if( !mail_loadmessage(mail_id, &msg) ) + return; + + if( msg.dest_id != char_id ) + return; + + if( msg.status != MAIL_READ ) + return; + + if( (msg.item.nameid < 1 || msg.item.amount < 1) && msg.zeny < 1 ) + return; // No Attachment + + if( !mail_DeleteAttach(mail_id) ) + return; + + WFIFOHEAD(fd, sizeof(struct item) + 12); + WFIFOW(fd,0) = 0x384a; + WFIFOW(fd,2) = sizeof(struct item) + 12; + WFIFOL(fd,4) = char_id; + WFIFOL(fd,8) = (msg.zeny > 0)?msg.zeny:0; + memcpy(WFIFOP(fd,12), &msg.item, sizeof(struct item)); + WFIFOSET(fd,WFIFOW(fd,2)); +} + +static void mapif_parse_Mail_getattach(int fd) +{ + mapif_Mail_getattach(fd, RFIFOL(fd,2), RFIFOL(fd,6)); +} + +/*========================================== + * Delete Mail + *------------------------------------------*/ +static void mapif_Mail_delete(int fd, int char_id, int mail_id) +{ + bool failed = false; + if ( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `id` = '%d'", mail_db, mail_id) ) + { + Sql_ShowDebug(sql_handle); + failed = true; + } + + WFIFOHEAD(fd,11); + WFIFOW(fd,0) = 0x384b; + WFIFOL(fd,2) = char_id; + WFIFOL(fd,6) = mail_id; + WFIFOB(fd,10) = failed; + WFIFOSET(fd,11); +} + +static void mapif_parse_Mail_delete(int fd) +{ + mapif_Mail_delete(fd, RFIFOL(fd,2), RFIFOL(fd,6)); +} + +/*========================================== + * Report New Mail to Map Server + *------------------------------------------*/ +void mapif_Mail_new(struct mail_message *msg) +{ + unsigned char buf[74]; + + if( !msg || !msg->id ) + return; + + WBUFW(buf,0) = 0x3849; + WBUFL(buf,2) = msg->dest_id; + WBUFL(buf,6) = msg->id; + memcpy(WBUFP(buf,10), msg->send_name, NAME_LENGTH); + memcpy(WBUFP(buf,34), msg->title, MAIL_TITLE_LENGTH); + mapif_sendall(buf, 74); +} + +/*========================================== + * Return Mail + *------------------------------------------*/ +static void mapif_Mail_return(int fd, int char_id, int mail_id) +{ + struct mail_message msg; + int new_mail = 0; + + if( mail_loadmessage(mail_id, &msg) ) + { + if( msg.dest_id != char_id) + return; + else if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `id` = '%d'", mail_db, mail_id) ) + Sql_ShowDebug(sql_handle); + else + { + char temp_[MAIL_TITLE_LENGTH]; + + // swap sender and receiver + swap(msg.send_id, msg.dest_id); + safestrncpy(temp_, msg.send_name, NAME_LENGTH); + safestrncpy(msg.send_name, msg.dest_name, NAME_LENGTH); + safestrncpy(msg.dest_name, temp_, NAME_LENGTH); + + // set reply message title + snprintf(temp_, MAIL_TITLE_LENGTH, "RE:%s", msg.title); + safestrncpy(msg.title, temp_, MAIL_TITLE_LENGTH); + + msg.status = MAIL_NEW; + msg.timestamp = time(NULL); + + new_mail = mail_savemessage(&msg); + mapif_Mail_new(&msg); + } + } + + WFIFOHEAD(fd,11); + WFIFOW(fd,0) = 0x384c; + WFIFOL(fd,2) = char_id; + WFIFOL(fd,6) = mail_id; + WFIFOB(fd,10) = (new_mail == 0); + WFIFOSET(fd,11); +} + +static void mapif_parse_Mail_return(int fd) +{ + mapif_Mail_return(fd, RFIFOL(fd,2), RFIFOL(fd,6)); +} + +/*========================================== + * Send Mail + *------------------------------------------*/ +static void mapif_Mail_send(int fd, struct mail_message* msg) +{ + int len = sizeof(struct mail_message) + 4; + + WFIFOHEAD(fd,len); + WFIFOW(fd,0) = 0x384d; + WFIFOW(fd,2) = len; + memcpy(WFIFOP(fd,4), msg, sizeof(struct mail_message)); + WFIFOSET(fd,len); +} + +static void mapif_parse_Mail_send(int fd) +{ + struct mail_message msg; + char esc_name[NAME_LENGTH*2+1]; + int account_id = 0; + + if(RFIFOW(fd,2) != 8 + sizeof(struct mail_message)) + return; + + account_id = RFIFOL(fd,4); + memcpy(&msg, RFIFOP(fd,8), sizeof(struct mail_message)); + + // Try to find the Dest Char by Name + Sql_EscapeStringLen(sql_handle, esc_name, msg.dest_name, strnlen(msg.dest_name, NAME_LENGTH)); + if ( SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id`, `char_id` FROM `%s` WHERE `name` = '%s'", char_db, esc_name) ) + Sql_ShowDebug(sql_handle); + else + if ( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + char *data; + Sql_GetData(sql_handle, 0, &data, NULL); + if (atoi(data) != account_id) + { // Cannot send mail to char in the same account + Sql_GetData(sql_handle, 1, &data, NULL); + msg.dest_id = atoi(data); + } + } + Sql_FreeResult(sql_handle); + msg.status = MAIL_NEW; + + if( msg.dest_id > 0 ) + msg.id = mail_savemessage(&msg); + + mapif_Mail_send(fd, &msg); +} + +void mail_sendmail(int send_id, const char* send_name, int dest_id, const char* dest_name, const char* title, const char* body, int zeny, struct item *item) +{ + struct mail_message msg; + memset(&msg, 0, sizeof(struct mail_message)); + + msg.send_id = send_id; + safestrncpy(msg.send_name, send_name, NAME_LENGTH); + msg.dest_id = dest_id; + safestrncpy(msg.dest_name, dest_name, NAME_LENGTH); + safestrncpy(msg.title, title, MAIL_TITLE_LENGTH); + safestrncpy(msg.body, body, MAIL_BODY_LENGTH); + msg.zeny = zeny; + if( item != NULL ) + memcpy(&msg.item, item, sizeof(struct item)); + + msg.timestamp = time(NULL); + + mail_savemessage(&msg); + mapif_Mail_new(&msg); +} + +/*========================================== + * Packets From Map Server + *------------------------------------------*/ +int inter_mail_parse_frommap(int fd) +{ + switch(RFIFOW(fd,0)) + { + case 0x3048: mapif_parse_Mail_requestinbox(fd); break; + case 0x3049: mapif_parse_Mail_read(fd); break; + case 0x304a: mapif_parse_Mail_getattach(fd); break; + case 0x304b: mapif_parse_Mail_delete(fd); break; + case 0x304c: mapif_parse_Mail_return(fd); break; + case 0x304d: mapif_parse_Mail_send(fd); break; + default: + return 0; + } + return 1; +} + +int inter_mail_sql_init(void) +{ + return 1; +} + +void inter_mail_sql_final(void) +{ + return; +} diff --git a/src/char/int_mail.h b/src/char/int_mail.h new file mode 100644 index 000000000..77db51e5b --- /dev/null +++ b/src/char/int_mail.h @@ -0,0 +1,16 @@ +// Copyright (c) Athena Dev Teams - Licensed under GNU GPL +// For more information, see LICENCE in the main folder + +#ifndef _INT_MAIL_SQL_H_ +#define _INT_MAIL_SQL_H_ + +int inter_mail_parse_frommap(int fd); +void mail_sendmail(int send_id, const char* send_name, int dest_id, const char* dest_name, const char* title, const char* body, int zeny, struct item *item); + +int inter_mail_sql_init(void); +void inter_mail_sql_final(void); + +int mail_savemessage(struct mail_message* msg); +void mapif_Mail_new(struct mail_message *msg); + +#endif /* _INT_MAIL_SQL_H_ */ diff --git a/src/char/int_mercenary.c b/src/char/int_mercenary.c new file mode 100644 index 000000000..1b11878b8 --- /dev/null +++ b/src/char/int_mercenary.c @@ -0,0 +1,218 @@ +// Copyright (c) Athena Dev Teams - Licensed under GNU GPL +// For more information, see LICENCE in the main folder + +#include "../common/mmo.h" +#include "../common/malloc.h" +#include "../common/strlib.h" +#include "../common/showmsg.h" +#include "../common/socket.h" +#include "../common/utils.h" +#include "../common/sql.h" +#include "char.h" +#include "inter.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +bool mercenary_owner_fromsql(int char_id, struct mmo_charstatus *status) +{ + char* data; + + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `merc_id`, `arch_calls`, `arch_faith`, `spear_calls`, `spear_faith`, `sword_calls`, `sword_faith` FROM `mercenary_owner` WHERE `char_id` = '%d'", char_id) ) + { + Sql_ShowDebug(sql_handle); + return false; + } + + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + { + Sql_FreeResult(sql_handle); + return false; + } + + Sql_GetData(sql_handle, 0, &data, NULL); status->mer_id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); status->arch_calls = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); status->arch_faith = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); status->spear_calls = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); status->spear_faith = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); status->sword_calls = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); status->sword_faith = atoi(data); + Sql_FreeResult(sql_handle); + + return true; +} + +bool mercenary_owner_tosql(int char_id, struct mmo_charstatus *status) +{ + if( SQL_ERROR == Sql_Query(sql_handle, "REPLACE INTO `mercenary_owner` (`char_id`, `merc_id`, `arch_calls`, `arch_faith`, `spear_calls`, `spear_faith`, `sword_calls`, `sword_faith`) VALUES ('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')", + char_id, status->mer_id, status->arch_calls, status->arch_faith, status->spear_calls, status->spear_faith, status->sword_calls, status->sword_faith) ) + { + Sql_ShowDebug(sql_handle); + return false; + } + + return true; +} + +bool mercenary_owner_delete(int char_id) +{ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `mercenary_owner` WHERE `char_id` = '%d'", char_id) ) + Sql_ShowDebug(sql_handle); + + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `mercenary` WHERE `char_id` = '%d'", char_id) ) + Sql_ShowDebug(sql_handle); + + return true; +} + +bool mapif_mercenary_save(struct s_mercenary* merc) +{ + bool flag = true; + + if( merc->mercenary_id == 0 ) + { // Create new DB entry + if( SQL_ERROR == Sql_Query(sql_handle, + "INSERT INTO `mercenary` (`char_id`,`class`,`hp`,`sp`,`kill_counter`,`life_time`) VALUES ('%d','%d','%d','%d','%u','%u')", + merc->char_id, merc->class_, merc->hp, merc->sp, merc->kill_count, merc->life_time) ) + { + Sql_ShowDebug(sql_handle); + flag = false; + } + else + merc->mercenary_id = (int)Sql_LastInsertId(sql_handle); + } + else if( SQL_ERROR == Sql_Query(sql_handle, + "UPDATE `mercenary` SET `char_id` = '%d', `class` = '%d', `hp` = '%d', `sp` = '%d', `kill_counter` = '%u', `life_time` = '%u' WHERE `mer_id` = '%d'", + merc->char_id, merc->class_, merc->hp, merc->sp, merc->kill_count, merc->life_time, merc->mercenary_id) ) + { // Update DB entry + Sql_ShowDebug(sql_handle); + flag = false; + } + + return flag; +} + +bool mapif_mercenary_load(int merc_id, int char_id, struct s_mercenary *merc) +{ + char* data; + + memset(merc, 0, sizeof(struct s_mercenary)); + merc->mercenary_id = merc_id; + merc->char_id = char_id; + + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `class`, `hp`, `sp`, `kill_counter`, `life_time` FROM `mercenary` WHERE `mer_id` = '%d' AND `char_id` = '%d'", merc_id, char_id) ) + { + Sql_ShowDebug(sql_handle); + return false; + } + + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + { + Sql_FreeResult(sql_handle); + return false; + } + + Sql_GetData(sql_handle, 0, &data, NULL); merc->class_ = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); merc->hp = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); merc->sp = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); merc->kill_count = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); merc->life_time = atoi(data); + Sql_FreeResult(sql_handle); + if( save_log ) + ShowInfo("Mercenary loaded (%d - %d).\n", merc->mercenary_id, merc->char_id); + + return true; +} + +bool mapif_mercenary_delete(int merc_id) +{ + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `mercenary` WHERE `mer_id` = '%d'", merc_id) ) + { + Sql_ShowDebug(sql_handle); + return false; + } + + return true; +} + +static void mapif_mercenary_send(int fd, struct s_mercenary *merc, unsigned char flag) +{ + int size = sizeof(struct s_mercenary) + 5; + + WFIFOHEAD(fd,size); + WFIFOW(fd,0) = 0x3870; + WFIFOW(fd,2) = size; + WFIFOB(fd,4) = flag; + memcpy(WFIFOP(fd,5),merc,sizeof(struct s_mercenary)); + WFIFOSET(fd,size); +} + +static void mapif_parse_mercenary_create(int fd, struct s_mercenary* merc) +{ + bool result = mapif_mercenary_save(merc); + mapif_mercenary_send(fd, merc, result); +} + +static void mapif_parse_mercenary_load(int fd, int merc_id, int char_id) +{ + struct s_mercenary merc; + bool result = mapif_mercenary_load(merc_id, char_id, &merc); + mapif_mercenary_send(fd, &merc, result); +} + +static void mapif_mercenary_deleted(int fd, unsigned char flag) +{ + WFIFOHEAD(fd,3); + WFIFOW(fd,0) = 0x3871; + WFIFOB(fd,2) = flag; + WFIFOSET(fd,3); +} + +static void mapif_parse_mercenary_delete(int fd, int merc_id) +{ + bool result = mapif_mercenary_delete(merc_id); + mapif_mercenary_deleted(fd, result); +} + +static void mapif_mercenary_saved(int fd, unsigned char flag) +{ + WFIFOHEAD(fd,3); + WFIFOW(fd,0) = 0x3872; + WFIFOB(fd,2) = flag; + WFIFOSET(fd,3); +} + +static void mapif_parse_mercenary_save(int fd, struct s_mercenary* merc) +{ + bool result = mapif_mercenary_save(merc); + mapif_mercenary_saved(fd, result); +} + +int inter_mercenary_sql_init(void) +{ + return 0; +} +void inter_mercenary_sql_final(void) +{ + return; +} + +/*========================================== + * Inter Packets + *------------------------------------------*/ +int inter_mercenary_parse_frommap(int fd) +{ + unsigned short cmd = RFIFOW(fd,0); + + switch( cmd ) + { + case 0x3070: mapif_parse_mercenary_create(fd, (struct s_mercenary*)RFIFOP(fd,4)); break; + case 0x3071: mapif_parse_mercenary_load(fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6)); break; + case 0x3072: mapif_parse_mercenary_delete(fd, (int)RFIFOL(fd,2)); break; + case 0x3073: mapif_parse_mercenary_save(fd, (struct s_mercenary*)RFIFOP(fd,4)); break; + default: + return 0; + } + return 1; +} diff --git a/src/char/int_mercenary.h b/src/char/int_mercenary.h new file mode 100644 index 000000000..01e4a841f --- /dev/null +++ b/src/char/int_mercenary.h @@ -0,0 +1,20 @@ +// Copyright (c) Athena Dev Teams - Licensed under GNU GPL +// For more information, see LICENCE in the main folder + +#ifndef _INT_MERCENARY_SQL_H_ +#define _INT_MERCENARY_SQL_H_ + +struct s_mercenary; + +int inter_mercenary_sql_init(void); +void inter_mercenary_sql_final(void); +int inter_mercenary_parse_frommap(int fd); + +// Mercenary Owner Database +bool mercenary_owner_fromsql(int char_id, struct mmo_charstatus *status); +bool mercenary_owner_tosql(int char_id, struct mmo_charstatus *status); +bool mercenary_owner_delete(int char_id); + +bool mapif_mercenary_delete(int merc_id); + +#endif /* _INT_MERCENARY_SQL_H_ */ diff --git a/src/char/int_party.c b/src/char/int_party.c index 2ae9e5319..7d0dd0b75 100644 --- a/src/char/int_party.c +++ b/src/char/int_party.c @@ -3,11 +3,13 @@ #include "../common/cbasetypes.h" #include "../common/mmo.h" +#include "../common/db.h" #include "../common/malloc.h" +#include "../common/strlib.h" #include "../common/socket.h" -#include "../common/db.h" -#include "../common/lock.h" #include "../common/showmsg.h" +#include "../common/mapindex.h" +#include "../common/sql.h" #include "char.h" #include "inter.h" #include "int_party.h" @@ -16,8 +18,6 @@ #include <stdlib.h> #include <string.h> -char party_txt[1024] = "save/party.txt"; -#ifndef TXT_SQL_CONVERT struct party_data { struct party party; unsigned int min_lv, max_lv; @@ -25,11 +25,11 @@ struct party_data { unsigned char size; //Total size of party. }; -static DBMap* party_db; // int party_id -> struct party_data* -static int party_newid = 100; +static struct party_data *party_pt; +static DBMap* party_db_; // int party_id -> struct party_data* -int mapif_party_broken(int party_id, int flag); -int party_check_empty(struct party *p); +int mapif_party_broken(int party_id,int flag); +int party_check_empty(struct party_data *p); int mapif_parse_PartyLeave(int fd, int party_id, int account_id, int char_id); int party_check_exp_share(struct party_data *p); int mapif_party_optionchanged(int fd,struct party *p, int account_id, int flag); @@ -41,7 +41,10 @@ static int int_party_check_lv(struct party_data *p) { p->min_lv = UINT_MAX; p->max_lv = 0; for(i=0;i<MAX_PARTY;i++){ - if(!p->party.member[i].online) + /** + * - If not online OR if it's a family party and this is the child (doesn't affect exp range) + **/ + if(!p->party.member[i].online || p->party.member[i].char_id == p->family ) continue; lv=p->party.member[i].lv; @@ -56,7 +59,6 @@ static int int_party_check_lv(struct party_data *p) { } return 1; } - //Calculates the state of a party. static void int_party_calc_state(struct party_data *p) { @@ -68,14 +70,20 @@ static void int_party_calc_state(struct party_data *p) p->size = p->family = 0; - //Check party size. + //Check party size for(i=0;i<MAX_PARTY;i++){ if (!p->party.member[i].lv) continue; p->size++; if(p->party.member[i].online) p->party.count++; } - if(p->size == 3) { + if( p->size == 2 && ( char_child(p->party.member[0].char_id,p->party.member[1].char_id) || char_child(p->party.member[1].char_id,p->party.member[0].char_id) ) ) { + //Child should be able to share with either of their parents [RoM] + if(p->party.member[0].class_&0x2000) //first slot is the child? + p->family = p->party.member[0].char_id; + else + p->family = p->party.member[1].char_id; + } else if( p->size == 3 ) { //Check Family State. p->family = char_family( p->party.member[0].char_id, @@ -103,212 +111,244 @@ static void int_party_calc_state(struct party_data *p) return; } -// パ?ティデ?タの文字列への?換 -int inter_party_tostr(char *str, struct party *p) { - int i, len; +// Save party to mysql +int inter_party_tosql(struct party *p, int flag, int index) +{ + // 'party' ('party_id','name','exp','item','leader_id','leader_char') + char esc_name[NAME_LENGTH*2+1];// escaped party name + int party_id; - len = sprintf(str, "%d\t%s\t%d,%d\t", p->party_id, p->name, p->exp, p->item); - for(i = 0; i < MAX_PARTY; i++) { - struct party_member *m = &p->member[i]; - len += sprintf(str + len, "%d,%d,%d\t", m->account_id, m->char_id, m->leader); - } + if( p == NULL || p->party_id == 0 ) + return 0; + party_id = p->party_id; - return 0; -} -#endif //TXT_SQL_CONVERT -// パ?ティデ?タの文字列からの?換 -int inter_party_fromstr(char *str, struct party *p) { - int i, j; - int tmp_int[16]; - char tmp_str[256]; -#ifndef TXT_SQL_CONVERT - struct mmo_charstatus* status; +#ifdef NOISY + ShowInfo("Save party request ("CL_BOLD"%d"CL_RESET" - %s).\n", party_id, p->name); #endif - - memset(p, 0, sizeof(struct party)); - - if (sscanf(str, "%d\t%255[^\t]\t%d,%d\t", &tmp_int[0], tmp_str, &tmp_int[1], &tmp_int[2]) != 4) + Sql_EscapeStringLen(sql_handle, esc_name, p->name, strnlen(p->name, NAME_LENGTH)); + + if( flag & PS_BREAK ) + {// Break the party + // we'll skip name-checking and just reset everyone with the same party id [celest] + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `party_id`='0' WHERE `party_id`='%d'", char_db, party_id) ) + Sql_ShowDebug(sql_handle); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `party_id`='%d'", party_db, party_id) ) + Sql_ShowDebug(sql_handle); + //Remove from memory + idb_remove(party_db_, party_id); return 1; + } - p->party_id = tmp_int[0]; - memcpy(p->name, tmp_str, NAME_LENGTH); - p->exp = tmp_int[1]?1:0; - p->item = tmp_int[2]; - - for(j = 0; j < 3 && str != NULL; j++) - str = strchr(str + 1, '\t'); - - for(i = 0; i < MAX_PARTY; i++) { - struct party_member *m = &p->member[i]; - if (str == NULL) - return 1; + if( flag & PS_CREATE ) + {// Create party + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` " + "(`name`, `exp`, `item`, `leader_id`, `leader_char`) " + "VALUES ('%s', '%d', '%d', '%d', '%d')", + party_db, esc_name, p->exp, p->item, p->member[index].account_id, p->member[index].char_id) ) + { + Sql_ShowDebug(sql_handle); + return 0; + } + party_id = p->party_id = (int)Sql_LastInsertId(sql_handle); + } - if (sscanf(str + 1, "%d,%d,%d\t", &tmp_int[0], &tmp_int[1], &tmp_int[2]) != 3) - return 1; + if( flag & PS_BASIC ) + {// Update party info. + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `name`='%s', `exp`='%d', `item`='%d' WHERE `party_id`='%d'", + party_db, esc_name, p->exp, p->item, party_id) ) + Sql_ShowDebug(sql_handle); + } - m->account_id = tmp_int[0]; - m->char_id = tmp_int[1]; - m->leader = tmp_int[2]?1:0; + if( flag & PS_LEADER ) + {// Update leader + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `leader_id`='%d', `leader_char`='%d' WHERE `party_id`='%d'", + party_db, p->member[index].account_id, p->member[index].char_id, party_id) ) + Sql_ShowDebug(sql_handle); + } + + if( flag & PS_ADDMEMBER ) + {// Add one party member. + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `party_id`='%d' WHERE `account_id`='%d' AND `char_id`='%d'", + char_db, party_id, p->member[index].account_id, p->member[index].char_id) ) + Sql_ShowDebug(sql_handle); + } - str = strchr(str + 1, '\t'); -#ifndef TXT_SQL_CONVERT - if (!m->account_id) continue; - //Lookup player for rest of data. - status = search_character(m->account_id, m->char_id); - if (!status) continue; - - memcpy(m->name, status->name, NAME_LENGTH); - m->class_ = status->class_; - m->map = status->last_point.map; - m->lv = status->base_level; -#endif //TXT_SQL_CONVERT + if( flag & PS_DELMEMBER ) + {// Remove one party member. + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `party_id`='0' WHERE `party_id`='%d' AND `account_id`='%d' AND `char_id`='%d'", + char_db, party_id, p->member[index].account_id, p->member[index].char_id) ) + Sql_ShowDebug(sql_handle); } - return 0; + if( save_log ) + ShowInfo("Party Saved (%d - %s)\n", party_id, p->name); + return 1; } -#ifndef TXT_SQL_CONVERT -// パ?ティデ?タのロ?ド -int inter_party_init() { - char line[8192]; - struct party_data *p; - FILE *fp; - int c = 0; - int i, j; - party_db = idb_alloc(DB_OPT_RELEASE_DATA); +// Read party from mysql +struct party_data *inter_party_fromsql(int party_id) +{ + int leader_id = 0; + int leader_char = 0; + struct party_data* p; + struct party_member* m; + char* data; + size_t len; + int i; - if ((fp = fopen(party_txt, "r")) == NULL) - return 1; +#ifdef NOISY + ShowInfo("Load party request ("CL_BOLD"%d"CL_RESET")\n", party_id); +#endif + if( party_id <= 0 ) + return NULL; + + //Load from memory + p = (struct party_data*)idb_get(party_db_, party_id); + if( p != NULL ) + return p; - while(fgets(line, sizeof(line), fp)) - { - j = 0; - if (sscanf(line, "%d\t%%newid%%\n%n", &i, &j) == 1 && j > 0 && party_newid <= i) { - party_newid = i; - continue; - } + p = party_pt; + memset(p, 0, sizeof(struct party_data)); - p = (struct party_data*)aCalloc(sizeof(struct party_data), 1); - if (p == NULL){ - ShowFatalError("int_party: out of memory!\n"); - exit(EXIT_FAILURE); - } - memset(p, 0, sizeof(struct party_data)); - if (inter_party_fromstr(line, &p->party) == 0 && p->party.party_id > 0) { - int_party_calc_state(p); - if (p->party.party_id >= party_newid) - party_newid = p->party.party_id + 1; - idb_put(party_db, p->party.party_id, p); - party_check_empty(&p->party); - } else { - ShowError("int_party: broken data [%s] line %d\n", party_txt, c + 1); - aFree(p); - } - c++; + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `party_id`, `name`,`exp`,`item`, `leader_id`, `leader_char` FROM `%s` WHERE `party_id`='%d'", party_db, party_id) ) + { + Sql_ShowDebug(sql_handle); + return NULL; } - fclose(fp); - return 0; -} + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + return NULL; -void inter_party_final() -{ - party_db->destroy(party_db, NULL); - return; -} + p->party.party_id = party_id; + Sql_GetData(sql_handle, 1, &data, &len); memcpy(p->party.name, data, min(len, NAME_LENGTH)); + Sql_GetData(sql_handle, 2, &data, NULL); p->party.exp = (atoi(data) ? 1 : 0); + Sql_GetData(sql_handle, 3, &data, NULL); p->party.item = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); leader_id = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); leader_char = atoi(data); + Sql_FreeResult(sql_handle); -// パ?ティ?デ?タのセ?ブ用 -int inter_party_save_sub(DBKey key, void *data, va_list ap) { - char line[8192]; - FILE *fp; + // Load members + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id`,`char_id`,`name`,`base_level`,`last_map`,`online`,`class` FROM `%s` WHERE `party_id`='%d'", char_db, party_id) ) + { + Sql_ShowDebug(sql_handle); + return NULL; + } + for( i = 0; i < MAX_PARTY && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + m = &p->party.member[i]; + Sql_GetData(sql_handle, 0, &data, NULL); m->account_id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); m->char_id = atoi(data); + Sql_GetData(sql_handle, 2, &data, &len); memcpy(m->name, data, min(len, NAME_LENGTH)); + Sql_GetData(sql_handle, 3, &data, NULL); m->lv = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); m->map = mapindex_name2id(data); + Sql_GetData(sql_handle, 5, &data, NULL); m->online = (atoi(data) ? 1 : 0); + Sql_GetData(sql_handle, 6, &data, NULL); m->class_ = atoi(data); + m->leader = (m->account_id == leader_id && m->char_id == leader_char ? 1 : 0); + } + Sql_FreeResult(sql_handle); + + if( save_log ) + ShowInfo("Party loaded (%d - %s).\n", party_id, p->party.name); + //Add party to memory. + CREATE(p, struct party_data, 1); + memcpy(p, party_pt, sizeof(struct party_data)); + //init state + int_party_calc_state(p); + idb_put(party_db_, party_id, p); + return p; +} - inter_party_tostr(line, &((struct party_data*)data)->party); - fp = va_arg(ap, FILE *); - fprintf(fp, "%s\n", line); +int inter_party_sql_init(void) +{ + //memory alloc + party_db_ = idb_alloc(DB_OPT_RELEASE_DATA); + party_pt = (struct party_data*)aCalloc(sizeof(struct party_data), 1); + if (!party_pt) { + ShowFatalError("inter_party_sql_init: Out of Memory!\n"); + exit(EXIT_FAILURE); + } + /* Uncomment the following if you want to do a party_db cleanup (remove parties with no members) on startup.[Skotlex] + ShowStatus("cleaning party table...\n"); + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` USING `%s` LEFT JOIN `%s` ON `%s`.leader_id =`%s`.account_id AND `%s`.leader_char = `%s`.char_id WHERE `%s`.account_id IS NULL", + party_db, party_db, char_db, party_db, char_db, party_db, char_db, char_db) ) + Sql_ShowDebug(sql_handle); + */ return 0; } -// パ?ティ?デ?タのセ?ブ -int inter_party_save() { - FILE *fp; - int lock; - - if ((fp = lock_fopen(party_txt, &lock)) == NULL) { - ShowError("int_party: can't write [%s] !!! data is lost !!!\n", party_txt); - return 1; - } - party_db->foreach(party_db, inter_party_save_sub, fp); - lock_fclose(fp,party_txt, &lock); - return 0; +void inter_party_sql_final(void) +{ + party_db_->destroy(party_db_, NULL); + aFree(party_pt); + return; } // Search for the party according to its name -struct party_data* search_partyname(char *str) +struct party_data* search_partyname(char* str) { - struct DBIterator* iter; - struct party_data* p; - struct party_data* result = NULL; - - iter = party_db->iterator(party_db); - for( p = (struct party_data*)iter->first(iter,NULL); iter->exists(iter); p = (struct party_data*)iter->next(iter,NULL) ) + char esc_name[NAME_LENGTH*2+1]; + char* data; + struct party_data* p = NULL; + + Sql_EscapeStringLen(sql_handle, esc_name, str, safestrnlen(str, NAME_LENGTH)); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `party_id` FROM `%s` WHERE `name`='%s'", party_db, esc_name) ) + Sql_ShowDebug(sql_handle); + else if( SQL_SUCCESS == Sql_NextRow(sql_handle) ) { - if( strncmpi(p->party.name, str, NAME_LENGTH) == 0 ) - { - result = p; - break; - } + Sql_GetData(sql_handle, 0, &data, NULL); + p = inter_party_fromsql(atoi(data)); } - iter->destroy(iter); + Sql_FreeResult(sql_handle); - return result; + return p; } // Returns whether this party can keep having exp share or not. -int party_check_exp_share(struct party_data *p) { - return (p->party.count < 2|| p->max_lv - p->min_lv <= party_share_level); +int party_check_exp_share(struct party_data *p) +{ + return (p->party.count < 2 || p->max_lv - p->min_lv <= party_share_level); } -// パ?ティが空かどうかチェック -int party_check_empty(struct party *p) { +// Is there any member in the party? +int party_check_empty(struct party_data *p) +{ int i; - - for(i = 0; i < MAX_PARTY; i++) { - if (p->member[i].account_id > 0) { - return 0; - } - } - mapif_party_broken(p->party_id, 0); - idb_remove(party_db, p->party_id); - + if (p==NULL||p->party.party_id==0) return 1; + for(i=0;i<MAX_PARTY && !p->party.member[i].account_id;i++); + if (i < MAX_PARTY) return 0; + // If there is no member, then break the party + mapif_party_broken(p->party.party_id,0); + inter_party_tosql(&p->party, PS_BREAK, 0); return 1; } //------------------------------------------------------------------- // map serverへの通信 -// パ?ティ作成可否 -int mapif_party_created(int fd,int account_id, int char_id, struct party *p) +// パーティ作成可否 +int mapif_party_created(int fd,int account_id,int char_id,struct party *p) { WFIFOHEAD(fd, 39); - WFIFOW(fd,0) = 0x3820; - WFIFOL(fd,2) = account_id; - WFIFOL(fd,6) = char_id; - if (p != NULL) { - WFIFOB(fd,10) = 0; - WFIFOL(fd,11) = p->party_id; - memcpy(WFIFOP(fd,15), p->name, NAME_LENGTH); - ShowInfo("Created party (%d - %s)\n", p->party_id, p->name); - } else { - WFIFOB(fd,10) = 1; - WFIFOL(fd,11) = 0; - memset(WFIFOP(fd,15), 0, NAME_LENGTH); + WFIFOW(fd,0)=0x3820; + WFIFOL(fd,2)=account_id; + WFIFOL(fd,6)=char_id; + if(p!=NULL){ + WFIFOB(fd,10)=0; + WFIFOL(fd,11)=p->party_id; + memcpy(WFIFOP(fd,15),p->name,NAME_LENGTH); + ShowInfo("int_party: Party created (%d - %s)\n",p->party_id,p->name); + }else{ + WFIFOB(fd,10)=1; + WFIFOL(fd,11)=0; + memset(WFIFOP(fd,15),0,NAME_LENGTH); } WFIFOSET(fd,39); + return 0; } -// パ?ティ情報見つからず +// パーティ情報見つからず static void mapif_party_noinfo(int fd, int party_id, int char_id) { WFIFOHEAD(fd, 12); @@ -319,8 +359,7 @@ static void mapif_party_noinfo(int fd, int party_id, int char_id) WFIFOSET(fd,12); ShowWarning("int_party: info not found (party_id=%d char_id=%d)\n", party_id, char_id); } - -// パ?ティ情報まとめ送り +// パーティ情報まとめ送り static void mapif_party_info(int fd, struct party* p, int char_id) { unsigned char buf[8 + sizeof(struct party)]; @@ -328,13 +367,13 @@ static void mapif_party_info(int fd, struct party* p, int char_id) WBUFW(buf,2) = 8 + sizeof(struct party); WBUFL(buf,4) = char_id; memcpy(WBUFP(buf,8), p, sizeof(struct party)); - if (fd < 0) - mapif_sendall(buf, WBUFW(buf,2)); + + if(fd<0) + mapif_sendall(buf,WBUFW(buf,2)); else - mapif_send(fd, buf, WBUFW(buf,2)); + mapif_send(fd,buf,WBUFW(buf,2)); } - -// パ?ティメンバ追加可否 +// パーティメンバ追加可否 int mapif_party_memberadded(int fd, int party_id, int account_id, int char_id, int flag) { WFIFOHEAD(fd, 15); WFIFOW(fd,0) = 0x3822; @@ -347,24 +386,24 @@ int mapif_party_memberadded(int fd, int party_id, int account_id, int char_id, i return 0; } -// パ?ティ設定?更通知 -int mapif_party_optionchanged(int fd,struct party *p, int account_id, int flag) { - unsigned char buf[15]; - - WBUFW(buf,0) = 0x3823; - WBUFL(buf,2) = p->party_id; - WBUFL(buf,6) = account_id; - WBUFW(buf,10) = p->exp; - WBUFW(buf,12) = p->item; - WBUFB(buf,14) = flag; - if (flag == 0) - mapif_sendall(buf, 15); +// パーティ設定変更通知 +int mapif_party_optionchanged(int fd,struct party *p,int account_id,int flag) +{ + unsigned char buf[16]; + WBUFW(buf,0)=0x3823; + WBUFL(buf,2)=p->party_id; + WBUFL(buf,6)=account_id; + WBUFW(buf,10)=p->exp; + WBUFW(buf,12)=p->item; + WBUFB(buf,14)=flag; + if(flag==0) + mapif_sendall(buf,15); else - mapif_send(fd, buf, 15); + mapif_send(fd,buf,15); return 0; } -// パ?ティ?退通知 +// パーティ脱退通知 int mapif_party_withdraw(int party_id,int account_id, int char_id) { unsigned char buf[16]; @@ -376,8 +415,9 @@ int mapif_party_withdraw(int party_id,int account_id, int char_id) { return 0; } -// パ?ティマップ更新通知 -int mapif_party_membermoved(struct party *p, int idx) { +// パーティマップ更新通知 +int mapif_party_membermoved(struct party *p,int idx) +{ unsigned char buf[20]; WBUFW(buf,0) = 0x3825; @@ -391,29 +431,27 @@ int mapif_party_membermoved(struct party *p, int idx) { return 0; } -// パ?ティ解散通知 -int mapif_party_broken(int party_id, int flag) { - unsigned char buf[7]; - WBUFW(buf,0) = 0x3826; - WBUFL(buf,2) = party_id; - WBUFB(buf,6) = flag; - mapif_sendall(buf, 7); - ShowInfo("Party broken (%d)\n", party_id); - +// パーティ解散通知 +int mapif_party_broken(int party_id,int flag) +{ + unsigned char buf[16]; + WBUFW(buf,0)=0x3826; + WBUFL(buf,2)=party_id; + WBUFB(buf,6)=flag; + mapif_sendall(buf,7); + //printf("int_party: broken %d\n",party_id); return 0; } - -// パ?ティ??言 -int mapif_party_message(int party_id, int account_id, char *mes, int len, int sfd) { - unsigned char buf[2048]; - - WBUFW(buf,0) = 0x3827; - WBUFW(buf,2) = len + 12; - WBUFL(buf,4) = party_id; - WBUFL(buf,8) = account_id; - memcpy(WBUFP(buf,12), mes, len); - mapif_sendallwos(sfd, buf,len + 12); - +// パーティ内発言 +int mapif_party_message(int party_id,int account_id,char *mes,int len, int sfd) +{ + unsigned char buf[512]; + WBUFW(buf,0)=0x3827; + WBUFW(buf,2)=len+12; + WBUFL(buf,4)=party_id; + WBUFL(buf,8)=account_id; + memcpy(WBUFP(buf,12),mes,len); + mapif_sendallwos(sfd, buf,len+12); return 0; } @@ -421,83 +459,72 @@ int mapif_party_message(int party_id, int account_id, char *mes, int len, int sf // map serverからの通信 -// パ?ティ +// Create Party int mapif_parse_CreateParty(int fd, char *name, int item, int item2, struct party_member *leader) { struct party_data *p; int i; - - //FIXME: this should be removed once the savefiles can handle all symbols - for(i = 0; i < NAME_LENGTH && name[i]; i++) { - if (!(name[i] & 0xe0) || name[i] == 0x7f) { - ShowInfo("int_party: illegal party name [%s]\n", name); - mapif_party_created(fd, leader->account_id, leader->char_id, NULL); - return 0; - } - } - - if ((p = search_partyname(name)) != NULL) { - ShowInfo("int_party: same name party exists [%s]\n", name); - mapif_party_created(fd, leader->account_id, leader->char_id, NULL); + if( (p=search_partyname(name))!=NULL){ + mapif_party_created(fd,leader->account_id,leader->char_id,NULL); return 0; } - // Check Authorised letters/symbols in the name of the character if (char_name_option == 1) { // only letters/symbols in char_name_letters are authorised for (i = 0; i < NAME_LENGTH && name[i]; i++) if (strchr(char_name_letters, name[i]) == NULL) { - mapif_party_created(fd, leader->account_id, leader->char_id, NULL); + mapif_party_created(fd,leader->account_id,leader->char_id,NULL); return 0; } } else if (char_name_option == 2) { // letters/symbols in char_name_letters are forbidden for (i = 0; i < NAME_LENGTH && name[i]; i++) if (strchr(char_name_letters, name[i]) != NULL) { - mapif_party_created(fd, leader->account_id, leader->char_id, NULL); + mapif_party_created(fd,leader->account_id,leader->char_id,NULL); return 0; } } - p = (struct party_data *) aCalloc(sizeof(struct party_data), 1); - if (p == NULL) { - ShowFatalError("int_party: out of memory !\n"); - mapif_party_created(fd,leader->account_id,leader->char_id,NULL); - return 0; - } - p->party.party_id = party_newid++; - memcpy(p->party.name, name, NAME_LENGTH); - p->party.exp = 0; + p = (struct party_data*)aCalloc(1, sizeof(struct party_data)); + + memcpy(p->party.name,name,NAME_LENGTH); + p->party.exp=0; p->party.item=(item?1:0)|(item2?2:0); + memcpy(&p->party.member[0], leader, sizeof(struct party_member)); - p->party.member[0].leader = 1; - int_party_calc_state(p); - idb_put(party_db, p->party.party_id, p); + p->party.member[0].leader=1; + p->party.member[0].online=1; - mapif_party_info(fd, &p->party, 0); - mapif_party_created(fd, leader->account_id, leader->char_id, &p->party); + p->party.party_id=-1;//New party. + if (inter_party_tosql(&p->party,PS_CREATE|PS_ADDMEMBER,0)) { + //Add party to db + int_party_calc_state(p); + idb_put(party_db_, p->party.party_id, p); + mapif_party_info(fd, &p->party, 0); + mapif_party_created(fd,leader->account_id,leader->char_id,&p->party); + } else { //Failed to create party. + aFree(p); + mapif_party_created(fd,leader->account_id,leader->char_id,NULL); + } return 0; } - -// パ?ティ情報要求 +// パーティ情報要求 static void mapif_parse_PartyInfo(int fd, int party_id, int char_id) { struct party_data *p; + p = inter_party_fromsql(party_id); - p = (struct party_data*)idb_get(party_db, party_id); - if (p != NULL) + if (p) mapif_party_info(fd, &p->party, char_id); - else { + else mapif_party_noinfo(fd, party_id, char_id); - } } - -// パーティ追加要求 +// パーティ追加要求 int mapif_parse_PartyAddMember(int fd, int party_id, struct party_member *member) { struct party_data *p; int i; - p = (struct party_data*)idb_get(party_db, party_id); + p = inter_party_fromsql(party_id); if( p == NULL || p->size == MAX_PARTY ) { mapif_party_memberadded(fd, party_id, member->account_id, member->char_id, 1); return 0; @@ -514,7 +541,7 @@ int mapif_parse_PartyAddMember(int fd, int party_id, struct party_member *member p->party.member[i].leader = 0; if (p->party.member[i].online) p->party.count++; p->size++; - if (p->size == 3) //Check family state. + if (p->size == 2 || p->size == 3) // Check family state. And also accept either of their Parents. [RoM] int_party_calc_state(p); else //Check even share range. if (member->lv < p->min_lv || member->lv > p->max_lv || p->family) { @@ -524,67 +551,89 @@ int mapif_parse_PartyAddMember(int fd, int party_id, struct party_member *member mapif_party_info(-1, &p->party, 0); mapif_party_memberadded(fd, party_id, member->account_id, member->char_id, 0); + inter_party_tosql(&p->party, PS_ADDMEMBER, i); return 0; } -// パ?ティ?設定?更要求 -int mapif_parse_PartyChangeOption(int fd, int party_id, int account_id, int exp, int item) +// パーティー設定変更要求 +int mapif_parse_PartyChangeOption(int fd,int party_id,int account_id,int exp,int item) { struct party_data *p; int flag = 0; + p = inter_party_fromsql(party_id); - p = (struct party_data*)idb_get(party_db, party_id); - if (p == NULL) + if(!p) return 0; - p->party.exp = exp; - if (exp>0 && !party_check_exp_share(p)) { - flag |= 0x01; - p->party.exp = 0; + p->party.exp=exp; + if( exp && !party_check_exp_share(p) ){ + flag|=0x01; + p->party.exp=0; } - p->party.item = item&0x3; - mapif_party_optionchanged(fd, &p->party, account_id, flag); + p->party.item = item&0x3; //Filter out invalid values. + mapif_party_optionchanged(fd,&p->party,account_id,flag); + inter_party_tosql(&p->party, PS_BASIC, 0); return 0; } - -// パ?ティ?退要求 +// パーティ脱退要求 int mapif_parse_PartyLeave(int fd, int party_id, int account_id, int char_id) { struct party_data *p; - int i,lv; + int i,j=-1; - p = (struct party_data*)idb_get(party_db, party_id); - if (!p) return 0; + p = inter_party_fromsql(party_id); + if( p == NULL ) + {// Party does not exists? + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `party_id`='0' WHERE `party_id`='%d'", char_db, party_id) ) + Sql_ShowDebug(sql_handle); + return 0; + } - for(i = 0; i < MAX_PARTY; i++) { + for (i = 0; i < MAX_PARTY; i++) { if(p->party.member[i].account_id == account_id && - p->party.member[i].char_id == char_id) + p->party.member[i].char_id == char_id) { + break; + } + } + if (i >= MAX_PARTY) + return 0; //Member not found? + + mapif_party_withdraw(party_id, account_id, char_id); + + if (p->party.member[i].leader){ + p->party.member[i].account_id = 0; + for (j = 0; j < MAX_PARTY; j++) { + if (!p->party.member[j].account_id) + continue; + mapif_party_withdraw(party_id, p->party.member[j].account_id, p->party.member[j].char_id); + p->party.member[j].account_id = 0; + } + //Party gets deleted on the check_empty call below. + } else { + inter_party_tosql(&p->party,PS_DELMEMBER,i); + j = p->party.member[i].lv; + if(p->party.member[i].online) p->party.count--; + memset(&p->party.member[i], 0, sizeof(struct party_member)); + p->size--; + if (j == p->min_lv || j == p->max_lv || p->family) { - mapif_party_withdraw(party_id, account_id, char_id); - lv = p->party.member[i].lv; - if(p->party.member[i].online) p->party.count--; - memset(&p->party.member[i], 0, sizeof(struct party_member)); - p->size--; - if (lv == p->min_lv || lv == p->max_lv || p->family) - { - if(p->family) p->family = 0; //Family state broken. - int_party_check_lv(p); - } - if (party_check_empty(&p->party) == 0) - mapif_party_info(-1, &p->party, 0); - return 0; + if(p->family) p->family = 0; //Family state broken. + int_party_check_lv(p); } } + + if (party_check_empty(p) == 0) + mapif_party_info(-1, &p->party, 0); return 0; } - +// When member goes to other map or levels up. int mapif_parse_PartyChangeMap(int fd, int party_id, int account_id, int char_id, unsigned short map, int online, unsigned int lv) { struct party_data *p; int i; - p = (struct party_data*)idb_get(party_db, party_id); + p = inter_party_fromsql(party_id); if (p == NULL) return 0; @@ -615,6 +664,7 @@ int mapif_parse_PartyChangeMap(int fd, int party_id, int account_id, int char_id //Send online/offline update. mapif_party_membermoved(&p->party, i); } + if (p->party.member[i].lv != lv) { if(p->party.member[i].lv == p->min_lv || p->party.member[i].lv == p->max_lv) @@ -626,6 +676,7 @@ int mapif_parse_PartyChangeMap(int fd, int party_id, int account_id, int char_id //There is no need to send level update to map servers //since they do nothing with it. } + if (p->party.member[i].map != map) { p->party.member[i].map = map; mapif_party_membermoved(&p->party, i); @@ -633,19 +684,23 @@ int mapif_parse_PartyChangeMap(int fd, int party_id, int account_id, int char_id return 0; } -// パ?ティ解散要求 -int mapif_parse_BreakParty(int fd, int party_id) { +// パーティ解散要求 +int mapif_parse_BreakParty(int fd,int party_id) +{ + struct party_data *p; - idb_remove(party_db, party_id); - mapif_party_broken(fd, party_id); + p = inter_party_fromsql(party_id); + if(!p) + return 0; + inter_party_tosql(&p->party,PS_BREAK,0); + mapif_party_broken(fd,party_id); return 0; } - -// パ?ティメッセ?ジ送信 -int mapif_parse_PartyMessage(int fd, int party_id, int account_id, char *mes, int len) +// パーティメッセージ送信 +int mapif_parse_PartyMessage(int fd,int party_id,int account_id,char *mes,int len) { - return mapif_party_message(party_id, account_id, mes, len, fd); + return mapif_party_message(party_id,account_id,mes,len, fd); } int mapif_parse_PartyLeaderChange(int fd,int party_id,int account_id,int char_id) @@ -653,8 +708,9 @@ int mapif_parse_PartyLeaderChange(int fd,int party_id,int account_id,int char_id struct party_data *p; int i; - p = (struct party_data*)idb_get(party_db, party_id); - if (p == NULL) + p = inter_party_fromsql(party_id); + + if(!p) return 0; for (i = 0; i < MAX_PARTY; i++) @@ -663,17 +719,21 @@ int mapif_parse_PartyLeaderChange(int fd,int party_id,int account_id,int char_id p->party.member[i].leader = 0; if(p->party.member[i].account_id == account_id && p->party.member[i].char_id == char_id) + { p->party.member[i].leader = 1; + inter_party_tosql(&p->party,PS_LEADER, i); + } } return 1; } // map server からの通信 -// ?1パケットのみ解析すること -// ?パケット長デ?タはinter.cにセットしておくこと -// ?パケット長チェックや、RFIFOSKIPは呼び出し元で行われるので行ってはならない -// ?エラ?なら0(false)、そうでないなら1(true)をかえさなければならない -int inter_party_parse_frommap(int fd) { +// ・1パケットのみ解析すること +// ・パケット長データはinter.cにセットしておくこと +// ・パケット長チェックや、RFIFOSKIPは呼び出し元で行われるので行ってはならない +// ・エラーなら0(false)、そうでないなら1(true)をかえさなければならない +int inter_party_parse_frommap(int fd) +{ RFIFOHEAD(fd); switch(RFIFOW(fd,0)) { case 0x3020: mapif_parse_CreateParty(fd, (char*)RFIFOP(fd,4), RFIFOB(fd,28), RFIFOB(fd,29), (struct party_member*)RFIFOP(fd,30)); break; @@ -688,12 +748,105 @@ int inter_party_parse_frommap(int fd) { default: return 0; } + return 1; +} + +// サーバーから脱退要求(キャラ削除用) +int inter_party_leave(int party_id,int account_id, int char_id) +{ + return mapif_parse_PartyLeave(-1,party_id,account_id, char_id); +} + +int inter_party_CharOnline(int char_id, int party_id) +{ + struct party_data* p; + int i; + + if( party_id == -1 ) + {// Get party_id from the database + char* data; + + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT party_id FROM `%s` WHERE char_id='%d'", char_db, char_id) ) + { + Sql_ShowDebug(sql_handle); + return 0; + } + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + return 0; //Eh? No party? + + Sql_GetData(sql_handle, 0, &data, NULL); + party_id = atoi(data); + Sql_FreeResult(sql_handle); + } + if (party_id == 0) + return 0; //No party... + + p = inter_party_fromsql(party_id); + if(!p) { + ShowError("Character %d's party %d not found!\n", char_id, party_id); + return 0; + } + + //Set member online + for(i=0; i<MAX_PARTY; i++) { + if (p->party.member[i].char_id == char_id) { + if (!p->party.member[i].online) { + p->party.member[i].online = 1; + p->party.count++; + if (p->party.member[i].lv < p->min_lv || + p->party.member[i].lv > p->max_lv) + int_party_check_lv(p); + } + break; + } + } return 1; } -// サ?バ?から?退要求(キャラ削除用) -int inter_party_leave(int party_id, int account_id, int char_id) { - return mapif_parse_PartyLeave(-1, party_id, account_id, char_id); +int inter_party_CharOffline(int char_id, int party_id) { + struct party_data *p=NULL; + int i; + + if( party_id == -1 ) + {// Get guild_id from the database + char* data; + + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT party_id FROM `%s` WHERE char_id='%d'", char_db, char_id) ) + { + Sql_ShowDebug(sql_handle); + return 0; + } + + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + return 0; //Eh? No party? + + Sql_GetData(sql_handle, 0, &data, NULL); + party_id = atoi(data); + Sql_FreeResult(sql_handle); + } + if (party_id == 0) + return 0; //No party... + + //Character has a party, set character offline and check if they were the only member online + if ((p = inter_party_fromsql(party_id)) == NULL) + return 0; + + //Set member offline + for(i=0; i< MAX_PARTY; i++) { + if(p->party.member[i].char_id == char_id) + { + p->party.member[i].online = 0; + p->party.count--; + if(p->party.member[i].lv == p->min_lv || + p->party.member[i].lv == p->max_lv) + int_party_check_lv(p); + break; + } + } + + if(!p->party.count) + //Parties don't have any data that needs be saved at this point... so just remove it from memory. + idb_remove(party_db_, party_id); + return 1; } -#endif //TXT_SQL_CONVERT diff --git a/src/char/int_party.h b/src/char/int_party.h index ad724e475..d7965c33b 100644 --- a/src/char/int_party.h +++ b/src/char/int_party.h @@ -1,20 +1,32 @@ // Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder -#ifndef _INT_PARTY_H_ -#define _INT_PARTY_H_ +#ifndef _INT_PARTY_SQL_H_ +#define _INT_PARTY_SQL_H_ + +//Party Flags on what to save/delete. +//Create a new party entry (index holds leader's info) +#define PS_CREATE 0x01 +//Update basic party info. +#define PS_BASIC 0x02 +//Update party's leader +#define PS_LEADER 0x04 +//Specify new party member (index specifies which party member) +#define PS_ADDMEMBER 0x08 +//Specify member that left (index specifies which party member) +#define PS_DELMEMBER 0x10 +//Specify that this party must be deleted. +#define PS_BREAK 0x20 struct party; -int inter_party_init(void); -void inter_party_final(void); -int inter_party_save(void); int inter_party_parse_frommap(int fd); +int inter_party_sql_init(void); +void inter_party_sql_final(void); int inter_party_leave(int party_id,int account_id, int char_id); +int inter_party_CharOnline(int char_id, int party_id); +int inter_party_CharOffline(int char_id, int party_id); +//Required for the TXT->SQL converter +int inter_party_tosql(struct party *p, int flag, int index); -extern char party_txt[1024]; - -//For the TXT->SQL converter -int inter_party_fromstr(char *str, struct party *p); - -#endif /* _INT_PARTY_H_ */ +#endif /* _INT_PARTY_SQL_H_ */ diff --git a/src/char/int_pet.c b/src/char/int_pet.c index 41d61fbc3..114398290 100644 --- a/src/char/int_pet.c +++ b/src/char/int_pet.c @@ -4,307 +4,251 @@ #include "../common/mmo.h" #include "../common/malloc.h" #include "../common/socket.h" -#include "../common/db.h" -#include "../common/lock.h" +#include "../common/strlib.h" #include "../common/showmsg.h" +#include "../common/utils.h" +#include "../common/sql.h" #include "char.h" #include "inter.h" -#include "int_pet.h" #include <stdio.h> #include <stdlib.h> #include <string.h> -char pet_txt[1024]="save/pet.txt"; +struct s_pet *pet_pt; -#ifndef TXT_SQL_CONVERT -static DBMap* pet_db; // int pet_id -> struct s_pet* -static int pet_newid = 100; - -int inter_pet_tostr(char *str,struct s_pet *p) +//--------------------------------------------------------- +int inter_pet_tosql(int pet_id, struct s_pet* p) { - int len; - - if(p->hungry < 0) - p->hungry = 0; - else if(p->hungry > 100) - p->hungry = 100; - if(p->intimate < 0) - p->intimate = 0; - else if(p->intimate > 1000) - p->intimate = 1000; - - len=sprintf(str,"%d,%d,%s\t%d,%d,%d,%d,%d,%d,%d,%d,%d", - p->pet_id,p->class_,p->name,p->account_id,p->char_id,p->level,p->egg_id, - p->equip,p->intimate,p->hungry,p->rename_flag,p->incuvate); + //`pet` (`pet_id`, `class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate`) + char esc_name[NAME_LENGTH*2+1];// escaped pet name + + Sql_EscapeStringLen(sql_handle, esc_name, p->name, strnlen(p->name, NAME_LENGTH)); + p->hungry = cap_value(p->hungry, 0, 100); + p->intimate = cap_value(p->intimate, 0, 1000); + + if( pet_id == -1 ) + {// New pet. + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` " + "(`class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate`) " + "VALUES ('%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')", + pet_db, p->class_, esc_name, p->account_id, p->char_id, p->level, p->egg_id, + p->equip, p->intimate, p->hungry, p->rename_flag, p->incuvate) ) + { + Sql_ShowDebug(sql_handle); + return 0; + } + p->pet_id = (int)Sql_LastInsertId(sql_handle); + } + else + {// Update pet. + if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `class`='%d',`name`='%s',`account_id`='%d',`char_id`='%d',`level`='%d',`egg_id`='%d',`equip`='%d',`intimate`='%d',`hungry`='%d',`rename_flag`='%d',`incuvate`='%d' WHERE `pet_id`='%d'", + pet_db, p->class_, esc_name, p->account_id, p->char_id, p->level, p->egg_id, + p->equip, p->intimate, p->hungry, p->rename_flag, p->incuvate, p->pet_id) ) + { + Sql_ShowDebug(sql_handle); + return 0; + } + } - return 0; + if (save_log) + ShowInfo("Pet saved %d - %s.\n", pet_id, p->name); + return 1; } -#endif //TXT_SQL_CONVERT -int inter_pet_fromstr(char *str,struct s_pet *p) -{ - int s; - int tmp_int[16]; - char tmp_str[256]; - - memset(p,0,sizeof(struct s_pet)); - - s=sscanf(str,"%d,%d,%[^\t]\t%d,%d,%d,%d,%d,%d,%d,%d,%d",&tmp_int[0],&tmp_int[1],tmp_str,&tmp_int[2], - &tmp_int[3],&tmp_int[4],&tmp_int[5],&tmp_int[6],&tmp_int[7],&tmp_int[8],&tmp_int[9],&tmp_int[10]); - - if(s!=12) - return 1; - - p->pet_id = tmp_int[0]; - p->class_ = tmp_int[1]; - memcpy(p->name,tmp_str,NAME_LENGTH); - p->account_id = tmp_int[2]; - p->char_id = tmp_int[3]; - p->level = tmp_int[4]; - p->egg_id = tmp_int[5]; - p->equip = tmp_int[6]; - p->intimate = tmp_int[7]; - p->hungry = tmp_int[8]; - p->rename_flag = tmp_int[9]; - p->incuvate = tmp_int[10]; - - if(p->hungry < 0) - p->hungry = 0; - else if(p->hungry > 100) - p->hungry = 100; - if(p->intimate < 0) - p->intimate = 0; - else if(p->intimate > 1000) - p->intimate = 1000; - return 0; -} -#ifndef TXT_SQL_CONVERT -int inter_pet_init() +int inter_pet_fromsql(int pet_id, struct s_pet* p) { - char line[8192]; - struct s_pet *p; - FILE *fp; - int c=0; + char* data; + size_t len; - pet_db= idb_alloc(DB_OPT_RELEASE_DATA); +#ifdef NOISY + ShowInfo("Loading pet (%d)...\n",pet_id); +#endif + memset(p, 0, sizeof(struct s_pet)); - if( (fp=fopen(pet_txt,"r"))==NULL ) - return 1; - while(fgets(line, sizeof(line), fp)) + //`pet` (`pet_id`, `class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate`) + + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `pet_id`, `class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate` FROM `%s` WHERE `pet_id`='%d'", pet_db, pet_id) ) { - p = (struct s_pet*)aCalloc(sizeof(struct s_pet), 1); - if(p==NULL){ - ShowFatalError("int_pet: out of memory!\n"); - exit(EXIT_FAILURE); - } - memset(p,0,sizeof(struct s_pet)); - if(inter_pet_fromstr(line,p)==0 && p->pet_id>0){ - if( p->pet_id >= pet_newid) - pet_newid=p->pet_id+1; - idb_put(pet_db,p->pet_id,p); - }else{ - ShowError("int_pet: broken data [%s] line %d\n",pet_txt,c); - aFree(p); - } - c++; + Sql_ShowDebug(sql_handle); + return 0; } - fclose(fp); - return 0; -} - -void inter_pet_final() -{ - pet_db->destroy(pet_db, NULL); - return; -} -int inter_pet_save_sub(DBKey key,void *data,va_list ap) -{ - char line[8192]; - FILE *fp; - inter_pet_tostr(line,(struct s_pet *)data); - fp=va_arg(ap,FILE *); - fprintf(fp,"%s\n",line); + if( SQL_SUCCESS == Sql_NextRow(sql_handle) ) + { + p->pet_id = pet_id; + Sql_GetData(sql_handle, 1, &data, NULL); p->class_ = atoi(data); + Sql_GetData(sql_handle, 2, &data, &len); memcpy(p->name, data, min(len, NAME_LENGTH)); + Sql_GetData(sql_handle, 3, &data, NULL); p->account_id = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); p->char_id = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); p->level = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); p->egg_id = atoi(data); + Sql_GetData(sql_handle, 7, &data, NULL); p->equip = atoi(data); + Sql_GetData(sql_handle, 8, &data, NULL); p->intimate = atoi(data); + Sql_GetData(sql_handle, 9, &data, NULL); p->hungry = atoi(data); + Sql_GetData(sql_handle, 10, &data, NULL); p->rename_flag = atoi(data); + Sql_GetData(sql_handle, 11, &data, NULL); p->incuvate = atoi(data); + + Sql_FreeResult(sql_handle); + + p->hungry = cap_value(p->hungry, 0, 100); + p->intimate = cap_value(p->intimate, 0, 1000); + + if( save_log ) + ShowInfo("Pet loaded (%d - %s).\n", pet_id, p->name); + } return 0; } +//---------------------------------------------- -int inter_pet_save() -{ - FILE *fp; - int lock; - if( (fp=lock_fopen(pet_txt,&lock))==NULL ){ - ShowError("int_pet: can't write [%s] !!! data is lost !!!\n",pet_txt); - return 1; - } - pet_db->foreach(pet_db,inter_pet_save_sub,fp); - lock_fclose(fp,pet_txt,&lock); +int inter_pet_sql_init(void){ + //memory alloc + pet_pt = (struct s_pet*)aCalloc(sizeof(struct s_pet), 1); return 0; } +void inter_pet_sql_final(void){ + if (pet_pt) aFree(pet_pt); + return; +} +//---------------------------------- +int inter_pet_delete(int pet_id){ + ShowInfo("delete pet request: %d...\n",pet_id); -int inter_pet_delete(int pet_id) -{ - struct s_pet *p; - p = (struct s_pet*)idb_get(pet_db,pet_id); - if( p == NULL) - return 1; - else { - idb_remove(pet_db,pet_id); - ShowInfo("Deleted pet (pet_id: %d)\n",pet_id); - } + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `pet_id`='%d'", pet_db, pet_id) ) + Sql_ShowDebug(sql_handle); return 0; } - -int mapif_pet_created(int fd,int account_id,struct s_pet *p) +//------------------------------------------------------ +int mapif_pet_created(int fd, int account_id, struct s_pet *p) { - WFIFOHEAD(fd, 11); - WFIFOW(fd,0)=0x3880; - WFIFOL(fd,2)=account_id; + WFIFOHEAD(fd, 11); + WFIFOW(fd, 0) =0x3880; + WFIFOL(fd, 2) =account_id; if(p!=NULL){ - WFIFOB(fd,6)=0; - WFIFOL(fd,7)=p->pet_id; - ShowInfo("Created pet (%d - %s)\n",p->pet_id,p->name); + WFIFOB(fd, 6)=0; + WFIFOL(fd, 7) =p->pet_id; + ShowInfo("int_pet: created pet %d - %s\n", p->pet_id, p->name); }else{ - WFIFOB(fd,6)=1; - WFIFOL(fd,7)=0; + WFIFOB(fd, 6)=1; + WFIFOL(fd, 7)=0; } - WFIFOSET(fd,11); + WFIFOSET(fd, 11); return 0; } -int mapif_pet_info(int fd,int account_id,struct s_pet *p) -{ +int mapif_pet_info(int fd, int account_id, struct s_pet *p){ WFIFOHEAD(fd, sizeof(struct s_pet) + 9); - WFIFOW(fd,0)=0x3881; - WFIFOW(fd,2)=sizeof(struct s_pet) + 9; - WFIFOL(fd,4)=account_id; - WFIFOB(fd,8)=0; - memcpy(WFIFOP(fd,9),p,sizeof(struct s_pet)); - WFIFOSET(fd,WFIFOW(fd,2)); + WFIFOW(fd, 0) =0x3881; + WFIFOW(fd, 2) =sizeof(struct s_pet) + 9; + WFIFOL(fd, 4) =account_id; + WFIFOB(fd, 8)=0; + memcpy(WFIFOP(fd, 9), p, sizeof(struct s_pet)); + WFIFOSET(fd, WFIFOW(fd, 2)); return 0; } -int mapif_pet_noinfo(int fd,int account_id) -{ - WFIFOHEAD(fd, sizeof(struct s_pet) + 9); - WFIFOW(fd,0)=0x3881; - WFIFOW(fd,2)=sizeof(struct s_pet) + 9; - WFIFOL(fd,4)=account_id; - WFIFOB(fd,8)=1; - memset(WFIFOP(fd,9),0,sizeof(struct s_pet)); - WFIFOSET(fd,WFIFOW(fd,2)); +int mapif_pet_noinfo(int fd, int account_id){ + WFIFOHEAD(fd, sizeof(struct s_pet) + 9); + WFIFOW(fd, 0) =0x3881; + WFIFOW(fd, 2) =sizeof(struct s_pet) + 9; + WFIFOL(fd, 4) =account_id; + WFIFOB(fd, 8)=1; + memset(WFIFOP(fd, 9), 0, sizeof(struct s_pet)); + WFIFOSET(fd, WFIFOW(fd, 2)); return 0; } -int mapif_save_pet_ack(int fd,int account_id,int flag) -{ - WFIFOHEAD(fd, 7); - WFIFOW(fd,0)=0x3882; - WFIFOL(fd,2)=account_id; - WFIFOB(fd,6)=flag; - WFIFOSET(fd,7); +int mapif_save_pet_ack(int fd, int account_id, int flag){ + WFIFOHEAD(fd, 7); + WFIFOW(fd, 0) =0x3882; + WFIFOL(fd, 2) =account_id; + WFIFOB(fd, 6) =flag; + WFIFOSET(fd, 7); return 0; } -int mapif_delete_pet_ack(int fd,int flag) -{ - WFIFOHEAD(fd, 3); - WFIFOW(fd,0)=0x3883; - WFIFOB(fd,2)=flag; - WFIFOSET(fd,3); +int mapif_delete_pet_ack(int fd, int flag){ + WFIFOHEAD(fd, 3); + WFIFOW(fd, 0) =0x3883; + WFIFOB(fd, 2) =flag; + WFIFOSET(fd, 3); return 0; } -int mapif_create_pet(int fd,int account_id,int char_id,short pet_class,short pet_lv,short pet_egg_id, - short pet_equip,short intimate,short hungry,char rename_flag,char incuvate,char *pet_name) +int mapif_create_pet(int fd, int account_id, int char_id, short pet_class, short pet_lv, short pet_egg_id, + short pet_equip, short intimate, short hungry, char rename_flag, char incuvate, char *pet_name) { - struct s_pet *p; - p= (struct s_pet *) aCalloc(sizeof(struct s_pet), 1); - if(p==NULL){ - ShowFatalError("int_pet: out of memory !\n"); - mapif_pet_created(fd,account_id,NULL); - return 0; - } -// memset(p,0,sizeof(struct s_pet)); unnecessary after aCalloc [Skotlex] - p->pet_id = pet_newid++; - memcpy(p->name,pet_name,NAME_LENGTH); + memset(pet_pt, 0, sizeof(struct s_pet)); + strncpy(pet_pt->name, pet_name, NAME_LENGTH); if(incuvate == 1) - p->account_id = p->char_id = 0; + pet_pt->account_id = pet_pt->char_id = 0; else { - p->account_id = account_id; - p->char_id = char_id; + pet_pt->account_id = account_id; + pet_pt->char_id = char_id; } - p->class_ = pet_class; - p->level = pet_lv; - p->egg_id = pet_egg_id; - p->equip = pet_equip; - p->intimate = intimate; - p->hungry = hungry; - p->rename_flag = rename_flag; - p->incuvate = incuvate; - - if(p->hungry < 0) - p->hungry = 0; - else if(p->hungry > 100) - p->hungry = 100; - if(p->intimate < 0) - p->intimate = 0; - else if(p->intimate > 1000) - p->intimate = 1000; - - idb_put(pet_db,p->pet_id,p); - - mapif_pet_created(fd,account_id,p); + pet_pt->class_ = pet_class; + pet_pt->level = pet_lv; + pet_pt->egg_id = pet_egg_id; + pet_pt->equip = pet_equip; + pet_pt->intimate = intimate; + pet_pt->hungry = hungry; + pet_pt->rename_flag = rename_flag; + pet_pt->incuvate = incuvate; + + if(pet_pt->hungry < 0) + pet_pt->hungry = 0; + else if(pet_pt->hungry > 100) + pet_pt->hungry = 100; + if(pet_pt->intimate < 0) + pet_pt->intimate = 0; + else if(pet_pt->intimate > 1000) + pet_pt->intimate = 1000; + + pet_pt->pet_id = -1; //Signal NEW pet. + if (inter_pet_tosql(pet_pt->pet_id,pet_pt)) + mapif_pet_created(fd, account_id, pet_pt); + else //Failed... + mapif_pet_created(fd, account_id, NULL); return 0; } -int mapif_load_pet(int fd,int account_id,int char_id,int pet_id) -{ - struct s_pet *p; - p = (struct s_pet*)idb_get(pet_db,pet_id); - if(p!=NULL) { - if(p->incuvate == 1) { - p->account_id = p->char_id = 0; - mapif_pet_info(fd,account_id,p); +int mapif_load_pet(int fd, int account_id, int char_id, int pet_id){ + memset(pet_pt, 0, sizeof(struct s_pet)); + + inter_pet_fromsql(pet_id, pet_pt); + + if(pet_pt!=NULL) { + if(pet_pt->incuvate == 1) { + pet_pt->account_id = pet_pt->char_id = 0; + mapif_pet_info(fd, account_id, pet_pt); } - else if(account_id == p->account_id && char_id == p->char_id) - mapif_pet_info(fd,account_id,p); + else if(account_id == pet_pt->account_id && char_id == pet_pt->char_id) + mapif_pet_info(fd, account_id, pet_pt); else - mapif_pet_noinfo(fd,account_id); + mapif_pet_noinfo(fd, account_id); } else - mapif_pet_noinfo(fd,account_id); + mapif_pet_noinfo(fd, account_id); return 0; } -static void* create_pet(DBKey key, va_list args) { - struct s_pet *p; - p=(struct s_pet *)aCalloc(sizeof(struct s_pet),1); - p->pet_id = key.i; - return p; -} -int mapif_save_pet(int fd,int account_id,struct s_pet *data) -{ - struct s_pet *p; - int pet_id, len; +int mapif_save_pet(int fd, int account_id, struct s_pet *data) { + //here process pet save request. + int len; RFIFOHEAD(fd); - len=RFIFOW(fd,2); - + len=RFIFOW(fd, 2); if(sizeof(struct s_pet)!=len-8) { - ShowError("inter pet: data size error %d %d\n",sizeof(struct s_pet),len-8); + ShowError("inter pet: data size error %d %d\n", sizeof(struct s_pet), len-8); } + else{ - pet_id = data->pet_id; - if (pet_id == 0) - pet_id = data->pet_id = pet_newid++; - p = (struct s_pet*)idb_ensure(pet_db,pet_id,create_pet); if(data->hungry < 0) data->hungry = 0; else if(data->hungry > 100) @@ -313,61 +257,47 @@ int mapif_save_pet(int fd,int account_id,struct s_pet *data) data->intimate = 0; else if(data->intimate > 1000) data->intimate = 1000; - memcpy(p,data,sizeof(struct s_pet)); - if(p->incuvate == 1) - p->account_id = p->char_id = 0; - - mapif_save_pet_ack(fd,account_id,0); + inter_pet_tosql(data->pet_id,data); + mapif_save_pet_ack(fd, account_id, 0); } return 0; } -int mapif_delete_pet(int fd,int pet_id) -{ - mapif_delete_pet_ack(fd,inter_pet_delete(pet_id)); +int mapif_delete_pet(int fd, int pet_id){ + mapif_delete_pet_ack(fd, inter_pet_delete(pet_id)); return 0; } -int mapif_parse_CreatePet(int fd) -{ +int mapif_parse_CreatePet(int fd){ RFIFOHEAD(fd); - mapif_create_pet(fd,RFIFOL(fd,2),RFIFOL(fd,6),RFIFOW(fd,10),RFIFOW(fd,12),RFIFOW(fd,14),RFIFOW(fd,16),RFIFOW(fd,18), - RFIFOW(fd,20),RFIFOB(fd,22),RFIFOB(fd,23),(char*)RFIFOP(fd,24)); + mapif_create_pet(fd, RFIFOL(fd, 2), RFIFOL(fd, 6), RFIFOW(fd, 10), RFIFOW(fd, 12), RFIFOW(fd, 14), RFIFOW(fd, 16), RFIFOW(fd, 18), + RFIFOW(fd, 20), RFIFOB(fd, 22), RFIFOB(fd, 23), (char*)RFIFOP(fd, 24)); return 0; } -int mapif_parse_LoadPet(int fd) -{ +int mapif_parse_LoadPet(int fd){ RFIFOHEAD(fd); - mapif_load_pet(fd,RFIFOL(fd,2),RFIFOL(fd,6),RFIFOL(fd,10)); + mapif_load_pet(fd, RFIFOL(fd, 2), RFIFOL(fd, 6), RFIFOL(fd, 10)); return 0; } -int mapif_parse_SavePet(int fd) -{ +int mapif_parse_SavePet(int fd){ RFIFOHEAD(fd); - mapif_save_pet(fd,RFIFOL(fd,4),(struct s_pet *)RFIFOP(fd,8)); + mapif_save_pet(fd, RFIFOL(fd, 4), (struct s_pet *) RFIFOP(fd, 8)); return 0; } -int mapif_parse_DeletePet(int fd) -{ +int mapif_parse_DeletePet(int fd){ RFIFOHEAD(fd); - mapif_delete_pet(fd,RFIFOL(fd,2)); + mapif_delete_pet(fd, RFIFOL(fd, 2)); return 0; } -// map server からの通信 -// ・1パケットのみ解析すること -// ・パケット長データはinter.cにセットしておくこと -// ・パケット長チェックや、RFIFOSKIPは呼び出し元で行われるので行ってはならない -// ・エラーなら0(false)、そうでないなら1(true)をかえさなければならない -int inter_pet_parse_frommap(int fd) -{ +int inter_pet_parse_frommap(int fd){ RFIFOHEAD(fd); - switch(RFIFOW(fd,0)){ + switch(RFIFOW(fd, 0)){ case 0x3080: mapif_parse_CreatePet(fd); break; case 0x3081: mapif_parse_LoadPet(fd); break; case 0x3082: mapif_parse_SavePet(fd); break; @@ -377,4 +307,3 @@ int inter_pet_parse_frommap(int fd) } return 1; } -#endif //TXT_SQL_CONVERT diff --git a/src/char/int_pet.h b/src/char/int_pet.h index 9234af109..733468c77 100644 --- a/src/char/int_pet.h +++ b/src/char/int_pet.h @@ -1,21 +1,21 @@ // Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder -#ifndef _INT_PET_H_ -#define _INT_PET_H_ +#ifndef _INT_PET_SQL_H_ +#define _INT_PET_SQL_H_ struct s_pet; int inter_pet_init(void); -void inter_pet_final(void); +void inter_pet_sql_final(void); int inter_pet_save(void); int inter_pet_delete(int pet_id); int inter_pet_parse_frommap(int fd); - -extern char pet_txt[1024]; +int inter_pet_sql_init(void); +//extern char pet_txt[256]; //Exported for use in the TXT-SQL converter. -int inter_pet_fromstr(char *str,struct s_pet *p); +int inter_pet_tosql(int pet_id, struct s_pet *p); -#endif /* _INT_PET_H_ */ +#endif /* _INT_PET_SQL_H_ */ diff --git a/src/char/int_quest.c b/src/char/int_quest.c new file mode 100644 index 000000000..224205412 --- /dev/null +++ b/src/char/int_quest.c @@ -0,0 +1,184 @@ +// Copyright (c) Athena Dev Teams - Licensed under GNU GPL +// For more information, see LICENCE in the main folder + +#include "../common/mmo.h" +#include "../common/db.h" +#include "../common/malloc.h" +#include "../common/showmsg.h" +#include "../common/socket.h" +#include "../common/strlib.h" +#include "../common/sql.h" +#include "../common/timer.h" + +#include "char.h" +#include "inter.h" +#include "int_quest.h" + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +//Load entire questlog for a character +int mapif_quests_fromsql(int char_id, struct quest questlog[]) +{ + int i; + struct quest tmp_quest; + SqlStmt * stmt; + + stmt = SqlStmt_Malloc(sql_handle); + if( stmt == NULL ) + { + SqlStmt_ShowDebug(stmt); + return 0; + } + + memset(&tmp_quest, 0, sizeof(struct quest)); + + if( SQL_ERROR == SqlStmt_Prepare(stmt, "SELECT `quest_id`, `state`, `time`, `count1`, `count2`, `count3` FROM `%s` WHERE `char_id`=? LIMIT %d", quest_db, MAX_QUEST_DB) + || SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0) + || SQL_ERROR == SqlStmt_Execute(stmt) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_INT, &tmp_quest.quest_id, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_INT, &tmp_quest.state, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_UINT, &tmp_quest.time, 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 3, SQLDT_INT, &tmp_quest.count[0], 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 4, SQLDT_INT, &tmp_quest.count[1], 0, NULL, NULL) + || SQL_ERROR == SqlStmt_BindColumn(stmt, 5, SQLDT_INT, &tmp_quest.count[2], 0, NULL, NULL) ) + SqlStmt_ShowDebug(stmt); + + for( i = 0; i < MAX_QUEST_DB && SQL_SUCCESS == SqlStmt_NextRow(stmt); ++i ) + memcpy(&questlog[i], &tmp_quest, sizeof(tmp_quest)); + + SqlStmt_Free(stmt); + return i; +} + +//Delete a quest +bool mapif_quest_delete(int char_id, int quest_id) +{ + if ( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `quest_id` = '%d' AND `char_id` = '%d'", quest_db, quest_id, char_id) ) + { + Sql_ShowDebug(sql_handle); + return false; + } + + return true; +} + +//Add a quest to a questlog +bool mapif_quest_add(int char_id, struct quest qd) +{ + if ( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s`(`quest_id`, `char_id`, `state`, `time`, `count1`, `count2`, `count3`) VALUES ('%d', '%d', '%d','%d', '%d', '%d', '%d')", quest_db, qd.quest_id, char_id, qd.state, qd.time, qd.count[0], qd.count[1], qd.count[2]) ) + { + Sql_ShowDebug(sql_handle); + return false; + } + + return true; +} + +//Update a questlog +bool mapif_quest_update(int char_id, struct quest qd) +{ + if ( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `state`='%d', `count1`='%d', `count2`='%d', `count3`='%d' WHERE `quest_id` = '%d' AND `char_id` = '%d'", quest_db, qd.state, qd.count[0], qd.count[1], qd.count[2], qd.quest_id, char_id) ) + { + Sql_ShowDebug(sql_handle); + return false; + } + + return true; +} + +//Save quests +int mapif_parse_quest_save(int fd) +{ + int i, j, k, num2, num1 = (RFIFOW(fd,2)-8)/sizeof(struct quest); + int char_id = RFIFOL(fd,4); + struct quest qd1[MAX_QUEST_DB],qd2[MAX_QUEST_DB]; + bool success = true; + + memset(qd1, 0, sizeof(qd1)); + memset(qd2, 0, sizeof(qd2)); + if( num1 ) memcpy(&qd1, RFIFOP(fd,8), RFIFOW(fd,2)-8); + num2 = mapif_quests_fromsql(char_id, qd2); + + for( i = 0; i < num1; i++ ) + { + ARR_FIND( 0, num2, j, qd1[i].quest_id == qd2[j].quest_id ); + if( j < num2 ) // Update existed quests + { // Only states and counts are changable. + ARR_FIND( 0, MAX_QUEST_OBJECTIVES, k, qd1[i].count[k] != qd2[j].count[k] ); + if( k != MAX_QUEST_OBJECTIVES || qd1[i].state != qd2[j].state ) + success &= mapif_quest_update(char_id, qd1[i]); + + if( j < (--num2) ) + { + memmove(&qd2[j],&qd2[j+1],sizeof(struct quest)*(num2-j)); + memset(&qd2[num2], 0, sizeof(struct quest)); + } + + } + else // Add new quests + success &= mapif_quest_add(char_id, qd1[i]); + } + + for( i = 0; i < num2; i++ ) // Quests not in qd1 but in qd2 are to be erased. + success &= mapif_quest_delete(char_id, qd2[i].quest_id); + + WFIFOHEAD(fd,7); + WFIFOW(fd,0) = 0x3861; + WFIFOL(fd,2) = char_id; + WFIFOB(fd,6) = success?1:0; + WFIFOSET(fd,7); + + return 0; +} + +//Send questlog to map server +int mapif_parse_quest_load(int fd) +{ + int char_id = RFIFOL(fd,2); + struct quest tmp_questlog[MAX_QUEST_DB]; + int num_quests, i, num_complete = 0; + int complete[MAX_QUEST_DB]; + + memset(tmp_questlog, 0, sizeof(tmp_questlog)); + memset(complete, 0, sizeof(complete)); + + num_quests = mapif_quests_fromsql(char_id, tmp_questlog); + + WFIFOHEAD(fd,num_quests*sizeof(struct quest)+8); + WFIFOW(fd,0) = 0x3860; + WFIFOW(fd,2) = num_quests*sizeof(struct quest)+8; + WFIFOL(fd,4) = char_id; + + //Active and inactive quests + for( i = 0; i < num_quests; i++ ) + { + if( tmp_questlog[i].state == Q_COMPLETE ) + { + complete[num_complete++] = i; + continue; + } + memcpy(WFIFOP(fd,(i-num_complete)*sizeof(struct quest)+8), &tmp_questlog[i], sizeof(struct quest)); + } + + // Completed quests + for( i = num_quests - num_complete; i < num_quests; i++ ) + memcpy(WFIFOP(fd,i*sizeof(struct quest)+8), &tmp_questlog[complete[i-num_quests+num_complete]], sizeof(struct quest)); + + WFIFOSET(fd,num_quests*sizeof(struct quest)+8); + + return 0; +} + +int inter_quest_parse_frommap(int fd) +{ + switch(RFIFOW(fd,0)) + { + case 0x3060: mapif_parse_quest_load(fd); break; + case 0x3061: mapif_parse_quest_save(fd); break; + default: + return 0; + } + return 1; +} diff --git a/src/char/int_quest.h b/src/char/int_quest.h new file mode 100644 index 000000000..f2a0b626e --- /dev/null +++ b/src/char/int_quest.h @@ -0,0 +1,13 @@ +// Copyright (c) Athena Dev Teams - Licensed under GNU GPL +// For more information, see LICENCE in the main folder + +#ifndef _QUEST_H_ +#define _QUEST_H_ + +/*questlog system*/ +struct quest; + +int inter_quest_parse_frommap(int fd); + +#endif + diff --git a/src/char/int_status.c b/src/char/int_status.c deleted file mode 100644 index 769d35f65..000000000 --- a/src/char/int_status.c +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) Athena Dev Teams - Licensed under GNU GPL -// For more information, see LICENCE in the main folder - -#include "../common/mmo.h" -#include "../common/db.h" -#include "../common/lock.h" -#include "../common/malloc.h" -#include "../common/showmsg.h" -#include "int_status.h" - -#include <stdio.h> - -// Contains all the status change data in-memory. [Skotlex] -static DBMap* scdata_db = NULL; // int char_id -> struct scdata* -char scdata_txt[1024]="save/scdata.txt"; //By [Skotlex] - -#ifdef ENABLE_SC_SAVING -static void* create_scdata(DBKey key, va_list args) -{ - struct scdata *data; - data = (struct scdata*)aCalloc(1, sizeof(struct scdata)); - data->account_id = va_arg(args, int); - data->char_id = key.i; - return data; -} - -/*========================================== - * Loads status change data of the player given. [Skotlex] - *------------------------------------------*/ -struct scdata* status_search_scdata(int aid, int cid) -{ - return (struct scdata*)scdata_db->ensure(scdata_db, db_i2key(cid), create_scdata, aid); -} - -/*========================================== - * Deletes status change data of the player given. [Skotlex] - * Should be invoked after the data of said player was successfully loaded. - *------------------------------------------*/ -void status_delete_scdata(int aid, int cid) -{ - struct scdata* scdata = (struct scdata*)idb_remove(scdata_db, cid); - if (scdata) - { - if (scdata->data) - aFree(scdata->data); - aFree(scdata); - } -} - - -static void inter_status_tostr(char* line, struct scdata *sc_data) -{ - int i, len; - - len = sprintf(line, "%d,%d,%d\t", sc_data->account_id, sc_data->char_id, sc_data->count); - for(i = 0; i < sc_data->count; i++) { - len += sprintf(line + len, "%d,%ld,%ld,%ld,%ld,%ld\t", sc_data->data[i].type, sc_data->data[i].tick, - sc_data->data[i].val1, sc_data->data[i].val2, sc_data->data[i].val3, sc_data->data[i].val4); - } - return; -} - -static int inter_scdata_fromstr(char *line, struct scdata *sc_data) -{ - int i, len, next; - - if (sscanf(line,"%d,%d,%d\t%n",&sc_data->account_id, &sc_data->char_id, &sc_data->count, &next) < 3) - return 0; - - if (sc_data->count < 1) - return 0; - - sc_data->data = (struct status_change_data*)aCalloc(sc_data->count, sizeof (struct status_change_data)); - - for (i = 0; i < sc_data->count; i++) - { - if (sscanf(line + next, "%hu,%ld,%ld,%ld,%ld,%ld\t%n", &sc_data->data[i].type, &sc_data->data[i].tick, - &sc_data->data[i].val1, &sc_data->data[i].val2, &sc_data->data[i].val3, &sc_data->data[i].val4, &len) < 6) - { - aFree(sc_data->data); - return 0; - } - next+=len; - } - return 1; -} -/*========================================== - * Loads all scdata from the given filename. - *------------------------------------------*/ -void status_load_scdata(const char* filename) -{ - FILE *fp; - int sd_count=0, sc_count=0; - char line[8192]; - struct scdata *sc; - - if ((fp = fopen(filename, "r")) == NULL) { - ShowError("status_load_scdata: Cannot open file %s!\n", filename); - return; - } - - while(fgets(line, sizeof(line), fp)) - { - sc = (struct scdata*)aCalloc(1, sizeof(struct scdata)); - if (inter_scdata_fromstr(line, sc)) { - sd_count++; - sc_count+= sc->count; - sc = (struct scdata*)idb_put(scdata_db, sc->char_id, sc); - if (sc) { - ShowError("Duplicate entry in %s for character %d\n", filename, sc->char_id); - if (sc->data) aFree(sc->data); - aFree(sc); - } - } else { - ShowError("status_load_scdata: Broken line data: %s\n", line); - aFree(sc); - } - } - fclose(fp); - ShowStatus("Loaded %d saved status changes for %d characters.\n", sc_count, sd_count); -} - -static int inter_status_save_sub(DBKey key, void *data, va_list ap) { - char line[8192]; - struct scdata * sc_data; - FILE *fp; - - sc_data = (struct scdata *)data; - if (sc_data->count < 1) - return 0; - - fp = va_arg(ap, FILE *); - inter_status_tostr(line, sc_data); - fprintf(fp, "%s\n", line); - return 0; -} - -/*========================================== - * Saves all scdata to the given filename. - *------------------------------------------*/ -void inter_status_save() -{ - FILE *fp; - int lock; - - if ((fp = lock_fopen(scdata_txt, &lock)) == NULL) { - ShowError("int_status: can't write [%s] !!! data is lost !!!\n", scdata_txt); - return; - } - scdata_db->foreach(scdata_db, inter_status_save_sub, fp); - lock_fclose(fp,scdata_txt, &lock); -} - -/*========================================== - * Initializes db. - *------------------------------------------*/ -void status_init() -{ - scdata_db = idb_alloc(DB_OPT_BASE); - status_load_scdata(scdata_txt); -} - -/*========================================== - * Frees up memory. - *------------------------------------------*/ -static int scdata_db_final(DBKey k,void *d,va_list ap) -{ - struct scdata *data = (struct scdata*)d; - if (data->data) - aFree(data->data); - aFree(data); - return 0; -} - -/*========================================== - * Final cleanup. - *------------------------------------------*/ -void status_final(void) -{ - scdata_db->destroy(scdata_db, scdata_db_final); -} - -#endif //ENABLE_SC_SAVING diff --git a/src/char/int_status.h b/src/char/int_status.h deleted file mode 100644 index 3202cd88e..000000000 --- a/src/char/int_status.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Athena Dev Teams - Licensed under GNU GPL -// For more information, see LICENCE in the main folder - -#ifndef _INT_STATUS_H_ -#define _INT_STATUS_H_ - -struct status_change_data; - -struct scdata { - int account_id, char_id; - int count; - struct status_change_data* data; -}; - -extern char scdata_txt[1024]; - -struct scdata* status_search_scdata(int aid, int cid); -void status_delete_scdata(int aid, int cid); -void inter_status_save(void); -void status_init(void); -void status_final(void); - -#endif /* _INT_STATUS_H_ */ diff --git a/src/char/int_storage.c b/src/char/int_storage.c index 2a041b286..248a4521f 100644 --- a/src/char/int_storage.c +++ b/src/char/int_storage.c @@ -3,414 +3,184 @@ #include "../common/mmo.h" #include "../common/malloc.h" -#include "../common/socket.h" -#include "../common/db.h" -#include "../common/lock.h" #include "../common/showmsg.h" -#include "../common/utils.h" +#include "../common/socket.h" +#include "../common/strlib.h" // StringBuf +#include "../common/sql.h" #include "char.h" #include "inter.h" -#include "int_storage.h" -#include "int_pet.h" -#include "int_guild.h" #include <stdio.h> #include <string.h> #include <stdlib.h> -// ファイル名のデフォルト -// inter_config_read()で再設定される -char storage_txt[1024]="save/storage.txt"; -char guild_storage_txt[1024]="save/g_storage.txt"; -static DBMap* storage_db = NULL; // int account_id -> struct storage_data* -static DBMap* guild_storage_db = NULL; // int guild_id -> struct guild_storage* +#define STORAGE_MEMINC 16 -// 倉庫データを文字列に変換 -bool storage_tostr(char* str, int account_id, struct storage_data* p) +/// Save storage data to sql +int storage_tosql(int account_id, struct storage_data* p) { - int i,j; - char *str_p = str; - str_p += sprintf(str_p, "%d,%d\t", account_id, p->storage_amount); - - for( i = 0; i < MAX_STORAGE; i++ ) - if( p->items[i].nameid > 0 && p->items[i].amount > 0 ) - { - str_p += sprintf(str_p, "%d,%d,%d,%d,%d,%d,%d", - p->items[i].id,p->items[i].nameid,p->items[i].amount,p->items[i].equip, - p->items[i].identify,p->items[i].refine,p->items[i].attribute); - for(j=0; j<MAX_SLOTS; j++) - str_p += sprintf(str_p,",%d",p->items[i].card[j]); - str_p += sprintf(str_p," "); - } - - *(str_p++)='\t'; - - *str_p='\0'; - - return true; -} - -// 文字列を倉庫データに変換 -bool storage_fromstr(char* str, int* account_id, struct storage_data* p) -{ - int tmp_int[256]; - char tmp_str[256]; - int next,len,i,j; - - if( sscanf(str, "%d,%d%n", &tmp_int[0], &tmp_int[1], &next) != 2 ) - return false; - - *account_id = tmp_int[0]; - p->storage_amount = tmp_int[1]; //FIXME: limit to MAX_STORAGE? - - next++; - for( i = 0; str[next] && str[next]!='\t' && i < MAX_STORAGE; i++ ) - { - if(sscanf(str + next, "%d,%d,%d,%d,%d,%d,%d%[0-9,-]%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], &tmp_int[3], - &tmp_int[4], &tmp_int[5], &tmp_int[6], tmp_str, &len) != 8) - return false; - - p->items[i].id = tmp_int[0]; - p->items[i].nameid = tmp_int[1]; - p->items[i].amount = tmp_int[2]; - p->items[i].equip = tmp_int[3]; - p->items[i].identify = tmp_int[4]; - p->items[i].refine = tmp_int[5]; - p->items[i].attribute = tmp_int[6]; - - for(j = 0; j < MAX_SLOTS && tmp_str[0] && sscanf(tmp_str, ",%d%[0-9,-]",&tmp_int[0], tmp_str) > 0; j++) - p->items[i].card[j] = tmp_int[0]; - - next += len; - if (str[next] == ' ') - next++; - } - - if( i >= MAX_STORAGE && str[next] && str[next] != '\t' ) - ShowWarning("storage_fromstr: Found a storage line with more items than MAX_STORAGE (%d), remaining items have been discarded!\n", MAX_STORAGE); - - return true; + memitemdata_to_sql(p->items, MAX_STORAGE, account_id, TABLE_STORAGE); + return 0; } -int guild_storage_tostr(char *str,struct guild_storage *p) +/// Load storage data to mem +int storage_fromsql(int account_id, struct storage_data* p) { - int i,j,f=0; - char *str_p = str; - str_p+=sprintf(str,"%d,%d\t",p->guild_id,p->storage_amount); + StringBuf buf; + struct item* item; + char* data; + int i; + int j; - for(i=0;i<MAX_GUILD_STORAGE;i++) - if( (p->items[i].nameid) && (p->items[i].amount) ){ - str_p += sprintf(str_p,"%d,%d,%d,%d,%d,%d,%d", - p->items[i].id,p->items[i].nameid,p->items[i].amount,p->items[i].equip, - p->items[i].identify,p->items[i].refine,p->items[i].attribute); - for(j=0; j<MAX_SLOTS; j++) - str_p += sprintf(str_p,",%d",p->items[i].card[j]); - str_p += sprintf(str_p," "); - f++; - } - - *(str_p++)='\t'; + memset(p, 0, sizeof(struct storage_data)); //clean up memory + p->storage_amount = 0; - *str_p='\0'; - if(!f) - str[0]=0; - return 0; -} + // storage {`account_id`/`id`/`nameid`/`amount`/`equip`/`identify`/`refine`/`attribute`/`card0`/`card1`/`card2`/`card3`} + StringBuf_Init(&buf); + StringBuf_AppendStr(&buf, "SELECT `id`,`nameid`,`amount`,`equip`,`identify`,`refine`,`attribute`,`expire_time`"); + for( j = 0; j < MAX_SLOTS; ++j ) + StringBuf_Printf(&buf, ",`card%d`", j); + StringBuf_Printf(&buf, " FROM `%s` WHERE `account_id`='%d' ORDER BY `nameid`", storage_db, account_id); -int guild_storage_fromstr(char *str,struct guild_storage *p) -{ - int tmp_int[256]; - char tmp_str[256]; - int set,next,len,i,j; + if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) ) + Sql_ShowDebug(sql_handle); - set=sscanf(str,"%d,%d%n",&tmp_int[0],&tmp_int[1],&next); - p->storage_amount=tmp_int[1]; + StringBuf_Destroy(&buf); - if(set!=2) - return 1; - if(str[next]=='\n' || str[next]=='\r') - return 0; - next++; - for(i=0;str[next] && str[next]!='\t' && i < MAX_GUILD_STORAGE;i++){ - if(sscanf(str + next, "%d,%d,%d,%d,%d,%d,%d%[0-9,-]%n", - &tmp_int[0], &tmp_int[1], &tmp_int[2], &tmp_int[3], - &tmp_int[4], &tmp_int[5], &tmp_int[6], tmp_str, &len) == 8) + for( i = 0; i < MAX_STORAGE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + item = &p->items[i]; + Sql_GetData(sql_handle, 0, &data, NULL); item->id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); item->nameid = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); item->amount = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); item->equip = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); item->identify = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); item->refine = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); item->attribute = atoi(data); + Sql_GetData(sql_handle, 7, &data, NULL); item->expire_time = (unsigned int)atoi(data); + for( j = 0; j < MAX_SLOTS; ++j ) { - p->items[i].id = tmp_int[0]; - p->items[i].nameid = tmp_int[1]; - p->items[i].amount = tmp_int[2]; - p->items[i].equip = tmp_int[3]; - p->items[i].identify = tmp_int[4]; - p->items[i].refine = tmp_int[5]; - p->items[i].attribute = tmp_int[6]; - for(j = 0; j < MAX_SLOTS && tmp_str[0] && sscanf(tmp_str, ",%d%[0-9,-]",&tmp_int[0], tmp_str) > 0; j++) - p->items[i].card[j] = tmp_int[0]; - next += len; - if (str[next] == ' ') - next++; + Sql_GetData(sql_handle, 8+j, &data, NULL); item->card[j] = atoi(data); } - else return 1; } - if (i >= MAX_GUILD_STORAGE && str[next] && str[next]!='\t') - ShowWarning("guild_storage_fromstr: Found a storage line with more items than MAX_GUILD_STORAGE (%d), remaining items have been discarded!\n", MAX_GUILD_STORAGE); - return 0; -} - -#ifndef TXT_SQL_CONVERT + p->storage_amount = i; + Sql_FreeResult(sql_handle); -static void* create_storage(DBKey key, va_list args) -{ - return (struct storage_data *) aCalloc(sizeof(struct storage_data), 1); + ShowInfo("storage load complete from DB - id: %d (total: %d)\n", account_id, p->storage_amount); + return 1; } -static void* create_guildstorage(DBKey key, va_list args) +/// Save guild_storage data to sql +int guild_storage_tosql(int guild_id, struct guild_storage* p) { - struct guild_storage* gs = NULL; - gs = (struct guild_storage *) aCalloc(sizeof(struct guild_storage), 1); - gs->guild_id=key.i; - return gs; + memitemdata_to_sql(p->items, MAX_GUILD_STORAGE, guild_id, TABLE_GUILD_STORAGE); + ShowInfo ("guild storage save to DB - guild: %d\n", guild_id); + return 0; } -/// Loads storage data into the provided data structure. -/// If data doesn't exist, the destination is zeroed and false is returned. -bool storage_load(int account_id, struct storage_data* storage) +/// Load guild_storage data to mem +int guild_storage_fromsql(int guild_id, struct guild_storage* p) { - struct storage_data* s = (struct storage_data*)idb_get(storage_db, account_id); + StringBuf buf; + struct item* item; + char* data; + int i; + int j; - if( s != NULL ) - memcpy(storage, s, sizeof(*storage)); - else - memset(storage, 0x00, sizeof(*storage)); - - return( s != NULL ); -} - -/// Writes provided data into storage cache. -/// If data contains 0 items, any existing entry in cache is destroyed. -/// If data contains 1+ items and no cache entry exists, a new one is created. -bool storage_save(int account_id, struct storage_data* storage) -{ - if( storage->storage_amount > 0 ) - { - struct storage_data* s = (struct storage_data*)idb_ensure(storage_db, account_id, create_storage); - memcpy(s, storage, sizeof(*storage)); - } - else - { - idb_remove(storage_db, account_id); - } + memset(p, 0, sizeof(struct guild_storage)); //clean up memory + p->storage_amount = 0; + p->guild_id = guild_id; - return true; -} + // storage {`guild_id`/`id`/`nameid`/`amount`/`equip`/`identify`/`refine`/`attribute`/`card0`/`card1`/`card2`/`card3`} + StringBuf_Init(&buf); + StringBuf_AppendStr(&buf, "SELECT `id`,`nameid`,`amount`,`equip`,`identify`,`refine`,`attribute`"); + for( j = 0; j < MAX_SLOTS; ++j ) + StringBuf_Printf(&buf, ",`card%d`", j); + StringBuf_Printf(&buf, " FROM `%s` WHERE `guild_id`='%d' ORDER BY `nameid`", guild_storage_db, guild_id); -//--------------------------------------------------------- -// 倉庫データを読み込む -int inter_storage_init() -{ - char line[65536]; - int c = 0; - FILE *fp; + if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) ) + Sql_ShowDebug(sql_handle); - storage_db = idb_alloc(DB_OPT_RELEASE_DATA); + StringBuf_Destroy(&buf); - fp=fopen(storage_txt,"r"); - if(fp==NULL){ - ShowError("can't read : %s\n",storage_txt); - return 1; - } - while( fgets(line, sizeof(line), fp) ) + for( i = 0; i < MAX_GUILD_STORAGE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) { - int account_id; - struct storage_data *s; - - s = (struct storage_data*)aCalloc(sizeof(struct storage_data), 1); - if( s == NULL ) - { - ShowFatalError("int_storage: out of memory!\n"); - exit(EXIT_FAILURE); - } - - if( storage_fromstr(line,&account_id,s) ) + item = &p->items[i]; + Sql_GetData(sql_handle, 0, &data, NULL); item->id = atoi(data); + Sql_GetData(sql_handle, 1, &data, NULL); item->nameid = atoi(data); + Sql_GetData(sql_handle, 2, &data, NULL); item->amount = atoi(data); + Sql_GetData(sql_handle, 3, &data, NULL); item->equip = atoi(data); + Sql_GetData(sql_handle, 4, &data, NULL); item->identify = atoi(data); + Sql_GetData(sql_handle, 5, &data, NULL); item->refine = atoi(data); + Sql_GetData(sql_handle, 6, &data, NULL); item->attribute = atoi(data); + item->expire_time = 0; + for( j = 0; j < MAX_SLOTS; ++j ) { - idb_put(storage_db,account_id,s); - } - else{ - ShowError("int_storage: broken data in [%s] line %d\n",storage_txt,c); - aFree(s); + Sql_GetData(sql_handle, 7+j, &data, NULL); item->card[j] = atoi(data); } - c++; } - fclose(fp); - - c = 0; - guild_storage_db = idb_alloc(DB_OPT_RELEASE_DATA); - - fp=fopen(guild_storage_txt,"r"); - if(fp==NULL){ - ShowError("can't read : %s\n",guild_storage_txt); - return 1; - } - while(fgets(line, sizeof(line), fp)) - { - int tmp_int; - struct guild_storage *gs; - - sscanf(line,"%d",&tmp_int); - gs = (struct guild_storage*)aCalloc(sizeof(struct guild_storage), 1); - if(gs==NULL){ - ShowFatalError("int_storage: out of memory!\n"); - exit(EXIT_FAILURE); - } -// memset(gs,0,sizeof(struct guild_storage)); aCalloc... - gs->guild_id=tmp_int; - if(gs->guild_id > 0 && guild_storage_fromstr(line,gs) == 0) { - idb_put(guild_storage_db,gs->guild_id,gs); - } - else{ - ShowError("int_storage: broken data [%s] line %d\n",guild_storage_txt,c); - aFree(gs); - } - c++; - } - fclose(fp); + p->storage_amount = i; + Sql_FreeResult(sql_handle); + ShowInfo("guild storage load complete from DB - id: %d (total: %d)\n", guild_id, p->storage_amount); return 0; } -void inter_storage_final() { - if(storage_db) - { - storage_db->destroy(storage_db, NULL); - } - if(guild_storage_db) - { - guild_storage_db->destroy(guild_storage_db, NULL); - } - return; -} - //--------------------------------------------------------- -// 倉庫データを書き込む -int inter_storage_save() +// storage data initialize +int inter_storage_sql_init(void) { - struct DBIterator* iter; - DBKey key; - struct storage_data* data; - FILE *fp; - int lock; - if( (fp=lock_fopen(storage_txt,&lock))==NULL ){ - ShowError("int_storage: can't write [%s] !!! data is lost !!!\n",storage_txt); - return 1; - } - - iter = storage_db->iterator(storage_db); - for( data = (struct storage_data*)iter->first(iter,&key); iter->exists(iter); data = (struct storage_data*)iter->next(iter,&key) ) - { - int account_id = key.i; - char line[65536]; - storage_tostr(line,account_id,data); - fprintf(fp,"%s\n",line); - } - iter->destroy(iter); - - lock_fclose(fp,storage_txt,&lock); - return 0; + return 1; } - -//--------------------------------------------------------- -// 倉庫データを書き込む -int inter_guild_storage_save() +// storage data finalize +void inter_storage_sql_final(void) { - struct DBIterator* iter; - struct guild_storage* data; - FILE *fp; - int lock; - if( (fp=lock_fopen(guild_storage_txt,&lock))==NULL ){ - ShowError("int_storage: can't write [%s] !!! data is lost !!!\n",guild_storage_txt); - return 1; - } - - iter = guild_storage_db->iterator(guild_storage_db); - for( data = (struct guild_storage*)iter->first(iter,NULL); iter->exists(iter); data = (struct guild_storage*)iter->next(iter,NULL) ) - { - char line[65536]; - if(inter_guild_search(data->guild_id) != NULL) - { - guild_storage_tostr(line,data); - if(*line) - fprintf(fp,"%s\n",line); - } - } - iter->destroy(iter); - - lock_fclose(fp,guild_storage_txt,&lock); - return 0; + return; } -// 倉庫データ削除 +// q?f[^? int inter_storage_delete(int account_id) { - struct storage_data *s = (struct storage_data*)idb_get(storage_db,account_id); - if(s) { - int i; - for(i=0;i<s->storage_amount;i++){ - if(s->items[i].card[0] == (short)0xff00) - inter_pet_delete( MakeDWord(s->items[i].card[1],s->items[i].card[2]) ); - } - idb_remove(storage_db,account_id); - } + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id`='%d'", storage_db, account_id) ) + Sql_ShowDebug(sql_handle); return 0; } - -// ギルド倉庫データ削除 int inter_guild_storage_delete(int guild_id) { - struct guild_storage *gs = (struct guild_storage*)idb_get(guild_storage_db,guild_id); - if(gs) { - int i; - for(i=0;i<gs->storage_amount;i++){ - if(gs->items[i].card[0] == (short)0xff00) - inter_pet_delete( MakeDWord(gs->items[i].card[1],gs->items[i].card[2]) ); - } - idb_remove(guild_storage_db,guild_id); - } + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id`='%d'", guild_storage_db, guild_id) ) + Sql_ShowDebug(sql_handle); return 0; } -struct guild_storage *guild2storage(int guild_id) -{ - struct guild_storage* gs = NULL; - if(inter_guild_search(guild_id) != NULL) - gs = (struct guild_storage*)idb_ensure(guild_storage_db, guild_id, create_guildstorage); - return gs; -} - //--------------------------------------------------------- -// map serverへの通信 +// packet from map server int mapif_load_guild_storage(int fd,int account_id,int guild_id) { - struct guild_storage *gs=guild2storage(guild_id); - WFIFOHEAD(fd, sizeof(struct guild_storage)+12); - WFIFOW(fd,0)=0x3818; - if(gs) { - WFIFOW(fd,2)=sizeof(struct guild_storage)+12; - WFIFOL(fd,4)=account_id; - WFIFOL(fd,8)=guild_id; - memcpy(WFIFOP(fd,12),gs,sizeof(struct guild_storage)); - } - else { - WFIFOW(fd,2)=12; - WFIFOL(fd,4)=account_id; - WFIFOL(fd,8)=0; + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `guild_id` FROM `%s` WHERE `guild_id`='%d'", guild_db, guild_id) ) + Sql_ShowDebug(sql_handle); + else if( Sql_NumRows(sql_handle) > 0 ) + {// guild exists + WFIFOHEAD(fd, sizeof(struct guild_storage)+12); + WFIFOW(fd,0) = 0x3818; + WFIFOW(fd,2) = sizeof(struct guild_storage)+12; + WFIFOL(fd,4) = account_id; + WFIFOL(fd,8) = guild_id; + guild_storage_fromsql(guild_id, (struct guild_storage*)WFIFOP(fd,12)); + WFIFOSET(fd, WFIFOW(fd,2)); + return 0; } - WFIFOSET(fd,WFIFOW(fd,2)); - + // guild does not exist + Sql_FreeResult(sql_handle); + WFIFOHEAD(fd, 12); + WFIFOW(fd,0) = 0x3818; + WFIFOW(fd,2) = 12; + WFIFOL(fd,4) = account_id; + WFIFOL(fd,8) = 0; + WFIFOSET(fd, 12); return 0; } - int mapif_save_guild_storage_ack(int fd,int account_id,int guild_id,int fail) { WFIFOHEAD(fd,11); @@ -423,7 +193,7 @@ int mapif_save_guild_storage_ack(int fd,int account_id,int guild_id,int fail) } //--------------------------------------------------------- -// map serverからの通信 +// packet from map server int mapif_parse_LoadGuildStorage(int fd) { @@ -434,31 +204,35 @@ int mapif_parse_LoadGuildStorage(int fd) int mapif_parse_SaveGuildStorage(int fd) { - struct guild_storage *gs; - int guild_id, len; + int guild_id; + int len; + RFIFOHEAD(fd); - guild_id=RFIFOL(fd,8); - len=RFIFOW(fd,2); - if(sizeof(struct guild_storage)!=len-12){ - ShowError("inter storage: data size error %d %d\n",sizeof(struct guild_storage),len-12); + guild_id = RFIFOL(fd,8); + len = RFIFOW(fd,2); + + if( sizeof(struct guild_storage) != len - 12 ) + { + ShowError("inter storage: data size error %d != %d\n", sizeof(struct guild_storage), len - 12); } - else { - gs=guild2storage(guild_id); - if(gs) { - memcpy(gs,RFIFOP(fd,12),sizeof(struct guild_storage)); - mapif_save_guild_storage_ack(fd,RFIFOL(fd,4),guild_id,0); + else + { + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `guild_id` FROM `%s` WHERE `guild_id`='%d'", guild_db, guild_id) ) + Sql_ShowDebug(sql_handle); + else if( Sql_NumRows(sql_handle) > 0 ) + {// guild exists + Sql_FreeResult(sql_handle); + guild_storage_tosql(guild_id, (struct guild_storage*)RFIFOP(fd,12)); + mapif_save_guild_storage_ack(fd, RFIFOL(fd,4), guild_id, 0); + return 0; } - else - mapif_save_guild_storage_ack(fd,RFIFOL(fd,4),guild_id,1); + Sql_FreeResult(sql_handle); } + mapif_save_guild_storage_ack(fd, RFIFOL(fd,4), guild_id, 1); return 0; } -// map server からの通信 -// ・1パケットのみ解析すること -// ・パケット長データはinter.cにセットしておくこと -// ・パケット長チェックや、RFIFOSKIPは呼び出し元で行われるので行ってはならない -// ・エラーなら0(false)、そうでないなら1(true)をかえさなければならない + int inter_storage_parse_frommap(int fd) { RFIFOHEAD(fd); @@ -470,4 +244,3 @@ int inter_storage_parse_frommap(int fd) } return 1; } -#endif //TXT_SQL_CONVERT diff --git a/src/char/int_storage.h b/src/char/int_storage.h index fdd2a5f28..811608f82 100644 --- a/src/char/int_storage.h +++ b/src/char/int_storage.h @@ -1,28 +1,22 @@ // Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder -#ifndef _INT_STORAGE_H_ -#define _INT_STORAGE_H_ +#ifndef _INT_STORAGE_SQL_H_ +#define _INT_STORAGE_SQL_H_ struct storage_data; struct guild_storage; -int inter_storage_init(void); -void inter_storage_final(void); -int inter_storage_save(void); -int inter_guild_storage_save(void); +int inter_storage_sql_init(void); +void inter_storage_sql_final(void); int inter_storage_delete(int account_id); int inter_guild_storage_delete(int guild_id); -int inter_storage_parse_frommap(int fd); -extern char storage_txt[1024]; -extern char guild_storage_txt[1024]; +int inter_storage_parse_frommap(int fd); //Exported for use in the TXT-SQL converter. -bool storage_fromstr(char* str, int* account_id, struct storage_data* p); -int guild_storage_fromstr(char *str,struct guild_storage *p); - -bool storage_load(int account_id, struct storage_data* storage); -bool storage_save(int account_id, struct storage_data* storage); +int storage_fromsql(int account_id, struct storage_data* p); +int storage_tosql(int account_id,struct storage_data *p); +int guild_storage_tosql(int guild_id, struct guild_storage *p); -#endif /* _INT_STORAGE_H_ */ +#endif /* _INT_STORAGE_SQL_H_ */ diff --git a/src/char/inter.c b/src/char/inter.c index 298ed38a5..2137579be 100644 --- a/src/char/inter.c +++ b/src/char/inter.c @@ -1,300 +1,327 @@ // Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder -#include "../common/db.h" #include "../common/mmo.h" -#include "../common/socket.h" -#include "../common/timer.h" +#include "../common/db.h" #include "../common/malloc.h" -#include "../common/lock.h" -#include "../common/showmsg.h" #include "../common/strlib.h" +#include "../common/showmsg.h" +#include "../common/socket.h" +#include "../common/timer.h" #include "char.h" #include "inter.h" #include "int_party.h" #include "int_guild.h" -#include "int_status.h" #include "int_storage.h" #include "int_pet.h" #include "int_homun.h" +#include "int_mercenary.h" +#include "int_mail.h" +#include "int_auction.h" +#include "int_quest.h" #include <stdio.h> #include <string.h> #include <stdlib.h> -#define WISDATA_TTL (60*1000) // Existence time of Wisp/page data (60 seconds) - // that is the waiting time of answers of all map-servers -#define WISDELLIST_MAX 256 // Number of elements of Wisp/page data deletion list +#define WISDATA_TTL (60*1000) // Wisデータの生存時間(60秒) +#define WISDELLIST_MAX 256 // Wisデータ削除リストの要素数 -char accreg_txt[1024] = "save/accreg.txt"; -#ifndef TXT_SQL_CONVERT -char inter_log_filename[1024] = "log/inter.log"; -char main_chat_nick[16] = "Main"; -static DBMap* accreg_db = NULL; // int account_id -> struct accreg* +Sql* sql_handle = NULL; + +int char_server_port = 3306; +char char_server_ip[32] = "127.0.0.1"; +char char_server_id[32] = "ragnarok"; +char char_server_pw[32] = "ragnarok"; +char char_server_db[32] = "ragnarok"; +char default_codepage[32] = ""; //Feature by irmin. +static struct accreg *accreg_pt; unsigned int party_share_level = 10; +char main_chat_nick[16] = "Main"; -// sending packet list -// NOTE: This variable ain't used at all! And it's confusing.. where do I add that the length of packet 0x2b07 is 10? x.x [Skotlex] -int inter_send_packet_length[]={ - -1,-1,27,-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //0x3000-0x300f - -1, 7, 0, 0, 0, 0, 0, 0, -1,11, 0, 0, 0, 0, 0, 0, - 35,-1,11,15, 34,29, 7,-1, 0, 0, 0, 0, 0, 0, 0, 0, - 10,-1,15, 0, 79,19, 7,-1, 0,-1,-1,-1, 14,67,186,-1, - 9, 9,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 11,-1, 7, 3, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -}; // recv. packet list -int inter_recv_packet_length[]={ - -1,-1, 7,-1, -1,13,36, 0, 0, 0, 0, 0, 0, 0, 0, 0, //0x3000-0x300f - 6,-1, 0, 0, 0, 0, 0, 0, 10,-1, 0, 0, 0, 0, 0, 0, //0x3010-0x301f - -1,10,-1,14, 14,19, 6,-1, 14,14, 0, 0, 0, 0, 0, 0, //0x3020-0x302f Party - -1, 6,-1,-1, 55,19, 6,-1, 14,-1,-1,-1, 18,19,186,-1, //0x3030-0x303f - 5, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //0x3040-0x304f - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //0x3050-0x305f - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //0x3060-0x306f - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //0x3070-0x307f - 48,14,-1, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //0x3080-0x308f - -1,10,-1, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //0x3090-0x309f Homunculus packets [albator] +int inter_recv_packet_length[] = { + -1,-1, 7,-1, -1,13,36, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3000- + 6,-1, 0, 0, 0, 0, 0, 0, 10,-1, 0, 0, 0, 0, 0, 0, // 3010- + -1,10,-1,14, 14,19, 6,-1, 14,14, 0, 0, 0, 0, 0, 0, // 3020- Party + -1, 6,-1,-1, 55,19, 6,-1, 14,-1,-1,-1, 18,19,186,-1, // 3030- + 5, 9, 0, 0, 0, 0, 0, 0, 7, 6,10,10, 10,-1, 0, 0, // 3040- + -1,-1,10,10, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3050- Auction System [Zephyrus] + 6,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3060- Quest system [Kevin] [Inkfish] + -1,10, 6,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3070- Mercenary packets [Zephyrus] + 48,14,-1, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3080- + -1,10,-1, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3090- Homunculus packets [albator] }; struct WisData { int id, fd, count, len; unsigned long tick; - unsigned char src[24], dst[24], msg[1024]; + unsigned char src[24], dst[24], msg[512]; }; static DBMap* wis_db = NULL; // int wis_id -> struct WisData* static int wis_dellist[WISDELLIST_MAX], wis_delnum; - //-------------------------------------------------------- +// Save registry to sql +int inter_accreg_tosql(int account_id, int char_id, struct accreg* reg, int type) +{ + struct global_reg* r; + SqlStmt* stmt; + int i; -// アカウント変数を文字列へ変換 -int inter_accreg_tostr(char *str, struct accreg *reg) { - int j; - char *p = str; - - p += sprintf(p, "%d\t", reg->account_id); - for(j = 0; j < reg->reg_num; j++) { - p += sprintf(p,"%s,%s ", reg->reg[j].str, reg->reg[j].value); - } - - return 0; -} -#endif //TXT_SQL_CONVERT -// アカウント変数を文字列から変換 -int inter_accreg_fromstr(const char *str, struct accreg *reg) { - int j, n; - const char *p = str; - - if (sscanf(p, "%d\t%n", ®->account_id, &n ) != 1 || reg->account_id <= 0) - return 1; + if( account_id <= 0 ) + return 0; + reg->account_id = account_id; + reg->char_id = char_id; - for(j = 0, p += n; j < ACCOUNT_REG_NUM; j++, p += n) { - if (sscanf(p, "%[^,],%[^ ] %n", reg->reg[j].str, reg->reg[j].value, &n) != 2) - break; + //`global_reg_value` (`type`, `account_id`, `char_id`, `str`, `value`) + switch( type ) + { + case 3: //Char Reg + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `type`=3 AND `char_id`='%d'", reg_db, char_id) ) + Sql_ShowDebug(sql_handle); + account_id = 0; + break; + case 2: //Account Reg + if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `type`=2 AND `account_id`='%d'", reg_db, account_id) ) + Sql_ShowDebug(sql_handle); + char_id = 0; + break; + case 1: //Account2 Reg + ShowError("inter_accreg_tosql: Char server shouldn't handle type 1 registry values (##). That is the login server's work!\n"); + return 0; + default: + ShowError("inter_accreg_tosql: Invalid type %d\n", type); + return 0; } - reg->reg_num = j; - return 0; -} -#ifndef TXT_SQL_CONVERT -// アカウント変数の読み込み -int inter_accreg_init(void) { - char line[8192]; - FILE *fp; - int c = 0; - struct accreg *reg; - - accreg_db = idb_alloc(DB_OPT_RELEASE_DATA); + if( reg->reg_num <= 0 ) + return 0; - if( (fp = fopen(accreg_txt, "r")) == NULL) - return 1; - while(fgets(line, sizeof(line), fp)) + stmt = SqlStmt_Malloc(sql_handle); + if( SQL_ERROR == SqlStmt_Prepare(stmt, "INSERT INTO `%s` (`type`, `account_id`, `char_id`, `str`, `value`) VALUES ('%d','%d','%d',?,?)", reg_db, type, account_id, char_id) ) + SqlStmt_ShowDebug(stmt); + for( i = 0; i < reg->reg_num; ++i ) { - reg = (struct accreg*)aCalloc(sizeof(struct accreg), 1); - if (reg == NULL) { - ShowFatalError("inter: accreg: out of memory!\n"); - exit(EXIT_FAILURE); + r = ®->reg[i]; + if( r->str[0] != '\0' && r->value != '\0' ) + { + // str + SqlStmt_BindParam(stmt, 0, SQLDT_STRING, r->str, strnlen(r->str, sizeof(r->str))); + // value + SqlStmt_BindParam(stmt, 1, SQLDT_STRING, r->value, strnlen(r->value, sizeof(r->value))); + + if( SQL_ERROR == SqlStmt_Execute(stmt) ) + SqlStmt_ShowDebug(stmt); } - if (inter_accreg_fromstr(line, reg) == 0 && reg->account_id > 0) { - idb_put(accreg_db, reg->account_id, reg); - } else { - ShowError("inter: accreg: broken data [%s] line %d\n", accreg_txt, c); - aFree(reg); - } - c++; } - fclose(fp); - - return 0; + SqlStmt_Free(stmt); + return 1; } -// アカウント変数のセーブ用 -int inter_accreg_save_sub(DBKey key, void *data, va_list ap) { - char line[8192]; - FILE *fp; - struct accreg *reg = (struct accreg *)data; - - if (reg->reg_num > 0) { - inter_accreg_tostr(line,reg); - fp = va_arg(ap, FILE *); - fprintf(fp, "%s\n", line); - } +// Load account_reg from sql (type=2) +int inter_accreg_fromsql(int account_id,int char_id, struct accreg *reg, int type) +{ + struct global_reg* r; + char* data; + size_t len; + int i; - return 0; -} + if( reg == NULL) + return 0; -// アカウント変数のセーブ -int inter_accreg_save(void) { - FILE *fp; - int lock; + memset(reg, 0, sizeof(struct accreg)); + reg->account_id = account_id; + reg->char_id = char_id; - if ((fp = lock_fopen(accreg_txt,&lock)) == NULL) { - ShowError("int_accreg: can't write [%s] !!! data is lost !!!\n", accreg_txt); - return 1; + //`global_reg_value` (`type`, `account_id`, `char_id`, `str`, `value`) + switch( type ) + { + case 3: //char reg + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `str`, `value` FROM `%s` WHERE `type`=3 AND `char_id`='%d'", reg_db, char_id) ) + Sql_ShowDebug(sql_handle); + break; + case 2: //account reg + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `str`, `value` FROM `%s` WHERE `type`=2 AND `account_id`='%d'", reg_db, account_id) ) + Sql_ShowDebug(sql_handle); + break; + case 1: //account2 reg + ShowError("inter_accreg_fromsql: Char server shouldn't handle type 1 registry values (##). That is the login server's work!\n"); + return 0; + default: + ShowError("inter_accreg_fromsql: Invalid type %d\n", type); + return 0; + } + for( i = 0; i < MAX_REG_NUM && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i ) + { + r = ®->reg[i]; + // str + Sql_GetData(sql_handle, 0, &data, &len); + memcpy(r->str, data, min(len, sizeof(r->str))); + // value + Sql_GetData(sql_handle, 1, &data, &len); + memcpy(r->value, data, min(len, sizeof(r->value))); } - accreg_db->foreach(accreg_db, inter_accreg_save_sub,fp); - lock_fclose(fp, accreg_txt, &lock); + reg->reg_num = i; + Sql_FreeResult(sql_handle); + return 1; +} +// Initialize +int inter_accreg_sql_init(void) +{ + CREATE(accreg_pt, struct accreg, 1); return 0; + } -//-------------------------------------------------------- -#endif //TXT_SQL_CONVERT /*========================================== - * 設定ファイルを読み込む + * read config file *------------------------------------------*/ -static int inter_config_read(const char *cfgName) { +static int inter_config_read(const char* cfgName) +{ + int i; char line[1024], w1[1024], w2[1024]; - FILE *fp; + FILE* fp; fp = fopen(cfgName, "r"); - if (fp == NULL) { + if(fp == NULL) { ShowError("file not found: %s\n", cfgName); return 1; } + + ShowInfo("reading file %s...\n", cfgName); + while(fgets(line, sizeof(line), fp)) { - if (line[0] == '/' && line[1] == '/') + i = sscanf(line, "%[^:]: %[^\r\n]", w1, w2); + if(i != 2) continue; - if (sscanf(line,"%[^:]: %[^\r\n]", w1, w2) != 2) - continue; - - if (strcmpi(w1, "storage_txt") == 0) { - strncpy(storage_txt, w2, sizeof(storage_txt)); - } else if (strcmpi(w1, "party_txt") == 0) { - strncpy(party_txt, w2, sizeof(party_txt)); - } else if (strcmpi(w1, "pet_txt") == 0) { - strncpy(pet_txt, w2, sizeof(pet_txt)); - } else if (strcmpi(w1, "accreg_txt") == 0) { - strncpy(accreg_txt, w2, sizeof(accreg_txt)); - } else if (strcmpi(w1, "guild_txt") == 0) { - strncpy(guild_txt, w2, sizeof(guild_txt)); - } else if (strcmpi(w1, "castle_txt") == 0) { - strncpy(castle_txt, w2, sizeof(castle_txt)); - } else if (strcmpi(w1, "guild_storage_txt") == 0) { - strncpy(guild_storage_txt, w2, sizeof(guild_storage_txt)); -#ifndef TXT_SQL_CONVERT - } else if (strcmpi(w1, "homun_txt") == 0) { - strncpy(homun_txt, w2, sizeof(homun_txt)); - } else if (strcmpi(w1, "party_share_level") == 0) { - party_share_level = (unsigned int)atof(w2); - } else if (strcmpi(w1, "inter_log_filename") == 0) { - strncpy(inter_log_filename, w2, sizeof(inter_log_filename)); - } else if(strcmpi(w1,"log_inter")==0) { + if(!strcmpi(w1,"char_server_ip")) { + strcpy(char_server_ip,w2); + ShowStatus ("set char_server_ip : %s\n", w2); + } else + if(!strcmpi(w1,"char_server_port")) { + char_server_port = atoi(w2); + ShowStatus ("set char_server_port : %s\n", w2); + } else + if(!strcmpi(w1,"char_server_id")) { + strcpy(char_server_id,w2); + ShowStatus ("set char_server_id : %s\n", w2); + } else + if(!strcmpi(w1,"char_server_pw")) { + strcpy(char_server_pw,w2); + ShowStatus ("set char_server_pw : %s\n", w2); + } else + if(!strcmpi(w1,"char_server_db")) { + strcpy(char_server_db,w2); + ShowStatus ("set char_server_db : %s\n", w2); + } else + if(!strcmpi(w1,"default_codepage")) { + strcpy(default_codepage,w2); + ShowStatus ("set default_codepage : %s\n", w2); + } + else if(!strcmpi(w1,"party_share_level")) + party_share_level = atoi(w2); + else if(!strcmpi(w1,"log_inter")) log_inter = atoi(w2); - } else if(strcmpi(w1, "main_chat_nick")==0){ // Main chat nick [LuzZza] + else if(!strcmpi(w1,"main_chat_nick")) safestrncpy(main_chat_nick, w2, sizeof(main_chat_nick)); -#endif //TXT_SQL_CONVERT - } else if (strcmpi(w1, "import") == 0) { + else if(!strcmpi(w1,"import")) inter_config_read(w2); - } } fclose(fp); + ShowInfo ("done reading %s.\n", cfgName); + return 0; } -#ifndef TXT_SQL_CONVERT -// ログ書き出し -int inter_log(char *fmt,...) { - FILE *logfp; + +// Save interlog into sql +int inter_log(char* fmt, ...) +{ + char str[255]; + char esc_str[sizeof(str)*2+1];// escaped str va_list ap; va_start(ap,fmt); - logfp = fopen(inter_log_filename, "a"); - if (logfp) { - vfprintf(logfp, fmt, ap); - fclose(logfp); - } + vsnprintf(str, sizeof(str), fmt, ap); va_end(ap); - return 0; -} - -// セーブ -int inter_save(void) { -#ifdef ENABLE_SC_SAVING - inter_status_save(); -#endif - inter_party_save(); - inter_guild_save(); - inter_storage_save(); - inter_guild_storage_save(); - inter_pet_save(); - inter_homun_save(); - inter_accreg_save(); + Sql_EscapeStringLen(sql_handle, esc_str, str, strnlen(str, sizeof(str))); + if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` (`time`, `log`) VALUES (NOW(), '%s')", interlog_db, esc_str) ) + Sql_ShowDebug(sql_handle); return 0; } -#endif //TXT_SQL_CONVERT -// 初期化 -int inter_init_txt(const char *file) +// initialize +int inter_init_sql(const char *file) { + //int i; + + ShowInfo ("interserver initialize...\n"); inter_config_read(file); -#ifndef TXT_SQL_CONVERT + //DB connection initialized + sql_handle = Sql_Malloc(); + ShowInfo("Connect Character DB server.... (Character Server)\n"); + if( SQL_ERROR == Sql_Connect(sql_handle, char_server_id, char_server_pw, char_server_ip, (uint16)char_server_port, char_server_db) ) + { + Sql_ShowDebug(sql_handle); + Sql_Free(sql_handle); + exit(EXIT_FAILURE); + } + + if( *default_codepage ) { + if( SQL_ERROR == Sql_SetEncoding(sql_handle, default_codepage) ) + Sql_ShowDebug(sql_handle); + } + wis_db = idb_alloc(DB_OPT_RELEASE_DATA); + inter_guild_sql_init(); + inter_storage_sql_init(); + inter_party_sql_init(); + inter_pet_sql_init(); + inter_homunculus_sql_init(); + inter_mercenary_sql_init(); + inter_accreg_sql_init(); + inter_mail_sql_init(); + inter_auction_sql_init(); - inter_party_init(); - inter_guild_init(); - inter_storage_init(); - inter_pet_init(); - inter_homun_init(); - inter_accreg_init(); -#endif //TXT_SQL_CONVERT return 0; } -#ifndef TXT_SQL_CONVERT + // finalize -void inter_final(void) { - accreg_db->destroy(accreg_db, NULL); +void inter_final(void) +{ wis_db->destroy(wis_db, NULL); - inter_party_final(); - inter_guild_final(); - inter_storage_final(); - inter_pet_final(); - inter_homun_final(); - + inter_guild_sql_final(); + inter_storage_sql_final(); + inter_party_sql_final(); + inter_pet_sql_final(); + inter_homunculus_sql_final(); + inter_mercenary_sql_final(); + inter_mail_sql_final(); + inter_auction_sql_final(); + + if (accreg_pt) aFree(accreg_pt); return; } -// マップサーバー接続 -int inter_mapif_init(int fd) { +int inter_mapif_init(int fd) +{ inter_guild_mapif_init(fd); return 0; } + //-------------------------------------------------------- -// sended packets to map-server // broadcast sending int mapif_broadcast(unsigned char *mes, int len, unsigned long fontColor, short fontType, short fontSize, short fontAlign, short fontY, int sfd) @@ -316,56 +343,32 @@ int mapif_broadcast(unsigned char *mes, int len, unsigned long fontColor, short return 0; } -// Wisp/page transmission to one map-server -int mapif_wis_message2(struct WisData *wd, int fd) { - WFIFOHEAD(fd, 56+wd->len); - WFIFOW(fd, 0) = 0x3801; - WFIFOW(fd, 2) = 56 + wd->len; - WFIFOL(fd, 4) = wd->id; - memcpy(WFIFOP(fd, 8), wd->src, NAME_LENGTH); - memcpy(WFIFOP(fd,32), wd->dst, NAME_LENGTH); - memcpy(WFIFOP(fd,56), wd->msg, wd->len); - wd->count = 1; - WFIFOSET(fd,WFIFOW(fd,2)); - return 1; -} - -// Wisp/page transmission to all map-server -int mapif_wis_message(struct WisData *wd) { +// Wis sending +int mapif_wis_message(struct WisData *wd) +{ unsigned char buf[2048]; if (wd->len > 2047-56) wd->len = 2047-56; //Force it to fit to avoid crashes. [Skotlex] WBUFW(buf, 0) = 0x3801; - WBUFW(buf, 2) = 56 + wd->len; + WBUFW(buf, 2) = 56 +wd->len; WBUFL(buf, 4) = wd->id; memcpy(WBUFP(buf, 8), wd->src, NAME_LENGTH); memcpy(WBUFP(buf,32), wd->dst, NAME_LENGTH); memcpy(WBUFP(buf,56), wd->msg, wd->len); - wd->count = mapif_sendall(buf, WBUFW(buf,2)); + wd->count = mapif_sendall(buf,WBUFW(buf,2)); return 0; } -int mapif_wis_fail(int fd, char *src) { - unsigned char buf[27]; - WBUFW(buf, 0) = 0x3802; - memcpy(WBUFP(buf, 2), src, NAME_LENGTH); - WBUFB(buf,26) = 1; // flag: 0: success to send wisper, 1: target character is not loged in?, 2: ignored by target - mapif_send(fd, buf, 27); - return 0; - -} - -// Wisp/page transmission result to map-server +// Wis sending result int mapif_wis_end(struct WisData *wd, int flag) { unsigned char buf[27]; - WBUFW(buf, 0) = 0x3802; - memcpy(WBUFP(buf, 2), wd->src, 24); - WBUFB(buf,26) = flag; // flag: 0: success to send wisper, 1: target character is not loged in?, 2: ignored by target - mapif_send(wd->fd, buf, 27); - + WBUFW(buf, 0)=0x3802; + memcpy(WBUFP(buf, 2),wd->src,24); + WBUFB(buf,26)=flag; + mapif_send(wd->fd,buf,27); return 0; } @@ -376,25 +379,28 @@ static void mapif_account_reg(int fd, unsigned char *src) mapif_sendallwos(fd, src, WBUFW(src,2)); } -// アカウント変数要求返信 -int mapif_account_reg_reply(int fd,int account_id, int char_id) +// Send the requested account_reg +int mapif_account_reg_reply(int fd,int account_id,int char_id, int type) { - struct accreg *reg = (struct accreg*)idb_get(accreg_db,account_id); - - WFIFOHEAD(fd, ACCOUNT_REG_NUM * 288+ 13); - WFIFOW(fd,0) = 0x3804; - WFIFOL(fd,4) = account_id; - WFIFOL(fd,8) = char_id; - WFIFOB(fd,12) = 2; //Acc Reg - if (reg == NULL) { - WFIFOW(fd,2) = 13; - } else { - int i, p; - for (p=13,i = 0; i < reg->reg_num; i++) { + struct accreg *reg=accreg_pt; + WFIFOHEAD(fd, 13 + 5000); + inter_accreg_fromsql(account_id,char_id,reg,type); + + WFIFOW(fd,0)=0x3804; + WFIFOL(fd,4)=account_id; + WFIFOL(fd,8)=char_id; + WFIFOB(fd,12)=type; + if(reg->reg_num==0){ + WFIFOW(fd,2)=13; + }else{ + int i,p; + for (p=13,i = 0; i < reg->reg_num && p < 5000; i++) { p+= sprintf((char*)WFIFOP(fd,p), "%s", reg->reg[i].str)+1; //We add 1 to consider the '\0' in place. p+= sprintf((char*)WFIFOP(fd,p), "%s", reg->reg[i].value)+1; } WFIFOW(fd,2)=p; + if (p>= 5000) + ShowWarning("Too many acc regs for %d:%d, not all values were loaded.\n", account_id, char_id); } WFIFOSET(fd,WFIFOW(fd,2)); return 0; @@ -403,22 +409,23 @@ int mapif_account_reg_reply(int fd,int account_id, int char_id) //Request to kick char from a certain map server. [Skotlex] int mapif_disconnectplayer(int fd, int account_id, int char_id, int reason) { - if (fd < 0) - return -1; - - WFIFOHEAD(fd, 7); - WFIFOW(fd,0) = 0x2b1f; - WFIFOL(fd,2) = account_id; - WFIFOB(fd,6) = reason; - WFIFOSET(fd,7); - - return 0; + if (fd >= 0) + { + WFIFOHEAD(fd,7); + WFIFOW(fd,0) = 0x2b1f; + WFIFOL(fd,2) = account_id; + WFIFOB(fd,6) = reason; + WFIFOSET(fd,7); + return 0; + } + return -1; } //-------------------------------------------------------- // Existence check of WISP data -int check_ttl_wisdata_sub(DBKey key, void *data, va_list ap) { +int check_ttl_wisdata_sub(DBKey key, void *data, va_list ap) +{ unsigned long tick; struct WisData *wd = (struct WisData *)data; tick = va_arg(ap, unsigned long); @@ -429,7 +436,8 @@ int check_ttl_wisdata_sub(DBKey key, void *data, va_list ap) { return 0; } -int check_ttl_wisdata(void) { +int check_ttl_wisdata(void) +{ unsigned long tick = gettick(); int i; @@ -449,41 +457,27 @@ int check_ttl_wisdata(void) { } //-------------------------------------------------------- -// received packets from map-server // broadcast sending int mapif_parse_broadcast(int fd) { - RFIFOHEAD(fd); mapif_broadcast(RFIFOP(fd,16), RFIFOW(fd,2), RFIFOL(fd,4), RFIFOW(fd,8), RFIFOW(fd,10), RFIFOW(fd,12), RFIFOW(fd,14), fd); return 0; } -static struct WisData* mapif_create_whisper(int fd, char* src, char* dst, char* mes, int meslen) -{ - static int wisid = 0; - struct WisData* wd = (struct WisData *)aCalloc(sizeof(struct WisData), 1); - if (wd == NULL){ - ShowFatalError("inter: WisRequest: out of memory !\n"); - return NULL; - } - wd->id = ++wisid; - wd->fd = fd; - wd->len= meslen; - memcpy(wd->src, src, NAME_LENGTH); - memcpy(wd->dst, dst, NAME_LENGTH); - memcpy(wd->msg, mes, meslen); - wd->tick = gettick(); - return wd; -} // Wisp/page request to send int mapif_parse_WisRequest(int fd) { - struct mmo_charstatus* char_status; struct WisData* wd; + static int wisid = 0; char name[NAME_LENGTH]; - int fd2; + char esc_name[NAME_LENGTH*2+1];// escaped name + char* data; + size_t len; + + + if ( fd <= 0 ) {return 0;} // check if we have a valid fd if (RFIFOW(fd,2)-52 >= sizeof(wd->msg)) { ShowWarning("inter: Wis message size too long.\n"); @@ -492,46 +486,73 @@ int mapif_parse_WisRequest(int fd) ShowError("inter: Wis message doesn't exist.\n"); return 0; } - + safestrncpy(name, (char*)RFIFOP(fd,28), NAME_LENGTH); //Received name may be too large and not contain \0! [Skotlex] + Sql_EscapeStringLen(sql_handle, esc_name, name, strnlen(name, NAME_LENGTH)); + if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `name` FROM `%s` WHERE `name`='%s'", char_db, esc_name) ) + Sql_ShowDebug(sql_handle); + // search if character exists before to ask all map-servers - char_status = search_character_byname(name); - if (char_status == NULL) - return mapif_wis_fail(fd, (char*)RFIFOP(fd, 4)); - - // Character exists. - // to be sure of the correct name, rewrite it - memset(name, 0, NAME_LENGTH); - strncpy(name, char_status->name, NAME_LENGTH); - // if source is destination, don't ask other servers. - if (strcmp((char*)RFIFOP(fd,4),name) == 0) - return mapif_wis_fail(fd, (char*)RFIFOP(fd, 4)); - - //Look for online character. - fd2 = search_character_online(char_status->account_id, char_status->char_id); - if (fd2 >= 0) { //Character online, send whisper. - wd = mapif_create_whisper(fd, (char*)RFIFOP(fd, 4), (char*)RFIFOP(fd,28), (char*)RFIFOP(fd,52), RFIFOW(fd,2)-52); - if (!wd) return 1; - idb_put(wis_db, wd->id, wd); - mapif_wis_message2(wd, fd2); - return 0; + if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) + { + unsigned char buf[27]; + WBUFW(buf, 0) = 0x3802; + memcpy(WBUFP(buf, 2), RFIFOP(fd, 4), NAME_LENGTH); + WBUFB(buf,26) = 1; // flag: 0: success to send wisper, 1: target character is not loged in?, 2: ignored by target + mapif_send(fd, buf, 27); + } + else + {// Character exists. So, ask all map-servers + // to be sure of the correct name, rewrite it + Sql_GetData(sql_handle, 0, &data, &len); + memset(name, 0, NAME_LENGTH); + memcpy(name, data, min(len, NAME_LENGTH)); + // if source is destination, don't ask other servers. + if( strncmp((const char*)RFIFOP(fd,4), name, NAME_LENGTH) == 0 ) + { + uint8 buf[27]; + WBUFW(buf, 0) = 0x3802; + memcpy(WBUFP(buf, 2), RFIFOP(fd, 4), NAME_LENGTH); + WBUFB(buf,26) = 1; // flag: 0: success to send wisper, 1: target character is not loged in?, 2: ignored by target + mapif_send(fd, buf, 27); + } + else + { + + CREATE(wd, struct WisData, 1); + + // Whether the failure of previous wisp/page transmission (timeout) + check_ttl_wisdata(); + + wd->id = ++wisid; + wd->fd = fd; + wd->len= RFIFOW(fd,2)-52; + memcpy(wd->src, RFIFOP(fd, 4), NAME_LENGTH); + memcpy(wd->dst, RFIFOP(fd,28), NAME_LENGTH); + memcpy(wd->msg, RFIFOP(fd,52), wd->len); + wd->tick = gettick(); + idb_put(wis_db, wd->id, wd); + mapif_wis_message(wd); + } } - //Not found. - return mapif_wis_fail(fd, (char*)RFIFOP(fd,4)); + + Sql_FreeResult(sql_handle); + return 0; } + // Wisp/page transmission result -int mapif_parse_WisReply(int fd) { +int mapif_parse_WisReply(int fd) +{ int id, flag; struct WisData *wd; - RFIFOHEAD(fd); + id = RFIFOL(fd,2); flag = RFIFOB(fd,6); wd = (struct WisData*)idb_get(wis_db, id); - if (wd == NULL) - return 0; // This wisp was probably suppress before, because it was timeout or because of target was found on another map-server + return 0; // This wisp was probably suppress before, because it was timeout of because of target was found on another map-server if ((--wd->count) <= 0 || flag != 1) { mapif_wis_end(wd, flag); // flag: 0: success to send wisper, 1: target character is not loged in?, 2: ignored by target @@ -542,10 +563,10 @@ int mapif_parse_WisReply(int fd) { } // Received wisp message from map-server for ALL gm (just copy the message and resends it to ALL map-servers) -int mapif_parse_WisToGM(int fd) { +int mapif_parse_WisToGM(int fd) +{ unsigned char buf[2048]; // 0x3003/0x3803 <packet_len>.w <wispname>.24B <min_gm_level>.w <message>.?B - - ShowDebug("Sent packet back!\n"); + memcpy(WBUFP(buf,0), RFIFOP(fd,0), RFIFOW(fd,2)); WBUFW(buf, 0) = 0x3803; mapif_sendall(buf, RFIFOW(fd,2)); @@ -553,32 +574,26 @@ int mapif_parse_WisToGM(int fd) { return 0; } -static void* create_accreg(DBKey key, va_list args) { - struct accreg *reg; - reg = (struct accreg*)aCalloc(sizeof(struct accreg), 1); - reg->account_id = key.i; - return reg; -} - -// アカウント変数保存要求 -int mapif_parse_Registry(int fd) { - int j, p, len; - struct accreg *reg; - RFIFOHEAD(fd); - - switch (RFIFOB(fd,12)) { - case 3: //Character registry - return char_parse_Registry(RFIFOL(fd,4), RFIFOL(fd,8), RFIFOP(fd,13), RFIFOW(fd,2)-13); - case 2: //Acc Reg - break; - case 1: //Acc Reg2, forward to login - return save_accreg2(RFIFOP(fd,4), RFIFOW(fd,2)-4); - default: //Error? - return 1; +// Save account_reg into sql (type=2) +int mapif_parse_Registry(int fd) +{ + int j,p,len, max; + struct accreg *reg=accreg_pt; + + memset(accreg_pt,0,sizeof(struct accreg)); + switch (RFIFOB(fd, 12)) { + case 3: //Character registry + max = GLOBAL_REG_NUM; + break; + case 2: //Account Registry + max = ACCOUNT_REG_NUM; + break; + case 1: //Account2 registry, must be sent over to login server. + return save_accreg2(RFIFOP(fd,4), RFIFOW(fd,2)-4); + default: + return 1; } - reg = (struct accreg*)idb_ensure(accreg_db, RFIFOL(fd,4), create_accreg); - - for(j=0,p=13;j<ACCOUNT_REG_NUM && p<RFIFOW(fd,2);j++){ + for(j=0,p=13;j<max && p<RFIFOW(fd,2);j++){ sscanf((char*)RFIFOP(fd,p), "%31c%n",reg->reg[j].str,&len); reg->reg[j].str[len]='\0'; p +=len+1; //+1 to skip the '\0' between strings. @@ -587,34 +602,32 @@ int mapif_parse_Registry(int fd) { p +=len+1; } reg->reg_num=j; - mapif_account_reg(fd, RFIFOP(fd,0)); // 他のMAPサーバーに送信 + inter_accreg_tosql(RFIFOL(fd,4),RFIFOL(fd,8),reg, RFIFOB(fd,12)); + mapif_account_reg(fd,RFIFOP(fd,0)); // Send updated accounts to other map servers. return 0; } // Request the value of all registries. int mapif_parse_RegistryRequest(int fd) -{ - RFIFOHEAD(fd); +{ //Load Char Registry - if (RFIFOB(fd,12)) - char_account_reg_reply(fd,RFIFOL(fd,2),RFIFOL(fd,6)); + if (RFIFOB(fd,12)) mapif_account_reg_reply(fd,RFIFOL(fd,2),RFIFOL(fd,6),3); //Load Account Registry - if (RFIFOB(fd,11)) - mapif_account_reg_reply(fd,RFIFOL(fd,2),RFIFOL(fd,6)); + if (RFIFOB(fd,11)) mapif_account_reg_reply(fd,RFIFOL(fd,2),RFIFOL(fd,6),2); //Ask Login Server for Account2 values. - if (RFIFOB(fd,10)) - request_accreg2(RFIFOL(fd,2),RFIFOL(fd,6)); + if (RFIFOB(fd,10)) request_accreg2(RFIFOL(fd,2),RFIFOL(fd,6)); return 1; } -static void mapif_namechange_ack(int fd, int account_id, int char_id, int type, int flag, char *name){ +static void mapif_namechange_ack(int fd, int account_id, int char_id, int type, int flag, char *name) +{ WFIFOHEAD(fd, NAME_LENGTH+13); - WFIFOW(fd, 0) =0x3806; - WFIFOL(fd, 2) =account_id; - WFIFOL(fd, 6) =char_id; - WFIFOB(fd,10) =type; - WFIFOB(fd,11) =flag; + WFIFOW(fd, 0) = 0x3806; + WFIFOL(fd, 2) = account_id; + WFIFOL(fd, 6) = char_id; + WFIFOB(fd,10) = type; + WFIFOB(fd,11) = flag; memcpy(WFIFOP(fd, 12), name, NAME_LENGTH); WFIFOSET(fd, NAME_LENGTH+13); } @@ -625,11 +638,10 @@ int mapif_parse_NameChangeRequest(int fd) char* name; int i; - RFIFOHEAD(fd); - account_id = RFIFOL(fd, 2); - char_id = RFIFOL(fd, 6); - type = RFIFOB(fd, 10); - name = (char*)RFIFOP(fd, 11); + account_id = RFIFOL(fd,2); + char_id = RFIFOL(fd,6); + type = RFIFOB(fd,10); + name = (char*)RFIFOP(fd,11); // Check Authorised letters/symbols in the name if (char_name_option == 1) { // only letters/symbols in char_name_letters are authorised @@ -675,24 +687,17 @@ int inter_check_length(int fd, int length) return length; } -// map server からの通信(1パケットのみ解析すること) -// エラーなら0(false)、処理できたなら1、 -// パケット長が足りなければ2をかえさなければならない -int inter_parse_frommap(int fd) { - int cmd, len; - RFIFOHEAD(fd); +int inter_parse_frommap(int fd) +{ + int cmd; + int len = 0; cmd = RFIFOW(fd,0); - len = 0; - // inter鯖管轄かを調べる - if (cmd < 0x3000 || cmd >= 0x3000 + ARRAYLENGTH(inter_recv_packet_length)) - return 0; - - if (inter_recv_packet_length[cmd-0x3000] == 0) //This is necessary, because otherwise we return 2 and the char server will just hang waiting for packets! [Skotlex] + if(cmd < 0x3000 || cmd >= 0x3000 + ARRAYLENGTH(inter_recv_packet_length) || inter_recv_packet_length[cmd - 0x3000] == 0) return 0; // パケット長を調べる - if ((len = inter_check_length(fd, inter_recv_packet_length[cmd - 0x3000])) == 0) + if((len = inter_check_length(fd, inter_recv_packet_length[cmd - 0x3000])) == 0) return 2; switch(cmd) { @@ -704,20 +709,21 @@ int inter_parse_frommap(int fd) { case 0x3005: mapif_parse_RegistryRequest(fd); break; case 0x3006: mapif_parse_NameChangeRequest(fd); break; default: - if (inter_party_parse_frommap(fd)) - break; - if (inter_guild_parse_frommap(fd)) - break; - if (inter_storage_parse_frommap(fd)) - break; - if (inter_pet_parse_frommap(fd)) - break; - if (inter_homun_parse_frommap(fd)) + if( inter_party_parse_frommap(fd) + || inter_guild_parse_frommap(fd) + || inter_storage_parse_frommap(fd) + || inter_pet_parse_frommap(fd) + || inter_homunculus_parse_frommap(fd) + || inter_mercenary_parse_frommap(fd) + || inter_mail_parse_frommap(fd) + || inter_auction_parse_frommap(fd) + || inter_quest_parse_frommap(fd) + ) break; - return 0; + else + return 0; } + RFIFOSKIP(fd, len); return 1; } - -#endif //TXT_SQL_CONVERT diff --git a/src/char/inter.h b/src/char/inter.h index cf3eb4b2e..ac2e1785f 100644 --- a/src/char/inter.h +++ b/src/char/inter.h @@ -1,16 +1,17 @@ // Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder -#ifndef _INTER_H_ -#define _INTER_H_ +#ifndef _INTER_SQL_H_ +#define _INTER_SQL_H_ struct accreg; +#include "../common/sql.h" -int inter_init_txt(const char *file); +int inter_init_sql(const char *file); void inter_final(void); -int inter_save(void); int inter_parse_frommap(int fd); int inter_mapif_init(int fd); +int mapif_send_gmaccounts(void); int mapif_disconnectplayer(int fd, int account_id, int char_id, int reason); int inter_log(char *fmt,...); @@ -18,10 +19,12 @@ int inter_log(char *fmt,...); #define inter_cfgName "conf/inter_athena.conf" extern unsigned int party_share_level; + +extern Sql* sql_handle; +extern Sql* lsql_handle; + extern char main_chat_nick[16]; -//For TXT->SQL conversion -extern char accreg_txt[]; -int inter_accreg_fromstr(const char *str, struct accreg *reg); +int inter_accreg_tosql(int account_id, int char_id, struct accreg *reg, int type); -#endif /* _INTER_H_ */ +#endif /* _INTER_SQL_H_ */ |