vending.cpp 22 KB

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