vending.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "../common/nullpo.h"
  4. #include "../common/malloc.h" // aMalloc, aFree
  5. #include "../common/showmsg.h" // ShowInfo
  6. #include "../common/strlib.h"
  7. #include "clif.h"
  8. #include "itemdb.h"
  9. #include "atcommand.h"
  10. #include "path.h"
  11. #include "chrif.h"
  12. #include "vending.h"
  13. #include "pc.h"
  14. #include "buyingstore.h" // struct s_autotrade_entry, struct s_autotrader
  15. #include <stdlib.h> // atoi
  16. static uint32 vending_nextid = 0; ///Vending_id counter
  17. static DBMap *vending_db; ///DB holder the vender : charid -> map_session_data
  18. //Autotrader
  19. static DBMap *vending_autotrader_db; /// Holds autotrader info: char_id -> struct s_autotrader
  20. static void vending_autotrader_remove(struct s_autotrader *at, bool remove);
  21. static int vending_autotrader_free(DBKey key, DBData *data, va_list ap);
  22. /**
  23. * Lookup to get the vending_db outside module
  24. * @return the vending_db
  25. */
  26. DBMap * vending_getdb()
  27. {
  28. return vending_db;
  29. }
  30. /**
  31. * Create an unique vending shop id.
  32. * @return the next vending_id
  33. */
  34. static int vending_getuid(void)
  35. {
  36. return ++vending_nextid;
  37. }
  38. /**
  39. * Make a player close his shop
  40. * @param sd : player session
  41. */
  42. void vending_closevending(struct map_session_data* sd)
  43. {
  44. nullpo_retv(sd);
  45. if( sd->state.vending ) {
  46. if( Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE vending_id = %d;", vending_items_table, sd->vender_id ) != SQL_SUCCESS ||
  47. Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE `id` = %d;", vendings_table, sd->vender_id ) != SQL_SUCCESS ) {
  48. Sql_ShowDebug(mmysql_handle);
  49. }
  50. sd->state.vending = false;
  51. sd->vender_id = 0;
  52. clif_closevendingboard(&sd->bl, 0);
  53. idb_remove(vending_db, sd->status.char_id);
  54. }
  55. }
  56. /**
  57. * Player request a shop's item list (a player shop)
  58. * @param sd : player requestion the list
  59. * @param id : vender account id (gid)
  60. */
  61. void vending_vendinglistreq(struct map_session_data* sd, int id)
  62. {
  63. struct map_session_data* vsd;
  64. nullpo_retv(sd);
  65. if( (vsd = map_id2sd(id)) == NULL )
  66. return;
  67. if( !vsd->state.vending )
  68. return; // not vending
  69. if (!pc_can_give_items(sd) || !pc_can_give_items(vsd)) { //check if both GMs are allowed to trade
  70. clif_displaymessage(sd->fd, msg_txt(sd,246));
  71. return;
  72. }
  73. sd->vended_id = vsd->vender_id; // register vending uid
  74. clif_vendinglist(sd, id, vsd->vending);
  75. }
  76. /**
  77. * Purchase item(s) from a shop
  78. * @param sd : buyer player session
  79. * @param aid : account id of vender
  80. * @param uid : shop unique id
  81. * @param data : items data who would like to purchase \n
  82. * data := {<index>.w <amount>.w }[count]
  83. * @param count : number of different items he's trying to buy
  84. */
  85. void vending_purchasereq(struct map_session_data* sd, int aid, int uid, const uint8* data, int count)
  86. {
  87. int i, j, cursor, w, new_ = 0, blank, vend_list[MAX_VENDING];
  88. double z;
  89. struct s_vending vending[MAX_VENDING]; // against duplicate packets
  90. struct map_session_data* vsd = map_id2sd(aid);
  91. nullpo_retv(sd);
  92. if( vsd == NULL || !vsd->state.vending || vsd->bl.id == sd->bl.id )
  93. return; // invalid shop
  94. if( vsd->vender_id != uid ) { // shop has changed
  95. clif_buyvending(sd, 0, 0, 6); // store information was incorrect
  96. return;
  97. }
  98. if( !searchstore_queryremote(sd, aid) && ( sd->bl.m != vsd->bl.m || !check_distance_bl(&sd->bl, &vsd->bl, AREA_SIZE) ) )
  99. return; // shop too far away
  100. searchstore_clearremote(sd);
  101. if( count < 1 || count > MAX_VENDING || count > vsd->vend_num )
  102. return; // invalid amount of purchased items
  103. blank = pc_inventoryblank(sd); //number of free cells in the buyer's inventory
  104. // duplicate item in vending to check hacker with multiple packets
  105. memcpy(&vending, &vsd->vending, sizeof(vsd->vending)); // copy vending list
  106. // some checks
  107. z = 0.; // zeny counter
  108. w = 0; // weight counter
  109. for( i = 0; i < count; i++ ) {
  110. short amount = *(uint16*)(data + 4*i + 0);
  111. short idx = *(uint16*)(data + 4*i + 2);
  112. idx -= 2;
  113. if( amount <= 0 )
  114. return;
  115. // check of item index in the cart
  116. if( idx < 0 || idx >= MAX_CART )
  117. return;
  118. ARR_FIND( 0, vsd->vend_num, j, vsd->vending[j].index == idx );
  119. if( j == vsd->vend_num )
  120. return; //picked non-existing item
  121. else
  122. vend_list[i] = j;
  123. z += ((double)vsd->vending[j].value * (double)amount);
  124. if( z > (double)sd->status.zeny || z < 0. || z > (double)MAX_ZENY ) {
  125. clif_buyvending(sd, idx, amount, 1); // you don't have enough zeny
  126. return;
  127. }
  128. if( z + (double)vsd->status.zeny > (double)MAX_ZENY && !battle_config.vending_over_max ) {
  129. clif_buyvending(sd, idx, vsd->vending[j].amount, 4); // too much zeny = overflow
  130. return;
  131. }
  132. w += itemdb_weight(vsd->cart.u.items_cart[idx].nameid) * amount;
  133. if( w + sd->weight > sd->max_weight ) {
  134. clif_buyvending(sd, idx, amount, 2); // you can not buy, because overweight
  135. return;
  136. }
  137. //Check to see if cart/vend info is in sync.
  138. if( vending[j].amount > vsd->cart.u.items_cart[idx].amount )
  139. vending[j].amount = vsd->cart.u.items_cart[idx].amount;
  140. // if they try to add packets (example: get twice or more 2 apples if marchand has only 3 apples).
  141. // here, we check cumulative amounts
  142. if( vending[j].amount < amount ) {
  143. // send more quantity is not a hack (an other player can have buy items just before)
  144. clif_buyvending(sd, idx, vsd->vending[j].amount, 4); // not enough quantity
  145. return;
  146. }
  147. vending[j].amount -= amount;
  148. switch( pc_checkadditem(sd, vsd->cart.u.items_cart[idx].nameid, amount) ) {
  149. case CHKADDITEM_EXIST:
  150. break; //We'd add this item to the existing one (in buyers inventory)
  151. case CHKADDITEM_NEW:
  152. new_++;
  153. if (new_ > blank)
  154. return; //Buyer has no space in his inventory
  155. break;
  156. case CHKADDITEM_OVERAMOUNT:
  157. return; //too many items
  158. }
  159. }
  160. pc_payzeny(sd, (int)z, LOG_TYPE_VENDING, vsd);
  161. if( battle_config.vending_tax )
  162. z -= z * (battle_config.vending_tax/10000.);
  163. pc_getzeny(vsd, (int)z, LOG_TYPE_VENDING, sd);
  164. for( i = 0; i < count; i++ ) {
  165. short amount = *(uint16*)(data + 4*i + 0);
  166. short idx = *(uint16*)(data + 4*i + 2);
  167. idx -= 2;
  168. z = 0.; // zeny counter
  169. // vending item
  170. pc_additem(sd, &vsd->cart.u.items_cart[idx], amount, LOG_TYPE_VENDING);
  171. vsd->vending[vend_list[i]].amount -= amount;
  172. z += ((double)vsd->vending[i].value * (double)amount);
  173. if( vsd->vending[vend_list[i]].amount ) {
  174. if( Sql_Query( mmysql_handle, "UPDATE `%s` SET `amount` = %d WHERE `vending_id` = %d and `cartinventory_id` = %d", vending_items_table, vsd->vending[vend_list[i]].amount, vsd->vender_id, vsd->cart.u.items_cart[idx].id ) != SQL_SUCCESS ) {
  175. Sql_ShowDebug( mmysql_handle );
  176. }
  177. } else {
  178. if( Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE `vending_id` = %d and `cartinventory_id` = %d", vending_items_table, vsd->vender_id, vsd->cart.u.items_cart[idx].id ) != SQL_SUCCESS ) {
  179. Sql_ShowDebug( mmysql_handle );
  180. }
  181. }
  182. pc_cart_delitem(vsd, idx, amount, 0, LOG_TYPE_VENDING);
  183. if( battle_config.vending_tax )
  184. z -= z * (battle_config.vending_tax/10000.);
  185. clif_vendingreport(vsd, idx, amount, sd->status.char_id, (int)z);
  186. //print buyer's name
  187. if( battle_config.buyer_name ) {
  188. char temp[256];
  189. sprintf(temp, msg_txt(sd,265), sd->status.name);
  190. clif_messagecolor(&vsd->bl, color_table[COLOR_LIGHT_GREEN], temp, false, SELF);
  191. }
  192. }
  193. // compact the vending list
  194. for( i = 0, cursor = 0; i < vsd->vend_num; i++ ) {
  195. if( vsd->vending[i].amount == 0 )
  196. continue;
  197. if( cursor != i ) { // speedup
  198. vsd->vending[cursor].index = vsd->vending[i].index;
  199. vsd->vending[cursor].amount = vsd->vending[i].amount;
  200. vsd->vending[cursor].value = vsd->vending[i].value;
  201. }
  202. cursor++;
  203. }
  204. vsd->vend_num = cursor;
  205. //Always save BOTH: customer (buyer) and vender
  206. if( save_settings&CHARSAVE_VENDING ) {
  207. chrif_save(sd, CSAVE_INVENTORY|CSAVE_CART);
  208. chrif_save(vsd, CSAVE_INVENTORY|CSAVE_CART);
  209. }
  210. //check for @AUTOTRADE users [durf]
  211. if( vsd->state.autotrade ) {
  212. //see if there is anything left in the shop
  213. ARR_FIND( 0, vsd->vend_num, i, vsd->vending[i].amount > 0 );
  214. if( i == vsd->vend_num ) {
  215. //Close Vending (this was automatically done by the client, we have to do it manually for autovenders) [Skotlex]
  216. vending_closevending(vsd);
  217. map_quit(vsd); //They have no reason to stay around anymore, do they?
  218. }
  219. }
  220. }
  221. /**
  222. * Player setup a new shop
  223. * @param sd : player opening the shop
  224. * @param message : shop title
  225. * @param data : itemlist data
  226. * data := {<index>.w <amount>.w <value>.l}[count]
  227. * @param count : number of different items
  228. * @param at Autotrader info, or NULL if requetsed not from autotrade persistance
  229. * @return 0 If success, 1 - Cannot open (die, not state.prevend, trading), 2 - No cart, 3 - Count issue, 4 - Cart data isn't saved yet, 5 - No valid item found
  230. */
  231. int8 vending_openvending(struct map_session_data* sd, const char* message, const uint8* data, int count, struct s_autotrader *at)
  232. {
  233. int i, j;
  234. int vending_skill_lvl;
  235. char message_sql[MESSAGE_SIZE*2];
  236. StringBuf buf;
  237. nullpo_retr(false,sd);
  238. if ( pc_isdead(sd) || !sd->state.prevend || pc_istrading(sd)) {
  239. return 1; // can't open vendings lying dead || didn't use via the skill (wpe/hack) || can't have 2 shops at once
  240. }
  241. vending_skill_lvl = pc_checkskill(sd, MC_VENDING);
  242. // skill level and cart check
  243. if( !vending_skill_lvl || !pc_iscarton(sd) ) {
  244. clif_skill_fail(sd, MC_VENDING, USESKILL_FAIL_LEVEL, 0);
  245. return 2;
  246. }
  247. // check number of items in shop
  248. if( count < 1 || count > MAX_VENDING || count > 2 + vending_skill_lvl ) { // invalid item count
  249. clif_skill_fail(sd, MC_VENDING, USESKILL_FAIL_LEVEL, 0);
  250. return 3;
  251. }
  252. if (save_settings&CHARSAVE_VENDING) // Avoid invalid data from saving
  253. chrif_save(sd, CSAVE_INVENTORY|CSAVE_CART);
  254. // filter out invalid items
  255. i = 0;
  256. for( j = 0; j < count; j++ ) {
  257. short index = *(uint16*)(data + 8*j + 0);
  258. short amount = *(uint16*)(data + 8*j + 2);
  259. unsigned int value = *(uint32*)(data + 8*j + 4);
  260. index -= 2; // offset adjustment (client says that the first cart position is 2)
  261. if( index < 0 || index >= MAX_CART // invalid position
  262. || pc_cartitem_amount(sd, index, amount) < 0 // invalid item or insufficient quantity
  263. //NOTE: official server does not do any of the following checks!
  264. || !sd->cart.u.items_cart[index].identify // unidentified item
  265. || sd->cart.u.items_cart[index].attribute == 1 // broken item
  266. || sd->cart.u.items_cart[index].expire_time // It should not be in the cart but just in case
  267. || (sd->cart.u.items_cart[index].bound && !pc_can_give_bounded_items(sd)) // can't trade account bound items and has no permission
  268. || !itemdb_cantrade(&sd->cart.u.items_cart[index], pc_get_group_level(sd), pc_get_group_level(sd)) ) // untradeable item
  269. continue;
  270. sd->vending[i].index = index;
  271. sd->vending[i].amount = amount;
  272. sd->vending[i].value = min(value, (unsigned int)battle_config.vending_max_value);
  273. i++; // item successfully added
  274. }
  275. if( i != j )
  276. clif_displaymessage (sd->fd, msg_txt(sd,266)); //"Some of your items cannot be vended and were removed from the shop."
  277. if( i == 0 ) { // no valid item found
  278. clif_skill_fail(sd, MC_VENDING, USESKILL_FAIL_LEVEL, 0); // custom reply packet
  279. return 5;
  280. }
  281. sd->state.prevend = 0;
  282. sd->state.vending = true;
  283. sd->state.workinprogress = WIP_DISABLE_NONE;
  284. sd->vender_id = vending_getuid();
  285. sd->vend_num = i;
  286. safestrncpy(sd->message, message, MESSAGE_SIZE);
  287. Sql_EscapeString( mmysql_handle, message_sql, sd->message );
  288. if( Sql_Query( mmysql_handle, "INSERT INTO `%s`(`id`, `account_id`, `char_id`, `sex`, `map`, `x`, `y`, `title`, `autotrade`, `body_direction`, `head_direction`, `sit`) "
  289. "VALUES( %d, %d, %d, '%c', '%s', %d, %d, '%s', %d, '%d', '%d', '%d' );",
  290. vendings_table, sd->vender_id, sd->status.account_id, sd->status.char_id, sd->status.sex == SEX_FEMALE ? 'F' : 'M', map[sd->bl.m].name, sd->bl.x, sd->bl.y, message_sql, sd->state.autotrade, at ? at->dir : sd->ud.dir, at ? at->head_dir : sd->head_dir, at ? at->sit : pc_issit(sd) ) != SQL_SUCCESS ) {
  291. Sql_ShowDebug(mmysql_handle);
  292. }
  293. StringBuf_Init(&buf);
  294. StringBuf_Printf(&buf, "INSERT INTO `%s`(`vending_id`,`index`,`cartinventory_id`,`amount`,`price`) VALUES", vending_items_table);
  295. for (j = 0; j < i; j++) {
  296. StringBuf_Printf(&buf, "(%d,%d,%d,%d,%d)", sd->vender_id, j, sd->cart.u.items_cart[sd->vending[j].index].id, sd->vending[j].amount, sd->vending[j].value);
  297. if (j < i-1)
  298. StringBuf_AppendStr(&buf, ",");
  299. }
  300. if (SQL_ERROR == Sql_QueryStr(mmysql_handle, StringBuf_Value(&buf)))
  301. Sql_ShowDebug(mmysql_handle);
  302. StringBuf_Destroy(&buf);
  303. clif_openvending(sd,sd->bl.id,sd->vending);
  304. clif_showvendingboard(&sd->bl,message,0);
  305. idb_put(vending_db, sd->status.char_id, sd);
  306. return 0;
  307. }
  308. /**
  309. * Checks if an item is being sold in given player's vending.
  310. * @param sd : vender session (player)
  311. * @param nameid : item id
  312. * @return 0:not selling it, 1: yes
  313. */
  314. bool vending_search(struct map_session_data* sd, unsigned short nameid)
  315. {
  316. int i;
  317. if( !sd->state.vending ) { // not vending
  318. return false;
  319. }
  320. ARR_FIND( 0, sd->vend_num, i, sd->cart.u.items_cart[sd->vending[i].index].nameid == (short)nameid );
  321. if( i == sd->vend_num ) { // not found
  322. return false;
  323. }
  324. return true;
  325. }
  326. /**
  327. * Searches for all items in a vending, that match given ids, price and possible cards.
  328. * @param sd : The vender session to search into
  329. * @param s : parameter of the search (see s_search_store_search)
  330. * @return Whether or not the search should be continued.
  331. */
  332. bool vending_searchall(struct map_session_data* sd, const struct s_search_store_search* s)
  333. {
  334. int i, c, slot;
  335. unsigned int idx, cidx;
  336. struct item* it;
  337. if( !sd->state.vending ) // not vending
  338. return true;
  339. for( idx = 0; idx < s->item_count; idx++ ) {
  340. ARR_FIND( 0, sd->vend_num, i, sd->cart.u.items_cart[sd->vending[i].index].nameid == (short)s->itemlist[idx] );
  341. if( i == sd->vend_num ) { // not found
  342. continue;
  343. }
  344. it = &sd->cart.u.items_cart[sd->vending[i].index];
  345. if( s->min_price && s->min_price > sd->vending[i].value ) { // too low price
  346. continue;
  347. }
  348. if( s->max_price && s->max_price < sd->vending[i].value ) { // too high price
  349. continue;
  350. }
  351. if( s->card_count ) { // check cards
  352. if( itemdb_isspecial(it->card[0]) ) { // something, that is not a carded
  353. continue;
  354. }
  355. slot = itemdb_slot(it->nameid);
  356. for( c = 0; c < slot && it->card[c]; c ++ ) {
  357. ARR_FIND( 0, s->card_count, cidx, s->cardlist[cidx] == it->card[c] );
  358. if( cidx != s->card_count ) { // found
  359. break;
  360. }
  361. }
  362. if( c == slot || !it->card[c] ) { // no card match
  363. continue;
  364. }
  365. }
  366. if( !searchstore_result(s->search_sd, sd->vender_id, sd->status.account_id, sd->message, it->nameid, sd->vending[i].amount, sd->vending[i].value, it->card, it->refine) ) { // result set full
  367. return false;
  368. }
  369. }
  370. return true;
  371. }
  372. /**
  373. * Open vending for Autotrader
  374. * @param sd Player as autotrader
  375. */
  376. void vending_reopen( struct map_session_data* sd )
  377. {
  378. struct s_autotrader *at = NULL;
  379. int8 fail = -1;
  380. nullpo_retv(sd);
  381. // Open vending for this autotrader
  382. if ((at = (struct s_autotrader *)uidb_get(vending_autotrader_db, sd->status.char_id)) && at->count && at->entries) {
  383. uint8 *data, *p;
  384. uint16 j, count;
  385. // Init vending data for autotrader
  386. CREATE(data, uint8, at->count * 8);
  387. for (j = 0, p = data, count = at->count; j < at->count; j++) {
  388. struct s_autotrade_entry *entry = at->entries[j];
  389. uint16 *index = (uint16*)(p + 0);
  390. uint16 *amount = (uint16*)(p + 2);
  391. uint32 *value = (uint32*)(p + 4);
  392. // Find item position in cart
  393. ARR_FIND(0, MAX_CART, entry->index, sd->cart.u.items_cart[entry->index].id == entry->cartinventory_id);
  394. if (entry->index == MAX_CART) {
  395. count--;
  396. continue;
  397. }
  398. *index = entry->index + 2;
  399. *amount = itemdb_isstackable(sd->cart.u.items_cart[entry->index].nameid) ? entry->amount : 1;
  400. *value = entry->price;
  401. p += 8;
  402. }
  403. sd->state.prevend = 1; // Set him into a hacked prevend state
  404. sd->state.autotrade = 1;
  405. // Make sure abort all NPCs
  406. npc_event_dequeue(sd);
  407. pc_cleareventtimer(sd);
  408. // Open the vending again
  409. if( (fail = vending_openvending(sd, at->title, data, count, at)) == 0 ) {
  410. // Make vendor look perfect
  411. pc_setdir(sd, at->dir, at->head_dir);
  412. clif_changed_dir(&sd->bl, AREA_WOS);
  413. if( at->sit ) {
  414. pc_setsit(sd);
  415. skill_sit(sd, 1);
  416. clif_sitting(&sd->bl);
  417. }
  418. // Immediate save
  419. chrif_save(sd, CSAVE_AUTOTRADE);
  420. ShowInfo("Vending loaded for '"CL_WHITE"%s"CL_RESET"' with '"CL_WHITE"%d"CL_RESET"' items at "CL_WHITE"%s (%d,%d)"CL_RESET"\n",
  421. sd->status.name, count, mapindex_id2name(sd->mapindex), sd->bl.x, sd->bl.y);
  422. }
  423. aFree(data);
  424. }
  425. if (at) {
  426. vending_autotrader_remove(at, true);
  427. if (db_size(vending_autotrader_db) == 0)
  428. vending_autotrader_db->clear(vending_autotrader_db, vending_autotrader_free);
  429. }
  430. if (fail != 0) {
  431. ShowError("vending_reopen: (Error:%d) Load failed for autotrader '"CL_WHITE"%s"CL_RESET"' (CID=%d/AID=%d)\n", fail, sd->status.name, sd->status.char_id, sd->status.account_id);
  432. map_quit(sd);
  433. }
  434. }
  435. /**
  436. * Initializing autotraders from table
  437. */
  438. void do_init_vending_autotrade(void)
  439. {
  440. if (battle_config.feature_autotrade) {
  441. if (Sql_Query(mmysql_handle,
  442. "SELECT `id`, `account_id`, `char_id`, `sex`, `title`, `body_direction`, `head_direction`, `sit` "
  443. "FROM `%s` "
  444. "WHERE `autotrade` = 1 AND (SELECT COUNT(`vending_id`) FROM `%s` WHERE `vending_id` = `id`) > 0 "
  445. "ORDER BY `id`;",
  446. vendings_table, vending_items_table ) != SQL_SUCCESS )
  447. {
  448. Sql_ShowDebug(mmysql_handle);
  449. return;
  450. }
  451. if( Sql_NumRows(mmysql_handle) > 0 ) {
  452. uint16 items = 0;
  453. DBIterator *iter = NULL;
  454. struct s_autotrader *at = NULL;
  455. // Init each autotrader data
  456. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle)) {
  457. size_t len;
  458. char* data;
  459. at = NULL;
  460. CREATE(at, struct s_autotrader, 1);
  461. Sql_GetData(mmysql_handle, 0, &data, NULL); at->id = atoi(data);
  462. Sql_GetData(mmysql_handle, 1, &data, NULL); at->account_id = atoi(data);
  463. Sql_GetData(mmysql_handle, 2, &data, NULL); at->char_id = atoi(data);
  464. Sql_GetData(mmysql_handle, 3, &data, NULL); at->sex = (data[0] == 'F') ? SEX_FEMALE : SEX_MALE;
  465. Sql_GetData(mmysql_handle, 4, &data, &len); safestrncpy(at->title, data, zmin(len + 1, MESSAGE_SIZE));
  466. Sql_GetData(mmysql_handle, 5, &data, NULL); at->dir = atoi(data);
  467. Sql_GetData(mmysql_handle, 6, &data, NULL); at->head_dir = atoi(data);
  468. Sql_GetData(mmysql_handle, 7, &data, NULL); at->sit = atoi(data);
  469. at->count = 0;
  470. if (battle_config.feature_autotrade_direction >= 0)
  471. at->dir = battle_config.feature_autotrade_direction;
  472. if (battle_config.feature_autotrade_head_direction >= 0)
  473. at->head_dir = battle_config.feature_autotrade_head_direction;
  474. if (battle_config.feature_autotrade_sit >= 0)
  475. at->sit = battle_config.feature_autotrade_sit;
  476. // initialize player
  477. CREATE(at->sd, struct map_session_data, 1);
  478. pc_setnewpc(at->sd, at->account_id, at->char_id, 0, gettick(), at->sex, 0);
  479. at->sd->state.autotrade = 1|2;
  480. at->sd->state.monster_ignore = (battle_config.autotrade_monsterignore);
  481. chrif_authreq(at->sd, true);
  482. uidb_put(vending_autotrader_db, at->char_id, at);
  483. }
  484. Sql_FreeResult(mmysql_handle);
  485. // Init items for each autotraders
  486. iter = db_iterator(vending_autotrader_db);
  487. for (at = (struct s_autotrader *)dbi_first(iter); dbi_exists(iter); at = (struct s_autotrader *)dbi_next(iter)) {
  488. uint16 j = 0;
  489. if (SQL_ERROR == Sql_Query(mmysql_handle,
  490. "SELECT `cartinventory_id`, `amount`, `price` "
  491. "FROM `%s` "
  492. "WHERE `vending_id` = %d "
  493. "ORDER BY `index` ASC;",
  494. vending_items_table, at->id ) )
  495. {
  496. Sql_ShowDebug(mmysql_handle);
  497. continue;
  498. }
  499. if (!(at->count = (uint16)Sql_NumRows(mmysql_handle))) {
  500. map_quit(at->sd);
  501. vending_autotrader_remove(at, true);
  502. continue;
  503. }
  504. //Init the list
  505. CREATE(at->entries, struct s_autotrade_entry *, at->count);
  506. //Add the item into list
  507. j = 0;
  508. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle) && j < at->count) {
  509. char *data;
  510. CREATE(at->entries[j], struct s_autotrade_entry, 1);
  511. Sql_GetData(mmysql_handle, 0, &data, NULL); at->entries[j]->cartinventory_id = atoi(data);
  512. Sql_GetData(mmysql_handle, 1, &data, NULL); at->entries[j]->amount = atoi(data);
  513. Sql_GetData(mmysql_handle, 2, &data, NULL); at->entries[j]->price = atoi(data);
  514. j++;
  515. }
  516. items += j;
  517. Sql_FreeResult(mmysql_handle);
  518. }
  519. dbi_destroy(iter);
  520. ShowStatus("Done loading '"CL_WHITE"%d"CL_RESET"' vending autotraders with '"CL_WHITE"%d"CL_RESET"' items.\n", db_size(vending_autotrader_db), items);
  521. }
  522. }
  523. // Everything is loaded fine, their entries will be reinserted once they are loaded
  524. if (Sql_Query( mmysql_handle, "DELETE FROM `%s`;", vendings_table ) != SQL_SUCCESS ||
  525. Sql_Query( mmysql_handle, "DELETE FROM `%s`;", vending_items_table ) != SQL_SUCCESS) {
  526. Sql_ShowDebug(mmysql_handle);
  527. }
  528. }
  529. /**
  530. * Remove an autotrader's data
  531. * @param at Autotrader
  532. * @param remove If true will removes from vending_autotrader_db
  533. **/
  534. static void vending_autotrader_remove(struct s_autotrader *at, bool remove) {
  535. nullpo_retv(at);
  536. if (at->count && at->entries) {
  537. uint16 i = 0;
  538. for (i = 0; i < at->count; i++) {
  539. if (at->entries[i])
  540. aFree(at->entries[i]);
  541. }
  542. aFree(at->entries);
  543. }
  544. if (remove)
  545. uidb_remove(vending_autotrader_db, at->char_id);
  546. aFree(at);
  547. }
  548. /**
  549. * Clear all autotraders
  550. * @author [Cydh]
  551. */
  552. static int vending_autotrader_free(DBKey key, DBData *data, va_list ap) {
  553. struct s_autotrader *at = (struct s_autotrader *)db_data2ptr(data);
  554. if (at)
  555. vending_autotrader_remove(at, false);
  556. return 0;
  557. }
  558. /**
  559. * Initialise the vending module
  560. * called in map::do_init
  561. */
  562. void do_final_vending(void)
  563. {
  564. db_destroy(vending_db);
  565. vending_autotrader_db->destroy(vending_autotrader_db, vending_autotrader_free);
  566. }
  567. /**
  568. * Destory the vending module
  569. * called in map::do_final
  570. */
  571. void do_init_vending(void)
  572. {
  573. vending_db = idb_alloc(DB_OPT_BASE);
  574. vending_autotrader_db = uidb_alloc(DB_OPT_BASE);
  575. vending_nextid = 0;
  576. }