buyingstore.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "buyingstore.hpp" // struct s_buyingstore
  4. #include <stdlib.h> // atoi
  5. #include "../common/db.hpp" // ARR_FIND
  6. #include "../common/malloc.hpp" // aMalloc, aFree
  7. #include "../common/nullpo.hpp"
  8. #include "../common/showmsg.hpp" // ShowWarning
  9. #include "../common/socket.hpp" // RBUF*
  10. #include "../common/strlib.hpp" // safestrncpy
  11. #include "../common/timer.hpp" // gettick
  12. #include "atcommand.hpp" // msg_txt
  13. #include "battle.hpp" // battle_config.*
  14. #include "chrif.hpp"
  15. #include "clif.hpp" // clif_buyingstore_*
  16. #include "log.hpp" // log_pick_pc, log_zeny
  17. #include "npc.hpp"
  18. #include "pc.hpp" // struct map_session_data
  19. //Autotrader
  20. static DBMap *buyingstore_autotrader_db; /// Holds autotrader info: char_id -> struct s_autotrader
  21. static void buyingstore_autotrader_remove(struct s_autotrader *at, bool remove);
  22. static int buyingstore_autotrader_free(DBKey key, DBData *data, va_list ap);
  23. /// constants (client-side restrictions)
  24. #define BUYINGSTORE_MAX_PRICE 99990000
  25. #define BUYINGSTORE_MAX_AMOUNT 9999
  26. static DBMap *buyingstore_db;
  27. DBMap *buyingstore_getdb(void) {
  28. return buyingstore_db;
  29. }
  30. /// failure constants for clif functions
  31. enum e_buyingstore_failure
  32. {
  33. BUYINGSTORE_CREATE = 1, // "Failed to open buying store."
  34. BUYINGSTORE_CREATE_OVERWEIGHT = 2, // "Total amount of then possessed items exceeds the weight limit by %d. Please re-enter."
  35. BUYINGSTORE_TRADE_BUYER_ZENY = 3, // "All items within the buy limit were purchased."
  36. BUYINGSTORE_TRADE_BUYER_NO_ITEMS = 4, // "All items were purchased."
  37. BUYINGSTORE_TRADE_SELLER_FAILED = 5, // "The deal has failed."
  38. BUYINGSTORE_TRADE_SELLER_COUNT = 6, // "The trade failed, because the entered amount of item %s is higher, than the buyer is willing to buy."
  39. BUYINGSTORE_TRADE_SELLER_ZENY = 7, // "The trade failed, because the buyer is lacking required balance."
  40. BUYINGSTORE_CREATE_NO_INFO = 8, // "No sale (purchase) information available."
  41. };
  42. static unsigned int buyingstore_nextid = 0;
  43. static const unsigned short buyingstore_blankslots[MAX_SLOTS] = { 0 }; // used when checking whether or not an item's card slots are blank
  44. /// Returns unique buying store id
  45. static unsigned int buyingstore_getuid(void)
  46. {
  47. return ++buyingstore_nextid;
  48. }
  49. /**
  50. * Attempt to setup buying store fast check before create new one
  51. * @param sd
  52. * @param slots Number of item on the list
  53. * @return 0 If success, 1 - Cannot open, 2 - Manner penalty, 3 - Mapflag restiction, 4 - Cell restriction
  54. */
  55. int8 buyingstore_setup(struct map_session_data* sd, unsigned char slots){
  56. nullpo_retr(1, sd);
  57. if (!battle_config.feature_buying_store || sd->state.vending || sd->state.buyingstore || sd->state.trading || slots == 0) {
  58. return 1;
  59. }
  60. if( sd->sc.data[SC_NOCHAT] && (sd->sc.data[SC_NOCHAT]->val1&MANNER_NOROOM) )
  61. {// custom: mute limitation
  62. return 2;
  63. }
  64. if( map_getmapflag(sd->bl.m, MF_NOVENDING) )
  65. {// custom: no vending maps
  66. clif_displaymessage(sd->fd, msg_txt(sd,276)); // "You can't open a shop on this map"
  67. return 3;
  68. }
  69. if( map_getcell(sd->bl.m, sd->bl.x, sd->bl.y, CELL_CHKNOVENDING) )
  70. {// custom: no vending cells
  71. clif_displaymessage(sd->fd, msg_txt(sd,204)); // "You can't open a shop on this cell."
  72. return 4;
  73. }
  74. if( slots > MAX_BUYINGSTORE_SLOTS )
  75. {
  76. ShowWarning("buyingstore_setup: Requested %d slots, but server supports only %d slots.\n", (int)slots, MAX_BUYINGSTORE_SLOTS);
  77. slots = MAX_BUYINGSTORE_SLOTS;
  78. }
  79. sd->buyingstore.slots = slots;
  80. clif_buyingstore_open(sd);
  81. return 0;
  82. }
  83. /**
  84. * Attempt to create new buying store
  85. * @param sd
  86. * @param zenylimit
  87. * @param result
  88. * @param storename
  89. * @param *itemlist { <nameid>.W, <amount>.W, <price>.L }*
  90. * @param count Number of item on the itemlist
  91. * @param at Autotrader info, or NULL if requetsed not from autotrade persistance
  92. * @return 0 If success, 1 - Cannot open, 2 - Manner penalty, 3 - Mapflag restiction, 4 - Cell restriction, 5 - Invalid count/result, 6 - Cannot give item, 7 - Will be overweight
  93. */
  94. int8 buyingstore_create( struct map_session_data* sd, int zenylimit, unsigned char result, const char* storename, const struct PACKET_CZ_REQ_OPEN_BUYING_STORE_sub* itemlist, unsigned int count, struct s_autotrader *at ){
  95. unsigned int i, weight, listidx;
  96. char message_sql[MESSAGE_SIZE*2];
  97. StringBuf buf;
  98. nullpo_retr(1, sd);
  99. if( !result || count == 0 )
  100. {// canceled, or no items
  101. return 5;
  102. }
  103. if( !battle_config.feature_buying_store || pc_istrading(sd) || sd->buyingstore.slots == 0 || count > sd->buyingstore.slots || zenylimit <= 0 || zenylimit > sd->status.zeny || !storename[0] )
  104. {// disabled or invalid input
  105. sd->buyingstore.slots = 0;
  106. clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0);
  107. return 1;
  108. }
  109. if( !pc_can_give_items(sd) )
  110. {// custom: GM is not allowed to buy (give zeny)
  111. sd->buyingstore.slots = 0;
  112. clif_displaymessage(sd->fd, msg_txt(sd,246));
  113. clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0);
  114. return 6;
  115. }
  116. if( sd->sc.data[SC_NOCHAT] && (sd->sc.data[SC_NOCHAT]->val1&MANNER_NOROOM) )
  117. {// custom: mute limitation
  118. return 2;
  119. }
  120. if( map_getmapflag(sd->bl.m, MF_NOVENDING) )
  121. {// custom: no vending maps
  122. clif_displaymessage(sd->fd, msg_txt(sd,276)); // "You can't open a shop on this map"
  123. return 3;
  124. }
  125. if( map_getcell(sd->bl.m, sd->bl.x, sd->bl.y, CELL_CHKNOVENDING) )
  126. {// custom: no vending cells
  127. clif_displaymessage(sd->fd, msg_txt(sd,204)); // "You can't open a shop on this cell."
  128. return 4;
  129. }
  130. weight = sd->weight;
  131. // check item list
  132. for( i = 0; i < count; i++ ){
  133. const struct PACKET_CZ_REQ_OPEN_BUYING_STORE_sub *item = &itemlist[i];
  134. struct item_data* id = itemdb_exists( item->itemId );
  135. // invalid input
  136. if( id == NULL || item->amount == 0 ){
  137. break;
  138. }
  139. // invalid price: unlike vending, items cannot be bought at 0 Zeny
  140. if( item->price <= 0 || item->price > BUYINGSTORE_MAX_PRICE ){
  141. break;
  142. }
  143. // restrictions: allowed and no character-bound items
  144. if( !id->flag.buyingstore || !itemdb_cantrade_sub( id, pc_get_group_level( sd ), pc_get_group_level( sd ) ) ){
  145. break;
  146. }
  147. int idx = pc_search_inventory( sd, item->itemId );
  148. // At least one must be owned
  149. if( idx < 0 ){
  150. break;
  151. }
  152. // too many items of same kind
  153. if( sd->inventory.u.items_inventory[idx].amount + item->amount > BUYINGSTORE_MAX_AMOUNT ){
  154. break;
  155. }
  156. // duplicate check. as the client does this too, only malicious intent should be caught here
  157. if( i ){
  158. ARR_FIND( 0, i, listidx, sd->buyingstore.items[listidx].nameid == item->itemId );
  159. // duplicate
  160. if( listidx != i ){
  161. ShowWarning( "buyingstore_create: Found duplicate item on buying list (nameid=%hu, amount=%hu, account_id=%d, char_id=%d).\n", item->itemId, item->amount, sd->status.account_id, sd->status.char_id );
  162. break;
  163. }
  164. }
  165. weight+= id->weight*item->amount;
  166. sd->buyingstore.items[i].nameid = item->itemId;
  167. sd->buyingstore.items[i].amount = item->amount;
  168. sd->buyingstore.items[i].price = item->price;
  169. }
  170. if( i != count )
  171. {// invalid item/amount/price
  172. sd->buyingstore.slots = 0;
  173. clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0);
  174. return 5;
  175. }
  176. if( (sd->max_weight*90)/100 < weight )
  177. {// not able to carry all wanted items without getting overweight (90%)
  178. sd->buyingstore.slots = 0;
  179. clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE_OVERWEIGHT, weight);
  180. return 7;
  181. }
  182. // success
  183. sd->state.buyingstore = true;
  184. sd->buyer_id = buyingstore_getuid();
  185. sd->buyingstore.zenylimit = zenylimit;
  186. sd->buyingstore.slots = i; // store actual amount of items
  187. safestrncpy(sd->message, storename, sizeof(sd->message));
  188. Sql_EscapeString( mmysql_handle, message_sql, sd->message );
  189. if( Sql_Query( mmysql_handle, "INSERT INTO `%s`(`id`, `account_id`, `char_id`, `sex`, `map`, `x`, `y`, `title`, `limit`, `autotrade`, `body_direction`, `head_direction`, `sit`) "
  190. "VALUES( %d, %d, %d, '%c', '%s', %d, %d, '%s', %d, %d, '%d', '%d', '%d' );",
  191. buyingstores_table, sd->buyer_id, sd->status.account_id, sd->status.char_id, sd->status.sex == 0 ? 'F' : 'M', map_getmapdata(sd->bl.m)->name, sd->bl.x, sd->bl.y, message_sql, sd->buyingstore.zenylimit, sd->state.autotrade, at ? at->dir : sd->ud.dir, at ? at->head_dir : sd->head_dir, at ? at->sit : pc_issit(sd) ) != SQL_SUCCESS ){
  192. Sql_ShowDebug(mmysql_handle);
  193. }
  194. StringBuf_Init(&buf);
  195. StringBuf_Printf(&buf, "INSERT INTO `%s`(`buyingstore_id`,`index`,`item_id`,`amount`,`price`) VALUES", buyingstore_items_table);
  196. for (i = 0; i < sd->buyingstore.slots; i++){
  197. StringBuf_Printf(&buf, "(%d,%d,%hu,%d,%d)", sd->buyer_id, i, sd->buyingstore.items[i].nameid, sd->buyingstore.items[i].amount, sd->buyingstore.items[i].price);
  198. if (i < sd->buyingstore.slots-1)
  199. StringBuf_AppendStr(&buf, ",");
  200. }
  201. if (SQL_ERROR == Sql_QueryStr(mmysql_handle, StringBuf_Value(&buf)))
  202. Sql_ShowDebug(mmysql_handle);
  203. StringBuf_Destroy(&buf);
  204. clif_buyingstore_myitemlist(sd);
  205. clif_buyingstore_entry(sd);
  206. idb_put(buyingstore_db, sd->status.char_id, sd);
  207. return 0;
  208. }
  209. /**
  210. * Close buying store and clear buying store data from tables
  211. * @param sd
  212. */
  213. void buyingstore_close(struct map_session_data* sd) {
  214. nullpo_retv(sd);
  215. if( sd->state.buyingstore ) {
  216. if(
  217. Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE buyingstore_id = %d;", buyingstore_items_table, sd->buyer_id ) != SQL_SUCCESS ||
  218. Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE `id` = %d;", buyingstores_table, sd->buyer_id ) != SQL_SUCCESS
  219. ) {
  220. Sql_ShowDebug(mmysql_handle);
  221. }
  222. sd->state.buyingstore = false;
  223. sd->buyer_id = 0;
  224. memset(&sd->buyingstore, 0, sizeof(sd->buyingstore));
  225. idb_remove(buyingstore_db, sd->status.char_id);
  226. // notify other players
  227. clif_buyingstore_disappear_entry(sd);
  228. }
  229. }
  230. /**
  231. * Open buying store from buyer
  232. * @param sd Player
  233. * @param account_id Buyer account ID
  234. */
  235. void buyingstore_open(struct map_session_data* sd, uint32 account_id)
  236. {
  237. struct map_session_data* pl_sd;
  238. nullpo_retv(sd);
  239. if( !battle_config.feature_buying_store || pc_istrading(sd) )
  240. {// not allowed to sell
  241. return;
  242. }
  243. if( !pc_can_give_items(sd) )
  244. {// custom: GM is not allowed to sell
  245. clif_displaymessage(sd->fd, msg_txt(sd,246));
  246. return;
  247. }
  248. if( ( pl_sd = map_id2sd(account_id) ) == NULL || !pl_sd->state.buyingstore )
  249. {// not online or not buying
  250. return;
  251. }
  252. if( !searchstore_queryremote(sd, account_id) && ( sd->bl.m != pl_sd->bl.m || !check_distance_bl(&sd->bl, &pl_sd->bl, AREA_SIZE) ) )
  253. {// out of view range
  254. return;
  255. }
  256. // success
  257. clif_buyingstore_itemlist(sd, pl_sd);
  258. }
  259. /**
  260. * Start transaction
  261. * @param sd Player/Seller
  262. * @param account_id Buyer account ID
  263. * @param *itemlist List of sold items { <index>.W, <nameid>.W, <amount>.W }*
  264. * @param count Number of item on the itemlist
  265. */
  266. void buyingstore_trade( struct map_session_data* sd, uint32 account_id, unsigned int buyer_id, const struct PACKET_CZ_REQ_TRADE_BUYING_STORE_sub* itemlist, unsigned int count ){
  267. int zeny = 0;
  268. unsigned int weight;
  269. struct map_session_data* pl_sd;
  270. nullpo_retv(sd);
  271. if( count == 0 )
  272. {// nothing to do
  273. return;
  274. }
  275. if( !battle_config.feature_buying_store || pc_istrading(sd) )
  276. {// not allowed to sell
  277. clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
  278. return;
  279. }
  280. if( !pc_can_give_items(sd) )
  281. {// custom: GM is not allowed to sell
  282. clif_displaymessage(sd->fd, msg_txt(sd,246));
  283. clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
  284. return;
  285. }
  286. if( ( pl_sd = map_id2sd(account_id) ) == NULL || !pl_sd->state.buyingstore || pl_sd->buyer_id != buyer_id )
  287. {// not online, not buying or not same store
  288. clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
  289. return;
  290. }
  291. if( !searchstore_queryremote(sd, account_id) && ( sd->bl.m != pl_sd->bl.m || !check_distance_bl(&sd->bl, &pl_sd->bl, AREA_SIZE) ) )
  292. {// out of view range
  293. clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
  294. return;
  295. }
  296. searchstore_clearremote(sd);
  297. // buyer lost zeny in the mean time? fix the limit
  298. if( pl_sd->status.zeny < pl_sd->buyingstore.zenylimit ){
  299. pl_sd->buyingstore.zenylimit = pl_sd->status.zeny;
  300. }
  301. weight = pl_sd->weight;
  302. // check item list
  303. for( int i = 0; i < count; i++ ){
  304. const struct PACKET_CZ_REQ_TRADE_BUYING_STORE_sub* item = &itemlist[i];
  305. // duplicate check. as the client does this too, only malicious intent should be caught here
  306. for( int k = 0; k < i; k++ ){
  307. // duplicate
  308. if( itemlist[k].index == item->index && k != i ){
  309. ShowWarning( "buyingstore_trade: Found duplicate item on selling list (prevnameid=%hu, prevamount=%hu, nameid=%hu, amount=%hu, account_id=%d, char_id=%d).\n", itemlist[k].itemId, itemlist[k].amount, item->itemId, item->amount, sd->status.account_id, sd->status.char_id );
  310. clif_buyingstore_trade_failed_seller( sd, BUYINGSTORE_TRADE_SELLER_FAILED, item->itemId );
  311. return;
  312. }
  313. }
  314. int index = item->index - 2; // TODO: clif::server_index
  315. // invalid input
  316. if( index < 0 || index >= ARRAYLENGTH( sd->inventory.u.items_inventory ) || sd->inventory_data[index] == NULL || sd->inventory.u.items_inventory[index].nameid != item->itemId || sd->inventory.u.items_inventory[index].amount < item->amount ){
  317. clif_buyingstore_trade_failed_seller( sd, BUYINGSTORE_TRADE_SELLER_FAILED, item->itemId );
  318. return;
  319. }
  320. // non-tradable item
  321. if( sd->inventory.u.items_inventory[index].expire_time || ( sd->inventory.u.items_inventory[index].bound && !pc_can_give_bounded_items( sd ) ) || !itemdb_cantrade( &sd->inventory.u.items_inventory[index], pc_get_group_level( sd ), pc_get_group_level( pl_sd ) ) || memcmp( sd->inventory.u.items_inventory[index].card, buyingstore_blankslots, sizeof( buyingstore_blankslots ) ) ){
  322. clif_buyingstore_trade_failed_seller( sd, BUYINGSTORE_TRADE_SELLER_FAILED, item->itemId );
  323. return;
  324. }
  325. int listidx;
  326. ARR_FIND( 0, pl_sd->buyingstore.slots, listidx, pl_sd->buyingstore.items[listidx].nameid == item->itemId );
  327. // there is no such item or the buyer has already bought all of them
  328. if( listidx == pl_sd->buyingstore.slots || pl_sd->buyingstore.items[listidx].amount == 0 ){
  329. clif_buyingstore_trade_failed_seller( sd, BUYINGSTORE_TRADE_SELLER_FAILED, item->itemId );
  330. return;
  331. }
  332. // buyer does not need that much of the item
  333. if( pl_sd->buyingstore.items[listidx].amount < item->amount ){
  334. clif_buyingstore_trade_failed_seller( sd, BUYINGSTORE_TRADE_SELLER_COUNT, item->itemId );
  335. return;
  336. }
  337. // buyer does not have enough space for this item
  338. if( pc_checkadditem( pl_sd, item->itemId, item->amount ) == CHKADDITEM_OVERAMOUNT ){
  339. clif_buyingstore_trade_failed_seller( sd, BUYINGSTORE_TRADE_SELLER_FAILED, item->itemId );
  340. return;
  341. }
  342. // normally this is not supposed to happen, as the total weight is
  343. // checked upon creation, but the buyer could have gained items
  344. if( item->amount * (unsigned int)sd->inventory_data[index]->weight > pl_sd->max_weight - weight ){
  345. clif_buyingstore_trade_failed_seller( sd, BUYINGSTORE_TRADE_SELLER_FAILED, item->itemId );
  346. return;
  347. }
  348. weight += item->amount * sd->inventory_data[index]->weight;
  349. // buyer does not have enough zeny
  350. if( item->amount * pl_sd->buyingstore.items[listidx].price > pl_sd->buyingstore.zenylimit - zeny ){
  351. clif_buyingstore_trade_failed_seller( sd, BUYINGSTORE_TRADE_SELLER_ZENY, item->itemId );
  352. return;
  353. }
  354. zeny += item->amount * pl_sd->buyingstore.items[listidx].price;
  355. }
  356. // process item list
  357. for( int i = 0; i < count; i++ ){
  358. const struct PACKET_CZ_REQ_TRADE_BUYING_STORE_sub* item = &itemlist[i];
  359. int listidx;
  360. ARR_FIND( 0, pl_sd->buyingstore.slots, listidx, pl_sd->buyingstore.items[listidx].nameid == item->itemId );
  361. zeny = item->amount * pl_sd->buyingstore.items[listidx].price;
  362. int index = item->index - 2; // TODO: clif::server_index
  363. // move item
  364. pc_additem(pl_sd, &sd->inventory.u.items_inventory[index], item->amount, LOG_TYPE_BUYING_STORE);
  365. pc_delitem(sd, index, item->amount, 1, 0, LOG_TYPE_BUYING_STORE);
  366. pl_sd->buyingstore.items[listidx].amount -= item->amount;
  367. if( pl_sd->buyingstore.items[listidx].amount > 0 ){
  368. if( Sql_Query( mmysql_handle, "UPDATE `%s` SET `amount` = %d WHERE `buyingstore_id` = %d AND `index` = %d;", buyingstore_items_table, pl_sd->buyingstore.items[listidx].amount, pl_sd->buyer_id, listidx ) != SQL_SUCCESS ){
  369. Sql_ShowDebug( mmysql_handle );
  370. }
  371. }else{
  372. if( Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE `buyingstore_id` = %d AND `index` = %d;", buyingstore_items_table, pl_sd->buyer_id, listidx ) != SQL_SUCCESS ){
  373. Sql_ShowDebug( mmysql_handle );
  374. }
  375. }
  376. // pay up
  377. pc_payzeny(pl_sd, zeny, LOG_TYPE_BUYING_STORE, sd);
  378. pc_getzeny(sd, zeny, LOG_TYPE_BUYING_STORE, pl_sd);
  379. pl_sd->buyingstore.zenylimit-= zeny;
  380. // notify clients
  381. clif_buyingstore_delete_item(sd, index, item->amount, pl_sd->buyingstore.items[listidx].price);
  382. clif_buyingstore_update_item(pl_sd, item->itemId, item->amount, sd->status.char_id, zeny);
  383. }
  384. if( save_settings&CHARSAVE_VENDING ) {
  385. chrif_save(sd, CSAVE_NORMAL|CSAVE_INVENTORY);
  386. chrif_save(pl_sd, CSAVE_NORMAL|CSAVE_INVENTORY);
  387. }
  388. // check whether or not there is still something to buy
  389. int i;
  390. ARR_FIND( 0, pl_sd->buyingstore.slots, i, pl_sd->buyingstore.items[i].amount != 0 );
  391. if( i == pl_sd->buyingstore.slots )
  392. {// everything was bought
  393. clif_buyingstore_trade_failed_buyer(pl_sd, BUYINGSTORE_TRADE_BUYER_NO_ITEMS);
  394. }
  395. else if( pl_sd->buyingstore.zenylimit == 0 )
  396. {// zeny limit reached
  397. clif_buyingstore_trade_failed_buyer(pl_sd, BUYINGSTORE_TRADE_BUYER_ZENY);
  398. }
  399. else
  400. {// continue buying
  401. if( Sql_Query( mmysql_handle, "UPDATE `%s` SET `limit` = %d WHERE `id` = %d;", buyingstores_table, pl_sd->buyingstore.zenylimit, pl_sd->buyer_id ) != SQL_SUCCESS ){
  402. Sql_ShowDebug( mmysql_handle );
  403. }
  404. return;
  405. }
  406. // cannot continue buying
  407. buyingstore_close(pl_sd);
  408. // remove auto-trader
  409. if( pl_sd->state.autotrade )
  410. {
  411. map_quit(pl_sd);
  412. }
  413. }
  414. /// Checks if an item is being bought in given player's buying store.
  415. bool buyingstore_search(struct map_session_data* sd, unsigned short nameid)
  416. {
  417. unsigned int i;
  418. nullpo_ret(sd);
  419. if( !sd->state.buyingstore )
  420. {// not buying
  421. return false;
  422. }
  423. ARR_FIND( 0, sd->buyingstore.slots, i, sd->buyingstore.items[i].nameid == nameid && sd->buyingstore.items[i].amount );
  424. if( i == sd->buyingstore.slots )
  425. {// not found
  426. return false;
  427. }
  428. return true;
  429. }
  430. /// Searches for all items in a buyingstore, that match given ids, price and possible cards.
  431. /// @return Whether or not the search should be continued.
  432. bool buyingstore_searchall(struct map_session_data* sd, const struct s_search_store_search* s)
  433. {
  434. unsigned int i, idx;
  435. struct s_buyingstore_item* it;
  436. nullpo_ret(sd);
  437. if( !sd->state.buyingstore )
  438. {// not buying
  439. return true;
  440. }
  441. for( idx = 0; idx < s->item_count; idx++ )
  442. {
  443. ARR_FIND( 0, sd->buyingstore.slots, i, sd->buyingstore.items[i].nameid == s->itemlist[idx].itemId && sd->buyingstore.items[i].amount );
  444. if( i == sd->buyingstore.slots )
  445. {// not found
  446. continue;
  447. }
  448. it = &sd->buyingstore.items[i];
  449. if( s->min_price && s->min_price > (unsigned int)it->price )
  450. {// too low price
  451. continue;
  452. }
  453. if( s->max_price && s->max_price < (unsigned int)it->price )
  454. {// too high price
  455. continue;
  456. }
  457. if( s->card_count )
  458. {// ignore cards, as there cannot be any
  459. ;
  460. }
  461. if( !searchstore_result(s->search_sd, sd->buyer_id, sd->status.account_id, sd->message, it->nameid, it->amount, it->price, buyingstore_blankslots, 0) )
  462. {// result set full
  463. return false;
  464. }
  465. }
  466. return true;
  467. }
  468. /**
  469. * Open buyingstore for Autotrader
  470. * @param sd Player as autotrader
  471. */
  472. void buyingstore_reopen( struct map_session_data* sd ){
  473. struct s_autotrader *at = NULL;
  474. int8 fail = -1;
  475. nullpo_retv(sd);
  476. // Ready to open buyingstore for this char
  477. if ((at = (struct s_autotrader *)uidb_get(buyingstore_autotrader_db, sd->status.char_id)) && at->count && at->entries) {
  478. struct PACKET_CZ_REQ_OPEN_BUYING_STORE_sub* data;
  479. // Init buyingstore data for autotrader
  480. CREATE(data, struct PACKET_CZ_REQ_OPEN_BUYING_STORE_sub, at->count );
  481. for( int j = 0; j < at->count; j++) {
  482. data[j].itemId = at->entries[j]->item_id;
  483. data[j].amount = at->entries[j]->amount;
  484. data[j].price = at->entries[j]->price;
  485. }
  486. sd->state.autotrade = 1;
  487. // Make sure abort all NPCs
  488. npc_event_dequeue(sd);
  489. pc_cleareventtimer(sd);
  490. // Open the buyingstore again
  491. if( (fail = buyingstore_setup( sd, (unsigned char)at->count )) == 0 &&
  492. (fail = buyingstore_create( sd, at->limit, 1, at->title, data, at->count, at )) == 0 )
  493. {
  494. // Make buyer look perfect
  495. pc_setdir(sd, at->dir, at->head_dir);
  496. clif_changed_dir(&sd->bl, AREA_WOS);
  497. if( at->sit ) {
  498. pc_setsit(sd);
  499. skill_sit(sd, 1);
  500. clif_sitting(&sd->bl);
  501. }
  502. // Immediate save
  503. chrif_save(sd, CSAVE_AUTOTRADE);
  504. ShowInfo("Buyingstore loaded for '" CL_WHITE "%s" CL_RESET "' with '" CL_WHITE "%d" CL_RESET "' items at " CL_WHITE "%s (%d,%d)" CL_RESET "\n",
  505. sd->status.name, at->count, mapindex_id2name(sd->mapindex), sd->bl.x, sd->bl.y);
  506. }
  507. aFree(data);
  508. }
  509. if (at) {
  510. buyingstore_autotrader_remove(at, true);
  511. if (db_size(buyingstore_autotrader_db) == 0)
  512. buyingstore_autotrader_db->clear(buyingstore_autotrader_db, buyingstore_autotrader_free);
  513. }
  514. if (fail != 0) {
  515. ShowError("buyingstore_reopen: (Error:%d) Load failed for autotrader '" CL_WHITE "%s" CL_RESET "' (CID=%/AID=%d)\n", fail, sd->status.name, sd->status.char_id, sd->status.account_id);
  516. map_quit(sd);
  517. }
  518. }
  519. /**
  520. * Initializing autotraders from table
  521. */
  522. void do_init_buyingstore_autotrade( void ) {
  523. if(battle_config.feature_autotrade) {
  524. if (Sql_Query(mmysql_handle,
  525. "SELECT `id`, `account_id`, `char_id`, `sex`, `title`, `limit`, `body_direction`, `head_direction`, `sit` "
  526. "FROM `%s` "
  527. "WHERE `autotrade` = 1 AND `limit` > 0 AND (SELECT COUNT(`buyingstore_id`) FROM `%s` WHERE `buyingstore_id` = `id`) > 0 "
  528. "ORDER BY `id`;",
  529. buyingstores_table, buyingstore_items_table ) != SQL_SUCCESS )
  530. {
  531. Sql_ShowDebug(mmysql_handle);
  532. return;
  533. }
  534. if( Sql_NumRows(mmysql_handle) > 0 ) {
  535. uint16 items = 0;
  536. DBIterator *iter = NULL;
  537. struct s_autotrader *at = NULL;
  538. // Init each autotrader data
  539. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle)) {
  540. size_t len;
  541. char* data;
  542. at = NULL;
  543. CREATE(at, struct s_autotrader, 1);
  544. Sql_GetData(mmysql_handle, 0, &data, NULL); at->id = atoi(data);
  545. Sql_GetData(mmysql_handle, 1, &data, NULL); at->account_id = atoi(data);
  546. Sql_GetData(mmysql_handle, 2, &data, NULL); at->char_id = atoi(data);
  547. Sql_GetData(mmysql_handle, 3, &data, NULL); at->sex = (data[0] == 'F') ? 0 : 1;
  548. Sql_GetData(mmysql_handle, 4, &data, &len); safestrncpy(at->title, data, zmin(len + 1, MESSAGE_SIZE));
  549. Sql_GetData(mmysql_handle, 5, &data, NULL); at->limit = atoi(data);
  550. Sql_GetData(mmysql_handle, 6, &data, NULL); at->dir = atoi(data);
  551. Sql_GetData(mmysql_handle, 7, &data, NULL); at->head_dir = atoi(data);
  552. Sql_GetData(mmysql_handle, 8, &data, NULL); at->sit = atoi(data);
  553. at->count = 0;
  554. if (battle_config.feature_autotrade_direction >= 0)
  555. at->dir = battle_config.feature_autotrade_direction;
  556. if (battle_config.feature_autotrade_head_direction >= 0)
  557. at->head_dir = battle_config.feature_autotrade_head_direction;
  558. if (battle_config.feature_autotrade_sit >= 0)
  559. at->sit = battle_config.feature_autotrade_sit;
  560. // initialize player
  561. CREATE(at->sd, struct map_session_data, 1);
  562. pc_setnewpc(at->sd, at->account_id, at->char_id, 0, gettick(), at->sex, 0);
  563. at->sd->state.autotrade = 1|4;
  564. if (battle_config.autotrade_monsterignore)
  565. at->sd->state.block_action |= PCBLOCK_IMMUNE;
  566. else
  567. at->sd->state.block_action &= ~PCBLOCK_IMMUNE;
  568. chrif_authreq(at->sd, true);
  569. uidb_put(buyingstore_autotrader_db, at->char_id, at);
  570. }
  571. Sql_FreeResult(mmysql_handle);
  572. // Init items for each autotraders
  573. iter = db_iterator(buyingstore_autotrader_db);
  574. for (at = (struct s_autotrader *)dbi_first(iter); dbi_exists(iter); at = (struct s_autotrader *)dbi_next(iter)) {
  575. uint16 j = 0;
  576. if (SQL_ERROR == Sql_Query(mmysql_handle,
  577. "SELECT `item_id`, `amount`, `price` "
  578. "FROM `%s` "
  579. "WHERE `buyingstore_id` = %d "
  580. "ORDER BY `index` ASC;",
  581. buyingstore_items_table, at->id ) )
  582. {
  583. Sql_ShowDebug(mmysql_handle);
  584. continue;
  585. }
  586. if (!(at->count = (uint16)Sql_NumRows(mmysql_handle))) {
  587. map_quit(at->sd);
  588. buyingstore_autotrader_remove(at, true);
  589. continue;
  590. }
  591. //Init the list
  592. CREATE(at->entries, struct s_autotrade_entry *,at->count);
  593. //Add the item into list
  594. j = 0;
  595. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle) && j < at->count) {
  596. char *data;
  597. CREATE(at->entries[j], struct s_autotrade_entry, 1);
  598. Sql_GetData(mmysql_handle, 0, &data, NULL); at->entries[j]->item_id = atoi(data);
  599. Sql_GetData(mmysql_handle, 1, &data, NULL); at->entries[j]->amount = atoi(data);
  600. Sql_GetData(mmysql_handle, 2, &data, NULL); at->entries[j]->price = atoi(data);
  601. j++;
  602. }
  603. items += j;
  604. Sql_FreeResult(mmysql_handle);
  605. }
  606. dbi_destroy(iter);
  607. ShowStatus("Done loading '" CL_WHITE "%d" CL_RESET "' buyingstore autotraders with '" CL_WHITE "%d" CL_RESET "' items.\n", db_size(buyingstore_autotrader_db), items);
  608. }
  609. }
  610. // Everything is loaded fine, their entries will be reinserted once they are loaded
  611. if (Sql_Query( mmysql_handle, "DELETE FROM `%s`;", buyingstores_table ) != SQL_SUCCESS ||
  612. Sql_Query( mmysql_handle, "DELETE FROM `%s`;", buyingstore_items_table ) != SQL_SUCCESS)
  613. {
  614. Sql_ShowDebug(mmysql_handle);
  615. }
  616. }
  617. /**
  618. * Remove an autotrader's data
  619. * @param at Autotrader
  620. * @param remove If true will removes from buyingstore_autotrader_db
  621. **/
  622. static void buyingstore_autotrader_remove(struct s_autotrader *at, bool remove) {
  623. nullpo_retv(at);
  624. if (at->count && at->entries) {
  625. uint16 i = 0;
  626. for (i = 0; i < at->count; i++) {
  627. if (at->entries[i])
  628. aFree(at->entries[i]);
  629. }
  630. aFree(at->entries);
  631. }
  632. if (remove)
  633. uidb_remove(buyingstore_autotrader_db, at->char_id);
  634. aFree(at);
  635. }
  636. /**
  637. * Clear all autotraders
  638. * @author [Cydh]
  639. */
  640. static int buyingstore_autotrader_free(DBKey key, DBData *data, va_list ap) {
  641. struct s_autotrader *at = (struct s_autotrader *)db_data2ptr(data);
  642. if (at)
  643. buyingstore_autotrader_remove(at, false);
  644. return 0;
  645. }
  646. /**
  647. * Initialise the buyingstore module
  648. * called in map::do_init
  649. */
  650. void do_final_buyingstore(void) {
  651. db_destroy(buyingstore_db);
  652. buyingstore_autotrader_db->destroy(buyingstore_autotrader_db, buyingstore_autotrader_free);
  653. }
  654. /**
  655. * Destory the buyingstore module
  656. * called in map::do_final
  657. */
  658. void do_init_buyingstore(void) {
  659. buyingstore_db = idb_alloc(DB_OPT_BASE);
  660. buyingstore_autotrader_db = uidb_alloc(DB_OPT_BASE);
  661. buyingstore_nextid = 0;
  662. }