buyingstore.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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 <cstdlib> // 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" // 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 uint32 buyingstore_nextid = 0;
  43. static const t_itemid 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 uint32 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(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.getSCE(SC_NOCHAT) && (sd->sc.getSCE(SC_NOCHAT)->val1&MANNER_NOROOM) )
  61. {// custom: mute limitation
  62. return 2;
  63. }
  64. if( map_getmapflag(sd->bl.m, MF_NOBUYINGSTORE) )
  65. {// custom: no buyingstore 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_CHKNOBUYINGSTORE) )
  70. {// custom: no buyingstore 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 nullptr 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( map_session_data* sd, int zenylimit, unsigned char result, const char* storename, const struct PACKET_CZ_REQ_OPEN_BUYING_STORE_sub* itemlist, uint32 count, struct s_autotrader *at ){
  95. uint32 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.getSCE(SC_NOCHAT) && (sd->sc.getSCE(SC_NOCHAT)->val1&MANNER_NOROOM) )
  117. {// custom: mute limitation
  118. return 2;
  119. }
  120. if( map_getmapflag(sd->bl.m, MF_NOBUYINGSTORE) )
  121. {// custom: no buyingstore 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_CHKNOBUYINGSTORE) )
  126. {// custom: no buyingstore 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. std::shared_ptr<item_data> id = item_db.find(item->itemId);
  135. // invalid input
  136. if( id == nullptr || 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.get(), 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=%u, 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,%u,%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(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(map_session_data* sd, uint32 account_id)
  236. {
  237. 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) ) == nullptr || !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( map_session_data* sd, uint32 account_id, uint32 buyer_id, const struct PACKET_CZ_REQ_TRADE_BUYING_STORE_sub* itemlist, uint32 count ){
  267. int zeny = 0;
  268. uint32 weight;
  269. 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) ) == nullptr || !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=%u, prevamount=%hu, nameid=%u, 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] == nullptr || 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 * (uint32)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->status.char_id);
  378. pc_getzeny(sd, zeny, LOG_TYPE_BUYING_STORE, pl_sd->status.char_id);
  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(map_session_data* sd, t_itemid nameid)
  416. {
  417. uint32 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(map_session_data* sd, const struct s_search_store_search* s)
  433. {
  434. uint32 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 > (uint32)it->price )
  450. {// too low price
  451. continue;
  452. }
  453. if( s->max_price && s->max_price < (uint32)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. // Check if the result set is full
  462. if( s->search_sd->searchstore.items.size() >= (uint32)battle_config.searchstore_maxresults ){
  463. return false;
  464. }
  465. std::shared_ptr<s_search_store_info_item> ssitem = std::make_shared<s_search_store_info_item>();
  466. ssitem->store_id = sd->buyer_id;
  467. ssitem->account_id = sd->status.account_id;
  468. safestrncpy( ssitem->store_name, sd->message, sizeof( ssitem->store_name ) );
  469. ssitem->nameid = it->nameid;
  470. ssitem->amount = it->amount;
  471. ssitem->price = it->price;
  472. for( int j = 0; j < MAX_SLOTS; j++ ){
  473. ssitem->card[j] = 0;
  474. }
  475. ssitem->refine = 0;
  476. ssitem->enchantgrade = 0;
  477. s->search_sd->searchstore.items.push_back( ssitem );
  478. }
  479. return true;
  480. }
  481. /**
  482. * Open buyingstore for Autotrader
  483. * @param sd Player as autotrader
  484. */
  485. void buyingstore_reopen( map_session_data* sd ){
  486. struct s_autotrader *at = nullptr;
  487. int8 fail = -1;
  488. nullpo_retv(sd);
  489. // Ready to open buyingstore for this char
  490. if ((at = (struct s_autotrader *)uidb_get(buyingstore_autotrader_db, sd->status.char_id)) && at->count && at->entries) {
  491. struct PACKET_CZ_REQ_OPEN_BUYING_STORE_sub* data;
  492. // Init buyingstore data for autotrader
  493. CREATE(data, struct PACKET_CZ_REQ_OPEN_BUYING_STORE_sub, at->count );
  494. for( int j = 0; j < at->count; j++) {
  495. data[j].itemId = at->entries[j]->item_id;
  496. data[j].amount = at->entries[j]->amount;
  497. data[j].price = at->entries[j]->price;
  498. }
  499. sd->state.autotrade = 1;
  500. // Make sure abort all NPCs
  501. npc_event_dequeue(sd);
  502. pc_cleareventtimer(sd);
  503. // Open the buyingstore again
  504. if( (fail = buyingstore_setup( sd, (unsigned char)at->count )) == 0 &&
  505. (fail = buyingstore_create( sd, at->limit, 1, at->title, data, at->count, at )) == 0 )
  506. {
  507. // Make buyer look perfect
  508. pc_setdir(sd, at->dir, at->head_dir);
  509. clif_changed_dir(sd->bl, AREA_WOS);
  510. if( at->sit ) {
  511. pc_setsit(sd);
  512. skill_sit(sd, 1);
  513. clif_sitting(sd->bl);
  514. }
  515. // Immediate save
  516. chrif_save(sd, CSAVE_AUTOTRADE);
  517. 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",
  518. sd->status.name, at->count, mapindex_id2name(sd->mapindex), sd->bl.x, sd->bl.y);
  519. }
  520. aFree(data);
  521. }
  522. if (at) {
  523. buyingstore_autotrader_remove(at, true);
  524. if (db_size(buyingstore_autotrader_db) == 0)
  525. buyingstore_autotrader_db->clear(buyingstore_autotrader_db, buyingstore_autotrader_free);
  526. }
  527. if (fail != 0) {
  528. 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);
  529. map_quit(sd);
  530. }
  531. }
  532. /**
  533. * Initializing autotraders from table
  534. */
  535. void do_init_buyingstore_autotrade( void ) {
  536. if(battle_config.feature_autotrade) {
  537. if (Sql_Query(mmysql_handle,
  538. "SELECT `id`, `account_id`, `char_id`, `sex`, `title`, `limit`, `body_direction`, `head_direction`, `sit` "
  539. "FROM `%s` "
  540. "WHERE `autotrade` = 1 AND `limit` > 0 AND (SELECT COUNT(`buyingstore_id`) FROM `%s` WHERE `buyingstore_id` = `id`) > 0 "
  541. "ORDER BY `id`;",
  542. buyingstores_table, buyingstore_items_table ) != SQL_SUCCESS )
  543. {
  544. Sql_ShowDebug(mmysql_handle);
  545. return;
  546. }
  547. if( Sql_NumRows(mmysql_handle) > 0 ) {
  548. uint16 items = 0;
  549. DBIterator *iter = nullptr;
  550. struct s_autotrader *at = nullptr;
  551. // Init each autotrader data
  552. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle)) {
  553. size_t len;
  554. char* data;
  555. at = nullptr;
  556. CREATE(at, struct s_autotrader, 1);
  557. Sql_GetData(mmysql_handle, 0, &data, nullptr); at->id = atoi(data);
  558. Sql_GetData(mmysql_handle, 1, &data, nullptr); at->account_id = atoi(data);
  559. Sql_GetData(mmysql_handle, 2, &data, nullptr); at->char_id = atoi(data);
  560. Sql_GetData(mmysql_handle, 3, &data, nullptr); at->sex = (data[0] == 'F') ? SEX_FEMALE : SEX_MALE;
  561. Sql_GetData(mmysql_handle, 4, &data, &len); safestrncpy(at->title, data, zmin(len + 1, MESSAGE_SIZE));
  562. Sql_GetData(mmysql_handle, 5, &data, nullptr); at->limit = atoi(data);
  563. Sql_GetData(mmysql_handle, 6, &data, nullptr); at->dir = atoi(data);
  564. Sql_GetData(mmysql_handle, 7, &data, nullptr); at->head_dir = atoi(data);
  565. Sql_GetData(mmysql_handle, 8, &data, nullptr); at->sit = atoi(data);
  566. at->count = 0;
  567. if (battle_config.feature_autotrade_direction >= 0)
  568. at->dir = battle_config.feature_autotrade_direction;
  569. if (battle_config.feature_autotrade_head_direction >= 0)
  570. at->head_dir = battle_config.feature_autotrade_head_direction;
  571. if (battle_config.feature_autotrade_sit >= 0)
  572. at->sit = battle_config.feature_autotrade_sit;
  573. // initialize player
  574. CREATE(at->sd, map_session_data, 1); // TODO: Dont use Memory Manager allocation anymore and rely on the C++ container
  575. new (at->sd) map_session_data();
  576. pc_setnewpc(at->sd, at->account_id, at->char_id, 0, gettick(), at->sex, 0);
  577. at->sd->state.autotrade = 1|4;
  578. if (battle_config.autotrade_monsterignore)
  579. at->sd->state.block_action |= PCBLOCK_IMMUNE;
  580. else
  581. at->sd->state.block_action &= ~PCBLOCK_IMMUNE;
  582. chrif_authreq(at->sd, true);
  583. uidb_put(buyingstore_autotrader_db, at->char_id, at);
  584. }
  585. Sql_FreeResult(mmysql_handle);
  586. // Init items for each autotraders
  587. iter = db_iterator(buyingstore_autotrader_db);
  588. for (at = (struct s_autotrader *)dbi_first(iter); dbi_exists(iter); at = (struct s_autotrader *)dbi_next(iter)) {
  589. uint16 j = 0;
  590. if (SQL_ERROR == Sql_Query(mmysql_handle,
  591. "SELECT `item_id`, `amount`, `price` "
  592. "FROM `%s` "
  593. "WHERE `buyingstore_id` = %d "
  594. "ORDER BY `index` ASC;",
  595. buyingstore_items_table, at->id ) )
  596. {
  597. Sql_ShowDebug(mmysql_handle);
  598. continue;
  599. }
  600. if (!(at->count = (uint16)Sql_NumRows(mmysql_handle))) {
  601. map_quit(at->sd);
  602. buyingstore_autotrader_remove(at, true);
  603. continue;
  604. }
  605. //Init the list
  606. CREATE(at->entries, struct s_autotrade_entry *,at->count);
  607. //Add the item into list
  608. j = 0;
  609. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle) && j < at->count) {
  610. char *data;
  611. CREATE(at->entries[j], struct s_autotrade_entry, 1);
  612. Sql_GetData(mmysql_handle, 0, &data, nullptr); at->entries[j]->item_id = strtoul(data, nullptr, 10);
  613. Sql_GetData(mmysql_handle, 1, &data, nullptr); at->entries[j]->amount = atoi(data);
  614. Sql_GetData(mmysql_handle, 2, &data, nullptr); at->entries[j]->price = atoi(data);
  615. j++;
  616. }
  617. items += j;
  618. Sql_FreeResult(mmysql_handle);
  619. }
  620. dbi_destroy(iter);
  621. ShowStatus("Done loading '" CL_WHITE "%d" CL_RESET "' buyingstore autotraders with '" CL_WHITE "%d" CL_RESET "' items.\n", db_size(buyingstore_autotrader_db), items);
  622. }
  623. }
  624. // Everything is loaded fine, their entries will be reinserted once they are loaded
  625. if (Sql_Query( mmysql_handle, "DELETE FROM `%s`;", buyingstores_table ) != SQL_SUCCESS ||
  626. Sql_Query( mmysql_handle, "DELETE FROM `%s`;", buyingstore_items_table ) != SQL_SUCCESS)
  627. {
  628. Sql_ShowDebug(mmysql_handle);
  629. }
  630. }
  631. /**
  632. * Remove an autotrader's data
  633. * @param at Autotrader
  634. * @param remove If true will removes from buyingstore_autotrader_db
  635. **/
  636. static void buyingstore_autotrader_remove(struct s_autotrader *at, bool remove) {
  637. nullpo_retv(at);
  638. if (at->count && at->entries) {
  639. uint16 i = 0;
  640. for (i = 0; i < at->count; i++) {
  641. if (at->entries[i])
  642. aFree(at->entries[i]);
  643. }
  644. aFree(at->entries);
  645. }
  646. if (remove)
  647. uidb_remove(buyingstore_autotrader_db, at->char_id);
  648. aFree(at);
  649. }
  650. /**
  651. * Clear all autotraders
  652. * @author [Cydh]
  653. */
  654. static int buyingstore_autotrader_free(DBKey key, DBData *data, va_list ap) {
  655. struct s_autotrader *at = (struct s_autotrader *)db_data2ptr(data);
  656. if (at)
  657. buyingstore_autotrader_remove(at, false);
  658. return 0;
  659. }
  660. /**
  661. * Update buyer location
  662. * @param sd: Player's session data
  663. */
  664. void buyingstore_update(map_session_data &sd)
  665. {
  666. if (Sql_Query(mmysql_handle, "UPDATE `%s` SET `map` = '%s', `x` = '%d', `y` = '%d', `body_direction` = '%d', `head_direction` = '%d', `sit` = '%d', `autotrade` = '%d' WHERE `id` = '%d'",
  667. buyingstores_table, map_getmapdata(sd.bl.m)->name, sd.bl.x, sd.bl.y, sd.ud.dir, sd.head_dir, pc_issit(&sd), sd.state.autotrade,
  668. sd.buyer_id
  669. ) != SQL_SUCCESS) {
  670. Sql_ShowDebug(mmysql_handle);
  671. }
  672. }
  673. /**
  674. * Initialise the buyingstore module
  675. * called in map::do_init
  676. */
  677. void do_final_buyingstore(void) {
  678. db_destroy(buyingstore_db);
  679. buyingstore_autotrader_db->destroy(buyingstore_autotrader_db, buyingstore_autotrader_free);
  680. }
  681. /**
  682. * Destory the buyingstore module
  683. * called in map::do_final
  684. */
  685. void do_init_buyingstore(void) {
  686. buyingstore_db = idb_alloc(DB_OPT_BASE);
  687. buyingstore_autotrader_db = uidb_alloc(DB_OPT_BASE);
  688. buyingstore_nextid = 0;
  689. }