WorldDatabase.cpp 353 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. EQ2Emulator is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include <math.h>
  17. #include <iostream>
  18. #include <sstream>
  19. #include <iomanip>
  20. #include <ios>
  21. #include <assert.h>
  22. #include <boost/algorithm/string/predicate.hpp>
  23. #include <boost/algorithm/string.hpp>
  24. #include "WorldDatabase.h"
  25. #include "../common/debug.h"
  26. #include "../common/packet_dump.h"
  27. #include "../common/GlobalHeaders.h"
  28. #include "Items/Items.h"
  29. #include "Factions.h"
  30. #include "World.h"
  31. #include "Variables.h"
  32. #include "VisualStates.h"
  33. #include "Appearances.h"
  34. #include "Skills.h"
  35. #include "Quests.h"
  36. #include "LuaInterface.h"
  37. #include "classes.h"
  38. #include "../common/Log.h"
  39. #include "Rules/Rules.h"
  40. #include "Titles.h"
  41. #include "Languages.h"
  42. #include "Traits/Traits.h"
  43. #include "ClientPacketFunctions.h"
  44. #include "Zone/ChestTrap.h"
  45. #include "../common/version.h"
  46. #include "SpellProcess.h"
  47. #include "races.h"
  48. extern Classes classes;
  49. extern Commands commands;
  50. extern MasterTitlesList master_titles_list;
  51. extern MasterItemList master_item_list;
  52. extern MasterSpellList master_spell_list;
  53. extern MasterTraitList master_trait_list;
  54. extern MasterFactionList master_faction_list;
  55. extern World world;
  56. extern Variables variables;
  57. extern VisualStates visual_states;
  58. extern Appearances master_appearance_list;
  59. extern MasterSkillList master_skill_list;
  60. extern MasterQuestList master_quest_list;
  61. extern LuaInterface* lua_interface;
  62. extern ZoneList zone_list;
  63. extern GuildList guild_list;
  64. extern MasterCollectionList master_collection_list;
  65. extern RuleManager rule_manager;
  66. extern MasterLanguagesList master_languages_list;
  67. extern ChestTrapList chest_trap_list;
  68. //devn00b: Fix for linux builds since we dont use stricmp we use strcasecmp
  69. #if defined(__GNUC__)
  70. #define stricmp strcasecmp
  71. #define strnicmp strncasecmp
  72. #include <sys/stat.h>
  73. #endif
  74. WorldDatabase::WorldDatabase(){
  75. }
  76. WorldDatabase::~WorldDatabase(){
  77. }
  78. bool WorldDatabase::ConnectNewDatabase() {
  79. /*
  80. TESTS
  81. database_new.Connect();
  82. DatabaseResult result;
  83. database_new.Select(&result, "select name from characters where id=1");
  84. if (result.Next()) {
  85. printf("'%s'\n", result.GetStringStr("name"));
  86. printf("'%s'\n", result.GetStringStr("nameBAD"));
  87. printf("'%s'\n", result.GetString(3));
  88. }
  89. return true;
  90. */
  91. return database_new.Connect();
  92. }
  93. void WorldDatabase::PingNewDB()
  94. {
  95. database_new.PingNewDB();
  96. }
  97. void WorldDatabase::DeleteBuyBack(int32 char_id, int32 item_id, int16 quantity, int32 price) {
  98. LogWrite(MERCHANT__DEBUG, 0, "Merchant", "Deleting Buyback - Player: %u, Item ID: %u, Qty: %i, Price: %u", char_id, item_id, quantity, price);
  99. Query query;
  100. query.RunQuery2(Q_DELETE, "DELETE FROM character_buyback WHERE char_id = %u AND item_id = %u AND quantity = %i AND price = %u", char_id, item_id, quantity, price);
  101. }
  102. void WorldDatabase::LoadBuyBacks(Client* client) {
  103. LogWrite(MERCHANT__DEBUG, 0, "Merchant", "Loading Buyback - Player: %u", client->GetCharacterID());
  104. Query query;
  105. MYSQL_ROW row;
  106. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, item_id, quantity, price FROM character_buyback where char_id = %u ORDER BY id desc limit 10", client->GetCharacterID());
  107. int8 count = 0;
  108. int32 last_id = 0;
  109. if(result)
  110. {
  111. while(result && (row = mysql_fetch_row(result)))
  112. {
  113. LogWrite(MERCHANT__DEBUG, 5, "Merchant", "AddBuyBack: item: %u, qty: %i, price: %u", atoul(row[1]), atoi(row[2]), atoul(row[3]));
  114. last_id = atoul(row[0]);
  115. client->AddBuyBack(last_id, atoul(row[1]), atoi(row[2]), atoul(row[3]), false);
  116. count++;
  117. }
  118. if(count >= 10)
  119. {
  120. LogWrite(MERCHANT__DEBUG, 0, "Merchant", "Deleting excess Buyback from Player: %u", client->GetCharacterID());
  121. Query query2;
  122. query2.RunQuery2(Q_DELETE, "DELETE FROM character_buyback WHERE char_id = %u AND id < %u", client->GetCharacterID(), last_id);
  123. }
  124. }
  125. }
  126. void WorldDatabase::SaveBuyBacks(Client* client)
  127. {
  128. LogWrite(MERCHANT__DEBUG, 3, "Merchant", "Saving Buybacks - Player: %u", client->GetCharacterID());
  129. deque<BuyBackItem*>* buybacks = client->GetBuyBacks();
  130. if(buybacks && buybacks->size() > 0)
  131. {
  132. BuyBackItem* item = 0;
  133. deque<BuyBackItem*>::iterator itr;
  134. for(itr = buybacks->begin(); itr != buybacks->end(); itr++)
  135. {
  136. item = *itr;
  137. if(item && item->save_needed)
  138. {
  139. LogWrite(MERCHANT__DEBUG, 5, "Merchant", "SaveBuyBack: char: %u, item: %u, qty: %i, price: %u", client->GetCharacterID(), item->item_id, item->quantity, item->price);
  140. SaveBuyBack(client->GetCharacterID(), item->item_id, item->quantity, item->price);
  141. item->save_needed = false;
  142. }
  143. }
  144. }
  145. }
  146. void WorldDatabase::SaveBuyBack(int32 char_id, int32 item_id, int16 quantity, int32 price)
  147. {
  148. LogWrite(MERCHANT__DEBUG, 3, "Merchant", "Saving Buyback - Player: %u, Item ID: %u, Qty: %i, Price: %u", char_id, item_id, quantity, price);
  149. Query query;
  150. string insert = string("INSERT INTO character_buyback (char_id, item_id, quantity, price) VALUES (%u, %u, %i, %u) ");
  151. query.AddQueryAsync(char_id, this, Q_INSERT, insert.c_str(), char_id, item_id, quantity, price);
  152. }
  153. int32 WorldDatabase::LoadCharacterSpells(int32 char_id, Player* player)
  154. {
  155. LogWrite(SPELL__DEBUG, 0, "Spells", "Loading Character Spells for player %s...", player->GetName());
  156. Query query;
  157. MYSQL_ROW row;
  158. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT spell_id, tier, knowledge_slot, spell_book_type, linked_timer_id FROM character_spells, spells where character_spells.spell_id = spells.id and character_spells.char_id = %u ORDER BY spell_id, tier desc", char_id);
  159. int32 old_spell_id = 0;
  160. int32 new_spell_id = 0;
  161. int32 count = 0;
  162. if(result && mysql_num_rows(result) >0)
  163. {
  164. while(result && (row = mysql_fetch_row(result)))
  165. {
  166. count++;
  167. new_spell_id = atoul(row[0]);
  168. if(new_spell_id == old_spell_id)
  169. continue;
  170. old_spell_id = new_spell_id;
  171. LogWrite(SPELL__DEBUG, 5, "Spells", "\tLoading SpellID: %u, tier: %i, slot: %i, type: %u linked_timer_id: %u", new_spell_id, atoi(row[1]), atoi(row[2]), atoul(row[3]), atoul(row[4]));
  172. int8 tier = atoi(row[1]);
  173. if (player->HasSpell(new_spell_id, tier, true))
  174. continue;
  175. player->AddSpellBookEntry(new_spell_id, tier, atoi(row[2]), atoul(row[3]), atoul(row[4]));
  176. }
  177. }
  178. return count;
  179. }
  180. void WorldDatabase::SavePlayerSpells(Client* client)
  181. {
  182. if(!client || client->GetCharacterID() < 1)
  183. return;
  184. LogWrite(SPELL__DEBUG, 3, "Spells", "Saving Spell(s) for Player: '%s'", client->GetPlayer()->GetName());
  185. vector<SpellBookEntry*>* spells = client->GetPlayer()->GetSpellsSaveNeeded();
  186. if(spells)
  187. {
  188. vector<SpellBookEntry*>::iterator itr;
  189. SpellBookEntry* spell = 0;
  190. for(itr = spells->begin(); itr != spells->end(); itr++)
  191. {
  192. spell = *itr;
  193. Query query;
  194. LogWrite(SPELL__DEBUG, 5, "Spells", "\tSaving SpellID: %u, tier: %i, slot: %i", spell->spell_id, spell->tier, spell->slot);
  195. query.AddQueryAsync(client->GetCharacterID(), this, Q_INSERT, "INSERT INTO character_spells (char_id, spell_id, tier) SELECT %u, %u, %i ON DUPLICATE KEY UPDATE tier = %i",
  196. client->GetPlayer()->GetCharacterID(), spell->spell_id, spell->tier, spell->tier);
  197. spell->save_needed = false;
  198. }
  199. safe_delete(spells);
  200. }
  201. }
  202. int32 WorldDatabase::LoadCharacterSkills(int32 char_id, Player* player)
  203. {
  204. Query query;
  205. MYSQL_ROW row;
  206. int32 count = 0;
  207. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT skill_id, current_val, max_val FROM character_skills, skills where character_skills.skill_id = skills.id and character_skills.char_id = %u", char_id);
  208. if(result && mysql_num_rows(result) >0)
  209. {
  210. while(result && (row = mysql_fetch_row(result)))
  211. {
  212. count++;
  213. LogWrite(SKILL__DEBUG, 5, "Skills", "Loading SkillID: %u, cur_val: %i, max_val: %l", strtoul(row[0], NULL, 0), atoi(row[1]), atoi(row[2]));
  214. player->AddSkill(strtoul(row[0], NULL, 0), atoi(row[1]), atoi(row[2]));
  215. }
  216. }
  217. return count;
  218. }
  219. void WorldDatabase::DeleteCharacterSkill(int32 char_id, Skill* skill)
  220. {
  221. if (char_id > 0 && skill)
  222. {
  223. LogWrite(SKILL__DEBUG, 0, "Skills", "Deleting Skill '%s' (%u) from char_id: %u", skill->name.data.c_str(), skill->skill_id, char_id);
  224. Query query;
  225. query.RunQuery2(Q_DELETE, "DELETE FROM `character_skills` WHERE `char_id`=%u AND `skill_id`=%u", char_id, skill->skill_id);
  226. }
  227. }
  228. int32 WorldDatabase::LoadSkills()
  229. {
  230. int32 total = 0;
  231. Query query;
  232. MYSQL_ROW row;
  233. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, short_name, name, description, skill_type, display FROM skills");
  234. if(result)
  235. {
  236. if (mysql_num_rows(result) >0)
  237. {
  238. Skill* skill = 0;
  239. while(result && (row = mysql_fetch_row(result)))
  240. {
  241. skill = new Skill();
  242. skill->skill_id = strtoul(row[0], NULL, 0);
  243. skill->short_name.data = string(row[1]);
  244. skill->short_name.size = skill->short_name.data.length();
  245. skill->name.data = string(row[2]);
  246. skill->name.size = skill->name.data.length();
  247. skill->description.data = string(row[3]);
  248. skill->description.size = skill->description.data.length();
  249. skill->skill_type = strtoul(row[4], NULL, 0);
  250. //these two need to be converted to the correct numbers
  251. if(skill->skill_type == 13)
  252. skill->skill_type = SKILL_TYPE_LANGUAGE;
  253. else if(skill->skill_type == 12)
  254. skill->skill_type = SKILL_TYPE_GENERAL;
  255. skill->display = atoi(row[5]);
  256. master_skill_list.AddSkill(skill);
  257. total++;
  258. LogWrite(SKILL__DEBUG, 5, "Skill", "---Loading Skill: %s (%u)", skill->name.data.c_str(), skill->skill_id);
  259. LogWrite(SKILL__DEBUG, 7, "Skill", "---short_name: %s, type: %i, display: %i", skill->short_name.data.c_str(), skill->skill_type, skill->display);
  260. }
  261. }
  262. }
  263. LogWrite(SKILL__DEBUG, 3, "Skill", "--Loaded %u Skill(s)", total);
  264. return total;
  265. }
  266. map<int8, vector<MacroData*> >* WorldDatabase::LoadCharacterMacros(int32 char_id)
  267. {
  268. Query query;
  269. MYSQL_ROW row;
  270. int32 total = 0;
  271. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT macro_number, macro_name, macro_icon, macro_text FROM character_macros where char_id = %u ORDER BY macro_number, id", char_id);
  272. if(result && mysql_num_rows(result) >0)
  273. {
  274. map<int8, vector<MacroData*> >* macros = new map<int8, vector<MacroData*> >;
  275. while(result && (row = mysql_fetch_row(result)))
  276. {
  277. MacroData* data = new MacroData;
  278. data->name = row[1];
  279. data->icon = atoi(row[2]);
  280. data->text = row[3];
  281. (*macros)[atoi(row[0])].push_back(data);
  282. total++;
  283. LogWrite(PLAYER__DEBUG, 5, "Player", "\tLoading macro: %i. %s for player: %u", atoi(row[0]), row[1], char_id);
  284. }
  285. LogWrite(PLAYER__DEBUG, 0, "Player", "\tLoaded %u macro%s", total, total == 1 ? "" : "s");
  286. return macros;
  287. }
  288. return 0;
  289. }
  290. void WorldDatabase::UpdateCharacterMacro(int32 char_id, int8 number, const char* name, int16 icon, vector<string>* updates)
  291. {
  292. LogWrite(PLAYER__DEBUG, 0, "Player", "Update player id %u macro: %i", char_id, number);
  293. Query query;
  294. Query query2;
  295. query.RunQuery2(Q_DELETE, "delete FROM character_macros where char_id = %u and macro_number = %i", char_id, number);
  296. if(name && updates && updates->size() > 0)
  297. {
  298. for(int8 i=0;i<updates->size();i++)
  299. {
  300. query2.RunQuery2(Q_INSERT, "insert into character_macros (char_id, macro_number, macro_name, macro_icon, macro_text) values(%u, %i, '%s', %i, '%s')", char_id, number, getSafeEscapeString(name).c_str(), icon, getSafeEscapeString(updates->at(i).c_str()).c_str());
  301. LogWrite(PLAYER__DEBUG, 5, "Player", "\tAdding macro: %s, %s (Player: %u)", name, updates->at(i).c_str(), char_id);
  302. }
  303. }
  304. }
  305. //we use our timestamp just in case db is on another server, otherwise times might be off
  306. void WorldDatabase::UpdateVitality(int32 timestamp, float amount){
  307. Query query, query2, query3;
  308. LogWrite(PLAYER__DEBUG, 3, "Player", "Reset Vitality > 100: %f", amount);
  309. query.RunQuery2(Q_UPDATE, "update character_details set xp_vitality=100 where (xp_vitality + %f) > 100", amount);
  310. LogWrite(PLAYER__DEBUG, 3, "Player", "Update Vitality <= 100: %f", amount);
  311. query2.RunQuery2(Q_UPDATE, "update character_details set xp_vitality=(xp_vitality+%f) where (xp_vitality + %f) <= 100", amount, amount);
  312. LogWrite(PLAYER__DEBUG, 3, "Player", "Update Vitality Timer: %u", timestamp);
  313. query3.RunQuery2(Q_UPDATE, "update variables set variable_value=%u where variable_name='vitalitytimer'", timestamp);
  314. }
  315. void WorldDatabase::SaveVariable(const char* name, const char* value, const char* comment){
  316. LogWrite(WORLD__DEBUG, 0, "Variables", "Saving Variable: %s = %s", name, value);
  317. Query query;
  318. if(comment){
  319. query.RunQuery2(Q_REPLACE, "replace into variables (variable_name, variable_value, comment) values('%s', '%s', '%s')",
  320. getSafeEscapeString(name).c_str(), getSafeEscapeString(value).c_str(), getSafeEscapeString(comment).c_str());
  321. }
  322. else{
  323. query.RunQuery2(Q_REPLACE, "replace into variables (variable_name, variable_value) values('%s', '%s')",
  324. getSafeEscapeString(name).c_str(), getSafeEscapeString(value).c_str());
  325. }
  326. }
  327. void WorldDatabase::LoadGlobalVariables(){
  328. variables.ClearVariables ( );
  329. int32 total = 0;
  330. Query query;
  331. MYSQL_ROW row;
  332. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT variable_name, variable_value, comment FROM variables");
  333. while(result && (row = mysql_fetch_row(result)))
  334. {
  335. Variable* newVar = new Variable(row[0], row[1], row[2]);
  336. variables.AddVariable(newVar);
  337. total++;
  338. LogWrite(WORLD__DEBUG, 5, "World", "---Loading variable: '%s' = '%s'", row[0], row[1]);
  339. }
  340. LogWrite(WORLD__DEBUG, 3, "World", "--Loaded %u variables", total);
  341. }
  342. void WorldDatabase::LoadAppearanceMasterList()
  343. {
  344. DatabaseResult result;
  345. int32 total = 0;
  346. int32 appearance_id;
  347. int16 appearance_version;
  348. master_appearance_list.ClearAppearances();
  349. database_new.Select(&result, "SELECT appearance_id, `name`, min_client_version FROM appearances ORDER BY appearance_id");
  350. while( result.Next() )
  351. {
  352. appearance_id = result.GetInt32Str("appearance_id");
  353. const char *appearance_name = result.GetStringStr("name");
  354. appearance_version = result.GetInt16Str("min_client_version");
  355. Appearance* a = new Appearance(appearance_id, appearance_name, appearance_version);
  356. master_appearance_list.InsertAppearance(a);
  357. total++;
  358. LogWrite(WORLD__DEBUG, 5, "World", "---Loading appearances: '%s' (%i)", appearance_name, appearance_id);
  359. }
  360. LogWrite(WORLD__DEBUG, 3, "World", "--Loaded %u appearances", total);
  361. }
  362. void WorldDatabase::LoadVisualStates()
  363. {
  364. visual_states.Reset();
  365. int32 total = 0;
  366. Query query;
  367. Query query2;
  368. Query query3;
  369. MYSQL_ROW row;
  370. MYSQL_ROW row2;
  371. MYSQL_ROW row3;
  372. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT visual_state_id, name FROM visual_states");
  373. while(result && (row = mysql_fetch_row(result)))
  374. {
  375. VisualState* vs = new VisualState(atoi(row[0]), row[1]);
  376. visual_states.InsertVisualState(vs);
  377. total++;
  378. LogWrite(WORLD__DEBUG, 5, "World", "---Loading visual state: '%s' (%i)", row[1], atoi(row[0]));
  379. }
  380. LogWrite(WORLD__DEBUG, 3, "World", "--Loaded %u visual states", total);
  381. total = 0;
  382. MYSQL_RES* result2 = query2.RunQuery2(Q_SELECT, "SELECT name, visual_state_id, message, targeted_message, min_version_range, max_version_range FROM emotes");
  383. while(result2 && (row2 = mysql_fetch_row(result2)))
  384. {
  385. EmoteVersionRange* range = 0;
  386. if ((range = visual_states.FindEmoteRange(string(row2[0]))) == NULL)
  387. {
  388. range = new EmoteVersionRange(row2[0]);
  389. visual_states.InsertEmoteRange(range);
  390. }
  391. range->AddVersionRange(atoul(row2[4]),atoul(row2[5]), row2[0], atoul(row2[1]), row2[2], row2[3]);
  392. total++;
  393. LogWrite(WORLD__DEBUG, 5, "World", "---Loading emote state: '%s' (%i)", row2[0], atoul(row2[0]));
  394. }
  395. LogWrite(WORLD__DEBUG, 3, "World", "--Loaded %u emote state(s)", total);
  396. total = 0;
  397. MYSQL_RES* result3 = query3.RunQuery2(Q_SELECT, "SELECT name, spell_visual_id, alternate_spell_visual, min_version_range, max_version_range FROM spell_visuals");
  398. while(result3 && (row3 = mysql_fetch_row(result3)))
  399. {
  400. EmoteVersionRange* range = 0;
  401. if ((range = visual_states.FindSpellVisualRange(string(row3[0]))) == NULL)
  402. {
  403. range = new EmoteVersionRange(row3[0]);
  404. visual_states.InsertSpellVisualRange(range, atoul(row3[1]));
  405. }
  406. range->AddVersionRange(atoul(row3[3]),atoul(row3[4]), row3[0], atoul(row3[1]), row3[2]);
  407. total++;
  408. LogWrite(WORLD__DEBUG, 5, "World", "---Loading spell visual state: '%s' (%u)", row3[1], atoul(row3[0]));
  409. }
  410. LogWrite(WORLD__DEBUG, 3, "World", "--Loaded %u spell visual state(s)", total);
  411. }
  412. void WorldDatabase::LoadSubCommandList()
  413. {
  414. int32 total = 0;
  415. Query query;
  416. MYSQL_ROW row;
  417. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT command, subcommand, handler, required_status FROM commands where length(subcommand) > 0 ORDER BY handler asc");
  418. while(result && (row = mysql_fetch_row(result)))
  419. {
  420. commands.GetRemoteCommands()->CheckAddSubCommand(string(row[0]), EQ2_RemoteCommandString(row[1], (int32)strtoul(row[2], NULL, 0), atoi(row[3])));
  421. total++;
  422. LogWrite(COMMAND__DEBUG, 5, "Command", "---Loading Command: '%s', sub '%s', handler, %u status %i", row[0], row[1], atoul(row[2]), atoi(row[3]));
  423. }
  424. LogWrite(COMMAND__DEBUG, 3, "Command", "--Loaded %i Subcommand(s)", total);
  425. }
  426. void WorldDatabase::LoadCommandList()
  427. {
  428. Query query;
  429. MYSQL_ROW row;
  430. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT command, handler, required_status FROM commands where length(subcommand) = 0 ORDER BY handler asc");
  431. int16 index = 0;
  432. while(result && (row = mysql_fetch_row(result)))
  433. {
  434. int32 handler = strtoul(row[1], NULL, 0);
  435. while(handler>index && handler != 999)
  436. {
  437. LogWrite(COMMAND__DEBUG, 5, "Command", "---Loading Remote Commands: handler %u, index %u", handler, index);
  438. commands.GetRemoteCommands()->addZero();
  439. index++;
  440. }
  441. LogWrite(COMMAND__DEBUG, 5, "Command", "---Loading Commands: handler %u, index %u", handler, index);
  442. commands.GetRemoteCommands()->addCommand(EQ2_RemoteCommandString(row[0], handler, atoi(row[2])));
  443. index++;
  444. }
  445. LogWrite(COMMAND__DEBUG, 3, "Command", "--Loaded %i Command%s", index, index > 0 ? "s" : "");
  446. LoadSubCommandList();
  447. }
  448. int32 WorldDatabase::LoadNPCSpells(){
  449. Query query;
  450. MYSQL_ROW row;
  451. int32 count = 0;
  452. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT spell_list_id, spell_id, spell_tier, on_spawn_cast, on_aggro_cast, required_hp_ratio FROM spawn_npc_spells where spell_list_id > 0");
  453. while(result && (row = mysql_fetch_row(result))){
  454. if(!row[0] || !row[1] || !row[2] || !row[3] || !row[4] || !row[5]) {
  455. LogWrite(NPC__ERROR, 0, "NPC", "---Loading NPC Spell List: %u, found NULL values in entry, SKIP!", row[0] ? atoul(row[0]) : 0);
  456. }
  457. else {
  458. world.AddNPCSpell(atoul(row[0]), atoul(row[1]), atoi(row[2]), atoul(row[3]), atoul(row[4]), atoi(row[5]));
  459. count++;
  460. LogWrite(NPC__DEBUG, 5, "NPC", "---Loading NPC Spell List: %u, spell id: %u, tier: %i", atoul(row[0]), atoul(row[1]), atoi(row[2]));
  461. }
  462. }
  463. return count;
  464. }
  465. int32 WorldDatabase::LoadNPCSkills(ZoneServer* zone){
  466. Query query;
  467. MYSQL_ROW row;
  468. int32 count = 0;
  469. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT skill_list_id, skill_id, starting_value FROM spawn_npc_skills");
  470. while(result && (row = mysql_fetch_row(result))){
  471. zone->AddNPCSkill(atoul(row[0]), atoul(row[1]), atoi(row[2]));
  472. count++;
  473. LogWrite(NPC__DEBUG, 5, "NPC", "---Loading NPC Skill List: %u, skill id: %u, value: %i", atoul(row[0]), atoul(row[1]), atoi(row[2]));
  474. }
  475. return count;
  476. }
  477. int32 WorldDatabase::LoadNPCEquipment(ZoneServer* zone){
  478. Query query;
  479. MYSQL_ROW row;
  480. int32 count = 0;
  481. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT equipment_list_id, item_id FROM spawn_npc_equipment");
  482. while(result && (row = mysql_fetch_row(result))){
  483. zone->AddNPCEquipment(atoul(row[0]), atoul(row[1]));
  484. count++;
  485. LogWrite(NPC__DEBUG, 5, "NPC", "---Loading NPC Equipment List: %u, item: %u", atoul(row[0]), atoul(row[1]));
  486. }
  487. return count;
  488. }
  489. int8 WorldDatabase::GetAppearanceType(string type){
  490. int8 ret = 255;
  491. if (type == "soga_hair_face_highlight_color")
  492. ret = APPEARANCE_SOGA_HFHC;
  493. else if (type == "soga_hair_type_highlight_color")
  494. ret = APPEARANCE_SOGA_HTHC;
  495. else if (type == "soga_hair_face_color")
  496. ret = APPEARANCE_SOGA_HFC;
  497. else if (type == "soga_hair_type_color")
  498. ret = APPEARANCE_SOGA_HTC;
  499. else if (type == "soga_hair_highlight")
  500. ret = APPEARANCE_SOGA_HH;
  501. else if (type == "soga_hair_color1")
  502. ret = APPEARANCE_SOGA_HC1;
  503. else if (type == "soga_hair_color2")
  504. ret = APPEARANCE_SOGA_HC2;
  505. else if (type == "hair_type_color")
  506. ret = APPEARANCE_HTC;
  507. else if (type == "soga_skin_color")
  508. ret = APPEARANCE_SOGA_SC;
  509. else if (type == "soga_eye_color")
  510. ret = APPEARANCE_SOGA_EC;
  511. else if (type == "hair_type_highlight_color")
  512. ret = APPEARANCE_HTHC;
  513. else if (type == "hair_face_highlight_color")
  514. ret = APPEARANCE_HFHC;
  515. else if (type == "hair_face_color")
  516. ret = APPEARANCE_HFC;
  517. else if (type == "hair_highlight")
  518. ret = APPEARANCE_HH;
  519. else if (type == "hair_color1")
  520. ret = APPEARANCE_HC1;
  521. else if (type == "wing_color1")
  522. ret = APPEARANCE_WC1;
  523. else if (type == "hair_color2")
  524. ret = APPEARANCE_HC2;
  525. else if (type == "wing_color2")
  526. ret = APPEARANCE_WC2;
  527. else if (type == "skin_color")
  528. ret = APPEARANCE_SC;
  529. else if (type == "eye_color")
  530. ret = APPEARANCE_EC;
  531. else if (type == "soga_eye_brow_type")
  532. ret = APPEARANCE_SOGA_EBT;
  533. else if (type == "soga_cheek_type")
  534. ret = APPEARANCE_SOGA_CHEEKT;
  535. else if (type == "soga_nose_type")
  536. ret = APPEARANCE_SOGA_NT;
  537. else if (type == "soga_chin_type")
  538. ret = APPEARANCE_SOGA_CHINT;
  539. else if (type == "soga_lip_type")
  540. ret = APPEARANCE_SOGA_LT;
  541. else if (type == "eye_brow_type")
  542. ret = APPEARANCE_EBT;
  543. else if (type == "soga_ear_type")
  544. ret = APPEARANCE_SOGA_EART;
  545. else if (type == "soga_eye_type")
  546. ret = APPEARANCE_SOGA_EYET;
  547. else if (type == "cheek_type")
  548. ret = APPEARANCE_CHEEKT;
  549. else if (type == "nose_type")
  550. ret = APPEARANCE_NT;
  551. else if (type == "chin_type")
  552. ret = APPEARANCE_CHINT;
  553. else if (type == "ear_type")
  554. ret = APPEARANCE_EART;
  555. else if (type == "eye_type")
  556. ret = APPEARANCE_EYET;
  557. else if (type == "lip_type")
  558. ret = APPEARANCE_LT;
  559. else if (type == "shirt_color")
  560. ret = APPEARANCE_SHIRT;
  561. else if (type == "unknown_chest_color")
  562. ret = APPEARANCE_UCC;
  563. else if (type == "pants_color")
  564. ret = APPEARANCE_PANTS;
  565. else if (type == "unknown_legs_color")
  566. ret = APPEARANCE_ULC;
  567. else if (type == "unknown9")
  568. ret = APPEARANCE_U9;
  569. else if (type == "body_size")
  570. ret = APPEARANCE_BODY_SIZE;
  571. else if (type == "soga_wing_color1")
  572. ret = APPEARANCE_SOGA_WC1;
  573. else if (type == "soga_wing_color2")
  574. ret = APPEARANCE_SOGA_WC2;
  575. else if (type == "soga_shirt_color")
  576. ret = APPEARANCE_SOGA_SHIRT;
  577. else if (type == "soga_unknown_chest_color")
  578. ret = APPEARANCE_SOGA_UCC;
  579. else if (type == "soga_pants_color")
  580. ret = APPEARANCE_SOGA_PANTS;
  581. else if (type == "soga_unknown_legs_color")
  582. ret = APPEARANCE_SOGA_ULC;
  583. else if (type == "soga_unknown13")
  584. ret = APPEARANCE_SOGA_U13;
  585. else if (type == "body_age")
  586. ret = APPEARANCE_BODY_AGE;
  587. else if (type == "model_color")
  588. ret = APPEARANCE_MC;
  589. else if (type == "soga_model_color")
  590. ret = APPEARANCE_SMC;
  591. else if (type == "soga_body_size")
  592. ret = APPEARANCE_SBS;
  593. else if (type == "soga_body_age")
  594. ret = APPEARANCE_SBA;
  595. return ret;
  596. }
  597. int32 WorldDatabase::LoadAppearances(ZoneServer* zone, Client* client){
  598. Query query, query2;
  599. MYSQL_ROW row;
  600. int32 count = 0, spawn_id = 0, new_spawn_id = 0;
  601. Entity* entity = 0;
  602. if(client)
  603. entity = client->GetPlayer();
  604. map<string, int8> appearance_types;
  605. map<int32, map<int8, EQ2_Color> > appearance_colors;
  606. EQ2_Color color;
  607. color.red = 0;
  608. color.green = 0;
  609. color.blue = 0;
  610. string type;
  611. MYSQL_RES* result = 0;
  612. if(!client)
  613. result = query.RunQuery2(Q_SELECT, "SELECT distinct `type` FROM npc_appearance where length(type) > 0");
  614. else
  615. result = query.RunQuery2(Q_SELECT, "SELECT distinct `type` FROM char_colors where length(type) > 0 and char_id=%u", client->GetCharacterID());
  616. while(result && (row = mysql_fetch_row(result))){
  617. type = string(row[0]);
  618. appearance_types[type] = GetAppearanceType(type);
  619. if(appearance_types[type] == 255)
  620. LogWrite(WORLD__ERROR, 0, "Appearance", "Unknown appearance type '%s' in LoadAppearances.", type.c_str());
  621. }
  622. MYSQL_RES* result2 = 0;
  623. if(!client)
  624. result2 = query2.RunQuery2(Q_SELECT, "SELECT `type`, spawn_id, signed_value, red, green, blue FROM npc_appearance where length(type) > 0 ORDER BY spawn_id");
  625. else
  626. result2 = query2.RunQuery2(Q_SELECT, "SELECT `type`, char_id, signed_value, red, green, blue FROM char_colors where length(type) > 0 and char_id=%u", client->GetCharacterID());
  627. while(result2 && (row = mysql_fetch_row(result2))){
  628. if(!client){
  629. new_spawn_id = atoul(row[1]);
  630. if(spawn_id != new_spawn_id){
  631. entity = zone->GetNPC(new_spawn_id, true);
  632. if(!entity)
  633. continue;
  634. if(spawn_id > 0)
  635. count++;
  636. spawn_id = new_spawn_id;
  637. }
  638. }
  639. if(appearance_types[row[0]] < APPEARANCE_SOGA_EBT){
  640. color.red = atoi(row[3]);
  641. color.green = atoi(row[4]);
  642. color.blue = atoi(row[5]);
  643. }
  644. switch(appearance_types[row[0]]){
  645. case APPEARANCE_SOGA_HFHC:{
  646. entity->features.soga_hair_face_highlight_color = color;
  647. break;
  648. }
  649. case APPEARANCE_SOGA_HTHC:{
  650. entity->features.soga_hair_type_highlight_color = color;
  651. break;
  652. }
  653. case APPEARANCE_SOGA_HFC:{
  654. entity->features.soga_hair_face_color = color;
  655. break;
  656. }
  657. case APPEARANCE_SOGA_HTC:{
  658. entity->features.soga_hair_type_color = color;
  659. break;
  660. }
  661. case APPEARANCE_SOGA_HH:{
  662. entity->features.soga_hair_highlight_color = color;
  663. break;
  664. }
  665. case APPEARANCE_SOGA_HC1:{
  666. entity->features.soga_hair_color1 = color;
  667. break;
  668. }
  669. case APPEARANCE_SOGA_HC2:{
  670. entity->features.soga_hair_color2 = color;
  671. break;
  672. }
  673. case APPEARANCE_SOGA_SC:{
  674. entity->features.soga_skin_color = color;
  675. break;
  676. }
  677. case APPEARANCE_SOGA_EC:{
  678. entity->features.soga_eye_color = color;
  679. break;
  680. }
  681. case APPEARANCE_HTHC:{
  682. entity->features.hair_type_highlight_color = color;
  683. break;
  684. }
  685. case APPEARANCE_HFHC:{
  686. entity->features.hair_face_highlight_color = color;
  687. break;
  688. }
  689. case APPEARANCE_HTC:{
  690. entity->features.hair_type_color = color;
  691. break;
  692. }
  693. case APPEARANCE_HFC:{
  694. entity->features.hair_face_color = color;
  695. break;
  696. }
  697. case APPEARANCE_HH:{
  698. entity->features.hair_highlight_color = color;
  699. break;
  700. }
  701. case APPEARANCE_HC1:{
  702. entity->features.hair_color1 = color;
  703. break;
  704. }
  705. case APPEARANCE_HC2:{
  706. entity->features.hair_color2 = color;
  707. break;
  708. }
  709. case APPEARANCE_WC1:{
  710. entity->features.wing_color1 = color;
  711. break;
  712. }
  713. case APPEARANCE_WC2:{
  714. entity->features.wing_color2 = color;
  715. break;
  716. }
  717. case APPEARANCE_SC:{
  718. entity->features.skin_color = color;
  719. break;
  720. }
  721. case APPEARANCE_EC:{
  722. entity->features.eye_color = color;
  723. break;
  724. }
  725. case APPEARANCE_SOGA_EBT:{
  726. for(int i=0;i<3;i++)
  727. entity->features.soga_eye_brow_type[i] = atoi(row[3+i]);
  728. break;
  729. }
  730. case APPEARANCE_SOGA_CHEEKT:{
  731. for(int i=0;i<3;i++)
  732. entity->features.soga_cheek_type[i] = atoi(row[3+i]);
  733. break;
  734. }
  735. case APPEARANCE_SOGA_NT:{
  736. for(int i=0;i<3;i++)
  737. entity->features.soga_nose_type[i] = atoi(row[3+i]);
  738. break;
  739. }
  740. case APPEARANCE_SOGA_CHINT:{
  741. for(int i=0;i<3;i++)
  742. entity->features.soga_chin_type[i] = atoi(row[3+i]);
  743. break;
  744. }
  745. case APPEARANCE_SOGA_LT:{
  746. for(int i=0;i<3;i++)
  747. entity->features.soga_lip_type[i] = atoi(row[3+i]);
  748. break;
  749. }
  750. case APPEARANCE_SOGA_EART:{
  751. for(int i=0;i<3;i++)
  752. entity->features.soga_ear_type[i] = atoi(row[3+i]);
  753. break;
  754. }
  755. case APPEARANCE_SOGA_EYET:{
  756. for(int i=0;i<3;i++)
  757. entity->features.soga_eye_type[i] = atoi(row[3+i]);
  758. break;
  759. }
  760. case APPEARANCE_EBT:{
  761. for(int i=0;i<3;i++)
  762. entity->features.eye_brow_type[i] = atoi(row[3+i]);
  763. break;
  764. }
  765. case APPEARANCE_CHEEKT:{
  766. for(int i=0;i<3;i++)
  767. entity->features.cheek_type[i] = atoi(row[3+i]);
  768. break;
  769. }
  770. case APPEARANCE_NT:{
  771. for(int i=0;i<3;i++)
  772. entity->features.nose_type[i] = atoi(row[3+i]);
  773. break;
  774. }
  775. case APPEARANCE_CHINT:{
  776. for(int i=0;i<3;i++)
  777. entity->features.chin_type[i] = atoi(row[3+i]);
  778. break;
  779. }
  780. case APPEARANCE_EART:{
  781. for(int i=0;i<3;i++)
  782. entity->features.ear_type[i] = atoi(row[3+i]);
  783. break;
  784. }
  785. case APPEARANCE_EYET:{
  786. for(int i=0;i<3;i++)
  787. entity->features.eye_type[i] = atoi(row[3+i]);
  788. break;
  789. }
  790. case APPEARANCE_LT:{
  791. for(int i=0;i<3;i++)
  792. entity->features.lip_type[i] = atoi(row[3+i]);
  793. break;
  794. }
  795. case APPEARANCE_SHIRT:{
  796. entity->features.shirt_color = color;
  797. break;
  798. }
  799. case APPEARANCE_UCC:{
  800. break;
  801. }
  802. case APPEARANCE_PANTS:{
  803. entity->features.pants_color = color;
  804. break;
  805. }
  806. case APPEARANCE_ULC:{
  807. break;
  808. }
  809. case APPEARANCE_U9:{
  810. break;
  811. }
  812. case APPEARANCE_BODY_SIZE:{
  813. entity->features.body_size = color.red;
  814. break;
  815. }
  816. case APPEARANCE_SOGA_WC1:{
  817. break;
  818. }
  819. case APPEARANCE_SOGA_WC2:{
  820. break;
  821. }
  822. case APPEARANCE_SOGA_SHIRT:{
  823. break;
  824. }
  825. case APPEARANCE_SOGA_UCC:{
  826. break;
  827. }
  828. case APPEARANCE_SOGA_PANTS:{
  829. break;
  830. }
  831. case APPEARANCE_SOGA_ULC:{
  832. break;
  833. }
  834. case APPEARANCE_SOGA_U13:{
  835. break;
  836. }
  837. case APPEARANCE_BODY_AGE: {
  838. entity->features.body_age = color.red;
  839. break;
  840. }
  841. case APPEARANCE_MC:{
  842. entity->features.model_color = color;
  843. break;
  844. }
  845. case APPEARANCE_SMC:{
  846. entity->features.soga_model_color = color;
  847. break;
  848. }
  849. case APPEARANCE_SBS: {
  850. entity->features.soga_body_size = color.red;
  851. break;
  852. }
  853. case APPEARANCE_SBA: {
  854. entity->features.soga_body_age = color.red;
  855. break;
  856. }
  857. }
  858. entity->info_changed = true;
  859. }
  860. return count;
  861. }
  862. void WorldDatabase::LoadNPCs(ZoneServer* zone){
  863. Query query;
  864. MYSQL_ROW row;
  865. NPC* npc = 0;
  866. int32 id = 0;
  867. int32 total = 0;
  868. MYSQL_RES* result = query.RunQuery2(Q_SELECT,"SELECT npc.spawn_id, s.name, npc.min_level, npc.max_level, npc.enc_level, s.race, s.model_type, npc.class_, npc.gender, s.command_primary, s.command_secondary, s.show_name, npc.min_group_size, npc.max_group_size, npc.hair_type_id, npc.facial_hair_type_id, npc.wing_type_id, npc.chest_type_id, npc.legs_type_id, npc.soga_hair_type_id, npc.soga_facial_hair_type_id, s.attackable, s.show_level, s.targetable, s.show_command_icon, s.display_hand_icon, s.hp, s.power, s.size, s.collision_radius, npc.action_state, s.visual_state, npc.mood_state, npc.initial_state, npc.activity_status, s.faction_id, s.sub_title, s.merchant_id, s.merchant_type, s.size_offset, npc.attack_type, npc.ai_strategy+0, npc.spell_list_id, npc.secondary_spell_list_id, npc.skill_list_id, npc.secondary_skill_list_id, npc.equipment_list_id, npc.str, npc.sta, npc.wis, npc.intel, npc.agi, npc.heat, npc.cold, npc.magic, npc.mental, npc.divine, npc.disease, npc.poison, npc.aggro_radius, npc.cast_percentage, npc.randomize, npc.soga_model_type, npc.heroic_flag, npc.alignment, npc.elemental, npc.arcane, npc.noxious, s.savagery, s.dissonance, npc.hide_hood, npc.emote_state, s.prefix, s.suffix, s.last_name, s.expansion_flag, s.holiday_flag, s.disable_sounds, s.merchant_min_level, s.merchant_max_level, s.aaxp_rewards, npc.water_type, npc.flying_type, s.loot_tier, s.loot_drop_type, npc.scared_by_strong_players, npc.action_state_str\n"
  869. "FROM spawn s\n"
  870. "INNER JOIN spawn_npcs npc\n"
  871. "ON s.id = npc.spawn_id\n"
  872. "INNER JOIN spawn_location_entry le\n"
  873. "ON npc.spawn_id = le.spawn_id\n"
  874. "INNER JOIN spawn_location_placement lp\n"
  875. "ON le.spawn_location_id = lp.spawn_location_id\n"
  876. "WHERE lp.zone_id = %u and (lp.instance_id = 0 or lp.instance_id = %u)\n"
  877. "GROUP BY s.id",
  878. zone->GetZoneID(), zone->GetInstanceID());
  879. while(result && (row = mysql_fetch_row(result))){
  880. /*npc->SetAppearanceID(atoi(row[12]));
  881. AppearanceData* appearance = world.GetNPCAppearance(npc->GetAppearanceID());
  882. if(appearance)
  883. memcpy(&npc->appearance, appearance, sizeof(AppearanceData));
  884. */
  885. int32 npcXpackFlag = atoul(row[75]);
  886. int32 npcHolidayFlag = atoul(row[76]);
  887. id = atoul(row[0]);
  888. if(zone->GetNPC(id, true))
  889. continue;
  890. npc = new NPC();
  891. if (!CheckExpansionFlags(zone, npcXpackFlag) || !CheckHolidayFlags(zone, npcHolidayFlag))
  892. npc->SetOmittedByDBFlag(true);
  893. npc->SetDatabaseID(id);
  894. strcpy(npc->appearance.name, row[1]);
  895. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(atoul(row[9]));
  896. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(atoul(row[10]));
  897. if(primary_command_list){
  898. npc->SetPrimaryCommands(primary_command_list);
  899. npc->primary_command_list_id = atoul(row[9]);
  900. }
  901. if(secondary_command_list){
  902. npc->SetSecondaryCommands(secondary_command_list);
  903. npc->secondary_command_list_id = atoul(row[10]);
  904. }
  905. npc->appearance.min_level = atoi(row[2]);
  906. npc->appearance.max_level = atoi(row[3]);
  907. npc->appearance.level = atoi(row[2]);
  908. npc->appearance.difficulty = atoi(row[4]);
  909. npc->appearance.race = atoi(row[5]);
  910. npc->appearance.model_type = atoi(row[6]);
  911. npc->appearance.soga_model_type = atoi(row[62]);
  912. npc->appearance.adventure_class = atoi(row[7]);
  913. npc->appearance.gender = atoi(row[8]);
  914. npc->appearance.display_name = atoi(row[11]);
  915. npc->features.hair_type = atoi(row[14]);
  916. npc->features.hair_face_type = atoi(row[15]);
  917. npc->features.wing_type = atoi(row[16]);
  918. npc->features.chest_type = atoi(row[17]);
  919. npc->features.legs_type = atoi(row[18]);
  920. npc->features.soga_hair_type = atoi(row[19]);
  921. npc->features.soga_hair_face_type = atoi(row[20]);
  922. npc->appearance.attackable = atoi(row[21]);
  923. npc->appearance.show_level = atoi(row[22]);
  924. npc->appearance.targetable = atoi(row[23]);
  925. npc->appearance.show_command_icon = atoi(row[24]);
  926. npc->appearance.display_hand_icon = atoi(row[25]);
  927. npc->appearance.hide_hood = atoi(row[70]);
  928. npc->appearance.randomize = atoi(row[61]);
  929. npc->SetTotalHP(atoul(row[26]));
  930. npc->SetTotalHPBaseInstance(atoul(row[26]));
  931. npc->SetTotalPower(atoul(row[27]));
  932. npc->SetTotalPowerBaseInstance(atoul(row[27]));
  933. npc->SetHP(npc->GetTotalHP());
  934. npc->SetPower(npc->GetTotalPower());
  935. if(npc->GetTotalHP() == 0){
  936. npc->SetTotalHP(15*npc->GetLevel() + 1);
  937. npc->SetHP(15*npc->GetLevel() + 1);
  938. }
  939. if(npc->GetTotalPower() == 0){
  940. npc->SetTotalPower(15*npc->GetLevel() + 1);
  941. npc->SetPower(15*npc->GetLevel() + 1);
  942. }
  943. npc->size = atoi(row[28]);
  944. npc->appearance.pos.collision_radius = atoi(row[29]);
  945. npc->appearance.action_state = atoi(row[30]);
  946. npc->appearance.visual_state = atoi(row[31]);
  947. npc->appearance.mood_state = atoi(row[32]);
  948. npc->appearance.emote_state = atoi(row[71]);
  949. npc->appearance.pos.state = atoi(row[33]);
  950. npc->appearance.activity_status = atoi(row[34]);
  951. npc->faction_id = atoul(row[35]);
  952. if(row[36]){
  953. std::string sub_title = std::string(row[36]);
  954. if(strncmp(row[36],"<Collector>", 11) == 0) {
  955. npc->SetCollector(true);
  956. }
  957. if(strlen(row[36]) < sizeof(npc->appearance.sub_title))
  958. strcpy(npc->appearance.sub_title, row[36]);
  959. else
  960. strncpy(npc->appearance.sub_title, row[36], sizeof(npc->appearance.sub_title));
  961. }
  962. npc->SetMerchantID(atoul(row[37]));
  963. npc->SetMerchantType(atoi(row[38]));
  964. npc->SetSizeOffset(atoi(row[39]));
  965. npc->SetAIStrategy(atoi(row[41]));
  966. npc->SetPrimarySpellList(atoul(row[42]));
  967. npc->SetSecondarySpellList(atoul(row[43]));
  968. npc->SetPrimarySkillList(atoul(row[44]));
  969. npc->SetSecondarySkillList(atoul(row[45]));
  970. npc->SetEquipmentListID(atoul(row[46]));
  971. InfoStruct* info = npc->GetInfoStruct();
  972. info->set_attack_type(atoi(row[40]));
  973. info->set_str_base(atoi(row[47]));
  974. info->set_sta_base(atoi(row[48]));
  975. info->set_wis_base(atoi(row[49]));
  976. info->set_intel_base(atoi(row[50]));
  977. info->set_agi_base(atoi(row[51]));
  978. info->set_heat_base(atoi(row[52]));
  979. info->set_cold_base(atoi(row[53]));
  980. info->set_magic_base(atoi(row[54]));
  981. info->set_mental_base(atoi(row[55]));
  982. info->set_divine_base(atoi(row[56]));
  983. info->set_disease_base(atoi(row[57]));
  984. info->set_poison_base(atoi(row[58]));
  985. info->set_alignment(atoi(row[64]));
  986. npc->SetAggroRadius(atof(row[59]));
  987. npc->SetCastPercentage(atoi(row[60]));
  988. npc->appearance.heroic_flag = atoi(row[63]);
  989. info->set_elemental_base(atoi(row[65]));
  990. info->set_arcane_base(atoi(row[66]));
  991. info->set_noxious_base(atoi(row[67]));
  992. npc->SetTotalSavagery(atoul(row[68]));
  993. npc->SetTotalDissonance(atoul(row[69]));
  994. npc->SetSavagery(npc->GetTotalSavagery());
  995. npc->SetDissonance(npc->GetTotalDissonance());
  996. if(npc->GetTotalSavagery() == 0){
  997. npc->SetTotalSavagery(15*npc->GetLevel() + 1);
  998. npc->SetSavagery(15*npc->GetLevel() + 1);
  999. }
  1000. if(npc->GetTotalDissonance() == 0){
  1001. npc->SetTotalDissonance(15*npc->GetLevel() + 1);
  1002. npc->SetDissonance(15*npc->GetLevel() + 1);
  1003. }
  1004. npc->SetPrefixTitle(row[72]);
  1005. npc->SetSuffixTitle(row[73]);
  1006. npc->SetLastName(row[74]);
  1007. // xpack+holiday value handled at top at position 75+76
  1008. int8 disableSounds = atoul(row[77]);
  1009. npc->SetSoundsDisabled(disableSounds);
  1010. npc->SetMerchantLevelRange(atoul(row[78]), atoul(row[79]));
  1011. npc->SetAAXPRewards(atoul(row[80]));
  1012. info->set_water_type(atoul(row[81]));
  1013. info->set_flying_type(atoul(row[82]));
  1014. npc->SetLootTier(atoul(row[83]));
  1015. npc->SetLootDropType(atoul(row[84]));
  1016. npc->SetScaredByStrongPlayers(atoul(row[85]));
  1017. if(row[86]){
  1018. std::string action_state_str = std::string(row[86]);
  1019. npc->GetInfoStruct()->set_action_state(action_state_str);
  1020. }
  1021. zone->AddNPC(id, npc);
  1022. total++;
  1023. LogWrite(NPC__DEBUG, 5, "NPC", "---Loading NPC: '%s' (%u)", npc->appearance.name, id);
  1024. }
  1025. LogWrite(NPC__INFO, 0, "NPC", "--Loaded %i NPC(s).", total);
  1026. LogWrite(NPC__INFO, 0, "NPC", "--Loaded %i NPC Skill(s).", LoadNPCSkills(zone));
  1027. LogWrite(NPC__INFO, 0, "NPC", "--Loaded %i NPC Equipment Piece(s).", LoadNPCEquipment(zone));
  1028. LogWrite(NPC__INFO, 0, "NPC", "--Loaded %i NPC Appearance(s).", LoadAppearances(zone));
  1029. LogWrite(NPC__INFO, 0, "NPC", "--Loaded %i NPC Equipment Appearance(s).", LoadNPCAppearanceEquipmentData(zone));
  1030. }
  1031. void WorldDatabase::LoadSpiritShards(ZoneServer* zone){
  1032. Query query;
  1033. MYSQL_ROW row;
  1034. int32 id = 0;
  1035. int32 total = 0;
  1036. MYSQL_RES* result = query.RunQuery2(Q_SELECT,"SELECT timestamp, name, level, race, gender, adventure_class, model_type, soga_model_type, hair_type, hair_face_type, wing_type, chest_type, legs_type, soga_hair_type, soga_hair_face_type, hide_hood, size, collision_radius, action_state, visual_state, mood_state, emote_state, pos_state, activity_status, sub_title, prefix_title, suffix_title, lastname, x, y, z, heading, gridid, id, charid\n"
  1037. "FROM character_spirit_shards\n"
  1038. "WHERE zoneid = %u and (instanceid = 0 or instanceid = %u)",
  1039. zone->GetZoneID(), zone->GetInstanceID());
  1040. while(result && (row = mysql_fetch_row(result))){
  1041. /*npc->SetAppearanceID(atoi(row[12]));
  1042. AppearanceData* appearance = world.GetNPCAppearance(npc->GetAppearanceID());
  1043. if(appearance)
  1044. memcpy(&npc->appearance, appearance, sizeof(AppearanceData));
  1045. */
  1046. sint64 timestamp = 0;
  1047. #ifdef WIN32
  1048. timestamp = _strtoui64(row[0], NULL, 10);
  1049. #else
  1050. timestamp = strtoull(row[0], 0, 10);
  1051. #endif
  1052. if(!row[1])
  1053. continue;
  1054. NPC* shard = new NPC();
  1055. shard->SetShardCreatedTimestamp(timestamp);
  1056. strcpy(shard->appearance.name, row[1]);
  1057. shard->appearance.level = atoul(row[2]);
  1058. shard->appearance.race = atoul(row[3]);
  1059. shard->appearance.gender = atoul(row[4]);
  1060. shard->appearance.adventure_class = atoul(row[5]);
  1061. shard->appearance.model_type = atoul(row[6]);
  1062. shard->appearance.soga_model_type = atoul(row[7]);
  1063. shard->appearance.display_name = 1;
  1064. shard->features.hair_type = atoul(row[8]);
  1065. shard->features.hair_face_type = atoul(row[9]);
  1066. shard->features.wing_type = atoul(row[10]);
  1067. shard->features.chest_type = atoul(row[11]);
  1068. shard->features.legs_type = atoul(row[12]);
  1069. shard->features.soga_hair_type = atoul(row[13]);
  1070. shard->features.soga_hair_face_type = atoul(row[14]);
  1071. shard->appearance.attackable = 0;
  1072. shard->appearance.show_level = 1;
  1073. shard->appearance.targetable = 1;
  1074. shard->appearance.show_command_icon = 1;
  1075. shard->appearance.display_hand_icon = 0;
  1076. shard->appearance.hide_hood = atoul(row[15]);
  1077. shard->size = atoul(row[16]);
  1078. shard->appearance.pos.collision_radius = atoul(row[17]);
  1079. shard->appearance.action_state = atoul(row[18]);
  1080. shard->appearance.visual_state = atoul(row[19]); // ghostly look
  1081. shard->appearance.mood_state = atoul(row[20]);
  1082. shard->appearance.emote_state = atoul(row[21]);
  1083. shard->appearance.pos.state = atoul(row[22]);
  1084. shard->appearance.activity_status = atoul(row[23]);
  1085. if(row[24])
  1086. strncpy(shard->appearance.sub_title, row[24], sizeof(shard->appearance.sub_title));
  1087. if(row[25])
  1088. shard->SetPrefixTitle(row[25]);
  1089. if(row[26])
  1090. shard->SetSuffixTitle(row[26]);
  1091. if(row[27])
  1092. shard->SetLastName(row[27]);
  1093. shard->SetX(atof(row[28]));
  1094. shard->SetY(atof(row[29]));
  1095. shard->SetZ(atof(row[30]));
  1096. shard->SetHeading(atof(row[31]));
  1097. shard->SetSpawnOrigX(shard->GetX());
  1098. shard->SetSpawnOrigY(shard->GetY());
  1099. shard->SetSpawnOrigZ(shard->GetZ());
  1100. shard->SetSpawnOrigHeading(shard->GetHeading());
  1101. shard->SetLocation(atoul(row[32]));
  1102. shard->SetShardID(atoul(row[33]));
  1103. shard->SetShardCharID(atoul(row[34]));
  1104. shard->SetAlive(false);
  1105. const char* script = rule_manager.GetGlobalRule(R_Combat, SpiritShardSpawnScript)->GetString();
  1106. if(script)
  1107. {
  1108. shard->SetSpawnScript(script);
  1109. zone->CallSpawnScript(shard, SPAWN_SCRIPT_PRESPAWN);
  1110. }
  1111. zone->AddSpawn(shard);
  1112. if(script)
  1113. zone->CallSpawnScript(shard, SPAWN_SCRIPT_SPAWN);
  1114. total++;
  1115. LogWrite(NPC__DEBUG, 5, "NPC", "---Loading Player Spirit Shard: '%s' (%u)", shard->appearance.name, id);
  1116. }
  1117. LogWrite(NPC__INFO, 0, "NPC", "--Loaded %i Spirit Shard(s).", total);
  1118. }
  1119. void WorldDatabase::LoadSigns(ZoneServer* zone){
  1120. Query query;
  1121. MYSQL_ROW row;
  1122. Sign* sign = 0;
  1123. int32 id = 0;
  1124. int32 total = 0;
  1125. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT ss.spawn_id, s.name, s.model_type, s.size, s.show_command_icon, ss.widget_id, ss.widget_x, ss.widget_y, ss.widget_z, s.command_primary, s.command_secondary, s.collision_radius, ss.icon, ss.type, ss.title, ss.description, ss.sign_distance, ss.zone_id, ss.zone_x, ss.zone_y, ss.zone_z, ss.zone_heading, ss.include_heading, ss.include_location, s.transport_id, s.size_offset, s.display_hand_icon, s.visual_state, s.expansion_flag, s.holiday_flag, s.disable_sounds, s.merchant_min_level, s.merchant_max_level, s.aaxp_rewards, s.loot_tier, s.loot_drop_type, ss.language\n"
  1126. "FROM spawn s\n"
  1127. "INNER JOIN spawn_signs ss\n"
  1128. "ON s.id = ss.spawn_id\n"
  1129. "INNER JOIN spawn_location_entry le\n"
  1130. "ON ss.spawn_id = le.spawn_id\n"
  1131. "INNER JOIN spawn_location_placement lp\n"
  1132. "ON le.spawn_location_id = lp.spawn_location_id\n"
  1133. "WHERE lp.zone_id = %u\n"
  1134. "GROUP BY s.id",
  1135. zone->GetZoneID());
  1136. while(result && (row = mysql_fetch_row(result))){
  1137. int32 signXpackFlag = atoul(row[28]);
  1138. int32 signHolidayFlag = atoul(row[29]);
  1139. id = atoul(row[0]);
  1140. if(zone->GetSign(id, true))
  1141. continue;
  1142. sign = new Sign();
  1143. if (!CheckExpansionFlags(zone, signXpackFlag) || !CheckHolidayFlags(zone, signHolidayFlag))
  1144. sign->SetOmittedByDBFlag(true);
  1145. sign->SetDatabaseID(id);
  1146. strcpy(sign->appearance.name, row[1]);
  1147. sign->appearance.model_type = atoi(row[2]);
  1148. sign->SetSize(atoi(row[3]));
  1149. sign->appearance.show_command_icon = atoi(row[4]);
  1150. sign->SetWidgetID(atoul(row[5]));
  1151. sign->SetWidgetX(atof(row[6]));
  1152. sign->SetWidgetY(atof(row[7]));
  1153. sign->SetWidgetZ(atof(row[8]));
  1154. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(atoul(row[9]));
  1155. if(primary_command_list){
  1156. sign->SetPrimaryCommands(primary_command_list);
  1157. sign->primary_command_list_id = atoul(row[9]);
  1158. }
  1159. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(atoul(row[10]));
  1160. if (secondary_command_list){
  1161. sign->SetSecondaryCommands(secondary_command_list);
  1162. sign->secondary_command_list_id = atoul(row[10]);
  1163. }
  1164. sign->appearance.pos.collision_radius = atoi(row[11]);
  1165. sign->SetSignIcon(atoi(row[12]));
  1166. if(strncasecmp(row[13],"Generic", 7) == 0)
  1167. sign->SetSignType(SIGN_TYPE_GENERIC);
  1168. else if(strncasecmp(row[13],"Zone", 4) == 0)
  1169. sign->SetSignType(SIGN_TYPE_ZONE);
  1170. sign->SetSignTitle(row[14]);
  1171. sign->SetSignDescription(row[15]);
  1172. sign->SetSignDistance(atof(row[16]));
  1173. sign->SetSignZoneID(atoul(row[17]));
  1174. sign->SetSignZoneX(atof(row[18]));
  1175. sign->SetSignZoneY(atof(row[19]));
  1176. sign->SetSignZoneZ(atof(row[20]));
  1177. sign->SetSignZoneHeading(atof(row[21]));
  1178. sign->SetIncludeHeading(atoi(row[22]) == 1);
  1179. sign->SetIncludeLocation(atoi(row[23]) == 1);
  1180. sign->SetTransporterID(atoul(row[24]));
  1181. sign->SetSizeOffset(atoi(row[25]));
  1182. sign->appearance.display_hand_icon = atoi(row[26]);
  1183. sign->SetVisualState(atoi(row[27]));
  1184. // xpack+holiday value handled at top at position 28+29
  1185. int8 disableSounds = atoul(row[30]);
  1186. sign->SetSoundsDisabled(disableSounds);
  1187. sign->SetMerchantLevelRange(atoul(row[31]), atoul(row[32]));
  1188. sign->SetAAXPRewards(atoul(row[33]));
  1189. sign->SetLootTier(atoul(row[34]));
  1190. sign->SetLootDropType(atoul(row[35]));
  1191. sign->SetLanguage(atoul(row[36]));
  1192. zone->AddSign(id, sign);
  1193. total++;
  1194. LogWrite(SIGN__DEBUG, 5, "Sign", "---Loading Sign: '%s' (%u).", sign->appearance.name, id);
  1195. }
  1196. LogWrite(SIGN__DEBUG, 0, "Sign", "--Loaded %i Sign(s)", total);
  1197. }
  1198. void WorldDatabase::LoadWidgets(ZoneServer* zone){
  1199. Query query;
  1200. MYSQL_ROW row;
  1201. Widget* widget = 0;
  1202. int32 id = 0;
  1203. int32 total = 0;
  1204. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT sw.spawn_id, s.name, s.model_type, s.size, s.show_command_icon, sw.widget_id, sw.widget_x, sw.widget_y, sw.widget_z, s.command_primary, s.command_secondary, s.collision_radius, sw.include_heading, sw.include_location, sw.icon, sw.type, sw.open_heading, sw.open_y, sw.action_spawn_id, sw.open_sound_file, sw.close_sound_file, sw.open_duration, sw.closed_heading, sw.linked_spawn_id, sw.close_y, s.transport_id, s.size_offset, sw.house_id, sw.open_x, sw.open_z, sw.close_x, sw.close_z, s.display_hand_icon, s.expansion_flag, s.holiday_flag, s.disable_sounds, s.merchant_min_level, s.merchant_max_level, s.aaxp_rewards, s.loot_tier, s.loot_drop_type\n"
  1205. "FROM spawn s\n"
  1206. "INNER JOIN spawn_widgets sw\n"
  1207. "ON s.id = sw.spawn_id\n"
  1208. "INNER JOIN spawn_location_entry le\n"
  1209. "ON sw.spawn_id = le.spawn_id\n"
  1210. "INNER JOIN spawn_location_placement lp\n"
  1211. "ON le.spawn_location_id = lp.spawn_location_id\n"
  1212. "WHERE lp.zone_id = %u\n"
  1213. "GROUP BY s.id",
  1214. zone->GetZoneID());
  1215. while(result && (row = mysql_fetch_row(result))){
  1216. int32 widgetXpackFlag = atoul(row[33]);
  1217. int32 widgetHolidayFlag = atoul(row[34]);
  1218. id = atoul(row[0]);
  1219. if(zone->GetWidget(id, true))
  1220. continue;
  1221. widget = new Widget();
  1222. if (!CheckExpansionFlags(zone, widgetXpackFlag) || !CheckHolidayFlags(zone, widgetHolidayFlag))
  1223. widget->SetOmittedByDBFlag(true);
  1224. widget->SetDatabaseID(id);
  1225. strcpy(widget->appearance.name, row[1]);
  1226. widget->appearance.model_type = atoi(row[2]);
  1227. widget->SetSize(atoi(row[3]));
  1228. widget->appearance.show_command_icon = atoi(row[4]);
  1229. if (row[5] == NULL)
  1230. widget->SetWidgetID(0xFFFFFFFF);
  1231. else
  1232. widget->SetWidgetID(atoul(row[5]));
  1233. widget->SetWidgetX(atof(row[6]));
  1234. widget->SetWidgetY(atof(row[7]));
  1235. widget->SetWidgetZ(atof(row[8]));
  1236. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(atoul(row[9]));
  1237. if(primary_command_list){
  1238. widget->SetPrimaryCommands(primary_command_list);
  1239. widget->primary_command_list_id = atoul(row[9]);
  1240. }
  1241. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(atoul(row[10]));
  1242. if (secondary_command_list) {
  1243. widget->SetSecondaryCommands(secondary_command_list);
  1244. widget->secondary_command_list_id = atoul(row[10]);
  1245. }
  1246. widget->appearance.pos.collision_radius = atoi(row[11]);
  1247. widget->SetIncludeHeading(atoi(row[12]) == 1);
  1248. widget->SetIncludeLocation(atoi(row[13]) == 1);
  1249. widget->SetWidgetIcon(atoi(row[14]));
  1250. if (strncasecmp(row[15], "Generic", 7) == 0)
  1251. widget->SetWidgetType(WIDGET_TYPE_GENERIC);
  1252. else if (strncasecmp(row[15], "Door", 4) == 0)
  1253. widget->SetWidgetType(WIDGET_TYPE_DOOR);
  1254. else if (strncasecmp(row[15], "Lift", 4) == 0)
  1255. widget->SetWidgetType(WIDGET_TYPE_LIFT);
  1256. widget->SetOpenHeading(atof(row[16]));
  1257. widget->SetOpenY(atof(row[17]));
  1258. widget->SetActionSpawnID(atoul(row[18]));
  1259. if(row[19] && strlen(row[19]) > 5)
  1260. widget->SetOpenSound(row[19]);
  1261. if(row[20] && strlen(row[20]) > 5)
  1262. widget->SetCloseSound(row[20]);
  1263. widget->SetOpenDuration(atoi(row[21]));
  1264. widget->SetClosedHeading(atof(row[22]));
  1265. widget->SetLinkedSpawnID(atoul(row[23]));
  1266. widget->SetCloseY(atof(row[24]));
  1267. widget->SetTransporterID(atoul(row[25]));
  1268. widget->SetSizeOffset(atoi(row[26]));
  1269. widget->SetHouseID(atoul(row[27]));
  1270. widget->SetOpenX(atof(row[28]));
  1271. widget->SetOpenZ(atof(row[29]));
  1272. widget->SetCloseX(atof(row[30]));
  1273. widget->SetCloseZ(atof(row[31]));
  1274. widget->appearance.display_hand_icon = atoi(row[32]);
  1275. // xpack+holiday value handled at top at position 33+34
  1276. int8 disableSounds = atoul(row[35]);
  1277. widget->SetSoundsDisabled(disableSounds);
  1278. widget->SetMerchantLevelRange(atoul(row[36]), atoul(row[37]));
  1279. widget->SetAAXPRewards(atoul(row[38]));
  1280. widget->SetLootTier(atoul(row[39]));
  1281. widget->SetLootDropType(atoul(row[40]));
  1282. zone->AddWidget(id, widget);
  1283. total++;
  1284. LogWrite(WIDGET__DEBUG, 5, "Widget", "---Loading Widget: '%s' (%u).", widget->appearance.name, id);
  1285. }
  1286. LogWrite(WIDGET__DEBUG, 0, "Widget", "--Loaded %i Widget(s)", total);
  1287. }
  1288. void WorldDatabase::LoadObjects(ZoneServer* zone){
  1289. Query query;
  1290. MYSQL_ROW row;
  1291. Object* object = 0;
  1292. int32 id = 0;
  1293. int32 total = 0;
  1294. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT so.spawn_id, s.name, s.race, s.model_type, s.command_primary, s.command_secondary, s.targetable, s.size, s.show_name, s.visual_state, s.attackable, s.show_level, s.show_command_icon, s.display_hand_icon, s.faction_id, s.collision_radius, s.transport_id, s.size_offset, so.device_id, s.expansion_flag, s.holiday_flag, s.disable_sounds, s.merchant_min_level, s.merchant_max_level, s.aaxp_rewards, s.loot_tier, s.loot_drop_type\n"
  1295. "FROM spawn s\n"
  1296. "INNER JOIN spawn_objects so\n"
  1297. "ON s.id = so.spawn_id\n"
  1298. "INNER JOIN spawn_location_entry le\n"
  1299. "ON so.spawn_id = le.spawn_id\n"
  1300. "INNER JOIN spawn_location_placement lp\n"
  1301. "ON le.spawn_location_id = lp.spawn_location_id\n"
  1302. "WHERE lp.zone_id = %u and (lp.instance_id = 0 or lp.instance_id = %u)\n"
  1303. "GROUP BY s.id",
  1304. zone->GetZoneID(), zone->GetInstanceID());
  1305. while(result && (row = mysql_fetch_row(result))){
  1306. int32 objXpackFlag = atoul(row[19]);
  1307. int32 objHolidayFlag = atoul(row[20]);
  1308. id = atoul(row[0]);
  1309. if(zone->GetObject(id, true))
  1310. continue;
  1311. object = new Object();
  1312. if (!CheckExpansionFlags(zone, objXpackFlag) || !CheckHolidayFlags(zone, objHolidayFlag))
  1313. object->SetOmittedByDBFlag(true);
  1314. object->SetDatabaseID(id);
  1315. strcpy(object->appearance.name, row[1]);
  1316. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(atoul(row[4]));
  1317. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(atoul(row[5]));
  1318. if(primary_command_list){
  1319. object->SetPrimaryCommands(primary_command_list);
  1320. object->primary_command_list_id = atoul(row[4]);
  1321. }
  1322. if(secondary_command_list){
  1323. object->SetSecondaryCommands(secondary_command_list);
  1324. object->secondary_command_list_id = atoul(row[5]);
  1325. }
  1326. object->appearance.race = atoi(row[2]);
  1327. object->appearance.model_type = atoi(row[3]);
  1328. object->appearance.targetable = atoi(row[6]);
  1329. object->size = atoi(row[7]);
  1330. object->appearance.display_name = atoi(row[8]);
  1331. object->appearance.visual_state = atoi(row[9]);
  1332. object->appearance.attackable = atoi(row[10]);
  1333. object->appearance.show_level = atoi(row[11]);
  1334. object->appearance.show_command_icon = atoi(row[12]);
  1335. object->appearance.display_hand_icon = atoi(row[13]);
  1336. object->faction_id = atoul(row[14]);
  1337. object->appearance.pos.collision_radius = atoi(row[15]);
  1338. object->SetTransporterID(atoul(row[16]));
  1339. object->SetSizeOffset(atoi(row[17]));
  1340. object->SetDeviceID(atoi(row[18]));
  1341. // xpack value handled at top at position 19
  1342. int8 disableSounds = atoul(row[21]);
  1343. object->SetSoundsDisabled(disableSounds);
  1344. object->SetMerchantLevelRange(atoul(row[22]), atoul(row[23]));
  1345. object->SetAAXPRewards(atoul(row[24]));
  1346. object->SetLootTier(atoul(row[25]));
  1347. object->SetLootDropType(atoul(row[26]));
  1348. zone->AddObject(id, object);
  1349. total++;
  1350. LogWrite(OBJECT__DEBUG, 5, "Object", "---Loading Object: '%s' (%u)", object->appearance.name, id);
  1351. }
  1352. LogWrite(OBJECT__DEBUG, 0, "Object", "--Loaded %i Object(s)", total);
  1353. }
  1354. void WorldDatabase::LoadGroundSpawns(ZoneServer* zone){
  1355. Query query;
  1356. MYSQL_ROW row;
  1357. GroundSpawn* spawn = 0;
  1358. int32 id = 0;
  1359. int32 total = 0;
  1360. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT sg.spawn_id, s.name, s.race, s.model_type, s.command_primary, s.command_secondary, s.targetable, s.size, s.show_name, s.visual_state, s.attackable, s.show_level, s.show_command_icon, s.display_hand_icon, s.faction_id, s.collision_radius, sg.number_harvests, sg.num_attempts_per_harvest, sg.groundspawn_id, sg.collection_skill, s.size_offset, s.expansion_flag, s.holiday_flag, s.disable_sounds, s.aaxp_rewards, s.loot_tier, s.loot_drop_type\n"
  1361. "FROM spawn s\n"
  1362. "INNER JOIN spawn_ground sg\n"
  1363. "ON s.id = sg.spawn_id\n"
  1364. "INNER JOIN spawn_location_entry le\n"
  1365. "ON sg.spawn_id = le.spawn_id\n"
  1366. "INNER JOIN spawn_location_placement lp\n"
  1367. "ON le.spawn_location_id = lp.spawn_location_id\n"
  1368. "WHERE lp.zone_id = %u\n"
  1369. "GROUP BY s.id",
  1370. zone->GetZoneID());
  1371. while(result && (row = mysql_fetch_row(result))){
  1372. int32 gsXpackFlag = atoul(row[21]);
  1373. int32 gsHolidayFlag = atoul(row[22]);
  1374. id = atoul(row[0]);
  1375. if(zone->GetGroundSpawn(id, true))
  1376. continue;
  1377. spawn = new GroundSpawn();
  1378. if (!CheckExpansionFlags(zone, gsXpackFlag) || !CheckHolidayFlags(zone, gsHolidayFlag))
  1379. spawn->SetOmittedByDBFlag(true);
  1380. spawn->SetDatabaseID(id);
  1381. spawn->forceMapCheck = true;
  1382. strcpy(spawn->appearance.name, row[1]);
  1383. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(atoul(row[4]));
  1384. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(atoul(row[5]));
  1385. if(primary_command_list){
  1386. spawn->SetPrimaryCommands(primary_command_list);
  1387. spawn->primary_command_list_id = atoul(row[4]);
  1388. }
  1389. if(secondary_command_list){
  1390. spawn->SetSecondaryCommands(secondary_command_list);
  1391. spawn->secondary_command_list_id = atoul(row[5]);
  1392. }
  1393. spawn->appearance.race = atoi(row[2]);
  1394. spawn->appearance.model_type = atoi(row[3]);
  1395. spawn->appearance.targetable = atoi(row[6]);
  1396. spawn->size = atoi(row[7]);
  1397. spawn->appearance.display_name = atoi(row[8]);
  1398. spawn->appearance.visual_state = atoi(row[9]);
  1399. spawn->appearance.attackable = atoi(row[10]);
  1400. spawn->appearance.show_level = atoi(row[11]);
  1401. spawn->appearance.show_command_icon = atoi(row[12]);
  1402. spawn->appearance.display_hand_icon = atoi(row[13]);
  1403. spawn->faction_id = atoul(row[14]);
  1404. spawn->appearance.pos.collision_radius = atoi(row[15]);
  1405. spawn->SetNumberHarvests(atoi(row[16]));
  1406. spawn->SetAttemptsPerHarvest(atoi(row[17]));
  1407. spawn->SetGroundSpawnEntryID(atoul(row[18]));
  1408. spawn->SetCollectionSkill(row[19]);
  1409. spawn->SetSizeOffset(atoi(row[20]));
  1410. // xpack+holiday value handled at top at position 21+22
  1411. int8 disableSounds = atoul(row[23]);
  1412. spawn->SetSoundsDisabled(disableSounds);
  1413. spawn->SetAAXPRewards(atoul(row[24]));
  1414. spawn->SetLootTier(atoul(row[25]));
  1415. spawn->SetLootDropType(atoul(row[26]));
  1416. zone->AddGroundSpawn(id, spawn);
  1417. total++;
  1418. LogWrite(GROUNDSPAWN__DEBUG, 5, "GSpawn", "---Loading GroundSpawn: '%s' (%u)", spawn->appearance.name, id);
  1419. }
  1420. LogWrite(GROUNDSPAWN__DEBUG, 0, "GSpawn", "--Loaded %i GroundSpawn(s)", total);
  1421. }
  1422. void WorldDatabase::LoadGroundSpawnItems(ZoneServer* zone) {
  1423. Query query;
  1424. MYSQL_ROW row;
  1425. int32 total = 0;
  1426. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT groundspawn_id, item_id, is_rare, grid_id FROM groundspawn_items;");
  1427. while(result && (row = mysql_fetch_row(result)))
  1428. {
  1429. zone->AddGroundSpawnItem(atoul(row[0]), atoul(row[1]), atoi(row[2]), atoul(row[3]));
  1430. LogWrite(GROUNDSPAWN__DEBUG, 5, "GSpawn", "---Loading GroundSpawn Items: ID: %u\n", atoul(row[0]));
  1431. LogWrite(GROUNDSPAWN__DEBUG, 5, "GSpawn", "---item: %ul, rare: %i, grid: %ul", atoul(row[1]), atoi(row[2]), atoul(row[3]));
  1432. total++;
  1433. }
  1434. LogWrite(GROUNDSPAWN__DEBUG, 0, "GSpawn", "--Loaded %i GroundSpawn Item%s.", total, total == 1 ? "" : "s");
  1435. }
  1436. void WorldDatabase::LoadGroundSpawnEntries(ZoneServer* zone) {
  1437. Query query;
  1438. MYSQL_ROW row;
  1439. int32 total = 0;
  1440. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT groundspawn_id, min_skill_level, min_adventure_level, bonus_table, harvest1, harvest3, harvest5, harvest_imbue, harvest_rare, harvest10, harvest_coin FROM groundspawns WHERE enabled = 1;");
  1441. while(result && (row = mysql_fetch_row(result)))
  1442. {
  1443. // this is getting ridonkulous...
  1444. LogWrite(GROUNDSPAWN__DEBUG, 5, "GSpawn", "---Loading GroundSpawn ID: %u\n" \
  1445. "---min_skill_level: %i, min_adventure_level: %i, bonus_table: %i\n" \
  1446. "---harvest1: %.2f, harvest3: %.2f, harvest5: %.2f\n" \
  1447. "---harvest_imbue: %.2f, harvest_rare: %.2f, harvest10: %.2f\n" \
  1448. "---harvest_coin: %u", atoul(row[0]), atoi(row[1]), atoi(row[2]), atoi(row[3]), atof(row[4]), atof(row[5]), atof(row[6]), atof(row[7]), atof(row[8]), atof(row[9]), atoul(row[10]));
  1449. zone->AddGroundSpawnEntry(atoul(row[0]), atoi(row[1]), atoi(row[2]), atoi(row[3]), atof(row[4]), atof(row[5]), atof(row[6]), atof(row[7]), atof(row[8]), atof(row[9]), atoul(row[10]));
  1450. total++;
  1451. }
  1452. LogWrite(GROUNDSPAWN__DEBUG, 0, "GSpawn", "--Loaded %i GroundSpawn Entr%s.", total, total == 1 ? "y" : "ies");
  1453. LoadGroundSpawnItems(zone);
  1454. }
  1455. bool WorldDatabase::LoadCharacterStats(int32 id, int32 account_id, Client* client)
  1456. {
  1457. DatabaseResult result;
  1458. if( database_new.Select(&result, "SELECT * FROM character_details WHERE char_id = %i LIMIT 0, 1", id) )
  1459. {
  1460. LogWrite(PLAYER__DEBUG, 0, "Player", "Loading character_details for '%s' (char_id: %u)", client->GetPlayer()->GetName(), id);
  1461. while( result.Next() )
  1462. {
  1463. InfoStruct* info = client->GetPlayer()->GetInfoStruct();
  1464. // must have totals up top before we set the current 'hp' / 'power'
  1465. client->GetPlayer()->SetTotalHP(result.GetSInt32Str("max_hp"));
  1466. client->GetPlayer()->SetTotalPower(result.GetSInt32Str("max_power"));
  1467. client->GetPlayer()->SetTotalHPBase(client->GetPlayer()->GetTotalHP());
  1468. client->GetPlayer()->SetTotalPowerBase(client->GetPlayer()->GetTotalPower());
  1469. client->GetPlayer()->SetHP(result.GetSInt32Str("hp"));
  1470. client->GetPlayer()->SetPower(result.GetSInt32Str("power"));
  1471. info->set_max_concentration_base(result.GetInt8Str("max_concentration"));
  1472. if (info->get_max_concentration_base() == 0)
  1473. info->set_max_concentration_base(5);
  1474. info->set_attack_base(result.GetInt16Str("attack"));
  1475. info->set_mitigation_base(result.GetInt16Str("mitigation"));
  1476. info->set_avoidance_base(result.GetInt16Str("avoidance"));
  1477. info->set_parry_base(result.GetInt16Str("parry"));
  1478. info->set_deflection_base(result.GetInt16Str("deflection"));
  1479. info->set_block_base(result.GetInt16Str("block"));
  1480. info->set_str_base(result.GetInt16Str("str"));
  1481. info->set_sta_base(result.GetInt16Str("sta"));
  1482. info->set_agi_base(result.GetInt16Str("agi"));
  1483. info->set_wis_base(result.GetInt16Str("wis"));
  1484. info->set_intel_base(result.GetInt16Str("intel"));
  1485. // old resist types
  1486. info->set_heat_base(result.GetInt16Str("heat"));
  1487. info->set_cold_base(result.GetInt16Str("cold"));
  1488. info->set_magic_base(result.GetInt16Str("magic"));
  1489. info->set_mental_base(result.GetInt16Str("mental"));
  1490. info->set_divine_base(result.GetInt16Str("divine"));
  1491. info->set_disease_base(result.GetInt16Str("disease"));
  1492. info->set_poison_base(result.GetInt16Str("poison"));
  1493. //
  1494. info->set_coin_copper(result.GetInt32Str("coin_copper"));
  1495. info->set_coin_silver(result.GetInt32Str("coin_silver"));
  1496. info->set_coin_gold(result.GetInt32Str("coin_gold"));
  1497. info->set_coin_plat(result.GetInt32Str("coin_plat"));
  1498. const char* bio = result.GetStringStr("biography");
  1499. if(bio && strlen(bio) > 0)
  1500. info->set_biography(std::string(bio));
  1501. info->set_status_points(result.GetInt32Str("status_points"));
  1502. client->GetPlayer()->GetPlayerInfo()->SetBindZone(result.GetInt32Str("bind_zone_id"));
  1503. client->GetPlayer()->GetPlayerInfo()->SetBindX(result.GetFloatStr("bind_x"));
  1504. client->GetPlayer()->GetPlayerInfo()->SetBindY(result.GetFloatStr("bind_y"));
  1505. client->GetPlayer()->GetPlayerInfo()->SetBindZ(result.GetFloatStr("bind_z"));
  1506. client->GetPlayer()->GetPlayerInfo()->SetBindHeading(result.GetFloatStr("bind_heading"));
  1507. client->GetPlayer()->GetPlayerInfo()->SetHouseZone(result.GetInt32Str("house_zone_id"));
  1508. client->GetPlayer()->SetAssignedAA(result.GetInt16Str("assigned_aa"));
  1509. client->GetPlayer()->SetUnassignedAA(result.GetInt16Str("unassigned_aa"));
  1510. client->GetPlayer()->SetTradeskillAA(result.GetInt16Str("tradeskill_aa"));
  1511. client->GetPlayer()->SetUnassignedTradeskillAA(result.GetInt16Str("unassigned_tradeskill_aa"));
  1512. client->GetPlayer()->SetPrestigeAA(result.GetInt16Str("prestige_aa"));
  1513. client->GetPlayer()->SetUnassignedPrestigeAA(result.GetInt16Str("unassigned_prestige_aa"));
  1514. client->GetPlayer()->SetTradeskillPrestigeAA(result.GetInt16Str("tradeskill_prestige_aa"));
  1515. client->GetPlayer()->SetUnassignedTradeskillPrestigeAA(result.GetInt16Str("unassigned_tradeskill_prestige_aa"));
  1516. info->set_xp(result.GetInt32Str("xp"));
  1517. info->set_xp_needed(result.GetInt32Str("xp_needed"));
  1518. if(info->get_xp_needed()== 0)
  1519. client->GetPlayer()->SetNeededXP();
  1520. info->set_xp_debt(result.GetFloatStr("xp_debt"));
  1521. info->set_xp_vitality(result.GetFloatStr("xp_vitality"));
  1522. info->set_ts_xp(result.GetInt32Str("tradeskill_xp"));
  1523. info->set_ts_xp_needed(result.GetInt32Str("tradeskill_xp_needed"));
  1524. if (info->get_ts_xp_needed() == 0)
  1525. client->GetPlayer()->SetNeededTSXP();
  1526. info->set_tradeskill_xp_vitality(result.GetFloatStr("tradeskill_xp_vitality"));
  1527. info->set_bank_coin_copper(result.GetInt32Str("bank_copper"));
  1528. info->set_bank_coin_silver(result.GetInt32Str("bank_silver"));
  1529. info->set_bank_coin_gold(result.GetInt32Str("bank_gold"));
  1530. info->set_bank_coin_plat(result.GetInt32Str("bank_plat"));
  1531. client->GetPlayer()->SetCombatVoice(result.GetInt16Str("combat_voice"));
  1532. client->GetPlayer()->SetEmoteVoice(result.GetInt16Str("emote_voice"));
  1533. client->GetPlayer()->SetBiography(result.GetStringStr("biography"));
  1534. client->GetPlayer()->GetInfoStruct()->set_flags(result.GetInt32Str("flags"));
  1535. client->GetPlayer()->GetInfoStruct()->set_flags2(result.GetInt32Str("flags2"));
  1536. client->GetPlayer()->SetLastName(result.GetStringStr("last_name"));
  1537. // new resist types
  1538. info->set_elemental_base(result.GetInt16Str("elemental"));
  1539. info->set_arcane_base(result.GetInt16Str("arcane"));
  1540. info->set_noxious_base(result.GetInt16Str("noxious"));
  1541. // new savagery and dissonance
  1542. client->GetPlayer()->SetSavagery(result.GetSInt16Str("savagery"));
  1543. client->GetPlayer()->SetDissonance(result.GetSInt16Str("dissonance"));
  1544. client->GetPlayer()->SetTotalSavageryBase(client->GetPlayer()->GetTotalSavagery());
  1545. client->GetPlayer()->SetTotalDissonanceBase(client->GetPlayer()->GetTotalDissonance());
  1546. client->GetPlayer()->SetCurrentLanguage(result.GetInt32Str("current_language"));
  1547. std::string petName = result.GetStringStr("pet_name");
  1548. boost::algorithm::to_lower(petName);
  1549. if(petName != "no pet") { // some reason we default to "no pet", the code handles an empty string as setting a random pet name when its summoned
  1550. client->GetPlayer()->GetInfoStruct()->set_pet_name(result.GetStringStr("pet_name"));
  1551. }
  1552. }
  1553. return true;
  1554. }
  1555. else
  1556. {
  1557. LogWrite(PLAYER__ERROR, 0, "Player", "Error loading character_details for '%s' (char_id: %u)", client->GetPlayer()->GetName(), id);
  1558. return false;
  1559. }
  1560. }
  1561. bool WorldDatabase::loadCharacter(const char* ch_name, int32 account_id, Client* client){
  1562. Query query, query4;
  1563. MYSQL_ROW row, row4;
  1564. int32 id = 0;
  1565. query.escaped_name = getEscapeString(ch_name);
  1566. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, current_zone_id, x, y, z, heading, admin_status, race, model_type, class, deity, level, gender, tradeskill_class, tradeskill_level, wing_type, hair_type, chest_type, legs_type, soga_wing_type, soga_hair_type, soga_chest_type, soga_legs_type, 0xFFFFFFFF - crc32(name), facial_hair_type, soga_facial_hair_type, instance_id, group_id, last_saved, DATEDIFF(curdate(), created_date) as accage, alignment, first_world_login FROM characters where name='%s' and account_id=%i AND deleted = 0", query.escaped_name, account_id);
  1567. // no character found
  1568. if ( result == NULL ) {
  1569. LogWrite(PLAYER__ERROR, 0, "Player", "Error loading character for '%s'", ch_name);
  1570. return false;
  1571. }
  1572. if (mysql_num_rows(result) == 1){
  1573. row = mysql_fetch_row(result);
  1574. id = strtoul(row[0], NULL, 0);
  1575. LogWrite(PLAYER__DEBUG, 0, "Player", "Loading character for '%s' (char_id: %u)", ch_name, id);
  1576. client->SetCharacterID(id);
  1577. client->GetPlayer()->SetCharacterID(id);
  1578. client->SetAccountID(account_id);
  1579. client->GetPlayer()->SetName(ch_name);
  1580. client->GetPlayer()->SetX(atof(row[2]));
  1581. client->GetPlayer()->SetY(atof(row[3]));
  1582. client->GetPlayer()->SetZ(atof(row[4]));
  1583. client->GetPlayer()->SetHeading(atof(row[5]));
  1584. client->SetAdminStatus(atoi(row[6]));
  1585. client->GetPlayer()->SetRace(atoi(row[7]));
  1586. client->GetPlayer()->SetModelType(atoi(row[8]));
  1587. client->GetPlayer()->SetAdventureClass(atoi(row[9]));
  1588. client->GetPlayer()->SetDeity(atoi(row[10]));
  1589. client->GetPlayer()->SetLevel(atoi(row[11]));
  1590. client->GetPlayer()->SetGender(atoi(row[12]));
  1591. client->GetPlayer()->SetTradeskillClass(atoi(row[13]));
  1592. client->GetPlayer()->SetTSLevel(atoi(row[14]));
  1593. client->GetPlayer()->features.wing_type = atoi(row[15]);
  1594. client->GetPlayer()->features.hair_type = atoi(row[16]);
  1595. client->GetPlayer()->features.chest_type = atoi(row[17]);
  1596. client->GetPlayer()->features.legs_type = atoi(row[18]);
  1597. client->GetPlayer()->features.wing_type = atoi(row[19]);
  1598. client->GetPlayer()->features.soga_hair_type = atoi(row[20]);
  1599. client->GetPlayer()->features.soga_chest_type = atoi(row[21]);
  1600. client->GetPlayer()->features.soga_legs_type = atoi(row[22]);
  1601. client->SetNameCRC(atoul(row[23]));
  1602. client->GetPlayer()->features.hair_face_type = atoi(row[24]);
  1603. client->GetPlayer()->features.soga_hair_face_type = atoi(row[25]);
  1604. int32 instanceid = atoi(row[26]);
  1605. int32 groupid = atoi(row[27]);
  1606. client->SetRejoinGroupID(groupid);
  1607. int32 zoneid = atoul(row[1]);
  1608. /*
  1609. JA Notes on SOGA: I think there are many more settings to add than were commented out here,
  1610. because I can load a SOGA model player, but some features are missing (Barbarian WOAD, Skin tons, etc)
  1611. SOGA chars looked ok in LoginServer screen tho... odd.
  1612. */
  1613. // load character instances here
  1614. if ( LoadCharacterInstances(client) )
  1615. client->UpdateCharacterInstances();
  1616. if ( instanceid > 0 )
  1617. client->SetCurrentZoneByInstanceID(instanceid, zoneid);
  1618. else
  1619. client->SetCurrentZone(zoneid);
  1620. int32 lastsavedtime = atoi(row[28]);
  1621. client->SetLastSavedTimeStamp(lastsavedtime);
  1622. if (row[29])
  1623. client->GetPlayer()->GetPlayerInfo()->SetAccountAge(atoi(row[29]));
  1624. client->GetPlayer()->GetInfoStruct()->set_alignment(atoi(row[30]));
  1625. client->GetPlayer()->GetInfoStruct()->set_first_world_login(atoi(row[31]));
  1626. LoadCharacterFriendsIgnoreList(client->GetPlayer());
  1627. MYSQL_RES* result4 = query4.RunQuery2(Q_SELECT, "SELECT `guild_id` FROM `guild_members` WHERE `char_id`=%u", id);
  1628. if (result4 && (row4 = mysql_fetch_row(result4))) {
  1629. Guild* guild = guild_list.GetGuild(atoul(row4[0]));
  1630. if (guild) {
  1631. client->GetPlayer()->SetGuild(guild);
  1632. string subtitle;
  1633. subtitle.append("<").append(guild->GetName()).append(">");
  1634. client->GetPlayer()->SetSubTitle(subtitle.c_str());
  1635. }
  1636. }
  1637. LoadCharacterHistory(id, client->GetPlayer());
  1638. LoadCharacterLUAHistory(id, client->GetPlayer());
  1639. LoadPlayerStatistics(client->GetPlayer(), id);
  1640. LoadPlayerCollections(client->GetPlayer());
  1641. LoadPlayerRecipes(client->GetPlayer());
  1642. //LoadPlayerAchievements(client->GetPlayer());
  1643. LoadPlayerAchievementsUpdates(client->GetPlayer());
  1644. LoadAppearances(client->GetCurrentZone(), client);
  1645. return LoadCharacterStats(id, account_id, client);
  1646. }
  1647. // should not be here...
  1648. LogWrite(PLAYER__ERROR, 0, "Player", "Error loading character for '%s'", ch_name);
  1649. return false;
  1650. }
  1651. void WorldDatabase::LoadCharacterQuestRewards(Client* client) {
  1652. Query query;
  1653. MYSQL_ROW row;
  1654. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT indexed, quest_id, is_temporary, is_collection, has_displayed, tmp_coin, tmp_status, description FROM character_quest_rewards where char_id = %u ORDER BY indexed asc", client->GetCharacterID());
  1655. int8 count = 0;
  1656. if(result)
  1657. {
  1658. while(result && (row = mysql_fetch_row(result)))
  1659. {
  1660. int32 index = atoul(row[0]);
  1661. int32 quest_id = atoul(row[1]);
  1662. bool is_temporary = atoul(row[2]);
  1663. bool is_collection = atoul(row[3]);
  1664. bool has_displayed = atoul(row[4]);
  1665. int64 tmp_coin = 0;
  1666. #ifdef WIN32
  1667. tmp_coin = _strtoui64(row[5], NULL, 10);
  1668. #else
  1669. tmp_coin = strtoull(row[5], 0, 10);
  1670. #endif
  1671. int32 tmp_status = atoul(row[6]);
  1672. std::string description = std::string("");
  1673. if(row[7]) {
  1674. std::string description = std::string(row[7]);
  1675. }
  1676. if(is_collection) {
  1677. map<int32, Collection*>* collections = client->GetPlayer()->GetCollectionList()->GetCollections();
  1678. map<int32, Collection*>::iterator itr;
  1679. Collection* collection = 0;
  1680. for (itr = collections->begin(); itr != collections->end(); itr++) {
  1681. collection = itr->second;
  1682. if (collection->GetIsReadyToTurnIn()) {
  1683. client->GetPlayer()->SetPendingCollectionReward(collection);
  1684. break;
  1685. }
  1686. }
  1687. }
  1688. if(is_temporary) {
  1689. LoadCharacterQuestTemporaryRewards(client, quest_id);
  1690. }
  1691. client->QueueQuestReward(quest_id, is_temporary, is_collection, has_displayed, tmp_coin, tmp_status, description, true, index);
  1692. count++;
  1693. }
  1694. }
  1695. if(count) {
  1696. client->SetQuestUpdateState(true);
  1697. }
  1698. }
  1699. void WorldDatabase::LoadCharacterQuestTemporaryRewards(Client* client, int32 quest_id) {
  1700. Query query;
  1701. MYSQL_ROW row;
  1702. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT item_id, count FROM character_quest_temporary_rewards where char_id = %u and quest_id = %u", client->GetCharacterID(), quest_id);
  1703. int8 count = 0;
  1704. if(result)
  1705. {
  1706. while(result && (row = mysql_fetch_row(result)))
  1707. {
  1708. int32 item_id = atoul(row[0]);
  1709. int16 item_count = atoul(row[1]);
  1710. client->GetPlayer()->AddQuestTemporaryReward(quest_id, item_id, item_count);
  1711. }
  1712. }
  1713. }
  1714. bool WorldDatabase::InsertCharacterStats(int32 character_id, int8 class_id, int8 race_id){
  1715. Query query1;
  1716. Query query2;
  1717. Query query3;
  1718. Query query4;
  1719. Query query5;
  1720. /* Blank record */
  1721. query1.RunQuery2(Q_INSERT, "INSERT INTO `character_details` (`char_id`) VALUES (%u)", character_id);
  1722. /* Using the class id and race id */
  1723. query2.RunQuery2(Q_UPDATE, "UPDATE character_details c, starting_details s SET c.max_hp = s.max_hp, c.hp = s.max_hp, c.max_power = s.max_power, c.power = s.max_power, c.str = s.str, c.sta = s.sta, c.agi = s.agi, c.wis = s.wis, c.intel = s.intel,c.heat = s.heat, c.cold = s.cold, c.magic = s.magic, c.mental = s.mental, c.divine = s.divine, c.disease = s.disease, c.poison = s.poison, c.coin_copper = s.coin_copper, c.coin_silver = s.coin_silver, c.coin_gold = s.coin_gold, c.coin_plat = s.coin_plat, c.status_points = s.status_points WHERE s.race_id = %d AND class_id = %d AND char_id = %u", race_id, class_id, character_id);
  1724. if (query2.GetAffectedRows() > 0)
  1725. return true;
  1726. /* Using the class id and race id = 255 */
  1727. query3.RunQuery2(Q_UPDATE, "UPDATE character_details c, starting_details s SET c.max_hp = s.max_hp, c.hp = s.max_hp, c.max_power = s.max_power, c.power = s.max_power, c.str = s.str, c.sta = s.sta, c.agi = s.agi, c.wis = s.wis, c.intel = s.intel,c.heat = s.heat, c.cold = s.cold, c.magic = s.magic, c.mental = s.mental, c.divine = s.divine, c.disease = s.disease, c.poison = s.poison, c.coin_copper = s.coin_copper, c.coin_silver = s.coin_silver, c.coin_gold = s.coin_gold, c.coin_plat = s.coin_plat, c.status_points = s.status_points WHERE s.race_id = 255 AND class_id = %d AND char_id = %u", class_id, character_id);
  1728. if (query3.GetAffectedRows() > 0)
  1729. return true;
  1730. /* Using class id = 255 and the race id */
  1731. query4.RunQuery2(Q_UPDATE, "UPDATE character_details c, starting_details s SET c.max_hp = s.max_hp, c.hp = s.max_hp, c.max_power = s.max_power, c.power = s.max_power, c.str = s.str, c.sta = s.sta, c.agi = s.agi, c.wis = s.wis, c.intel = s.intel,c.heat = s.heat, c.cold = s.cold, c.magic = s.magic, c.mental = s.mental, c.divine = s.divine, c.disease = s.disease, c.poison = s.poison, c.coin_copper = s.coin_copper, c.coin_silver = s.coin_silver, c.coin_gold = s.coin_gold, c.coin_plat = s.coin_plat, c.status_points = s.status_points WHERE s.race_id = %d AND class_id = 255 AND char_id = %u", race_id, character_id);
  1732. if (query4.GetAffectedRows() > 0)
  1733. return true;
  1734. /* Using class id = 255 and race id = 255 */
  1735. query5.RunQuery2(Q_UPDATE, "UPDATE character_details c, starting_details s SET c.max_hp = s.max_hp, c.hp = s.max_hp, c.max_power = s.max_power, c.power = s.max_power, c.str = s.str, c.sta = s.sta, c.agi = s.agi, c.wis = s.wis, c.intel = s.intel,c.heat = s.heat, c.cold = s.cold, c.magic = s.magic, c.mental = s.mental, c.divine = s.divine, c.disease = s.disease, c.poison = s.poison, c.coin_copper = s.coin_copper, c.coin_silver = s.coin_silver, c.coin_gold = s.coin_gold, c.coin_plat = s.coin_plat, c.status_points = s.status_points WHERE s.race_id = 255 AND class_id = 255 AND char_id = %u", character_id);
  1736. if (query5.GetAffectedRows() > 0)
  1737. return true;
  1738. return false;
  1739. }
  1740. int32 WorldDatabase::GetCharacterTimeStamp(int32 character_id, int32 account_id,bool* char_exists){
  1741. Query query;
  1742. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT unix_timestamp FROM characters where id=%i and account_id=%i",character_id,account_id);
  1743. if(result && mysql_num_rows(result) > 0) {
  1744. MYSQL_ROW row;
  1745. row = mysql_fetch_row(result);
  1746. *char_exists = true;
  1747. return atoi(row[0]); // Return timestamp
  1748. }
  1749. else
  1750. LogWrite(WORLD__ERROR, 0, "World", "Error in GetCharacterTimeStamp query '%s': %s", query.GetQuery(), query.GetError());
  1751. *char_exists = false;
  1752. return 0;
  1753. }
  1754. int32 WorldDatabase::GetCharacterTimeStamp(int32 character_id) {
  1755. Query query;
  1756. MYSQL_ROW row;
  1757. MYSQL_RES *result = query.RunQuery2(Q_SELECT, "SELECT unix_timestamp FROM characters WHERE id=%u", character_id);
  1758. int32 ret = 0;
  1759. if (result && (row = mysql_fetch_row(result)))
  1760. ret = atoul(row[0]);
  1761. return ret;
  1762. }
  1763. bool WorldDatabase::UpdateCharacterTimeStamp(int32 account_id, int32 character_id, int32 timestamp_update){
  1764. Query query;
  1765. string update_charts = string("update characters set unix_timestamp=%i where id=%i and account_id=%i");
  1766. query.RunQuery2(Q_UPDATE, update_charts.c_str(),timestamp_update,character_id,account_id);
  1767. if(!query.GetAffectedRows())
  1768. {
  1769. LogWrite(WORLD__ERROR, 0, "World", "Error in UpdateCharacterTimeStamp query '%s': %s", query.GetQuery(), query.GetError());
  1770. return false;
  1771. }
  1772. return true;
  1773. }
  1774. bool WorldDatabase::insertCharacterProperty(Client* client, char* propName, char* propValue) {
  1775. Query query, query2;
  1776. string update_status = string("update character_properties set propvalue='%s' where charid=%i and propname='%s'");
  1777. query.RunQuery2(Q_UPDATE, update_status.c_str(), propValue, client->GetCharacterID(), propName);
  1778. if (!query.GetAffectedRows())
  1779. {
  1780. query2.RunQuery2(Q_UPDATE, "insert into character_properties (charid, propname, propvalue) values(%i, '%s', '%s')", client->GetCharacterID(), propName, propValue);
  1781. if (query2.GetErrorNumber() && query2.GetError() && query2.GetErrorNumber() < 0xFFFFFFFF) {
  1782. LogWrite(WORLD__ERROR, 0, "World", "Error in insertCharacterProperty query '%s': %s", query.GetQuery(), query.GetError());
  1783. return false;
  1784. }
  1785. }
  1786. return true;
  1787. }
  1788. bool WorldDatabase::loadCharacterProperties(Client* client) {
  1789. Query query;
  1790. MYSQL_ROW row;
  1791. int32 id = 0;
  1792. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT propname, propvalue FROM character_properties where charid = %i", client->GetCharacterID());
  1793. // no character found
  1794. if (result == NULL) {
  1795. LogWrite(PLAYER__ERROR, 0, "Player", "Error loading character properties for '%s'", client->GetPlayer()->GetName());
  1796. return false;
  1797. }
  1798. while (result && (row = mysql_fetch_row(result))) {
  1799. char* prop_name = row[0];
  1800. char* prop_value = row[1];
  1801. if (!prop_name || !prop_value)
  1802. continue;
  1803. if (!stricmp(prop_name, CHAR_PROPERTY_SPEED))
  1804. {
  1805. float new_speed = atof(prop_value);
  1806. client->GetPlayer()->SetSpeed(new_speed, true);
  1807. client->GetPlayer()->SetCharSheetChanged(true);
  1808. }
  1809. else if (!stricmp(prop_name, CHAR_PROPERTY_FLYMODE))
  1810. {
  1811. int8 flymode = atoul(prop_value);
  1812. if (flymode) // avoid fly mode notification unless enabled
  1813. ClientPacketFunctions::SendFlyMode(client, flymode, false);
  1814. }
  1815. else if (!stricmp(prop_name, CHAR_PROPERTY_INVUL))
  1816. {
  1817. int8 invul = atoul(prop_value);
  1818. client->GetPlayer()->SetInvulnerable(invul == 1);
  1819. if (client->GetPlayer()->GetInvulnerable())
  1820. client->SimpleMessage(CHANNEL_COLOR_YELLOW, "You are now invulnerable!");
  1821. }
  1822. else if (!stricmp(prop_name, CHAR_PROPERTY_GMVISION))
  1823. {
  1824. int8 val = atoul(prop_value);
  1825. client->GetPlayer()->SetGMVision(val == 1);
  1826. client->GetCurrentZone()->SendAllSpawnsForVisChange(client, false);
  1827. if (val)
  1828. client->SimpleMessage(CHANNEL_COLOR_YELLOW, "GM Vision Enabled!");
  1829. }
  1830. else if (!stricmp(prop_name, CHAR_PROPERTY_REGIONDEBUG))
  1831. {
  1832. int8 val = atoul(prop_value);
  1833. client->SetRegionDebug(val == 1);
  1834. if (val)
  1835. client->SimpleMessage(CHANNEL_COLOR_YELLOW, "Region Debug Enabled!");
  1836. }
  1837. else if (!stricmp(prop_name, CHAR_PROPERTY_LUADEBUG))
  1838. {
  1839. int8 val = atoul(prop_value);
  1840. if (val)
  1841. {
  1842. client->SetLuaDebugClient(true);
  1843. if (lua_interface)
  1844. lua_interface->UpdateDebugClients(client);
  1845. client->SimpleMessage(CHANNEL_COLOR_YELLOW, "You will now receive LUA error messages.");
  1846. }
  1847. }
  1848. else if (!stricmp(prop_name, CHAR_PROPERTY_GROUPLOOTMETHOD))
  1849. {
  1850. int8 val = atoul(prop_value);
  1851. client->GetPlayer()->GetInfoStruct()->set_group_loot_method(val);
  1852. }
  1853. else if (!stricmp(prop_name, CHAR_PROPERTY_GROUPLOOTITEMRARITY))
  1854. {
  1855. int8 val = atoul(prop_value);
  1856. client->GetPlayer()->GetInfoStruct()->set_group_loot_items_rarity(val);
  1857. }
  1858. else if (!stricmp(prop_name, CHAR_PROPERTY_GROUPAUTOSPLIT))
  1859. {
  1860. int8 val = atoul(prop_value);
  1861. client->GetPlayer()->GetInfoStruct()->set_group_auto_split(val);
  1862. }
  1863. else if (!stricmp(prop_name, CHAR_PROPERTY_GROUPDEFAULTYELL))
  1864. {
  1865. int8 val = atoul(prop_value);
  1866. client->GetPlayer()->GetInfoStruct()->set_group_default_yell(val);
  1867. }
  1868. else if (!stricmp(prop_name, CHAR_PROPERTY_GROUPAUTOLOCK))
  1869. {
  1870. int8 val = atoul(prop_value);
  1871. client->GetPlayer()->GetInfoStruct()->set_group_autolock(val);
  1872. }
  1873. else if (!stricmp(prop_name, CHAR_PROPERTY_GROUPSOLOAUTOLOCK))
  1874. {
  1875. int8 val = atoul(prop_value);
  1876. client->GetPlayer()->GetInfoStruct()->set_group_solo_autolock(val);
  1877. }
  1878. else if (!stricmp(prop_name, CHAR_PROPERTY_AUTOLOOTMETHOD))
  1879. {
  1880. int8 val = atoul(prop_value);
  1881. client->GetPlayer()->GetInfoStruct()->set_group_auto_loot_method(val);
  1882. }
  1883. else if (!stricmp(prop_name, CHAR_PROPERTY_GROUPLOCKMETHOD))
  1884. {
  1885. int8 val = atoul(prop_value);
  1886. client->GetPlayer()->GetInfoStruct()->set_group_lock_method(val);
  1887. }
  1888. else if (!stricmp(prop_name, CHAR_PROPERTY_ASSISTAUTOATTACK))
  1889. {
  1890. int8 val = atoul(prop_value);
  1891. client->GetPlayer()->GetInfoStruct()->set_assist_auto_attack(val);
  1892. }
  1893. }
  1894. return true;
  1895. }
  1896. //gets the name FROM the db with the right letters in caps
  1897. string WorldDatabase::GetPlayerName(char* name){
  1898. Query query;
  1899. string ret = "";
  1900. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT name FROM characters where name='%s'", getSafeEscapeString(name).c_str());
  1901. if(result && mysql_num_rows(result) > 0) {
  1902. MYSQL_ROW row;
  1903. row = mysql_fetch_row(result);
  1904. if(row[0])
  1905. ret = string(row[0]);
  1906. }
  1907. return ret;
  1908. }
  1909. int32 WorldDatabase::GetCharacterID(const char* name) {
  1910. int32 id = 0;
  1911. Query query;
  1912. if (name) {
  1913. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `id` FROM `characters` WHERE `name`='%s'", name);
  1914. if (result && mysql_num_rows(result) > 0) {
  1915. MYSQL_ROW row;
  1916. row = mysql_fetch_row(result);
  1917. id = atoul(row[0]);
  1918. }
  1919. }
  1920. return id;
  1921. }
  1922. int32 WorldDatabase::GetCharacterCurrentZoneID(int32 character_id) {
  1923. int32 id = 0;
  1924. Query query;
  1925. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `current_zone_id` FROM `characters` WHERE `id`=%u", character_id);
  1926. if (result && mysql_num_rows(result) > 0) {
  1927. MYSQL_ROW row;
  1928. row = mysql_fetch_row(result);
  1929. id = atoul(row[0]);
  1930. }
  1931. return id;
  1932. }
  1933. int32 WorldDatabase::GetCharacterAccountID(int32 character_id) {
  1934. int32 id = 0;
  1935. Query query;
  1936. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `account_id` FROM `characters` WHERE `id`=%u", character_id);
  1937. if (result && mysql_num_rows(result) > 0) {
  1938. MYSQL_ROW row;
  1939. row = mysql_fetch_row(result);
  1940. id = atoul(row[0]);
  1941. }
  1942. return id;
  1943. }
  1944. sint16 WorldDatabase::GetHighestCharacterAdminStatus(int32 account_id){
  1945. Query query;
  1946. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT max(admin_status) FROM characters where account_id=%i ",account_id);
  1947. if(result && mysql_num_rows(result) > 0) {
  1948. MYSQL_ROW row;
  1949. row = mysql_fetch_row(result);
  1950. if ( row[0] != NULL )
  1951. return atoi(row[0]); // Return characters status
  1952. else
  1953. return 0;
  1954. }
  1955. return 0;
  1956. }
  1957. sint16 WorldDatabase::GetLowestCharacterAdminStatus(int32 account_id){
  1958. Query query;
  1959. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT min(admin_status) FROM characters where account_id=%i ",account_id);
  1960. if(result && mysql_num_rows(result) > 0) {
  1961. MYSQL_ROW row;
  1962. row = mysql_fetch_row(result);
  1963. if ( row[0] != NULL )
  1964. return atoi(row[0]); // Return characters status
  1965. else
  1966. return 0;
  1967. }
  1968. return 0;
  1969. }
  1970. sint16 WorldDatabase::GetCharacterAdminStatus(char* character_name){
  1971. Query query;
  1972. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT admin_status FROM characters where name='%s'", getSafeEscapeString(character_name).c_str());
  1973. if(result && mysql_num_rows(result) > 0) {
  1974. MYSQL_ROW row;
  1975. row = mysql_fetch_row(result);
  1976. return atoi(row[0]); // Return characters level
  1977. }
  1978. else
  1979. LogWrite(WORLD__ERROR, 0, "World", "Error in GetCharacterAdminStatus query '%s': %s", query.GetQuery(), query.GetError());
  1980. return -10;
  1981. }
  1982. sint16 WorldDatabase::GetCharacterAdminStatus(int32 account_id , int32 char_id){
  1983. Query query;
  1984. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT admin_status FROM characters where account_id=%i and id=%i",account_id,char_id);
  1985. if(result && mysql_num_rows(result) > 0) {
  1986. MYSQL_ROW row;
  1987. row = mysql_fetch_row(result);
  1988. return atoi(row[0]); // Return characters status
  1989. }
  1990. else{
  1991. Query query2;
  1992. result = query2.RunQuery2(Q_SELECT, "SELECT count(id) FROM characters where account_id=%i and id=%i",account_id,char_id);
  1993. if(result && mysql_num_rows(result) > 0) {
  1994. MYSQL_ROW row;
  1995. row = mysql_fetch_row(result);
  1996. if(atoi(row[0]) == 0) //old character, needs to be deleted FROM login server
  1997. return -10;
  1998. return -8;
  1999. }
  2000. else
  2001. LogWrite(WORLD__ERROR, 0, "World", "Error in GetCharacterAdminStatus query '%s': %s", query.GetQuery(), query.GetError());
  2002. }
  2003. return PLAY_ERROR_PROBLEM;
  2004. }
  2005. bool WorldDatabase::UpdateAdminStatus(char* character_name, sint16 flag){
  2006. Query query;
  2007. string update_status = string("update characters set admin_status=%i where name='%s'");
  2008. query.RunQuery2(Q_UPDATE, update_status.c_str(),flag,character_name);
  2009. if(!query.GetAffectedRows())
  2010. {
  2011. LogWrite(WORLD__ERROR, 0, "World", "Error in UpdateAdminStatus query '%s': %s", query.GetQuery(), query.GetError());
  2012. return false;
  2013. }
  2014. return true;
  2015. }
  2016. void WorldDatabase::SaveCharacterFloats(int32 char_id, const char* type, float float1, float float2, float float3, float multiplier){
  2017. Query query;
  2018. string create_char = string("insert into char_colors (char_id, type, red, green, blue, signed_value) values(%i,'%s',%i,%i,%i, 1)");
  2019. query.RunQuery2(Q_INSERT, create_char.c_str(), char_id, type, (sint8)(float1*multiplier), (sint8)(float2*multiplier), (sint8)(float3*multiplier));
  2020. if(query.GetError() && strlen(query.GetError()) > 0){
  2021. LogWrite(WORLD__ERROR, 0, "World", "Error in SaveCharacterFloats query '%s': %s", query.GetQuery(), query.GetError());
  2022. }
  2023. }
  2024. void WorldDatabase::SaveCharacterColors(int32 char_id, const char* type, EQ2_Color color){
  2025. Query query;
  2026. string create_char = string("insert into char_colors (char_id, type, red, green, blue) values(%i,'%s',%i,%i,%i)");
  2027. query.RunQuery2(Q_INSERT, create_char.c_str(), char_id, type, color.red, color.green, color.blue);
  2028. if(query.GetError() && strlen(query.GetError()) > 0){
  2029. LogWrite(WORLD__ERROR, 0, "World", "Error in SaveCharacterColors query '%s': %s", query.GetQuery(), query.GetError());
  2030. }
  2031. }
  2032. void WorldDatabase::SaveNPCAppearanceEquipment(int32 spawn_id, int8 slot_id, int16 type, int8 red, int8 green, int8 blue, int8 hred, int8 hgreen, int8 hblue){
  2033. Query query;
  2034. string appearance = string("INSERT INTO npc_appearance_equip (spawn_id, slot_id, equip_type, red, green, blue, highlight_red, highlight_green, highlight_blue) values (%i, %i, %i, %i, %i, %i, %i, %i, %i) ON DUPLICATE KEY UPDATE equip_type=%i, red=%i, green=%i, blue=%i, highlight_red=%i, highlight_green=%i, highlight_blue=%i");
  2035. query.RunQuery2(Q_INSERT, appearance.c_str(), spawn_id, slot_id, type, red, green, blue, hred, hgreen, hblue, type, red, green, blue, hred, hgreen, hblue);
  2036. if(query.GetError() && strlen(query.GetError()) > 0){
  2037. LogWrite(WORLD__ERROR, 0, "World", "Error in SaveNPCAppearanceEquipment query '%s': %s", query.GetQuery(), query.GetError());
  2038. }
  2039. }
  2040. int32 WorldDatabase::LoadNPCAppearanceEquipmentData(ZoneServer* zone){
  2041. Query query;
  2042. MYSQL_ROW row;
  2043. int32 spawn_id = 0, new_spawn_id = 0, count = 0;
  2044. NPC* npc = 0;
  2045. int8 slot = 0;
  2046. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT spawn_id, slot_id, equip_type, red, green, blue, highlight_red, highlight_green, highlight_blue FROM npc_appearance_equip ORDER BY spawn_id");
  2047. while(result && (row = mysql_fetch_row(result))){
  2048. new_spawn_id = atoul(row[0]);
  2049. if(new_spawn_id != spawn_id){
  2050. npc = zone->GetNPC(new_spawn_id, true);
  2051. if(!npc)
  2052. continue;
  2053. if(spawn_id > 0)
  2054. count++;
  2055. spawn_id = new_spawn_id;
  2056. }
  2057. slot = atoul(row[1]);
  2058. if(slot < NUM_SLOTS){
  2059. npc->SetEquipment(slot, atoul(row[2]), atoul(row[3]), atoul(row[4]), atoul(row[5]), atoul(row[6]), atoul(row[7]), atoul(row[8]));
  2060. }
  2061. }
  2062. if(query.GetError() && strlen(query.GetError()) > 0)
  2063. LogWrite(WORLD__ERROR, 0, "World", "Error in LoadNPCAppearanceEquipmentData query '%s': %s", query.GetQuery(), query.GetError());
  2064. return count;
  2065. }
  2066. int16 WorldDatabase::GetAppearanceID(string name){
  2067. int32 id = 0;
  2068. Query query;
  2069. MYSQL_ROW row;
  2070. query.escaped_name = getEscapeString(name.c_str());
  2071. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT appearance_id FROM appearances where name='%s'", query.escaped_name);
  2072. if(result && mysql_num_rows(result) == 1){
  2073. row = mysql_fetch_row(result);
  2074. id = atoi(row[0]);
  2075. }
  2076. return id;
  2077. }
  2078. vector<int16>* WorldDatabase::GetAppearanceIDsLikeName(string name, bool filtered) {
  2079. vector<int16>* ids = 0;
  2080. Query query;
  2081. MYSQL_ROW row;
  2082. query.escaped_name = getEscapeString(name.c_str());
  2083. MYSQL_RES* result;
  2084. if (filtered)
  2085. result = query.RunQuery2(Q_SELECT, "SELECT `appearance_id` FROM `appearances` WHERE `name` RLIKE '%s' AND `name` NOT RLIKE 'ghost' AND `name` NOT RLIKE 'headless' AND `name` NOT RLIKE 'elemental' AND `name` NOT RLIKE 'test' AND `name` NOT RLIKE 'zombie' AND `name` NOT RLIKE 'vampire'", query.escaped_name);
  2086. else
  2087. result = query.RunQuery2(Q_SELECT, "SELECT `appearance_id` FROM `appearances` WHERE `name` RLIKE '%s' AND `name` NOT RLIKE 'ghost' AND `name`", query.escaped_name);
  2088. while (result && (row = mysql_fetch_row(result))) {
  2089. if (!ids)
  2090. ids = new vector<int16>;
  2091. ids->push_back(atoi(row[0]));
  2092. }
  2093. return ids;
  2094. }
  2095. string WorldDatabase::GetAppearanceName(int16 appearance_id) {
  2096. Query query;
  2097. MYSQL_ROW row;
  2098. string name;
  2099. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `name` FROM `appearances` WHERE `appearance_id`=%u", appearance_id);
  2100. if (result && (row = mysql_fetch_row(result)))
  2101. name = string(row[0]);
  2102. return name;
  2103. }
  2104. void WorldDatabase::UpdateRandomize(int32 spawn_id, sint32 value) {
  2105. Query query;
  2106. query.RunQuery2(Q_UPDATE, "UPDATE `spawn_npcs` SET `randomize`=`randomize` + %i WHERE `spawn_id`=%u", value, spawn_id);
  2107. }
  2108. int32 WorldDatabase::SaveCharacter(PacketStruct* create, int32 loginID){
  2109. Query query;
  2110. int8 race_id = create->getType_int8_ByName("race");
  2111. int8 orig_class_id = create->getType_int8_ByName("class");//Normal server
  2112. int8 class_id = orig_class_id;
  2113. if ( create->GetVersion() <= 546 ) {
  2114. class_id = 0; //Classic Server Only
  2115. }
  2116. create->PrintPacket();
  2117. int8 gender_id = create->getType_int8_ByName("gender");
  2118. sint16 auto_admin_status = 0;
  2119. // fetch rules related to setting auto-admin status for server
  2120. bool auto_admin_players = rule_manager.GetGlobalRule(R_World, AutoAdminPlayers)->GetBool();
  2121. bool auto_admin_gm = rule_manager.GetGlobalRule(R_World, AutoAdminGMs)->GetBool();
  2122. /*
  2123. The way I think this is supposed to work :) is if any of your chars are already GM, and AutoAdminGMs rule is true,
  2124. set the new character's admin_status to your highest status for any character active on your loginID.
  2125. - If status > 0, new character > 0
  2126. - If status = 0, new character = 0
  2127. - If status < 0, new character < 0, too... even if auto_admin_gm is true
  2128. If we're not a GM (status = 0) but AutoAdminPlayers rule is true,
  2129. set the new character's admin_status to the default set in AutoAdminStatusValue rule.
  2130. Else, if both rules are False, set everyone to 0 like normal.
  2131. */
  2132. auto_admin_status = GetHighestCharacterAdminStatus(loginID);
  2133. if( auto_admin_status > 0 && auto_admin_gm ) {
  2134. LogWrite(WORLD__WARNING, 0, "World", "New character '%s' granted GM status (%i) from accountID: %i", create->getType_EQ2_16BitString_ByName("name").data.c_str(), auto_admin_status, loginID);
  2135. }
  2136. else if( auto_admin_players )
  2137. {
  2138. auto_admin_status = rule_manager.GetGlobalRule(R_World, AutoAdminStatusValue)->GetSInt16();
  2139. LogWrite(WORLD__DEBUG, 0, "World", "New character '%s' granted AutoAdminPlayer status: %i", create->getType_EQ2_16BitString_ByName("name").data.c_str(), auto_admin_status);
  2140. }
  2141. else {
  2142. auto_admin_status = 0;
  2143. }
  2144. string create_char = string("Insert into characters (account_id, server_id, name, race, class, gender, deity, body_size, body_age, soga_wing_type, soga_chest_type, soga_legs_type, soga_hair_type, soga_model_type, legs_type, chest_type, wing_type, hair_type, model_type, facial_hair_type, soga_facial_hair_type, created_date, last_saved, admin_status, first_world_login) values(%i, %i, '%s', %i, %i, %i, %i, %f, %f, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, now(), unix_timestamp(), %i, 1)");
  2145. query.RunQuery2(Q_INSERT, create_char.c_str(),
  2146. loginID,
  2147. create->getType_int32_ByName("server_id"),
  2148. create->getType_EQ2_16BitString_ByName("name").data.c_str(),
  2149. race_id,
  2150. class_id,
  2151. gender_id,
  2152. create->getType_int8_ByName("deity"),
  2153. create->getType_float_ByName("body_size"),
  2154. create->getType_float_ByName("body_age"),
  2155. GetAppearanceID(create->getType_EQ2_16BitString_ByName("soga_wing_file").data),
  2156. GetAppearanceID(create->getType_EQ2_16BitString_ByName("soga_chest_file").data),
  2157. GetAppearanceID(create->getType_EQ2_16BitString_ByName("soga_legs_file").data),
  2158. GetAppearanceID(create->getType_EQ2_16BitString_ByName("soga_hair_file").data),
  2159. GetAppearanceID(create->getType_EQ2_16BitString_ByName("soga_race_file").data),
  2160. GetAppearanceID(create->getType_EQ2_16BitString_ByName("legs_file").data),
  2161. GetAppearanceID(create->getType_EQ2_16BitString_ByName("chest_file").data),
  2162. GetAppearanceID(create->getType_EQ2_16BitString_ByName("wing_file").data),
  2163. GetAppearanceID(create->getType_EQ2_16BitString_ByName("hair_file").data),
  2164. GetAppearanceID(create->getType_EQ2_16BitString_ByName("race_file").data),
  2165. GetAppearanceID(create->getType_EQ2_16BitString_ByName("face_file").data),
  2166. GetAppearanceID(create->getType_EQ2_16BitString_ByName("soga_face_file").data),
  2167. auto_admin_status);
  2168. if(query.GetError() && strlen(query.GetError()) > 0)
  2169. {
  2170. LogWrite(PLAYER__ERROR, 0, "Player", "Error in SaveCharacter query '%s': %s", query.GetQuery(), query.GetError());
  2171. return 0;
  2172. }
  2173. int32 last_insert_id = query.GetLastInsertedID();
  2174. int32 char_id = last_insert_id;
  2175. UpdateStartingFactions(char_id, create->getType_int8_ByName("starting_zone"));
  2176. UpdateStartingZone(char_id, class_id, race_id, create);
  2177. UpdateStartingItems(char_id, class_id, race_id);
  2178. UpdateStartingSkills(char_id, class_id, race_id);
  2179. UpdateStartingSpells(char_id, class_id, race_id);
  2180. UpdateStartingSkillbar(char_id, class_id, race_id);
  2181. UpdateStartingTitles(char_id, class_id, race_id, gender_id);
  2182. InsertCharacterStats(char_id, class_id, race_id);
  2183. UpdateStartingLanguage(char_id, race_id, create->getType_int8_ByName("starting_zone"));
  2184. LoadClaimItems(char_id); //insert claim items, from claim_items to the character_ version.
  2185. AddNewPlayerToServerGuild(loginID, char_id);
  2186. if (create->GetVersion() <= 546) {
  2187. float classic_multiplier = 250.0f;
  2188. SaveCharacterFloats(char_id, "skin_color", create->getType_float_ByName("skin_color", 0), create->getType_float_ByName("skin_color", 1), create->getType_float_ByName("skin_color", 2), classic_multiplier);
  2189. SaveCharacterFloats(char_id, "eye_color", create->getType_float_ByName("eye_color", 0), create->getType_float_ByName("eye_color", 1), create->getType_float_ByName("eye_color", 2), classic_multiplier);
  2190. SaveCharacterFloats(char_id, "hair_color1", create->getType_float_ByName("hair_color1", 0), create->getType_float_ByName("hair_color1", 1), create->getType_float_ByName("hair_color1", 2), classic_multiplier);
  2191. SaveCharacterFloats(char_id, "hair_color2", create->getType_float_ByName("hair_color2", 0), create->getType_float_ByName("hair_color2", 1), create->getType_float_ByName("hair_color2", 2), classic_multiplier);
  2192. SaveCharacterFloats(char_id, "hair_highlight", create->getType_float_ByName("hair_highlight", 0), create->getType_float_ByName("hair_highlight", 1), create->getType_float_ByName("hair_highlight", 2), classic_multiplier);
  2193. SaveCharacterFloats(char_id, "hair_type_color", create->getType_float_ByName("hair_type_color", 0), create->getType_float_ByName("hair_type_color", 1), create->getType_float_ByName("hair_type_color", 2), classic_multiplier);
  2194. SaveCharacterFloats(char_id, "hair_type_highlight_color", create->getType_float_ByName("hair_type_highlight_color", 0), create->getType_float_ByName("hair_type_highlight_color", 1), create->getType_float_ByName("hair_type_highlight_color", 2), classic_multiplier);
  2195. SaveCharacterFloats(char_id, "hair_type_color", create->getType_float_ByName("hair_type_color", 0), create->getType_float_ByName("hair_type_color", 1), create->getType_float_ByName("hair_type_color", 2), classic_multiplier);
  2196. SaveCharacterFloats(char_id, "hair_type_highlight_color", create->getType_float_ByName("hair_type_highlight_color", 0), create->getType_float_ByName("hair_type_highlight_color", 1), create->getType_float_ByName("hair_type_highlight_color", 2), classic_multiplier);
  2197. SaveCharacterFloats(char_id, "hair_face_color", create->getType_float_ByName("hair_face_color", 0), create->getType_float_ByName("hair_face_color", 1), create->getType_float_ByName("hair_face_color", 2), classic_multiplier);
  2198. SaveCharacterFloats(char_id, "hair_face_highlight_color", create->getType_float_ByName("hair_face_highlight_color", 0), create->getType_float_ByName("hair_face_highlight_color", 1), create->getType_float_ByName("hair_face_highlight_color", 2), classic_multiplier);
  2199. SaveCharacterFloats(char_id, "shirt_color", create->getType_float_ByName("shirt_color", 0), create->getType_float_ByName("shirt_color", 1), create->getType_float_ByName("shirt_color", 2), classic_multiplier);
  2200. SaveCharacterFloats(char_id, "unknown_chest_color", create->getType_float_ByName("unknown_chest_color", 0), create->getType_float_ByName("unknown_chest_color", 1), create->getType_float_ByName("unknown_chest_color", 2), classic_multiplier);
  2201. SaveCharacterFloats(char_id, "pants_color", create->getType_float_ByName("pants_color", 0), create->getType_float_ByName("pants_color", 1), create->getType_float_ByName("pants_color", 2), classic_multiplier);
  2202. SaveCharacterFloats(char_id, "unknown_legs_color", create->getType_float_ByName("unknown_legs_color", 0), create->getType_float_ByName("unknown_legs_color", 1), create->getType_float_ByName("unknown_legs_color", 2), classic_multiplier);
  2203. SaveCharacterFloats(char_id, "unknown9", create->getType_float_ByName("unknown9", 0), create->getType_float_ByName("unknown9", 1), create->getType_float_ByName("unknown9", 2), classic_multiplier);
  2204. }
  2205. else {
  2206. SaveCharacterColors(char_id, "skin_color", create->getType_EQ2_Color_ByName("skin_color"));
  2207. SaveCharacterColors(char_id, "model_color", create->getType_EQ2_Color_ByName("model_color"));
  2208. SaveCharacterColors(char_id, "eye_color", create->getType_EQ2_Color_ByName("eye_color"));
  2209. SaveCharacterColors(char_id, "hair_color1", create->getType_EQ2_Color_ByName("hair_color1"));
  2210. SaveCharacterColors(char_id, "hair_color2", create->getType_EQ2_Color_ByName("hair_color2"));
  2211. SaveCharacterColors(char_id, "hair_highlight", create->getType_EQ2_Color_ByName("hair_highlight"));
  2212. SaveCharacterColors(char_id, "hair_type_color", create->getType_EQ2_Color_ByName("hair_type_color"));
  2213. SaveCharacterColors(char_id, "hair_type_highlight_color", create->getType_EQ2_Color_ByName("hair_type_highlight_color"));
  2214. SaveCharacterColors(char_id, "hair_face_color", create->getType_EQ2_Color_ByName("hair_face_color"));
  2215. SaveCharacterColors(char_id, "hair_face_highlight_color", create->getType_EQ2_Color_ByName("hair_face_highlight_color"));
  2216. SaveCharacterColors(char_id, "wing_color1", create->getType_EQ2_Color_ByName("wing_color1"));
  2217. SaveCharacterColors(char_id, "wing_color2", create->getType_EQ2_Color_ByName("wing_color2"));
  2218. SaveCharacterColors(char_id, "shirt_color", create->getType_EQ2_Color_ByName("shirt_color"));
  2219. SaveCharacterColors(char_id, "unknown_chest_color", create->getType_EQ2_Color_ByName("unknown_chest_color"));
  2220. SaveCharacterColors(char_id, "pants_color", create->getType_EQ2_Color_ByName("pants_color"));
  2221. SaveCharacterColors(char_id, "unknown_legs_color", create->getType_EQ2_Color_ByName("unknown_legs_color"));
  2222. SaveCharacterColors(char_id, "unknown9", create->getType_EQ2_Color_ByName("unknown9"));
  2223. SaveCharacterColors(char_id, "soga_skin_color", create->getType_EQ2_Color_ByName("soga_skin_color"));
  2224. SaveCharacterColors(char_id, "soga_model_color", create->getType_EQ2_Color_ByName("soga_model_color"));
  2225. SaveCharacterColors(char_id, "soga_eye_color", create->getType_EQ2_Color_ByName("soga_eye_color"));
  2226. SaveCharacterColors(char_id, "soga_hair_color1", create->getType_EQ2_Color_ByName("soga_hair_color1"));
  2227. SaveCharacterColors(char_id, "soga_hair_color2", create->getType_EQ2_Color_ByName("soga_hair_color2"));
  2228. SaveCharacterColors(char_id, "soga_hair_highlight", create->getType_EQ2_Color_ByName("soga_hair_highlight"));
  2229. SaveCharacterColors(char_id, "soga_hair_type_color", create->getType_EQ2_Color_ByName("soga_hair_type_color"));
  2230. SaveCharacterColors(char_id, "soga_hair_type_highlight_color", create->getType_EQ2_Color_ByName("soga_hair_type_highlight_color"));
  2231. SaveCharacterColors(char_id, "soga_hair_face_color", create->getType_EQ2_Color_ByName("soga_hair_face_color"));
  2232. SaveCharacterColors(char_id, "soga_hair_face_highlight_color", create->getType_EQ2_Color_ByName("soga_hair_face_highlight_color"));
  2233. SaveCharacterColors(char_id, "soga_wing_color1", create->getType_EQ2_Color_ByName("soga_wing_color1"));
  2234. SaveCharacterColors(char_id, "soga_wing_color2", create->getType_EQ2_Color_ByName("soga_wing_color2"));
  2235. SaveCharacterColors(char_id, "soga_shirt_color", create->getType_EQ2_Color_ByName("soga_shirt_color"));
  2236. SaveCharacterColors(char_id, "soga_unknown_chest_color", create->getType_EQ2_Color_ByName("soga_unknown_chest_color"));
  2237. SaveCharacterColors(char_id, "soga_pants_color", create->getType_EQ2_Color_ByName("soga_pants_color"));
  2238. SaveCharacterColors(char_id, "soga_unknown_legs_color", create->getType_EQ2_Color_ByName("soga_unknown_legs_color"));
  2239. SaveCharacterColors(char_id, "soga_unknown13", create->getType_EQ2_Color_ByName("soga_unknown13"));
  2240. SaveCharacterFloats(char_id, "soga_eye_type", create->getType_float_ByName("soga_eyes2", 0), create->getType_float_ByName("soga_eyes2", 1), create->getType_float_ByName("soga_eyes2", 2));
  2241. SaveCharacterFloats(char_id, "soga_ear_type", create->getType_float_ByName("soga_ears", 0), create->getType_float_ByName("soga_ears", 1), create->getType_float_ByName("soga_ears", 2));
  2242. SaveCharacterFloats(char_id, "soga_eye_brow_type", create->getType_float_ByName("soga_eye_brows", 0), create->getType_float_ByName("soga_eye_brows", 1), create->getType_float_ByName("soga_eye_brows", 2));
  2243. SaveCharacterFloats(char_id, "soga_cheek_type", create->getType_float_ByName("soga_cheeks", 0), create->getType_float_ByName("soga_cheeks", 1), create->getType_float_ByName("soga_cheeks", 2));
  2244. SaveCharacterFloats(char_id, "soga_lip_type", create->getType_float_ByName("soga_lips", 0), create->getType_float_ByName("soga_lips", 1), create->getType_float_ByName("soga_lips", 2));
  2245. SaveCharacterFloats(char_id, "soga_chin_type", create->getType_float_ByName("soga_chin", 0), create->getType_float_ByName("soga_chin", 1), create->getType_float_ByName("soga_chin", 2));
  2246. SaveCharacterFloats(char_id, "soga_nose_type", create->getType_float_ByName("soga_nose", 0), create->getType_float_ByName("soga_nose", 1), create->getType_float_ByName("soga_nose", 2));
  2247. }
  2248. SaveCharacterFloats(char_id, "eye_type", create->getType_float_ByName("eyes2", 0), create->getType_float_ByName("eyes2", 1), create->getType_float_ByName("eyes2", 2));
  2249. SaveCharacterFloats(char_id, "ear_type", create->getType_float_ByName("ears", 0), create->getType_float_ByName("ears", 1), create->getType_float_ByName("ears", 2));
  2250. SaveCharacterFloats(char_id, "eye_brow_type", create->getType_float_ByName("eye_brows", 0), create->getType_float_ByName("eye_brows", 1), create->getType_float_ByName("eye_brows", 2));
  2251. SaveCharacterFloats(char_id, "cheek_type", create->getType_float_ByName("cheeks", 0), create->getType_float_ByName("cheeks", 1), create->getType_float_ByName("cheeks", 2));
  2252. SaveCharacterFloats(char_id, "lip_type", create->getType_float_ByName("lips", 0), create->getType_float_ByName("lips", 1), create->getType_float_ByName("lips", 2));
  2253. SaveCharacterFloats(char_id, "chin_type", create->getType_float_ByName("chin", 0), create->getType_float_ByName("chin", 1), create->getType_float_ByName("chin", 2));
  2254. SaveCharacterFloats(char_id, "nose_type", create->getType_float_ByName("nose", 0), create->getType_float_ByName("nose", 1), create->getType_float_ByName("nose", 2));
  2255. SaveCharacterFloats(char_id, "body_size", create->getType_float_ByName("body_size", 0), 0, 0);
  2256. return char_id;
  2257. }
  2258. int8 WorldDatabase::CheckNameFilter(const char* name, int8 min_length, int8 max_length) {
  2259. // the minimum 4 is enforced by the client too
  2260. if(!name || strlen(name) < min_length || strlen(name) > max_length) // Even 20 char length is long...
  2261. return BADNAMELENGTH_REPLY;
  2262. uchar* checkname = (uchar*)name;
  2263. for (int32 i = 0; i < strlen(name); i++)
  2264. {
  2265. if(!alpha_check(checkname[i]))
  2266. return NAMEINVALID_REPLY;
  2267. }
  2268. Query query;
  2269. LogWrite(WORLD__DEBUG, 0, "World", "Name check on: %s", name);
  2270. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT count(*) FROM characters WHERE name='%s'",name);
  2271. if(result && mysql_num_rows(result) > 0) {
  2272. MYSQL_ROW row;
  2273. row = mysql_fetch_row(result);
  2274. if(row[0] != 0 && atoi(row[0]) > 0)
  2275. return NAMETAKEN_REPLY;
  2276. }
  2277. else
  2278. LogWrite(WORLD__ERROR, 0, "World", "Error in CheckNameFilter (name exist check) (Name query '%s': %s", query.GetQuery(), query.GetError());
  2279. Query query3;
  2280. LogWrite(WORLD__DEBUG, 0, "World", "Name check on: %s (Bots table)", name);
  2281. MYSQL_RES* result3 = query3.RunQuery2(Q_SELECT, "SELECT count(*) FROM bots WHERE name='%s'", name);
  2282. if (result3 && mysql_num_rows(result3) > 0) {
  2283. MYSQL_ROW row;
  2284. row = mysql_fetch_row(result3);
  2285. if (row[0] != 0 && atoi(row[0]) > 0)
  2286. return NAMETAKEN_REPLY;
  2287. }
  2288. else
  2289. LogWrite(WORLD__ERROR, 0, "World", "Error in CheckNameFilter (name exist check, bot table) (Name query '%s': %s", query3.GetQuery(), query3.GetError());
  2290. Query query2;
  2291. MYSQL_RES* result2 = query2.RunQuery2(Q_SELECT, "SELECT count(*) FROM name_filter WHERE '%s' like name",name);
  2292. if(result2 && mysql_num_rows(result2) > 0) {
  2293. MYSQL_ROW row;
  2294. row = mysql_fetch_row(result2);
  2295. if(row[0] != 0 && atoi(row[0]) > 0)
  2296. return NAMEFILTER_REPLY;
  2297. else if(row[0] != 0 && atoi(row[0]) == 0)
  2298. return CREATESUCCESS_REPLY;
  2299. }
  2300. else
  2301. LogWrite(WORLD__ERROR, 0, "World", "Error in CheckNameFilter (name_filter check) query '%s': %s", query.GetQuery(), query.GetError());
  2302. return UNKNOWNERROR_REPLY;
  2303. }
  2304. char* WorldDatabase::GetCharacterName(int32 character_id){
  2305. LogWrite(WORLD__TRACE, 9, "World", "Enter: %s", __FUNCTION__);
  2306. Query query;
  2307. char* name = 0;
  2308. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT name FROM characters where id=%u",character_id);
  2309. if(result && mysql_num_rows(result) > 0) {
  2310. MYSQL_ROW row;
  2311. row = mysql_fetch_row(result);
  2312. if(row[0] && strlen(row[0]) > 0)
  2313. {
  2314. name = new char[strlen(row[0])+1];
  2315. memset(name,0, strlen(row[0])+1);
  2316. strcpy(name, row[0]);
  2317. }
  2318. }
  2319. else
  2320. LogWrite(WORLD__ERROR, 0, "World", "Error in GetCharacterName query '%s': %s", query.GetQuery(), query.GetError());
  2321. LogWrite(WORLD__TRACE, 9, "World", "Exit: %s", __FUNCTION__);
  2322. return name;
  2323. }
  2324. int8 WorldDatabase::GetCharacterLevel(int32 character_id){
  2325. Query query;
  2326. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT level FROM characters where id=%u",character_id);
  2327. if(result && mysql_num_rows(result) > 0) {
  2328. MYSQL_ROW row;
  2329. row = mysql_fetch_row(result);
  2330. return atoi(row[0]); // Return characters level
  2331. }
  2332. else
  2333. LogWrite(WORLD__ERROR, 0, "World", "Error in GetCharacterLevel query '%s': %s", query.GetQuery(), query.GetError());
  2334. return 0;
  2335. }
  2336. int16 WorldDatabase::GetCharacterModelType(int32 character_id){
  2337. Query query;
  2338. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT model_type FROM characters where id=%u",character_id);
  2339. if(result && mysql_num_rows(result) > 0) {
  2340. MYSQL_ROW row;
  2341. row = mysql_fetch_row(result);
  2342. return atoi(row[0]); // Return characters race
  2343. }
  2344. else
  2345. LogWrite(WORLD__ERROR, 0, "World", "Error in GetCharacterModelType query '%s': %s", query.GetQuery(), query.GetError());
  2346. return 0;
  2347. }
  2348. int8 WorldDatabase::GetCharacterClass(int32 character_id){
  2349. Query query;
  2350. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT class FROM characters where id=%u",character_id);
  2351. if(result && mysql_num_rows(result) > 0) {
  2352. MYSQL_ROW row;
  2353. row = mysql_fetch_row(result);
  2354. return atoi(row[0]); // Return characters class
  2355. }
  2356. else
  2357. LogWrite(WORLD__ERROR, 0, "World", "Error in GetCharacterClass query '%s': %s", query.GetQuery(), query.GetError());
  2358. return 0;
  2359. }
  2360. int8 WorldDatabase::GetCharacterGender(int32 character_id){
  2361. Query query;
  2362. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT gender FROM characters where id=%u",character_id);
  2363. if(result && mysql_num_rows(result) > 0) {
  2364. MYSQL_ROW row;
  2365. row = mysql_fetch_row(result);
  2366. return atoi(row[0]); // Return characters gender
  2367. }
  2368. else
  2369. LogWrite(WORLD__ERROR, 0, "World", "Error in GetCharacterGender query '%s': %s", query.GetQuery(), query.GetError());
  2370. return 0;
  2371. }
  2372. void WorldDatabase::DeleteCharacterQuest(int32 quest_id, int32 char_id, bool repeated_quest) {
  2373. if (repeated_quest) {
  2374. if (!database_new.Query("UPDATE `character_quests` SET `given_date` = `completed_date` WHERE `char_id` = %u AND `quest_id` = %u", char_id, quest_id))
  2375. LogWrite(DATABASE__ERROR, 0, "DBNew", "Error (%u) in DeleteCharacterQuest query:\n%s", database_new.GetError(), database_new.GetErrorMsg());
  2376. }
  2377. else {
  2378. if (!database_new.Query("DELETE FROM `character_quests` WHERE `char_id` = %u AND `quest_id` = %u", char_id, quest_id))
  2379. LogWrite(DATABASE__ERROR, 0, "DBNew", "Error (%u) in DeleteCharacterQuest query:\n%s", database_new.GetError(), database_new.GetErrorMsg());
  2380. }
  2381. if (!database_new.Query("DELETE FROM `character_quest_progress` WHERE `char_id` = %u AND `quest_id` = %u", char_id, quest_id))
  2382. LogWrite(DATABASE__ERROR, 0, "DBNew", "Error (%u) in DeleteCharacterQuest query:\n%s", database_new.GetError(), database_new.GetErrorMsg());
  2383. }
  2384. void WorldDatabase::SaveCharacterSkills(Client* client){
  2385. vector<Skill*>* skills = client->GetPlayer()->GetSkills()->GetSaveNeededSkills();
  2386. if(skills){
  2387. Query query;
  2388. if(skills->size() > 0){
  2389. Skill* skill = 0;
  2390. for(int32 i=0;i<skills->size();i++){
  2391. skill = skills->at(i);
  2392. query.AddQueryAsync(client->GetCharacterID(),this,Q_REPLACE, "replace into character_skills (char_id, skill_id, current_val, max_val) values(%u, %u, %i, %i)", client->GetCharacterID(), skill->skill_id, skill->current_val, skill->max_val);
  2393. }
  2394. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF)
  2395. LogWrite(WORLD__ERROR, 0, "World", "Error in SaveCharacterSkills query '%s': %s", query.GetQuery(), query.GetError());
  2396. }
  2397. safe_delete(skills);
  2398. }
  2399. }
  2400. void WorldDatabase::SaveCharacterQuests(Client* client){
  2401. Query query;
  2402. map<int32, Quest*>::iterator itr;
  2403. master_quest_list.LockQuests(); //prevent reloading until we are done
  2404. client->GetPlayer()->MPlayerQuests.writelock(__FUNCTION__, __LINE__); //prevent all quest modifications until we are done
  2405. map<int32, Quest*>* quests = client->GetPlayer()->GetPlayerQuests();
  2406. for(itr = quests->begin(); itr != quests->end(); itr++){
  2407. if(client->GetCurrentQuestID() == itr->first){
  2408. query.AddQueryAsync(client->GetCharacterID(),this,Q_UPDATE, "update character_quests set current_quest = 0 where char_id = %u", client->GetCharacterID());
  2409. query.AddQueryAsync(client->GetCharacterID(), this,Q_UPDATE, "update character_quests set current_quest = 1 where char_id = %u and quest_id = %u", client->GetCharacterID(), itr->first);
  2410. }
  2411. if(itr->second && itr->second->GetSaveNeeded()){
  2412. query.AddQueryAsync(client->GetCharacterID(), this,Q_INSERT, "insert ignore into character_quests (char_id, quest_id, given_date, quest_giver) values(%u, %u, now(), %u)", client->GetCharacterID(), itr->first, itr->second->GetQuestGiver());
  2413. query.AddQueryAsync(client->GetCharacterID(), this,Q_UPDATE, "update character_quests set tracked = %i, quest_flags = %u, hidden = %i, complete_count = %u where char_id = %u and quest_id = %u", itr->second->IsTracked() ? 1 : 0, itr->second->GetQuestFlags(), itr->second->IsHidden() ? 1 : 0, itr->second->GetCompleteCount(), client->GetCharacterID(), itr->first);
  2414. SaveCharacterQuestProgress(client, itr->second);
  2415. itr->second->SetSaveNeeded(false);
  2416. }
  2417. }
  2418. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF)
  2419. LogWrite(WORLD__ERROR, 0, "World", "Error in SaveCharacterQuests query '%s': %s", query.GetQuery(), query.GetError());
  2420. quests = client->GetPlayer()->GetCompletedPlayerQuests();
  2421. for(itr = quests->begin(); itr != quests->end(); itr++){
  2422. if(itr->second && itr->second->GetSaveNeeded()){
  2423. query.AddQueryAsync(client->GetCharacterID(), this,Q_DELETE, "delete FROM character_quest_progress where char_id = %u and quest_id = %u", client->GetCharacterID(), itr->first);
  2424. /* incase the quest is completed before the quest could be inserted in the PlayerQuests loop, we first try to insert it. If it already exists then we can just update
  2425. * the completed_date */
  2426. query.AddQueryAsync(client->GetCharacterID(), this,Q_INSERT, "INSERT INTO character_quests (char_id, quest_id, quest_giver, current_quest, given_date, completed_date, complete_count) values (%u,%u,%u,0, now(),now(), %u) ON DUPLICATE KEY UPDATE completed_date = now(), complete_count = %u, current_quest = 0", client->GetCharacterID(), itr->first, itr->second->GetQuestGiver(), itr->second->GetCompleteCount(), itr->second->GetCompleteCount());
  2427. itr->second->SetSaveNeeded(false);
  2428. }
  2429. }
  2430. client->GetPlayer()->MPlayerQuests.releasewritelock(__FUNCTION__, __LINE__);
  2431. master_quest_list.UnlockQuests();
  2432. }
  2433. void WorldDatabase::SaveCharRepeatableQuest(Client* client, int32 quest_id, int16 quest_complete_count) {
  2434. if (!database_new.Query("UPDATE `character_quests` SET `given_date` = now(), complete_count = %u WHERE `char_id` = %u AND `quest_id` = %u", quest_complete_count, client->GetCharacterID(), quest_id))
  2435. LogWrite(DATABASE__ERROR, 0, "DBNew", "DB Error %u\n%s", database_new.GetError(), database_new.GetErrorMsg());
  2436. }
  2437. void WorldDatabase::SaveCharacterQuestProgress(Client* client, Quest* quest){
  2438. vector<QuestStep*>* steps = quest->GetQuestSteps();
  2439. vector<QuestStep*>::iterator itr;
  2440. QuestStep* step = 0;
  2441. quest->MQuestSteps.readlock(__FUNCTION__, __LINE__);
  2442. if(steps){
  2443. for(itr = steps->begin(); itr != steps->end(); itr++){
  2444. step = *itr;
  2445. if(step && step->GetQuestCurrentQuantity() > 0) {
  2446. Query query;
  2447. query.RunQuery2(Q_REPLACE, "replace into character_quest_progress (char_id, quest_id, step_id, progress) values(%u, %u, %u, %i)", client->GetCharacterID(), quest->GetQuestID(), step->GetStepID(), step->GetQuestCurrentQuantity());
  2448. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF)
  2449. LogWrite(WORLD__ERROR, 0, "World", "Error in SaveCharacterQuestProgress query '%s': %s", query.GetQuery(), query.GetError());
  2450. }
  2451. }
  2452. }
  2453. quest->MQuestSteps.releasereadlock(__FUNCTION__, __LINE__);
  2454. }
  2455. void WorldDatabase::LoadCharacterQuestProgress(Client* client){
  2456. Query query;
  2457. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT character_quest_progress.quest_id, step_id, progress FROM character_quest_progress, character_quests where character_quest_progress.char_id=%u and character_quest_progress.quest_id = character_quests.quest_id and character_quest_progress.char_id = character_quests.char_id ORDER BY character_quest_progress.quest_id",client->GetCharacterID());
  2458. if(result && mysql_num_rows(result) > 0) {
  2459. MYSQL_ROW row;
  2460. Quest* quest = 0;
  2461. int32 quest_id = 0;
  2462. map<int32, int32>* progress_map = new map<int32, int32>();
  2463. while(result && (row = mysql_fetch_row(result))){
  2464. if(quest_id != atoul(row[0])){
  2465. if(quest_id > 0){
  2466. quest = client->GetPlayer()->GetQuest(quest_id);
  2467. if(quest)
  2468. client->SetPlayerQuest(quest, progress_map);
  2469. }
  2470. quest_id = atoul(row[0]);
  2471. progress_map->clear();
  2472. }
  2473. (*progress_map)[atoul(row[1])] = atoul(row[2]);
  2474. }
  2475. if(progress_map->size() > 0){
  2476. quest = client->GetPlayer()->GetQuest(quest_id);
  2477. if(quest)
  2478. client->SetPlayerQuest(quest, progress_map);
  2479. }
  2480. safe_delete(progress_map);
  2481. }
  2482. else if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF)
  2483. LogWrite(WORLD__ERROR, 0, "World", "Error in LoadCharacterQuestProgress query '%s': %s", query.GetQuery(), query.GetError());
  2484. }
  2485. void WorldDatabase::LoadCharacterQuests(Client* client){
  2486. LogWrite(PLAYER__DEBUG, 0, "Player", "Loading Character Quests...");
  2487. Query query;
  2488. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT quest_id, DAY(given_date), MONTH(given_date), YEAR(given_date), DAY(completed_date), MONTH(completed_date), YEAR(completed_date), quest_giver, tracked, quest_flags, hidden, UNIX_TIMESTAMP(given_date), UNIX_TIMESTAMP(completed_date), complete_count FROM character_quests WHERE char_id=%u ORDER BY current_quest", client->GetCharacterID());
  2489. if(result && mysql_num_rows(result) > 0) {
  2490. MYSQL_ROW row;
  2491. Quest* quest = 0;
  2492. while(result && (row = mysql_fetch_row(result))){
  2493. quest = master_quest_list.GetQuest(atoul(row[0]));
  2494. if(quest) {
  2495. LogWrite(PLAYER__DEBUG, 5, "Player", "\tLoading quest_id: %u", atoul(row[0]));
  2496. bool addQuest = true;
  2497. if(row[4] && atoi(row[4]) > 0){
  2498. quest->SetTurnedIn(true);
  2499. if(row[4])
  2500. quest->SetDay(atoi(row[4]));
  2501. if(row[5])
  2502. quest->SetMonth(atoi(row[5]));
  2503. if(row[6] && atoi(row[6]) > 2000)
  2504. quest->SetYear(atoi(row[6]) - 2000);
  2505. client->GetPlayer()->AddCompletedQuest(quest);
  2506. // Added timestamps to quickly compare given and completed dates
  2507. int32 given_timestamp = atoul(row[11]);
  2508. int32 completed_timestamp = atoul(row[12]);
  2509. // If given timestamp is greater then completed then this is a repeatable quest we are working on
  2510. // so get a fresh quest object to add as an active quest
  2511. if (given_timestamp > completed_timestamp)
  2512. {
  2513. lua_interface->SetLuaUserDataStale(quest);
  2514. safe_delete(quest);
  2515. quest = master_quest_list.GetQuest(atoul(row[0]));
  2516. }
  2517. else
  2518. addQuest = false;
  2519. quest->SetCompleteCount(atoi(row[13]));
  2520. }
  2521. if (addQuest) {
  2522. if(row[1])
  2523. quest->SetDay(atoi(row[1]));
  2524. if(row[2])
  2525. quest->SetMonth(atoi(row[2]));
  2526. if(row[3] && atoi(row[3]) > 2000)
  2527. quest->SetYear(atoi(row[3]) - 2000);
  2528. quest->SetQuestGiver(atoul(row[7]));
  2529. quest->SetTracked(atoi(row[8]) == 1 ? true : false);
  2530. quest->SetQuestFlags(atoul(row[9]));
  2531. quest->SetHidden(atoi(row[10]) == 1 ? true : false);
  2532. client->AddPlayerQuest(quest, false, false);
  2533. }
  2534. quest->SetSaveNeeded(false);
  2535. // Changed this to call reload with step = 0 for all quests and not
  2536. // just quests with quest flags to allow customized set up if needed
  2537. if (lua_interface)
  2538. lua_interface->CallQuestFunction(quest, "Reload", client->GetPlayer(), 0);
  2539. }
  2540. }
  2541. LoadCharacterQuestProgress(client);
  2542. }
  2543. }
  2544. void WorldDatabase::LoadCharacterFriendsIgnoreList(Player* player) {
  2545. if (player) {
  2546. Query query;
  2547. MYSQL_ROW row;
  2548. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `name`, `type` FROM `character_social` WHERE `char_id`=%u", player->GetCharacterID());
  2549. while (result && (row = mysql_fetch_row(result))) {
  2550. if (strncmp(row[1], "FRIEND", 6) == 0)
  2551. player->AddFriend(row[0], false);
  2552. else
  2553. player->AddIgnore(row[0], false);
  2554. }
  2555. }
  2556. }
  2557. void WorldDatabase::LoadZoneInfo(ZoneServer* zone){
  2558. Query query;
  2559. int32 ruleset_id;
  2560. char* escaped = getEscapeString(zone->GetZoneName());
  2561. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, file, description, underworld, safe_x, safe_y, safe_z, min_status, min_level, max_level, instance_type+0, shutdown_timer, zone_motd, default_reenter_time, default_reset_time, default_lockout_time, force_group_to_zone, safe_heading, xp_modifier, ruleset_id, expansion_id, weather_allowed, sky_file, can_bind, can_gate, city_zone, can_evac FROM zones where name='%s'",escaped);
  2562. if(result && mysql_num_rows(result) > 0) {
  2563. MYSQL_ROW row;
  2564. row = mysql_fetch_row(result);
  2565. zone->SetZoneName(escaped);
  2566. zone->SetZoneID(strtoul(row[0], NULL, 0));
  2567. zone->SetZoneFile(row[1]);
  2568. zone->SetZoneDescription(row[2]);
  2569. zone->SetUnderWorld(atof(row[3]));
  2570. zone->SetSafeX(atof(row[4]));
  2571. zone->SetSafeY(atof(row[5]));
  2572. zone->SetSafeZ(atof(row[6]));
  2573. zone->SetMinimumStatus(atoi(row[7]));
  2574. zone->SetMinimumLevel(atoi(row[8]));
  2575. zone->SetMaximumLevel(atoi(row[9]));
  2576. int8 type = (atoi(row[10]) == 0) ? 0 : atoi(row[10]) - 1;
  2577. zone->SetInstanceType(type);
  2578. zone->SetShutdownTimer(atoul(row[11]));
  2579. char* zone_motd = row[12];
  2580. if (zone_motd && strlen(zone_motd) > 0)
  2581. zone->SetZoneMOTD(string(zone_motd));
  2582. zone->SetDefaultReenterTime(atoi(row[13]));
  2583. zone->SetDefaultResetTime(atoi(row[14]));
  2584. zone->SetDefaultLockoutTime(atoi(row[15]));
  2585. zone->SetForceGroupZoneOption(atoi(row[16]));
  2586. zone->SetSafeHeading(atof(row[17]));
  2587. zone->SetXPModifier(atof(row[18]));
  2588. if ((ruleset_id = atoul(row[19])) > 0 && !rule_manager.SetZoneRuleSet(zone->GetZoneID(), ruleset_id))
  2589. LogWrite(ZONE__ERROR, 0, "Zones", "Error setting rule set for zone '%s' (%u). A rule set with ID %u does not exist.", zone->GetZoneName(), zone->GetZoneID(), ruleset_id);
  2590. // check data_version to see if client has proper expansion to enter a zone
  2591. zone->SetMinimumVersion(GetMinimumClientVersion(atoi(row[20])));
  2592. zone->SetWeatherAllowed(atoi(row[21]) == 0 ? false : true);
  2593. zone->SetZoneSkyFile(row[22]);
  2594. if (zone->IsInstanceZone())
  2595. {
  2596. if ( zone->GetInstanceID() < 1 )
  2597. zone->SetupInstance(CreateNewInstance(zone->GetZoneID()));
  2598. else
  2599. zone->SetupInstance(zone->GetInstanceID());
  2600. }
  2601. zone->SetCanBind(atoul(row[23]));
  2602. zone->SetCanGate(atoul(row[24]));
  2603. zone->SetCityZone(atoi(row[25]));
  2604. zone->SetCanEvac(atoul(row[26]));
  2605. }
  2606. safe_delete_array(escaped);
  2607. }
  2608. void WorldDatabase::LoadZoneInfo(ZoneInfo* zone_info) {
  2609. Query query;
  2610. int32 ruleset_id;
  2611. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT name, file, description, underworld, safe_x, safe_y, safe_z, min_status, min_level, max_level, instance_type, shutdown_timer, zone_motd, default_reenter_time, default_reset_time, default_lockout_time, force_group_to_zone, lua_script, xp_modifier, ruleset_id, expansion_id, always_loaded, city_zone, start_zone, zone_type, weather_allowed, sky_file FROM zones WHERE id = %u", zone_info->id);
  2612. if (result && mysql_num_rows(result) > 0) {
  2613. MYSQL_ROW row;
  2614. row = mysql_fetch_row(result);
  2615. strncpy(zone_info->name, row[0], sizeof(zone_info->name));
  2616. strncpy(zone_info->file, row[1], sizeof(zone_info->file));
  2617. strncpy(zone_info->description, row[2], sizeof(zone_info->description));
  2618. zone_info->underworld = atof(row[3]);
  2619. zone_info->safe_x = atof(row[4]);
  2620. zone_info->safe_y = atof(row[5]);
  2621. zone_info->safe_z = atof(row[6]);
  2622. zone_info->min_status = atoi(row[7]);
  2623. zone_info->min_level = atoi(row[8]);
  2624. zone_info->max_level = atoi(row[9]);
  2625. zone_info->instance_type = (atoi(row[10]) == 0) ? 0 : atoi(row[10]) - 1;
  2626. zone_info->shutdown_timer = atoul(row[11]);
  2627. row[12] == NULL ? strncpy(zone_info->zone_motd, "", sizeof(zone_info->zone_motd)) : strncpy(zone_info->zone_motd, row[12], sizeof(zone_info->zone_motd));
  2628. zone_info->default_reenter_time = atoi(row[13]);
  2629. zone_info->default_reset_time = atoi(row[14]);
  2630. zone_info->default_lockout_time = atoi(row[15]);
  2631. zone_info->force_group_to_zone = atoi(row[16]);
  2632. row[17] == NULL ? strncpy(zone_info->lua_script, "", sizeof(zone_info->lua_script)) : strncpy(zone_info->lua_script, row[17], sizeof(zone_info->lua_script));
  2633. zone_info->xp_modifier = atof(row[18]);
  2634. zone_info->ruleset_id = atoul(row[19]);
  2635. if ((ruleset_id = atoul(row[19])) > 0 && !rule_manager.SetZoneRuleSet(zone_info->id, ruleset_id))
  2636. LogWrite(ZONE__ERROR, 0, "Zones", "Error setting rule set for zone '%s' (%u). A rule set with ID %u does not exist.", zone_info->name, zone_info->id, ruleset_id);
  2637. zone_info->expansion_id = atoi(row[20]);
  2638. zone_info->min_version = GetMinimumClientVersion(zone_info->expansion_id);
  2639. zone_info->always_loaded = atoi(row[21]);
  2640. zone_info->city_zone = atoi(row[22]);
  2641. zone_info->start_zone = atoi(row[23]);
  2642. row[24] == NULL ? strncpy(zone_info->zone_type, "", sizeof(zone_info->zone_type)) : strncpy(zone_info->zone_type, row[24], sizeof(zone_info->zone_type));
  2643. zone_info->weather_allowed = atoi(row[25]);
  2644. strncpy(zone_info->sky_file, row[26], sizeof(zone_info->sky_file));
  2645. }
  2646. }
  2647. void WorldDatabase::SaveZoneInfo(int32 zone_id, const char* field, sint32 value) {
  2648. Query query;
  2649. query.RunQuery2(Q_UPDATE, "UPDATE `zones` SET `%s`=%i WHERE `id`=%u", field, value, zone_id);
  2650. }
  2651. void WorldDatabase::SaveZoneInfo(int32 zone_id, const char* field, float value) {
  2652. Query query;
  2653. query.RunQuery2(Q_UPDATE, "UPDATE `zones` SET `%s`=%f WHERE `id`=%u", field, value, zone_id);
  2654. }
  2655. void WorldDatabase::SaveZoneInfo(int32 zone_id, const char* field, const char* value) {
  2656. Query query;
  2657. query.RunQuery2(Q_UPDATE, "UPDATE `zones` SET `%s`='%s' WHERE `id`=%u", field, const_cast<char*>(getEscapeString(value)), zone_id);
  2658. }
  2659. int32 WorldDatabase::GetZoneID(const char* name) {
  2660. int32 zone_id = 0;
  2661. Query query;
  2662. char* escaped = getEscapeString(name);
  2663. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `id` FROM zones WHERE `name`=\"%s\"", escaped);
  2664. if (result && mysql_num_rows(result) > 0) {
  2665. MYSQL_ROW row;
  2666. row = mysql_fetch_row(result);
  2667. zone_id = atoi(row[0]);
  2668. }
  2669. safe_delete_array(escaped);
  2670. return zone_id;
  2671. }
  2672. bool WorldDatabase::GetZoneRequirements(const char* zoneName, sint16* minStatus, int16* minLevel, int16* maxLevel, int16* minVersion) {
  2673. Query query;
  2674. char* escaped = getEscapeString(zoneName);
  2675. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT min_status, min_level, max_level, expansion_id FROM zones where name='%s'",escaped);
  2676. if(result && mysql_num_rows(result) > 0) {
  2677. MYSQL_ROW row;
  2678. row = mysql_fetch_row(result);
  2679. sint16 status = (sint16)atoi(row[0]);
  2680. int16 levelMin = (int16)atoi(row[1]);
  2681. int16 levelMax = (int16)atoi(row[2]);
  2682. int8 expansion_id = (int8)atoi(row[3]);
  2683. *minStatus = status;
  2684. *minLevel = levelMin;
  2685. *maxLevel = levelMax;
  2686. if( expansion_id >= 40 ) // lowest client we support is RoK - exp04
  2687. *minVersion = GetMinimumClientVersion(expansion_id);
  2688. else
  2689. *minVersion = 0;
  2690. safe_delete_array(escaped);
  2691. return true;
  2692. }
  2693. safe_delete_array(escaped);
  2694. return false;
  2695. }
  2696. int16 WorldDatabase::GetMinimumClientVersion(int8 expansion_id)
  2697. {
  2698. /*
  2699. 1 n/a Classic Expansion
  2700. 2 adv01 Bloodline Chronicles
  2701. 3 adv02 Splitpaw Saga
  2702. 10 exp01 Desert of Flames
  2703. 20 exp02 Kingdom of Sky
  2704. 21 adv04 Fallen Dynasty
  2705. 30 exp03 Echoes of Faydwer
  2706. 40 exp04 Rise of Kunark
  2707. 50 exp05 The Shadow Odyssey
  2708. 60 exp06 Sentinel's Fate
  2709. 61 halas Halas Reborn
  2710. 70 exp07 Destiny of Velious
  2711. 80 exp08 Age of Discovery
  2712. */
  2713. int16 minVer = 0;
  2714. // TODO: eventually replace this with reading values from eq2expansions table
  2715. switch(expansion_id)
  2716. {
  2717. case 40: // ROK
  2718. {
  2719. minVer = 843;
  2720. break;
  2721. }
  2722. case 50: // TSO
  2723. {
  2724. minVer = 908;
  2725. break;
  2726. }
  2727. case 60: // SF
  2728. {
  2729. minVer = 1008;
  2730. break;
  2731. }
  2732. case 61: // Halas
  2733. {
  2734. minVer = 1045;
  2735. break;
  2736. }
  2737. case 70: // DoV
  2738. {
  2739. minVer = 1096;
  2740. break;
  2741. }
  2742. case 80: // AoD
  2743. {
  2744. minVer = 1144;
  2745. break;
  2746. }
  2747. case 90: // CoE
  2748. {
  2749. minVer = 1188;
  2750. break;
  2751. }
  2752. }
  2753. return minVer;
  2754. }
  2755. // returns Expansion Name depending on the connected client's data version
  2756. string WorldDatabase::GetExpansionIDByVersion(int16 version)
  2757. {
  2758. /*
  2759. 0 n/a Classic Expansion
  2760. 0 adv01 Bloodline Chronicles
  2761. 0 adv02 Splitpaw Saga
  2762. 0 exp01 Desert of Flames
  2763. 0 exp02 Kingdom of Sky
  2764. 0 adv04 Fallen Dynasty
  2765. 0 exp03 Echoes of Faydwer
  2766. 843 exp04 Rise of Kunark
  2767. 908 exp05 The Shadow Odyssey
  2768. 1008 exp06 Sentinel's Fate
  2769. 1045 halas Halas Reborn
  2770. 1096 exp07 Destiny of Velious
  2771. 1142 exp08 Age of Discovery
  2772. 1188 exp09 Chains of Eternity
  2773. 9999 (and beyond)
  2774. */
  2775. string ret = "";
  2776. if( version >= 9999 )
  2777. ret = "Unknown";
  2778. else if( version >= 1188 )
  2779. ret = "Chains of Eternity";
  2780. else if( version >= 1142 )
  2781. ret = "Age of Discovery";
  2782. else if( version >= 1096 )
  2783. ret = "Destiny of Velious";
  2784. else if( version >= 1045 )
  2785. ret = "Halas Reborn";
  2786. else if( version >= 1008 )
  2787. ret = "Sentinel's Fate";
  2788. else if( version >= 908 )
  2789. ret = "The Shadow Odyssey";
  2790. else if( version >= 843 )
  2791. ret = "Rise of Kunark";
  2792. else
  2793. ret = "Any";
  2794. return ret;
  2795. }
  2796. void WorldDatabase::LoadSpecialZones(){
  2797. Query query;
  2798. ZoneServer* zone = 0;
  2799. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, name, always_loaded FROM zones where always_loaded = 1");
  2800. if(result && mysql_num_rows(result) > 0) {
  2801. MYSQL_ROW row;
  2802. while(result && (row = mysql_fetch_row(result))){
  2803. zone = new ZoneServer(row[1]);
  2804. LoadZoneInfo(zone);
  2805. zone->Init();
  2806. zone->SetAlwaysLoaded(atoi(row[2]) == 1);
  2807. }
  2808. }
  2809. }
  2810. bool WorldDatabase::SpawnGroupRemoveAssociation(int32 group1, int32 group2){
  2811. Query query;
  2812. query.RunQuery2(Q_DELETE, "delete FROM spawn_location_group_associations where (group_id1 = %u and group_id2 = %u) or (group_id1 = %u and group_id2 = %u)", group1, group2, group2, group1);
  2813. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  2814. LogWrite(WORLD__ERROR, 0, "World", "Error in SpawnGroupRemoveSpawn query '%s': %s", query.GetQuery(), query.GetError());
  2815. return false;
  2816. }
  2817. return true;
  2818. }
  2819. bool WorldDatabase::SpawnGroupAddAssociation(int32 group1, int32 group2){
  2820. Query query;
  2821. query.RunQuery2(Q_INSERT, "insert ignore into spawn_location_group_associations (group_id1, group_id2) values(%u, %u)", group1, group2);
  2822. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  2823. LogWrite(WORLD__ERROR, 0, "World", "Error in SpawnGroupAddAssociation query '%s': %s", query.GetQuery(), query.GetError());
  2824. return false;
  2825. }
  2826. return true;
  2827. }
  2828. bool WorldDatabase::SpawnGroupAddSpawn(Spawn* spawn, int32 group_id){
  2829. Query query;
  2830. query.RunQuery2(Q_INSERT, "insert ignore into spawn_location_group (group_id, placement_id) values(%u, %u)", group_id, spawn->GetSpawnLocationPlacementID());
  2831. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  2832. LogWrite(WORLD__ERROR, 0, "World", "Error in SpawnGroupAddSpawn query '%s': %s", query.GetQuery(), query.GetError());
  2833. return false;
  2834. }
  2835. return true;
  2836. }
  2837. bool WorldDatabase::SpawnGroupRemoveSpawn(Spawn* spawn, int32 group_id){
  2838. Query query;
  2839. query.RunQuery2(Q_DELETE, "delete FROM spawn_location_group where group_id = %u and placement_id = %u", group_id, spawn->GetSpawnLocationPlacementID());
  2840. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  2841. LogWrite(WORLD__ERROR, 0, "World", "Error in SpawnGroupRemoveSpawn query '%s': %s", query.GetQuery(), query.GetError());
  2842. return false;
  2843. }
  2844. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT count(group_id) FROM spawn_location_group where group_id = %u", group_id);
  2845. if(result && mysql_num_rows(result) > 0) {
  2846. MYSQL_ROW row;
  2847. if((row = mysql_fetch_row(result))){
  2848. if(atoul(row[0]) == 0)
  2849. DeleteSpawnGroup(group_id);
  2850. }
  2851. }
  2852. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  2853. LogWrite(WORLD__ERROR, 0, "World", "Error in SpawnGroupRemoveSpawn query '%s': %s", query.GetQuery(), query.GetError());
  2854. return false;
  2855. }
  2856. return true;
  2857. }
  2858. int32 WorldDatabase::CreateSpawnGroup(Spawn* spawn, string name)
  2859. {
  2860. int32 group_id = 0;
  2861. Query query;
  2862. // JA: As of 0.7.1, DB Milestone 2, Content Team needs to use group_id's from Raw Data, so start any manual group_id's > 100,000
  2863. query.RunQuery2(Q_INSERT, "INSERT INTO spawn_location_group (group_id, placement_id, name) SELECT IF(ISNULL(MAX(group_id))=1, 100000, MAX(group_id)+1), %u, '%s' FROM spawn_location_group", spawn->GetSpawnLocationPlacementID(), getSafeEscapeString(name.c_str()).c_str());
  2864. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF)
  2865. return 0;
  2866. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT max(group_id) FROM spawn_location_group");
  2867. if(result && mysql_num_rows(result) > 0)
  2868. {
  2869. MYSQL_ROW row;
  2870. if((row = mysql_fetch_row(result)))
  2871. {
  2872. if(row[0])
  2873. group_id = atoul(row[0]);
  2874. }
  2875. }
  2876. return group_id;
  2877. }
  2878. void WorldDatabase::DeleteSpawnGroup(int32 id){
  2879. Query query;
  2880. query.RunQuery2(Q_DELETE, "delete FROM spawn_location_group where group_id = %u", id);
  2881. }
  2882. bool WorldDatabase::SetGroupSpawnChance(int32 id, float chance){
  2883. Query query;
  2884. query.RunQuery2(Q_UPDATE, "replace into spawn_location_group_chances (group_id, percentage) values(%u, %f)", id, chance);
  2885. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  2886. LogWrite(WORLD__ERROR, 0, "World", "Error in SetGroupSpawnChance query '%s': %s", query.GetQuery(), query.GetError());
  2887. return false;
  2888. }
  2889. return true;
  2890. }
  2891. int32 WorldDatabase::LoadSpawnGroupChances(ZoneServer* zone){
  2892. Query query;
  2893. int32 count = 0;
  2894. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT slgc.group_id, slgc.percentage FROM spawn_location_group_chances slgc, spawn_location_group slg, spawn_location_placement slp where slgc.group_id = slg.group_id and slg.placement_id = slp.id and slp.zone_id = %u", zone->GetZoneID());
  2895. if(result && mysql_num_rows(result) > 0) {
  2896. MYSQL_ROW row;
  2897. int32 group_id = 0;
  2898. float percent = 0;
  2899. while(result && (row = mysql_fetch_row(result))){
  2900. group_id = atoul(row[0]);
  2901. percent = atof(row[1]);
  2902. zone->AddSpawnGroupChance(group_id, percent);
  2903. count++;
  2904. }
  2905. }
  2906. return count;
  2907. }
  2908. int32 WorldDatabase::LoadSpawnLocationGroupAssociations(ZoneServer* zone){
  2909. Query query;
  2910. int32 count = 0;
  2911. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT distinct slga.group_id1, slga.group_id2 FROM spawn_location_group_associations slga, spawn_location_group slg, spawn_location_placement slp where (slg.group_id = slga.group_id1 or slg.group_id = slga.group_id2) and slg.placement_id = slp.id and slp.zone_id = %u", zone->GetZoneID());
  2912. if(result && mysql_num_rows(result) > 0) {
  2913. MYSQL_ROW row;
  2914. while(result && (row = mysql_fetch_row(result))){
  2915. zone->AddSpawnGroupAssociation(atoul(row[0]), atoul(row[1]));
  2916. count++;
  2917. }
  2918. }
  2919. return count;
  2920. }
  2921. int32 WorldDatabase::LoadSpawnLocationGroups(ZoneServer* zone){
  2922. Query query;
  2923. int32 count = 0;
  2924. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT slg.group_id, slg.placement_id, slp.spawn_location_id FROM spawn_location_group slg, spawn_location_placement slp WHERE slg.placement_id = slp.id and slp.zone_id = %u", zone->GetZoneID());
  2925. if(result && mysql_num_rows(result) > 0) {
  2926. MYSQL_ROW row;
  2927. int32 placement_id = 0;
  2928. int32 group_id = 0;
  2929. int32 spawn_location_id = 0;
  2930. while(result && (row = mysql_fetch_row(result))){
  2931. group_id = atoul(row[0]);
  2932. placement_id = atoul(row[1]);
  2933. spawn_location_id = atoul(row[2]);
  2934. zone->AddSpawnGroupLocation(group_id, placement_id, spawn_location_id);
  2935. count++;
  2936. }
  2937. }
  2938. return count;
  2939. }
  2940. int32 WorldDatabase::ProcessSpawnLocations(ZoneServer* zone, const char* sql_query, int8 type){
  2941. int32 number = 0;
  2942. Query query;
  2943. MYSQL_RES* result = query.RunQuery2(Q_SELECT, sql_query, zone->GetZoneID());
  2944. if(result && mysql_num_rows(result) > 0) {
  2945. MYSQL_ROW row;
  2946. int32 spawn_location_id = 0xFFFFFFFF;
  2947. SpawnLocation* spawn_location = 0;
  2948. while(result && (row = mysql_fetch_row(result))){
  2949. if((spawn_location_id == 0xFFFFFFFF) || atoul(row[0]) != spawn_location_id){
  2950. if(spawn_location){
  2951. zone->AddSpawnLocation(spawn_location_id, spawn_location);
  2952. number++;
  2953. }
  2954. spawn_location = new SpawnLocation();
  2955. }
  2956. SpawnEntry* entry = new SpawnEntry;
  2957. spawn_location_id = atoul(row[0]);
  2958. entry->spawn_location_id = spawn_location_id;
  2959. entry->spawn_entry_id = atoul(row[1]);
  2960. entry->spawn_type = type;
  2961. entry->spawn_id = atoul(row[9]);
  2962. entry->spawn_percentage = atof(row[10]);
  2963. entry->respawn = atoul(row[11]);
  2964. entry->expire_time = atoul(row[14]);
  2965. entry->expire_offset = atoul(row[15]);
  2966. //devn00b add stat overrides. Just a slight increase in size. Used in ZoneServer::AddNPCSpawn.
  2967. entry->lvl_override = atoul(row[19]);
  2968. entry->hp_override = atoul(row[20]);
  2969. entry->mp_override = atoul(row[21]);
  2970. entry->str_override = atoul(row[22]);
  2971. entry->sta_override = atoul(row[23]);
  2972. entry->wis_override = atoul(row[24]);
  2973. entry->int_override = atoul(row[25]);
  2974. entry->agi_override = atoul(row[26]);
  2975. entry->heat_override = atoul(row[27]);
  2976. entry->cold_override = atoul(row[28]);
  2977. entry->magic_override = atoul(row[29]);
  2978. entry->mental_override = atoul(row[30]);
  2979. entry->divine_override = atoul(row[31]);
  2980. entry->disease_override = atoul(row[32]);
  2981. entry->poison_override = atoul(row[33]);
  2982. entry->difficulty_override = atoul(row[34]);
  2983. spawn_location->x = atof(row[2]);
  2984. spawn_location->y = atof(row[3]);
  2985. spawn_location->z = atof(row[4]);
  2986. spawn_location->x_offset = atof(row[5]);
  2987. spawn_location->y_offset = atof(row[6]);
  2988. spawn_location->z_offset = atof(row[7]);
  2989. spawn_location->heading = atof(row[8]);
  2990. spawn_location->pitch = atof(row[16]);
  2991. spawn_location->roll = atof(row[17]);
  2992. spawn_location->conditional = atoi(row[18]);
  2993. spawn_location->total_percentage += entry->spawn_percentage;
  2994. spawn_location->grid_id = strtoul(row[12], NULL, 0);
  2995. spawn_location->placement_id = strtoul(row[13], NULL, 0);
  2996. spawn_location->AddSpawn(entry);
  2997. }
  2998. if(spawn_location){
  2999. zone->AddSpawnLocation(spawn_location_id, spawn_location);
  3000. number++;
  3001. }
  3002. }
  3003. return number;
  3004. }
  3005. void WorldDatabase::ResetDatabase(){
  3006. Query query;
  3007. query.RunQuery2("delete FROM table_versions where name != 'table_versions'", Q_DELETE);
  3008. }
  3009. void WorldDatabase::EnableConstraints(){
  3010. Query query;
  3011. query.RunQuery2("/*!40101 SET SQL_MODE=@OLD_SQL_MODE */", Q_DBMS);
  3012. query.RunQuery2("/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */", Q_DBMS);
  3013. }
  3014. void WorldDatabase::DisableConstraints(){
  3015. Query query;
  3016. query.RunQuery2("/*!40101 SET NAMES utf8 */", Q_DBMS);
  3017. query.RunQuery2("/*!40101 SET SQL_MODE=''*/", Q_DBMS);
  3018. query.RunQuery2("/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */", Q_DBMS);
  3019. query.RunQuery2("/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */", Q_DBMS);
  3020. }
  3021. void WorldDatabase::LoadSpawns(ZoneServer* zone)
  3022. {
  3023. Query query;
  3024. int32 npcs = 0, objects = 0, widgets = 0, signs = 0, ground_spawns = 0, spawn_groups = 0, spawn_group_associations = 0, spawn_group_chances = 0;
  3025. LogWrite(SPAWN__TRACE, 0, "Spawn", "Enter LoadSpawns");
  3026. npcs = ProcessSpawnLocations(zone, "SELECT sln.id, sle.id, slp.x, slp.y, slp.z, slp.x_offset, slp.y_offset, slp.z_offset, slp.heading, sle.spawn_id, sle.spawnpercentage, slp.respawn, slp.grid_id, slp.id, slp.expire_timer, slp.expire_offset, slp.pitch, slp.roll, sle.condition, slp.lvl_override, slp.hp_override, slp.mp_override, slp.str_override, slp.sta_override, slp.wis_override, slp.int_override, slp.agi_override, slp.heat_override, slp.cold_override, slp.magic_override, slp.mental_override, slp.divine_override, slp.disease_override, slp.poison_override, difficulty_override FROM spawn_location_placement slp, spawn_location_name sln, spawn_location_entry sle, spawn_npcs sn where sn.spawn_id = sle.spawn_id and sln.id = sle.spawn_location_id and sln.id = slp.spawn_location_id and slp.zone_id=%i ORDER BY sln.id, sle.id", SPAWN_ENTRY_TYPE_NPC);
  3027. objects = ProcessSpawnLocations(zone, "SELECT sln.id, sle.id, slp.x, slp.y, slp.z, slp.x_offset, slp.y_offset, slp.z_offset, slp.heading, sle.spawn_id, sle.spawnpercentage, slp.respawn, slp.grid_id, slp.id, slp.expire_timer, slp.expire_offset, slp.pitch, slp.roll, sle.condition, slp.lvl_override, slp.hp_override, slp.mp_override, slp.str_override, slp.sta_override, slp.wis_override, slp.int_override, slp.agi_override, slp.heat_override, slp.cold_override, slp.magic_override, slp.mental_override, slp.divine_override, slp.disease_override, slp.poison_override, difficulty_override FROM spawn_location_placement slp, spawn_location_name sln, spawn_location_entry sle, spawn_objects so where so.spawn_id = sle.spawn_id and sln.id = sle.spawn_location_id and sln.id = slp.spawn_location_id and slp.zone_id=%i ORDER BY sln.id, sle.id", SPAWN_ENTRY_TYPE_OBJECT);
  3028. widgets = ProcessSpawnLocations(zone, "SELECT sln.id, sle.id, slp.x, slp.y, slp.z, slp.x_offset, slp.y_offset, slp.z_offset, slp.heading, sle.spawn_id, sle.spawnpercentage, slp.respawn, slp.grid_id, slp.id, slp.expire_timer, slp.expire_offset, slp.pitch, slp.roll, sle.condition, slp.lvl_override, slp.hp_override, slp.mp_override, slp.str_override, slp.sta_override, slp.wis_override, slp.int_override, slp.agi_override, slp.heat_override, slp.cold_override, slp.magic_override, slp.mental_override, slp.divine_override, slp.disease_override, slp.poison_override, difficulty_override FROM spawn_location_placement slp, spawn_location_name sln, spawn_location_entry sle, spawn_widgets sw where sw.spawn_id = sle.spawn_id and sln.id = sle.spawn_location_id and sln.id = slp.spawn_location_id and slp.zone_id=%i ORDER BY sln.id, sle.id", SPAWN_ENTRY_TYPE_WIDGET);
  3029. signs = ProcessSpawnLocations(zone, "SELECT sln.id, sle.id, slp.x, slp.y, slp.z, slp.x_offset, slp.y_offset, slp.z_offset, slp.heading, sle.spawn_id, sle.spawnpercentage, slp.respawn, slp.grid_id, slp.id, slp.expire_timer, slp.expire_offset, slp.pitch, slp.roll, sle.condition, slp.lvl_override, slp.hp_override, slp.mp_override, slp.str_override, slp.sta_override, slp.wis_override, slp.int_override, slp.agi_override, slp.heat_override, slp.cold_override, slp.magic_override, slp.mental_override, slp.divine_override, slp.disease_override, slp.poison_override, difficulty_override FROM spawn_location_placement slp, spawn_location_name sln, spawn_location_entry sle, spawn_signs ss where ss.spawn_id = sle.spawn_id and sln.id = sle.spawn_location_id and sln.id = slp.spawn_location_id and slp.zone_id=%i ORDER BY sln.id, sle.id", SPAWN_ENTRY_TYPE_SIGN);
  3030. ground_spawns = ProcessSpawnLocations(zone, "SELECT sln.id, sle.id, slp.x, slp.y, slp.z, slp.x_offset, slp.y_offset, slp.z_offset, slp.heading, sle.spawn_id, sle.spawnpercentage, slp.respawn, slp.grid_id, slp.id, slp.expire_timer, slp.expire_offset, slp.pitch, slp.roll, sle.condition, slp.lvl_override, slp.hp_override, slp.mp_override, slp.str_override, slp.sta_override, slp.wis_override, slp.int_override, slp.agi_override, slp.heat_override, slp.cold_override, slp.magic_override, slp.mental_override, slp.divine_override, slp.disease_override, slp.poison_override, difficulty_override FROM spawn_location_placement slp, spawn_location_name sln, spawn_location_entry sle, spawn_ground sg where sg.spawn_id = sle.spawn_id and sln.id = sle.spawn_location_id and sln.id = slp.spawn_location_id and slp.zone_id=%i ORDER BY sln.id, sle.id", SPAWN_ENTRY_TYPE_GROUNDSPAWN);
  3031. spawn_groups = LoadSpawnLocationGroups(zone);
  3032. spawn_group_associations = LoadSpawnLocationGroupAssociations(zone);
  3033. spawn_group_chances = LoadSpawnGroupChances(zone);
  3034. LogWrite(SPAWN__INFO, 0, "Spawn", "Loaded for zone '%s' (%u):\n\t%u NPC(s), %u Object(s), %u Widget(s)\n\t%u Sign(s), %u Ground Spawn(s), %u Spawn Group(s)\n\t%u Spawn Group Association(s), %u Spawn Group Chance(s)", zone->GetZoneName(), zone->GetZoneID(), npcs, objects, widgets, signs, ground_spawns, spawn_groups, spawn_group_associations, spawn_group_chances);
  3035. LogWrite(SPAWN__TRACE, 0, "Spawn", "Exit LoadSpawns");
  3036. }
  3037. bool WorldDatabase::UpdateSpawnLocationSpawns(Spawn* spawn) {
  3038. Query query;
  3039. query.RunQuery2(Q_UPDATE, "update spawn_location_placement set x=%f, y=%f, z=%f, heading=%f, x_offset=%f, y_offset=%f, z_offset=%f, respawn=%u, expire_timer=%u, expire_offset=%u, grid_id=%u, pitch=%f, roll=%f where id = %u",
  3040. spawn->GetX(), spawn->GetY(), spawn->GetZ(), spawn->GetHeading(), spawn->GetXOffset(), spawn->GetYOffset(), spawn->GetZOffset(), spawn->GetRespawnTime(), spawn->GetExpireTime(), spawn->GetExpireOffsetTime(), spawn->GetLocation(), spawn->GetPitch(), spawn->GetRoll(), spawn->GetSpawnLocationPlacementID());
  3041. if (query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF) {
  3042. LogWrite(WORLD__ERROR, 0, "World", "Error in UpdateSpawnLocationSpawns query '%s': %s", query.GetQuery(), query.GetError());
  3043. return false;
  3044. }
  3045. return true;
  3046. }
  3047. bool WorldDatabase::UpdateSpawnWidget(int32 widget_id, char* queryString) {
  3048. Query query;
  3049. query.RunQuery2(Q_UPDATE, "update spawn_widgets set %s where widget_id = %u",
  3050. queryString, widget_id);
  3051. if (query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF) {
  3052. LogWrite(WORLD__ERROR, 0, "World", "Error in UpdateSpawnWidget query '%s': %s", query.GetQuery(), query.GetError());
  3053. return false;
  3054. }
  3055. return true;
  3056. }
  3057. vector<string>* WorldDatabase::GetSpawnNameList(const char* in_name){
  3058. Query query;
  3059. string names = "";
  3060. vector<string>* ret = 0;
  3061. string name = getSafeEscapeString(in_name);
  3062. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT concat(spawn.id, ', ', name) FROM spawn where name like '%%%s%%'", name.c_str());
  3063. if(result && mysql_num_rows(result) > 0){
  3064. ret = new vector<string>;
  3065. MYSQL_ROW row;
  3066. int8 num = 0;
  3067. while(result && (row = mysql_fetch_row(result))){
  3068. if(num >= 10)
  3069. break;
  3070. ret->push_back(string(row[0]));
  3071. num++;
  3072. }
  3073. char total[60] = {0};
  3074. if(mysql_num_rows(result) > 10)
  3075. sprintf(total, "Total number of results: %u (Limited to 10)", (int32)mysql_num_rows(result));
  3076. else
  3077. sprintf(total, "Total number of results: %u", (int32)mysql_num_rows(result));
  3078. ret->push_back(string(total));
  3079. }
  3080. return ret;
  3081. }
  3082. string WorldDatabase::GetZoneName(char* zone_description){
  3083. string ret;
  3084. Query query;
  3085. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT name FROM zones where description = '%s'", getSafeEscapeString(zone_description).c_str());
  3086. if(result && mysql_num_rows(result) > 0){
  3087. MYSQL_ROW row = mysql_fetch_row(result);
  3088. ret = string(row[0]);
  3089. }
  3090. return ret;
  3091. }
  3092. void WorldDatabase::LoadRevivePoints(vector<RevivePoint*>* revive_points, int32 zone_id){
  3093. if(revive_points && revive_points->size() > 0){
  3094. LogWrite(WORLD__ERROR, 0, "World", "Revive points have already been loaded for this zone!");
  3095. return;
  3096. }
  3097. else if(!revive_points || zone_id == 0){
  3098. LogWrite(WORLD__ERROR, 0, "World", "LoadRevivePoints called with null variables!");
  3099. return;
  3100. }
  3101. Query query;
  3102. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT respawn_zone_id, location_name, safe_x, safe_y, safe_z, heading, always_included FROM revive_points where zone_id=%u ORDER BY id asc", zone_id);
  3103. if(revive_points && result && mysql_num_rows(result) > 0){
  3104. MYSQL_ROW row;
  3105. int32 id = 0;
  3106. RevivePoint* point = 0;
  3107. while(result && (row=mysql_fetch_row(result))){
  3108. point = new RevivePoint;
  3109. point->id = id;
  3110. point->zone_id = atoul(row[0]);
  3111. point->location_name = string(row[1]);
  3112. point->x = atof(row[2]);
  3113. point->y = atof(row[3]);
  3114. point->z = atof(row[4]);
  3115. point->heading = atof(row[5]);
  3116. point->always_included = atoul(row[6]);
  3117. revive_points->push_back(point);
  3118. id++;
  3119. }
  3120. }
  3121. }
  3122. int32 WorldDatabase::GetNextSpawnIDInZone(int32 zone_id)
  3123. {
  3124. Query query;
  3125. int32 ret = 0;
  3126. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT MAX(id) FROM spawn where id LIKE '%i____'", zone_id);
  3127. if(result && mysql_num_rows(result) > 0) {
  3128. MYSQL_ROW row;
  3129. row = mysql_fetch_row(result);
  3130. if(row[0])
  3131. ret = atoi(row[0]) + 1;
  3132. }
  3133. if( ret == 0 )
  3134. ret = zone_id * 10000; // there are no spawns for that zone yet, to start with the first ID
  3135. LogWrite(WORLD__DEBUG, 0, "World", "Next Spawn ID for Zone %i: %u", zone_id, ret);
  3136. return ret;
  3137. }
  3138. bool WorldDatabase::SaveSpawnInfo(Spawn* spawn){
  3139. Query query;
  3140. string name = getSafeEscapeString(spawn->GetName());
  3141. string suffix = getSafeEscapeString(spawn->GetSuffixTitle());
  3142. string prefix = getSafeEscapeString(spawn->GetPrefixTitle());
  3143. string last_name = getSafeEscapeString(spawn->GetLastName());
  3144. if(spawn->GetDatabaseID() == 0){
  3145. int8 isInstanceType = (spawn->GetZone()->GetInstanceType() == Instance_Type::PERSONAL_HOUSE_INSTANCE);
  3146. int32 new_spawn_id = GetNextSpawnIDInZone(spawn->GetZone()->GetZoneID());
  3147. query.RunQuery2(Q_INSERT, "insert into spawn (id, name, race, model_type, size, targetable, show_name, command_primary, command_secondary, visual_state, attackable, show_level, show_command_icon, display_hand_icon, faction_id, collision_radius, hp, power, prefix, suffix, last_name, is_instanced_spawn, merchant_min_level, merchant_max_level) values(%u, '%s', %i, %i, %i, %i, %i, %u, %u, %i, %i, %i, %i, %i, %u, %i, %u, %u, '%s', '%s', '%s', %u, %u, %u)",
  3148. new_spawn_id, name.c_str(), spawn->GetRace(), spawn->GetModelType(), spawn->GetSize(), spawn->appearance.targetable, spawn->appearance.display_name, spawn->GetPrimaryCommandListID(), spawn->GetSecondaryCommandListID(), spawn->GetVisualState(), spawn->appearance.attackable, spawn->appearance.show_level, spawn->appearance.show_command_icon, spawn->appearance.display_hand_icon, 0, spawn->appearance.pos.collision_radius, spawn->GetTotalHP(), spawn->GetTotalPower(), prefix.c_str(), suffix.c_str(), last_name.c_str(), isInstanceType, spawn->GetMerchantMinLevel(), spawn->GetMerchantMaxLevel());
  3149. if( new_spawn_id > 0 )
  3150. spawn->SetDatabaseID(new_spawn_id); // use the new zone_id range
  3151. else if( query.GetLastInsertedID() > 0 )
  3152. spawn->SetDatabaseID(query.GetLastInsertedID()); // else fall back to last_inserted_id
  3153. else
  3154. return false; // else, hang your head in shame as you are an utter failure
  3155. if(spawn->IsNPC()){
  3156. query.RunQuery2(Q_INSERT, "insert into spawn_npcs (spawn_id, min_level, max_level, enc_level, class_, gender, min_group_size, max_group_size, hair_type_id, facial_hair_type_id, wing_type_id, chest_type_id, legs_type_id, soga_hair_type_id, soga_facial_hair_type_id, soga_model_type, heroic_flag, action_state, mood_state, initial_state, activity_status, hide_hood, emote_state) values(%u, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i, %i)",
  3157. spawn->GetDatabaseID(), spawn->GetLevel(), spawn->GetLevel(), spawn->GetDifficulty(), spawn->GetAdventureClass(), spawn->GetGender(), 0, 0, ((NPC*)spawn)->features.hair_type, ((NPC*)spawn)->features.hair_face_type,
  3158. ((NPC*)spawn)->features.wing_type, ((NPC*)spawn)->features.chest_type, ((NPC*)spawn)->features.legs_type, ((NPC*)spawn)->features.soga_hair_type, ((NPC*)spawn)->features.soga_hair_face_type, spawn->appearance.soga_model_type, spawn->appearance.heroic_flag, spawn->GetActionState(), spawn->GetMoodState(), spawn->GetInitialState(), spawn->GetActivityStatus(), spawn->appearance.hide_hood, spawn->appearance.emote_state);
  3159. }
  3160. else if(spawn->IsObject()){
  3161. query.RunQuery2(Q_INSERT, "insert into spawn_objects (spawn_id) values(%u)", spawn->GetDatabaseID());
  3162. }
  3163. else if(spawn->IsWidget()){
  3164. Widget* widget = (Widget*)spawn;
  3165. query.RunQuery2(Q_INSERT, "insert into spawn_widgets (spawn_id, widget_id) values(%u, %u)", spawn->GetDatabaseID(), widget->GetWidgetID());
  3166. }
  3167. else if(spawn->IsSign()){
  3168. query.RunQuery2(Q_INSERT, "insert into spawn_signs (spawn_id, description) values(%u, 'change me')", spawn->GetDatabaseID());
  3169. }
  3170. else if (spawn->IsGroundSpawn()) {
  3171. query.RunQuery2(Q_INSERT, "insert into spawn_ground (spawn_id) values(%u)", spawn->GetDatabaseID());
  3172. }
  3173. }
  3174. else{
  3175. if(spawn->IsNPC()){
  3176. query.RunQuery2(Q_UPDATE, "update spawn_npcs, spawn set name='%s', min_level=%i, max_level=%i, enc_level=%i, race=%i, model_type=%i, class_=%i, gender=%i, show_name=%i, attackable=%i, show_level=%i, targetable=%i, show_command_icon=%i, display_hand_icon=%i, hair_type_id=%i, facial_hair_type_id=%i, wing_type_id=%i, chest_type_id=%i, legs_type_id=%i, soga_hair_type_id=%i, soga_facial_hair_type_id=%i, soga_model_type=%i, size=%i, hp=%u, heroic_flag=%i, power=%u, collision_radius=%i, command_primary=%u, command_secondary=%u, visual_state=%i, action_state=%i, mood_state=%i, initial_state=%i, activity_status=%i, alignment=%i, faction_id=%u, hide_hood=%i, emote_state=%i, suffix ='%s', prefix='%s', last_name='%s', merchant_min_level = %u, merchant_max_level = %u where spawn_npcs.spawn_id = spawn.id and spawn.id = %u",
  3177. name.c_str(), spawn->GetLevel(), spawn->GetLevel(), spawn->GetDifficulty(), spawn->GetRace(), spawn->GetModelType(),
  3178. spawn->GetAdventureClass(), spawn->GetGender(), spawn->appearance.display_name, spawn->appearance.attackable, spawn->appearance.show_level, spawn->appearance.targetable, spawn->appearance.show_command_icon, spawn->appearance.display_hand_icon, ((NPC*)spawn)->features.hair_type,
  3179. ((NPC*)spawn)->features.hair_face_type, ((NPC*)spawn)->features.wing_type, ((NPC*)spawn)->features.chest_type, ((NPC*)spawn)->features.legs_type, ((NPC*)spawn)->features.soga_hair_type, ((NPC*)spawn)->features.soga_hair_face_type, spawn->appearance.soga_model_type, spawn->GetSize(),
  3180. spawn->GetTotalHPBase(), spawn->appearance.heroic_flag, spawn->GetTotalPowerBase(), spawn->GetCollisionRadius(), spawn->GetPrimaryCommandListID(),
  3181. spawn->GetSecondaryCommandListID(), spawn->GetVisualState(), spawn->GetActionState(), spawn->GetMoodState(), spawn->GetInitialState(),
  3182. spawn->GetActivityStatus(), ((NPC*)spawn)->GetAlignment(), spawn->GetFactionID(), spawn->appearance.hide_hood, spawn->appearance.emote_state,
  3183. suffix.c_str(), prefix.c_str(), last_name.c_str(), spawn->GetMerchantMinLevel(), spawn->GetMerchantMaxLevel(), spawn->GetDatabaseID());
  3184. }
  3185. else if(spawn->IsObject()){
  3186. query.RunQuery2(Q_UPDATE, "update spawn_objects, spawn set name='%s', model_type=%i, show_name=%i, targetable=%i, size=%i, command_primary=%u, command_secondary=%u, visual_state=%i, attackable=%i, show_level=%i, show_command_icon=%i, display_hand_icon=%i, collision_radius=%i, hp = %u, power = %u, device_id = %i, merchant_min_level = %u, merchant_max_level = %u where spawn_objects.spawn_id = spawn.id and spawn.id = %u",
  3187. name.c_str(), spawn->GetModelType(), spawn->appearance.display_name, spawn->appearance.targetable, spawn->GetSize(), spawn->GetPrimaryCommandListID(), spawn->GetSecondaryCommandListID(), spawn->GetVisualState(), spawn->appearance.attackable, spawn->appearance.show_level, spawn->appearance.show_command_icon, spawn->appearance.display_hand_icon,
  3188. spawn->GetCollisionRadius(), spawn->GetTotalHP(), spawn->GetTotalPower(), ((Object*)spawn)->GetDeviceID(), spawn->GetMerchantMinLevel(), spawn->GetMerchantMaxLevel(), spawn->GetDatabaseID());
  3189. }
  3190. else if(spawn->IsWidget()){
  3191. Widget* widget = (Widget*)spawn;
  3192. char* openSound = 0;
  3193. char* closeSound = 0;
  3194. if (widget->GetOpenSound() != NULL) openSound = (char*)widget->GetOpenSound(); else openSound = (char*)string("0").c_str();
  3195. if (widget->GetCloseSound() != NULL) closeSound = (char*)widget->GetCloseSound(); else closeSound = (char*)string("0").c_str();
  3196. query.RunQuery2(Q_UPDATE, "update spawn_widgets, spawn set name='%s', race=%i, model_type=%i, show_name=%i, attackable=%i, show_level=%i, show_command_icon=%i, display_hand_icon=%i, size=%i, hp=%u, power=%u, collision_radius=%i, command_primary=%u, command_secondary=%u, visual_state=%i, faction_id=%u, suffix ='%s', prefix='%s', last_name='%s',widget_id = %u,widget_x = %f,widget_y = %f,widget_z = %f,include_heading = %u,include_location = %u,icon = %u,type='%s',open_heading = %f,closed_heading = %f,open_x = %f,open_y = %f,open_z = %f,action_spawn_id = %u,open_sound_file='%s',close_sound_file='%s',open_duration = %u,close_x = %f,close_y=%f,close_z=%f,linked_spawn_id = %u,house_id = %u, merchant_min_level = %u, merchant_max_level = %u where spawn_widgets.spawn_id = spawn.id and spawn.id = %u",
  3197. name.c_str(), spawn->GetRace(), spawn->GetModelType(), spawn->appearance.display_name, spawn->appearance.attackable, spawn->appearance.show_level, spawn->appearance.show_command_icon, spawn->appearance.display_hand_icon, spawn->GetSize(),
  3198. spawn->GetTotalHP(), spawn->GetTotalPower(), spawn->GetCollisionRadius(), spawn->GetPrimaryCommandListID(), spawn->GetSecondaryCommandListID(), spawn->GetVisualState(), spawn->GetFactionID(),
  3199. suffix.c_str(), prefix.c_str(), last_name.c_str(), widget->GetWidgetID(), widget->GetX(), widget->GetY(), widget->GetZ(), widget->GetIncludeHeading(), widget->GetIncludeLocation(), widget->GetIconValue(), Widget::GetWidgetTypeNameByTypeID(widget->GetWidgetType()).c_str(),
  3200. widget->GetOpenHeading(), widget->GetClosedHeading(), widget->GetOpenX(), widget->GetOpenY(), widget->GetOpenZ(),
  3201. widget->GetActionSpawnID(), openSound, closeSound,widget->GetOpenDuration(),
  3202. widget->GetCloseX(),widget->GetCloseY(),widget->GetCloseZ(),widget->GetLinkedSpawnID(),widget->GetHouseID(),
  3203. spawn->GetMerchantMinLevel(), spawn->GetMerchantMaxLevel(), spawn->GetDatabaseID());
  3204. }
  3205. else if(spawn->IsSign()){
  3206. Sign* sign = (Sign*)spawn;
  3207. query.RunQuery2(Q_UPDATE, "update spawn_signs, spawn set name='%s', race=%i, model_type=%i, show_name=%i, attackable=%i, show_level=%i, show_command_icon=%i, display_hand_icon=%i, size=%i, hp=%u, power=%u, collision_radius=%i, command_primary=%u, command_secondary=%u, visual_state=%i, faction_id=%u, suffix ='%s', prefix='%s', last_name='%s', `type`='%s', zone_id = %u, widget_id = %u, title='%s', widget_x = %f, widget_y = %f, widget_z = %f, icon = %u, description='%s', sign_distance = %f, zone_x = %f, zone_y = %f, zone_z = %f, zone_heading = %f, include_heading = %u, include_location = %u, merchant_min_level = %u, merchant_max_level = %u, language = %u where spawn_signs.spawn_id = spawn.id and spawn.id = %u",
  3208. name.c_str(), spawn->GetRace(), spawn->GetModelType(), spawn->appearance.display_name, spawn->appearance.attackable, spawn->appearance.show_level, spawn->appearance.show_command_icon, spawn->appearance.display_hand_icon, spawn->GetSize(),
  3209. spawn->GetTotalHP(), spawn->GetTotalPower(), spawn->GetCollisionRadius(), spawn->GetPrimaryCommandListID(), spawn->GetSecondaryCommandListID(), spawn->GetVisualState(), spawn->GetFactionID(),
  3210. suffix.c_str(), prefix.c_str(), last_name.c_str(), sign->GetSignType() == SIGN_TYPE_GENERIC ? "Generic" : "Zone", sign->GetSignZoneID(),
  3211. sign->GetWidgetID(), sign->GetSignTitle(), sign->GetWidgetX(), sign->GetWidgetY(), sign->GetWidgetZ(),
  3212. sign->GetIconValue(), sign->GetSignDescription(), sign->GetSignDistance(), sign->GetSignZoneX(),
  3213. sign->GetSignZoneY(), sign->GetSignZoneZ(), sign->GetSignZoneHeading(), sign->GetIncludeHeading(),
  3214. sign->GetIncludeLocation(), spawn->GetMerchantMinLevel(), spawn->GetMerchantMaxLevel(), sign->GetLanguage(), spawn->GetDatabaseID());
  3215. }
  3216. }
  3217. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  3218. LogWrite(SPAWN__ERROR, 0, "Spawn", "Error in SaveSpawnInfo query '%s': %s", query.GetQuery(), query.GetError());
  3219. return false;
  3220. }
  3221. return true;
  3222. }
  3223. int32 WorldDatabase::SaveCombinedSpawnLocation(ZoneServer* zone, Spawn* in_spawn, const char* name){
  3224. vector<Spawn*>* spawns = in_spawn->GetSpawnGroup();
  3225. uint32 spawnLocationID = 0;
  3226. if(spawns && spawns->size() > 0){
  3227. vector<Spawn*>::iterator itr;
  3228. map<Spawn*, int32>::iterator freq_itr;
  3229. Spawn* spawn = 0;
  3230. map<Spawn*, int32> database_spawns;
  3231. int32 total = 0;
  3232. float x_offset = GetSpawnLocationPlacementOffsetX(in_spawn->GetSpawnLocationID());
  3233. float y_offset = GetSpawnLocationPlacementOffsetY(in_spawn->GetSpawnLocationID());
  3234. float z_offset = GetSpawnLocationPlacementOffsetZ(in_spawn->GetSpawnLocationID());
  3235. int32 spawn_location_id = GetNextSpawnLocation();
  3236. spawnLocationID = spawn_location_id;
  3237. if(!name)
  3238. name = "Combine SpawnGroup Generated";
  3239. if(!CreateNewSpawnLocation(spawn_location_id, name)){
  3240. safe_delete(spawns);
  3241. return 0;
  3242. }
  3243. for(itr = spawns->begin();itr!=spawns->end();itr++){
  3244. spawn = *itr;
  3245. if (spawn) {
  3246. RemoveSpawnFromSpawnLocation(spawn);
  3247. spawn->SetSpawnLocationID(spawn_location_id);
  3248. bool add = true;
  3249. for (freq_itr = database_spawns.begin(); freq_itr != database_spawns.end(); freq_itr++) {
  3250. if (spawn->GetDatabaseID() == freq_itr->first->GetDatabaseID()) {
  3251. freq_itr->second++;
  3252. total++;
  3253. add = false;
  3254. }
  3255. }
  3256. if (add) {
  3257. database_spawns[spawn] = 1;
  3258. total++;
  3259. }
  3260. }
  3261. }
  3262. for(freq_itr = database_spawns.begin(); freq_itr != database_spawns.end(); freq_itr++){
  3263. int8 percent = (freq_itr->second*100)/total;
  3264. if(!SaveSpawnEntry(freq_itr->first, name, percent, x_offset, y_offset, z_offset, freq_itr->first == in_spawn, false)){
  3265. safe_delete(spawns);
  3266. return 0;
  3267. }
  3268. }
  3269. for(itr=spawns->begin();itr!=spawns->end();itr++){
  3270. spawn = *itr;
  3271. zone->RemoveSpawn(spawn, true, true, true, true, true);
  3272. }
  3273. safe_delete(spawns);
  3274. }
  3275. else{
  3276. safe_delete(spawns);
  3277. return 0;
  3278. }
  3279. return spawnLocationID;
  3280. }
  3281. bool WorldDatabase::SaveSpawnEntry(Spawn* spawn, const char* spawn_location_name, int8 percent, float x_offset, float y_offset, float z_offset, bool save_zonespawn, bool create_spawnlocation){
  3282. Query query;
  3283. Query query2;
  3284. int32 count = 0;
  3285. if(create_spawnlocation){
  3286. count = GetSpawnLocationCount(spawn->GetSpawnLocationID());
  3287. if(count == 0){
  3288. if(!CreateNewSpawnLocation(spawn->GetSpawnLocationID(), spawn_location_name))
  3289. return false;
  3290. }
  3291. }
  3292. query.RunQuery2(Q_INSERT, "insert into spawn_location_entry (spawn_id, spawn_location_id, spawnpercentage) values(%u, %u, %i)", spawn->GetDatabaseID(), spawn->GetSpawnLocationID(), percent);
  3293. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  3294. LogWrite(SPAWN__ERROR, 0, "Spawn", "Error in SaveSpawnEntry query '%s': %s", query.GetQuery(), query.GetError());
  3295. return false;
  3296. }
  3297. if(save_zonespawn){
  3298. query2.RunQuery2(Q_INSERT, "insert into spawn_location_placement (zone_id, instance_id, spawn_location_id, x, y, z, x_offset, y_offset, z_offset, heading, grid_id) values(%u, %u, %u, %f, %f, %f, %f, %f, %f, %f, %u)", spawn->GetZone()->GetZoneID(), spawn->GetZone()->GetInstanceID(), spawn->GetSpawnLocationID(), spawn->GetX(), spawn->GetY(), spawn->GetZ(),x_offset, y_offset, z_offset, spawn->GetHeading(), spawn->GetLocation());
  3299. if(query2.GetErrorNumber() && query2.GetError() && query2.GetErrorNumber() < 0xFFFFFFFF){
  3300. LogWrite(SPAWN__ERROR, 0, "Spawn", "Error in SaveSpawnEntry query '%s': %s", query2.GetQuery(), query2.GetError());
  3301. return false;
  3302. }
  3303. spawn->SetSpawnLocationPlacementID(query2.GetLastInsertedID());
  3304. }
  3305. return true;
  3306. }
  3307. float WorldDatabase::GetSpawnLocationPlacementOffsetX(int32 location_id) {
  3308. Query query;
  3309. MYSQL_ROW row;
  3310. float ret = 0;
  3311. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `x_offset` FROM `spawn_location_placement` WHERE `spawn_location_id`=%u", location_id);
  3312. if (result && (row = mysql_fetch_row(result))) {
  3313. if (row[0])
  3314. ret = atof(row[0]);
  3315. }
  3316. return ret;
  3317. }
  3318. float WorldDatabase::GetSpawnLocationPlacementOffsetY(int32 location_id) {
  3319. Query query;
  3320. MYSQL_ROW row;
  3321. float ret = 0;
  3322. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `y_offset` FROM `spawn_location_placement` WHERE `spawn_location_id`=%u", location_id);
  3323. if (result && (row = mysql_fetch_row(result))) {
  3324. if (row[0])
  3325. ret = atof(row[0]);
  3326. }
  3327. return ret;
  3328. }
  3329. float WorldDatabase::GetSpawnLocationPlacementOffsetZ(int32 location_id) {
  3330. Query query;
  3331. MYSQL_ROW row;
  3332. float ret = 0;
  3333. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `z_offset` FROM `spawn_location_placement` WHERE `spawn_location_id`=%u", location_id);
  3334. if (result && (row = mysql_fetch_row(result))) {
  3335. if (row[0])
  3336. ret = atof(row[0]);
  3337. }
  3338. return ret;
  3339. }
  3340. bool WorldDatabase::CreateNewSpawnLocation(int32 id, const char* name){
  3341. Query query;
  3342. if(!name)
  3343. name = "Unknown Spawn Location Name";
  3344. string str_name = getSafeEscapeString(name);
  3345. query.RunQuery2(Q_INSERT, "insert into spawn_location_name (id, name) values(%u, '%s')", id, str_name.c_str());
  3346. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  3347. LogWrite(SPAWN__ERROR, 0, "Spawn", "Error in CreateNewSpawnLocation query '%s': %s", query.GetQuery(), query.GetError());
  3348. return false;
  3349. }
  3350. return true;
  3351. }
  3352. int32 WorldDatabase::GetSpawnLocationCount(int32 location, Spawn* spawn){
  3353. Query query;
  3354. int32 ret = 0;
  3355. MYSQL_RES* result = 0;
  3356. if(spawn)
  3357. result = query.RunQuery2(Q_SELECT, "SELECT count(id) FROM spawn_location_entry where spawn_location_id=%u and spawn_id=%u", location, spawn->GetDatabaseID());
  3358. else
  3359. result = query.RunQuery2(Q_SELECT, "SELECT count(id) FROM spawn_location_entry where spawn_location_id=%u", location);
  3360. if(result && mysql_num_rows(result) > 0){
  3361. MYSQL_ROW row;
  3362. while(result && (row = mysql_fetch_row(result)) && row[0]){
  3363. ret = strtoul(row[0], NULL, 0);
  3364. }
  3365. }
  3366. return ret;
  3367. }
  3368. int32 WorldDatabase::GetNextSpawnLocation(){
  3369. Query query;
  3370. int32 ret = 0;
  3371. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT max(id) FROM spawn_location_name");
  3372. if(result && mysql_num_rows(result) > 0){
  3373. MYSQL_ROW row;
  3374. while(result && (row = mysql_fetch_row(result)) && row[0]){
  3375. ret = strtoul(row[0], NULL, 0);
  3376. }
  3377. }
  3378. ret++;
  3379. return ret;
  3380. }
  3381. bool WorldDatabase::RemoveSpawnFromSpawnLocation(Spawn* spawn){
  3382. Query query;
  3383. Query query2;
  3384. int32 count = GetSpawnLocationCount(spawn->GetSpawnLocationID(), spawn);
  3385. query.RunQuery2(Q_DELETE, "delete FROM spawn_location_placement where spawn_location_id=%u", spawn->GetSpawnLocationID());
  3386. if(count == 1)
  3387. query.RunQuery2(Q_DELETE, "delete FROM spawn_location_name where id=%u", spawn->GetSpawnLocationID());
  3388. query2.RunQuery2(Q_DELETE, "delete FROM spawn_location_entry where spawn_id=%u and spawn_location_id = %u", spawn->GetDatabaseID(), spawn->GetSpawnLocationID());
  3389. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  3390. LogWrite(WORLD__ERROR, 0, "World", "Error in RemoveSpawnFromSpawnLocation query '%s': %s", query.GetQuery(), query.GetError());
  3391. return false;
  3392. }
  3393. else if(query2.GetErrorNumber() && query2.GetError() && query2.GetErrorNumber() < 0xFFFFFFFF){
  3394. LogWrite(SPAWN__ERROR, 0, "Spawn", "Error in RemoveSpawnFromSpawnLocation query '%s': %s", query2.GetQuery(), query.GetError());
  3395. return false;
  3396. }
  3397. return true;
  3398. }
  3399. map<int32, string>* WorldDatabase::GetZoneList(const char* name, bool is_admin)
  3400. {
  3401. Query query;
  3402. map<int32, string>* ret = 0;
  3403. string zone_name = getSafeEscapeString(name);
  3404. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `id`, `name` FROM zones WHERE `name` RLIKE '%s' %s", zone_name.c_str(), (is_admin)?"":" LIMIT 0,10");
  3405. if(result && mysql_num_rows(result) > 0)
  3406. {
  3407. ret = new map<int32, string>;
  3408. MYSQL_ROW row;
  3409. while(result && (row = mysql_fetch_row(result)))
  3410. {
  3411. zone_name = row[1];
  3412. (*ret)[atoi(row[0])] = zone_name;
  3413. }
  3414. }
  3415. return ret;
  3416. }
  3417. void WorldDatabase::UpdateStartingFactions(int32 char_id, int8 choice){
  3418. Query query;
  3419. query.RunQuery2(Q_INSERT, "insert into character_factions (char_id, faction_id, faction_level) select %u, faction_id, value FROM starting_factions where starting_city=%i", char_id, choice);
  3420. }
  3421. string WorldDatabase::GetStartingZoneName(int8 choice){
  3422. Query query;
  3423. string zone_name = "";
  3424. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT name FROM zones where start_zone = %u", choice);
  3425. if(result && mysql_num_rows(result) > 0){
  3426. MYSQL_ROW row;
  3427. while(result && (row = mysql_fetch_row(result))){
  3428. zone_name = string(row[0]);
  3429. }
  3430. }
  3431. return zone_name;
  3432. }
  3433. void WorldDatabase::UpdateStartingZone(int32 char_id, int8 class_id, int8 race_id, PacketStruct* create)
  3434. {
  3435. Query query,query2;
  3436. int32 packetVersion = create->GetVersion();
  3437. int8 choice = create->getType_int8_ByName("starting_zone"); // 0 = far journey, 1 = isle of refuge
  3438. int8 deity = create->getType_int8_ByName("deity"); // aka 'alignment' for early DOF, 0 = evil, 1 = good
  3439. int32 startingZoneRuleFlag = rule_manager.GetGlobalRule(R_World, StartingZoneRuleFlag)->GetInt32();
  3440. bool enforceRacialAlignment = rule_manager.GetGlobalRule(R_World, EnforceRacialAlignment)->GetBool();
  3441. if((startingZoneRuleFlag == 1 || startingZoneRuleFlag == 2) && packetVersion > 546)
  3442. {
  3443. LogWrite(PLAYER__INFO, 0, "Player", "Starting zone rule flag %u override choice %u to deity value of 0", startingZoneRuleFlag, choice);
  3444. choice = 0;
  3445. }
  3446. LogWrite(PLAYER__INFO, 0, "Player", "Adding default zone for race: %i, class: %i for char_id: %u (choice: %i), deity(alignment): %u, version: %u.", race_id, class_id, char_id, choice, deity, packetVersion);
  3447. // first, check to see if there is a starting_zones record for this race/class/choice combo (now using extended Archetype/BaseClass/Class combos
  3448. MYSQL_RES* result = 0;
  3449. string whereRuleFlag("");
  3450. if(startingZoneRuleFlag > 0)
  3451. whereRuleFlag = string(" AND ruleflag & " + std::to_string(startingZoneRuleFlag));
  3452. string syntaxSelect("SELECT z.name, sz.zone_id, z.safe_x, z.safe_y, z.safe_z, sz.x, sz.y, sz.z, sz.heading, sz.is_instance, z.city_zone, sz.start_alignment FROM");
  3453. if ( class_id == 0 )
  3454. result = query.RunQuery2(Q_SELECT, "%s starting_zones sz, zones z WHERE sz.zone_id = z.id AND class_id = 255 AND race_id IN (%i, 255) AND deity IN (%i, 255) AND choice = %u AND (min_version = 0 or min_version <= %u) AND (max_version = 0 or max_version >= %u)%s",
  3455. syntaxSelect.c_str(), race_id, deity, choice, packetVersion, packetVersion, whereRuleFlag.c_str());
  3456. else
  3457. result = query.RunQuery2(Q_SELECT, "%s starting_zones sz, zones z WHERE sz.zone_id = z.id AND class_id IN (%i, %i, %i, 255) AND race_id IN (%i, 255) AND deity IN (%i, 255) AND choice IN (%i, 255) AND (min_version = 0 or min_version <= %u) AND (max_version = 0 or max_version >= %u)%s",
  3458. syntaxSelect.c_str(), classes.GetBaseClass(class_id), classes.GetSecondaryBaseClass(class_id), class_id, race_id, deity, choice, packetVersion, packetVersion, whereRuleFlag.c_str());
  3459. if(result && mysql_num_rows(result) > 0)
  3460. {
  3461. string zone_name = "ERROR";
  3462. MYSQL_ROW row;
  3463. bool zoneSet = false;
  3464. float safeX = 0.0f, safeY = 0.0f, safeZ = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f, heading = 0.0f;
  3465. int8 is_instance = 0;
  3466. int32 zone_id = 0;
  3467. int32 instance_id = 0;
  3468. int8 starting_city = 0;
  3469. sint8 start_alignment = 0;
  3470. if( result && (row = mysql_fetch_row(result)) )
  3471. {
  3472. int8 i=0;
  3473. zoneSet = true;
  3474. zone_name = string(row[i++]);
  3475. zone_id = atoul(row[i++]);
  3476. safeX = atof(row[i++]);
  3477. safeY = atof(row[i++]);
  3478. safeZ = atof(row[i++]);
  3479. x = atof(row[i++]);
  3480. y = atof(row[i++]);
  3481. z = atof(row[i++]);
  3482. if ( x == -999999.0f && y == -999999.0f && z == -999999.0f)
  3483. {
  3484. x = safeX;
  3485. y = safeY;
  3486. z = safeZ;
  3487. }
  3488. heading = atof(row[i++]);
  3489. if(heading == -999999.0f )
  3490. heading = 0.0f;
  3491. is_instance = atoul(row[i++]);
  3492. starting_city = atoul(row[i++]);
  3493. start_alignment = atoi(row[i++]);
  3494. }
  3495. // all EQ2 clients hard-code these restrictions in some form (later clients added Neutral instead of good/evil only)
  3496. // start with good races only
  3497. if(enforceRacialAlignment && (race_id == DWARF || race_id == FROGLOK || race_id == HALFLING ||
  3498. race_id == HIGH_ELF || race_id == WOOD_ELF || race_id == FAE)) {
  3499. start_alignment = ALIGNMENT_GOOD; // always should good
  3500. }
  3501. // we drop into this case because it is a special check compared to the straigt good/evil checks on top and below
  3502. else if(start_alignment == ALIGNMENT_EVIL && deity == ALIGNMENT_GOOD) {
  3503. if (enforceRacialAlignment && (race_id == AERAKYN || race_id == RATONGA || race_id == BARBARIAN || race_id == ERUDITE ||
  3504. race_id == HUMAN || race_id == VAMPIRE || race_id == HALF_ELF || race_id == GNOME || race_id == KERRA)) {
  3505. if(zone_id == 21 || zone_id == 25 || zone_id == 26 || zone_id == 27) { // far journey zones
  3506. start_alignment = deity; // inheriting the clients alignment of 'good' due to the fact we start in far journey and it is a shared instance right now (farjourneyfreeport)
  3507. }
  3508. // otherwise we use the starting zone alignment since these particular races can be evil which will be set in start_alignment of 0 within starting_zones (neriak, freeport, etc.)
  3509. }
  3510. else if(enforceRacialAlignment) {
  3511. LogWrite(WORLD__WARNING, 0, "World", "Starting alignment seems unexpected, zone id %u, race id %u, deity(alignment) choice: %u, start alignment: %i", zone_id, race_id, deity, start_alignment);
  3512. }
  3513. }
  3514. // anyone else is simply evil with the enforcement check
  3515. else if(enforceRacialAlignment && (race_id != DWARF && race_id != FROGLOK && race_id != HALFLING &&
  3516. race_id != HIGH_ELF && race_id != WOOD_ELF && race_id != FAE)) {
  3517. start_alignment = ALIGNMENT_EVIL;
  3518. }
  3519. if(is_instance) // should only be true if we get a result
  3520. {
  3521. // this will force a pre-load
  3522. ZoneServer* instance_zone = zone_list.GetByInstanceID(0, zone_id);
  3523. if (instance_zone) {
  3524. instance_id = CreateNewInstance(zone_id);
  3525. AddCharacterInstance(char_id, instance_id, string(instance_zone->GetZoneName()), instance_zone->GetInstanceType(), Timer::GetUnixTimeStamp(), 0, instance_zone->GetDefaultLockoutTime(), instance_zone->GetDefaultReenterTime());
  3526. // make sure we inherit the instance id setup in the AddCharacterInstance
  3527. instance_zone->SetupInstance(instance_id);
  3528. }
  3529. }
  3530. query2.RunQuery2(Q_UPDATE, "UPDATE characters SET current_zone_id = %u, x = %f, y = %f, z = %f, heading = %f, starting_city = %i, instance_id = %u, alignment = %u WHERE id = %u",
  3531. zone_id, x, y, z, heading, starting_city, instance_id, start_alignment, char_id);
  3532. if(query2.GetErrorNumber() && query2.GetError() && query2.GetErrorNumber() < 0xFFFFFFFF){
  3533. LogWrite(PLAYER__ERROR, 0, "Player", "Error in UpdateStartingZone custom starting_zones, query: '%s': %s", query2.GetQuery(), query2.GetError());
  3534. return;
  3535. }
  3536. if(query2.GetAffectedRows() > 0)
  3537. {
  3538. LogWrite(PLAYER__INFO, 0, "Player", "Setting New Character Starting Zone to '%s' with location %f, %f, %f and heading %f FROM starting_zones table.", zone_name.c_str(), x, y, z, heading);
  3539. return;
  3540. }
  3541. }
  3542. else
  3543. {
  3544. // there was no matching starting_zone value, so use default 'choice' starting city
  3545. query2.RunQuery2(Q_UPDATE, "UPDATE characters c, zones z SET c.current_zone_id = z.id, c.x = z.safe_x, c.y = z.safe_y, c.z = z.safe_z, c.starting_city = %i WHERE z.start_zone = %i and c.id = %u",
  3546. choice, choice, char_id);
  3547. if(query2.GetErrorNumber() && query2.GetError() && query2.GetErrorNumber() < 0xFFFFFFFF)
  3548. {
  3549. LogWrite(PLAYER__ERROR, 0, "Player", "Error in UpdateStartingZone player choice, query: '%s': %s", query2.GetQuery(), query2.GetError());
  3550. return;
  3551. }
  3552. if(query2.GetAffectedRows() > 0)
  3553. {
  3554. LogWrite(PLAYER__DEBUG, 0, "Player", "Setting New Character Starting Zone to '%s' FROM player choice.", GetStartingZoneName(choice).c_str());
  3555. return;
  3556. }
  3557. }
  3558. // if we are here, it's a bad thing. zone tables have no start_city values to match client 'choice', so throw the player into zone according to R_World::DefaultStartingZoneID rule.
  3559. // shout a few warnings so the admin fixes this asap!
  3560. int16 default_zone_id = rule_manager.GetGlobalRule(R_World, DefaultStartingZoneID)->GetInt16();
  3561. LogWrite(WORLD__WARNING, 0, "World", "No Starting City defined for player choice: %i! BAD! BAD! BAD! Defaulting player to zone %i.", choice, default_zone_id);
  3562. query.RunQuery2(Q_UPDATE, "UPDATE characters c, zones z SET c.current_zone_id = z.id, c.x = z.safe_x, c.y = z.safe_y, c.z = z.safe_z, c.heading = z.safe_heading, c.starting_city = 1 WHERE z.id = %i and c.id = %u", default_zone_id, char_id);
  3563. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF)
  3564. {
  3565. LogWrite(PLAYER__ERROR, 0, "Player", "Error in UpdateStartingZone default zone %i, query: '%s': %s", default_zone_id, query.GetQuery(), query.GetError());
  3566. return;
  3567. }
  3568. if (query.GetAffectedRows() > 0) {
  3569. string zone_name = GetZoneName(1);
  3570. if(zone_name.length() > 0)
  3571. LogWrite(PLAYER__DEBUG, 0, "Player", "Setting New Character Starting Zone to '%s' due to no valid options!", zone_name.c_str());
  3572. else
  3573. LogWrite(PLAYER__DEBUG, 0, "Player", "Unable to set New Character Starting Zone due to no valid options!");
  3574. }
  3575. return;
  3576. }
  3577. void WorldDatabase::UpdateStartingItems(int32 char_id, int8 class_id, int8 race_id, bool base_class){
  3578. LogWrite(PLAYER__DEBUG, 0, "Player", "Adding default items for race: %i, class: %i for char_id: %u", race_id, class_id, char_id);
  3579. Query query;
  3580. Query query2;
  3581. vector<Item*> items;
  3582. vector<Item*> bags;
  3583. map<int32, int8> total_slots;
  3584. map<int32, int8> slots_left;
  3585. map<int8, bool> equip_slots;
  3586. map<Item*, StartingItem> item_list;
  3587. int32 item_id = 0;
  3588. Item* item = 0;
  3589. StartingItem* starting_item = 0;
  3590. //first get a list of the starting items for the character
  3591. MYSQL_RES* result = 0;
  3592. /*if(!base_class)
  3593. result = query2.RunQuery2(Q_SELECT, "SELECT `type`, item_id, creator, condition_, attuned, count FROM starting_items where (class_id=%i and race_id=%i) or (class_id=%i and race_id=255) or (class_id=255 and race_id=%i) or (class_id=255 and race_id=255) ORDER BY id", class_id, race_id, class_id, race_id);
  3594. else
  3595. result = query2.RunQuery2(Q_SELECT, "SELECT `type`, item_id, creator, condition_, attuned, count FROM starting_items where (class_id=%i and race_id=%i) or (class_id=%i and race_id=255) ORDER BY id", class_id, race_id, class_id);*/
  3596. result = query2.RunQuery2(Q_SELECT, "SELECT `type`, item_id, creator, condition_, attuned, count FROM starting_items WHERE class_id IN (%i, %i, %i, 255) AND race_id IN (%i, 255) ORDER BY id", classes.GetBaseClass(class_id), classes.GetSecondaryBaseClass(class_id), class_id, race_id);
  3597. if(result && mysql_num_rows(result) > 0){
  3598. MYSQL_ROW row;
  3599. while(result && (row = mysql_fetch_row(result))){
  3600. item_id = atoul(row[1]);
  3601. item = master_item_list.GetItem(item_id);
  3602. if(item){
  3603. starting_item = &(item_list[item]);
  3604. starting_item->type = (row[0]) ? string(row[0]) : "";
  3605. starting_item->item_id = atoul(row[1]);
  3606. starting_item->creator = (row[2]) ? string(row[2]) : "";
  3607. starting_item->condition = atoi(row[3]);
  3608. starting_item->attuned = atoi(row[4]);
  3609. starting_item->count = atoi(row[5]);
  3610. item = master_item_list.GetItem(starting_item->item_id);
  3611. if(item){
  3612. if(bags.size() < NUM_INV_SLOTS && item->IsBag() && item->details.num_slots > 0)
  3613. bags.push_back(item);
  3614. else
  3615. items.push_back(item);
  3616. }
  3617. }
  3618. }
  3619. }
  3620. slots_left[0] = NUM_INV_SLOTS;
  3621. //next create the bags in the inventory
  3622. for(int8 i=0;i<bags.size();i++){
  3623. item = bags[i];
  3624. query.RunQuery2(Q_INSERT, "insert into character_items (char_id, type, slot, item_id, creator, condition_, attuned, bag_id, count) values(%u, '%s', %i, %u, '%s', %i, %i, %u, %i)",
  3625. char_id, item_list[item].type.c_str(), i, item_list[item].item_id, getSafeEscapeString(item_list[item].creator.c_str()).c_str(), item_list[item].condition, item_list[item].attuned, 0, item_list[item].count);
  3626. slots_left[query.GetLastInsertedID()] = item->details.num_slots;
  3627. total_slots[query.GetLastInsertedID()] = item->details.num_slots;
  3628. slots_left[0]--;
  3629. }
  3630. map<int32, int8>::iterator itr;
  3631. int32 inv_slot = 0;
  3632. int8 slot = 0;
  3633. //finally process the rest of the items, placing them in the first available slot
  3634. for(int32 x=0;x<items.size();x++){
  3635. item = items[x];
  3636. if(item_list[item].type.find("NOT") < 0xFFFFFFFF){ // NOT-EQUIPPED Items
  3637. for(itr = slots_left.begin(); itr != slots_left.end(); itr++){
  3638. if(itr->second > 0){
  3639. if(itr->first == 0 && slots_left.size() > 1) //we want items to go into bags first, then inventory after bags are full
  3640. continue;
  3641. inv_slot = itr->first;
  3642. slot = total_slots[itr->first] - itr->second;
  3643. itr->second--;
  3644. if(itr->second == 0)
  3645. slots_left.erase(itr);
  3646. break;
  3647. }
  3648. }
  3649. query.RunQuery2(Q_INSERT, "insert into character_items (char_id, type, slot, item_id, creator, condition_, attuned, bag_id, count) values(%u, '%s', %i, %u, '%s', %i, %i, %u, %i)",
  3650. char_id, item_list[item].type.c_str(), slot, item_list[item].item_id, getSafeEscapeString(item_list[item].creator.c_str()).c_str(), item_list[item].condition, item_list[item].attuned, inv_slot, item_list[item].count);
  3651. }
  3652. else{ //EQUIPPED Items
  3653. for(int8 i=0;i<item->slot_data.size();i++){
  3654. if(equip_slots.count(item->slot_data[i]) == 0){
  3655. equip_slots[item->slot_data[i]] = true;
  3656. query.RunQuery2(Q_INSERT, "insert into character_items (char_id, type, slot, item_id, creator, condition_, attuned, bag_id, count) values(%u, '%s', %i, %u, '%s', %i, %i, %u, %i)",
  3657. char_id, item_list[item].type.c_str(), item->slot_data[i], item_list[item].item_id, getSafeEscapeString(item_list[item].creator.c_str()).c_str(), item_list[item].condition, item_list[item].attuned, 0, item_list[item].count);
  3658. break;
  3659. }
  3660. }
  3661. }
  3662. }
  3663. }
  3664. void WorldDatabase::UpdateStartingSkills(int32 char_id, int8 class_id, int8 race_id)
  3665. {
  3666. Query query;
  3667. LogWrite(PLAYER__DEBUG, 0, "Player", "Adding default skills for race: %i, class: %i for char_id: %u", race_id, class_id, char_id);
  3668. query.RunQuery2(Q_INSERT, "INSERT IGNORE INTO character_skills (char_id, skill_id, current_val, max_val) SELECT %u, skill_id, current_val, max_val FROM starting_skills WHERE class_id IN (%i, %i, %i, 255) AND race_id IN (%i, 255)",
  3669. char_id, classes.GetBaseClass(class_id), classes.GetSecondaryBaseClass(class_id), class_id, race_id);
  3670. }
  3671. void WorldDatabase::UpdateStartingSpells(int32 char_id, int8 class_id, int8 race_id){
  3672. Query query;
  3673. LogWrite(PLAYER__DEBUG, 0, "Player", "Adding default spells for race: %i, class: %i for char_id: %u", race_id, class_id, char_id);
  3674. query.RunQuery2(Q_INSERT, "INSERT IGNORE INTO character_spells (char_id, spell_id, tier, knowledge_slot) SELECT %u, spell_id, tier, knowledge_slot FROM starting_spells WHERE class_id IN (%i, %i, %i, 255) AND race_id IN (%i, 255)",
  3675. char_id, classes.GetBaseClass(class_id), classes.GetSecondaryBaseClass(class_id), class_id, race_id);
  3676. }
  3677. void WorldDatabase::UpdateStartingSkillbar(int32 char_id, int8 class_id, int8 race_id){
  3678. Query query;
  3679. LogWrite(PLAYER__DEBUG, 0, "Player", "Adding default skillbar for race: %i, class: %i for char_id: %u", race_id, class_id, char_id);
  3680. query.RunQuery2(Q_INSERT, "INSERT IGNORE INTO character_skillbar (char_id, type, hotbar, spell_id, slot, text_val) SELECT %u, type, hotbar, spell_id, slot, text_val FROM starting_skillbar WHERE class_id IN (%i, %i, %i, 255) AND race_id IN (%i, 255)",
  3681. char_id, classes.GetBaseClass(class_id), classes.GetSecondaryBaseClass(class_id), class_id, race_id);
  3682. }
  3683. void WorldDatabase::UpdateStartingTitles(int32 char_id, int8 class_id, int8 race_id, int8 gender_id) {
  3684. Query query;
  3685. LogWrite(PLAYER__DEBUG, 0, "Player", "Adding default titles for race: %i, class: %i, gender: %i for char_id: %u", race_id, class_id, gender_id, char_id);
  3686. query.RunQuery2(Q_INSERT, "INSERT IGNORE INTO character_titles (char_id, title_id) SELECT %u, title_id FROM starting_titles WHERE class_id IN (%i, %i, %i, 255) AND race_id IN (%i, 255) and gender_id IN (%i, 255)",
  3687. char_id, classes.GetBaseClass(class_id), classes.GetSecondaryBaseClass(class_id), class_id, race_id, gender_id);
  3688. }
  3689. string WorldDatabase::GetZoneDescription(int32 id){
  3690. Query query;
  3691. string ret = "";
  3692. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT description FROM zones where id = %u", id);
  3693. if(result && mysql_num_rows(result) > 0){
  3694. MYSQL_ROW row;
  3695. row = mysql_fetch_row(result);
  3696. ret = string(row[0]);
  3697. }
  3698. return ret;
  3699. }
  3700. string WorldDatabase::GetZoneName(int32 id){
  3701. if (zone_names.count(id) > 0){
  3702. return zone_names[id];
  3703. }
  3704. Query query;
  3705. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `name` FROM zones where `id` = %u", id);
  3706. if(result && mysql_num_rows(result) > 0){
  3707. MYSQL_ROW row;
  3708. row = mysql_fetch_row(result);
  3709. zone_names[id] = row[0];
  3710. return zone_names[id];
  3711. }
  3712. return string("");
  3713. }
  3714. bool WorldDatabase::VerifyZone(const char* name){
  3715. Query query;
  3716. char* escaped = getEscapeString(name);
  3717. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT name FROM zones where name='%s'",escaped);
  3718. safe_delete_array(escaped);
  3719. if(result && mysql_num_rows(result) > 0)
  3720. return true;
  3721. else
  3722. return false;
  3723. }
  3724. int8 WorldDatabase::GetInstanceTypeByZoneID(int32 zoneID)
  3725. {
  3726. std::map<int32, int8>::iterator itr = zone_instance_types.find(zoneID);
  3727. if(itr != zone_instance_types.end())
  3728. return itr->second;
  3729. DatabaseResult result;
  3730. int8 ret = 0;
  3731. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Getting instances for zone_id %u", zoneID);
  3732. if( !database_new.Select(&result, "SELECT instance_type+0 FROM zones WHERE id = %u", zoneID) )
  3733. {
  3734. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in GetInstanceTypeByZoneID() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  3735. return ret;
  3736. }
  3737. if( result.GetNumRows() > 0 )
  3738. {
  3739. result.Next();
  3740. ret = (result.GetInt8Str("instance_type+0") == 0) ? 0 : result.GetInt8Str("instance_type+0") - 1;
  3741. zone_instance_types.insert(make_pair(zoneID, ret));
  3742. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Found instance type %i for zone_id %u", ret, zoneID);
  3743. }
  3744. else
  3745. LogWrite(INSTANCE__DEBUG, 0, "Instance", "No instances found for zone_id %u", zoneID);
  3746. return ret;
  3747. }
  3748. void WorldDatabase::Save(Client* client){
  3749. Query query;
  3750. Player* player = client->GetPlayer();
  3751. if(!player->CheckPlayerInfo())
  3752. return;
  3753. int32 instance_id = 0;
  3754. if ( client->GetCurrentZone ( ) != NULL )
  3755. instance_id = client->GetCurrentZone()->GetInstanceID();
  3756. int32 zone_id = 0;
  3757. if(client->GetCurrentZone())
  3758. zone_id = client->GetCurrentZone()->GetZoneID();
  3759. query.AddQueryAsync(client->GetCharacterID(), this, Q_UPDATE, "update characters set current_zone_id=%u, x=%f, y=%f, z=%f, heading=%f, level=%i,instance_id=%i,last_saved=%i, `class`=%i, `tradeskill_level`=%i, `tradeskill_class`=%i, `group_id`=%u, deity = %u, alignment = %u where id = %u", zone_id, player->GetX(), player->GetY(), player->GetZ(), player->GetHeading(), player->GetLevel(), instance_id, client->GetLastSavedTimeStamp(), client->GetPlayer()->GetAdventureClass(), client->GetPlayer()->GetTSLevel(), client->GetPlayer()->GetTradeskillClass(), client->GetPlayer()->GetGroupMemberInfo() ? client->GetPlayer()->GetGroupMemberInfo()->group_id : client->GetRejoinGroupID(), client->GetPlayer()->GetDeity(), client->GetPlayer()->GetInfoStruct()->get_alignment(), client->GetCharacterID());
  3760. query.AddQueryAsync(client->GetCharacterID(), this, Q_UPDATE, "update character_details set hp=%u, power=%u, str=%i, sta=%i, agi=%i, wis=%i, intel=%i, heat=%i, cold=%i, magic=%i, mental=%i, divine=%i, disease=%i, poison=%i, coin_copper=%u, coin_silver=%u, coin_gold=%u, coin_plat=%u, max_hp = %u, max_power=%u, xp = %u, xp_needed = %u, xp_debt = %f, xp_vitality = %f, tradeskill_xp = %u, tradeskill_xp_needed = %u, tradeskill_xp_vitality = %f, bank_copper = %u, bank_silver = %u, bank_gold = %u, bank_plat = %u, status_points = %u, bind_zone_id=%u, bind_x = %f, bind_y = %f, bind_z = %f, bind_heading = %f, house_zone_id=%u, combat_voice = %i, emote_voice = %i, biography='%s', flags=%u, flags2=%u, last_name='%s', assigned_aa = %i, unassigned_aa = %i, tradeskill_aa = %i, unassigned_tradeskill_aa = %i, prestige_aa = %i, unassigned_prestige_aa = %i, tradeskill_prestige_aa = %i, unassigned_tradeskill_prestige_aa = %i, pet_name = '%s' where char_id = %u",
  3761. player->GetHP(), player->GetPower(), player->GetStrBase(), player->GetStaBase(), player->GetAgiBase(), player->GetWisBase(), player->GetIntBase(), player->GetHeatResistanceBase(), player->GetColdResistanceBase(), player->GetMagicResistanceBase(),
  3762. player->GetMentalResistanceBase(), player->GetDivineResistanceBase(), player->GetDiseaseResistanceBase(), player->GetPoisonResistanceBase(), player->GetCoinsCopper(), player->GetCoinsSilver(), player->GetCoinsGold(), player->GetCoinsPlat(), player->GetTotalHPBase(), player->GetTotalPowerBase(), player->GetXP(), player->GetNeededXP(), player->GetXPDebt(), player->GetXPVitality(), player->GetTSXP(), player->GetNeededTSXP(), player->GetTSXPVitality(), player->GetBankCoinsCopper(),
  3763. player->GetBankCoinsSilver(), player->GetBankCoinsGold(), player->GetBankCoinsPlat(), player->GetStatusPoints(), client->GetPlayer()->GetPlayerInfo()->GetBindZoneID(), client->GetPlayer()->GetPlayerInfo()->GetBindZoneX(), client->GetPlayer()->GetPlayerInfo()->GetBindZoneY(), client->GetPlayer()->GetPlayerInfo()->GetBindZoneZ(), client->GetPlayer()->GetPlayerInfo()->GetBindZoneHeading(), client->GetPlayer()->GetPlayerInfo()->GetHouseZoneID(),
  3764. client->GetPlayer()->GetCombatVoice(), client->GetPlayer()->GetEmoteVoice(), getSafeEscapeString(client->GetPlayer()->GetBiography().c_str()).c_str(), player->GetFlags(), player->GetFlags2(), client->GetPlayer()->GetLastName(),
  3765. client->GetPlayer()->GetAssignedAA(), client->GetPlayer()->GetUnassignedAA(), client->GetPlayer()->GetTradeskillAA(), client->GetPlayer()->GetUnassignedTradeskillAA(), client->GetPlayer()->GetPrestigeAA(),
  3766. client->GetPlayer()->GetUnassignedPretigeAA(), client->GetPlayer()->GetTradeskillPrestigeAA(), client->GetPlayer()->GetUnassignedTradeskillPrestigeAA(), client->GetPlayer()->GetInfoStruct()->get_pet_name().c_str(), client->GetCharacterID());
  3767. map<string, int8>::iterator itr;
  3768. map<string, int8>* friends = player->GetFriends();
  3769. if(friends && friends->size() > 0){
  3770. for(itr = friends->begin(); itr != friends->end(); itr++){
  3771. if(itr->second == 1){
  3772. query.AddQueryAsync(client->GetCharacterID(), this, Q_INSERT, "insert ignore into character_social (char_id, name, type) values(%u, '%s', 'FRIEND')", client->GetCharacterID(), getSafeEscapeString(itr->first.c_str()).c_str());
  3773. itr->second = 0;
  3774. }
  3775. else if(itr->second == 2){
  3776. query.AddQueryAsync(client->GetCharacterID(), this, Q_DELETE, "delete FROM character_social where char_id = %u and name = '%s'", client->GetCharacterID(), getSafeEscapeString(itr->first.c_str()).c_str());
  3777. itr->second = 3;
  3778. }
  3779. }
  3780. }
  3781. map<string, int8>* ignored = player->GetIgnoredPlayers();
  3782. if(ignored && ignored->size() > 0){
  3783. for(itr = ignored->begin(); itr != ignored->end(); itr++){
  3784. if(itr->second == 1){
  3785. query.AddQueryAsync(client->GetCharacterID(), this, Q_INSERT, "insert ignore into character_social (char_id, name, type) values(%u, '%s', 'IGNORE')", client->GetCharacterID(), getSafeEscapeString(itr->first.c_str()).c_str());
  3786. itr->second = 0;
  3787. }
  3788. else if(itr->second == 2){
  3789. query.AddQueryAsync(client->GetCharacterID(), this, Q_DELETE, "delete FROM character_social where char_id = %u and name = '%s'", client->GetCharacterID(), getSafeEscapeString(itr->first.c_str()).c_str());
  3790. itr->second = 3;
  3791. }
  3792. }
  3793. }
  3794. SavePlayerFactions(client);
  3795. SaveCharacterQuests(client);
  3796. SaveCharacterSkills(client);
  3797. SavePlayerSpells(client);
  3798. SavePlayerMail(client);
  3799. SavePlayerCollections(client);
  3800. client->SaveQuestRewardData();
  3801. LogWrite(PLAYER__INFO, 3, "Player", "Player '%s' (%u) data saved.", player->GetName(), player->GetCharacterID());
  3802. }
  3803. void WorldDatabase::LoadEntityCommands(ZoneServer* zone) {
  3804. int32 total = 0;
  3805. int32 id = 0;
  3806. EntityCommand* command = 0;
  3807. DatabaseResult result;
  3808. if (!database_new.Select(&result, "SELECT `command_list_id`, `command_text`, `distance`, `command`, `error_text`, `cast_time`, `spell_visual` FROM `entity_commands` ORDER BY `id`")) {
  3809. LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error %u: %s", database_new.GetError(), database_new.GetErrorMsg());
  3810. return;
  3811. }
  3812. while (result.Next()) {
  3813. command = new EntityCommand;
  3814. id = result.GetInt32(0);
  3815. command->name = result.GetString(1);
  3816. command->distance = result.GetFloat(2);
  3817. command->command = result.GetString(3);
  3818. command->error_text = result.GetString(4);
  3819. command->cast_time = result.GetInt16(5);
  3820. command->spell_visual = result.GetInt32(6);
  3821. command->default_allow_list = true;
  3822. zone->SetEntityCommandList(id, command);
  3823. LogWrite(COMMAND__DEBUG, 5, "Command", "---Loading Command: '%s' (%s)", command->name.c_str(), command->command.c_str());
  3824. total++;
  3825. }
  3826. LogWrite(COMMAND__DEBUG, 0, "Command", "--Loaded %i entity command(s)", total);
  3827. }
  3828. void WorldDatabase::LoadFactionAlliances()
  3829. {
  3830. LogWrite(FACTION__DEBUG, 1, "Faction", "-Loading faction alliances...");
  3831. int32 total = 0;
  3832. int32 fTotal = 0;
  3833. int32 hTotal = 0;
  3834. Query query;
  3835. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT faction_id, friend_faction, hostile_faction FROM faction_alliances");
  3836. if(result && mysql_num_rows(result) > 0)
  3837. {
  3838. MYSQL_ROW row;
  3839. int32 faction_id = 0;
  3840. int32 friendly_id = 0;
  3841. int32 hostile_id = 0;
  3842. while(result && (row = mysql_fetch_row(result)))
  3843. {
  3844. faction_id = atoul(row[0]);
  3845. friendly_id = atoul(row[1]);
  3846. hostile_id = atoul(row[2]);
  3847. if(friendly_id > 0)
  3848. {
  3849. master_faction_list.AddFriendlyFaction(faction_id, friendly_id);
  3850. fTotal++;
  3851. LogWrite(FACTION__DEBUG, 5, "Faction", "---Faction %i is friendly towards %i", faction_id, friendly_id);
  3852. }
  3853. if(hostile_id > 0)
  3854. {
  3855. master_faction_list.AddHostileFaction(faction_id, hostile_id);
  3856. hTotal++;
  3857. LogWrite(FACTION__DEBUG, 5, "Faction", "---Faction %i is hostile towards %i", faction_id, hostile_id);
  3858. }
  3859. total++;
  3860. }
  3861. }
  3862. LogWrite(FACTION__DEBUG, 3, "Faction", "--Loaded %u Alliances: %i friendly, %i hostile", total, fTotal, hTotal);
  3863. }
  3864. bool WorldDatabase::UpdateSpawnScriptData(int32 spawn_id, int32 spawn_location_id, int32 spawnentry_id, const char* name){
  3865. bool ret = false;
  3866. if((spawn_id > 0 || spawn_location_id > 0 || spawnentry_id > 0) && name){
  3867. Query query, query2;
  3868. int32 row_id = 0;
  3869. if(spawn_id > 0){
  3870. query.RunQuery2(Q_DELETE, "DELETE FROM spawn_scripts where spawn_id=%u", spawn_id);
  3871. query2.RunQuery2(Q_INSERT, "INSERT into spawn_scripts (spawn_id, lua_script) values(%u, '%s')", spawn_id, getSafeEscapeString(name).c_str());
  3872. if(query2.GetErrorNumber() && query2.GetError() && query2.GetErrorNumber() < 0xFFFFFFFF)
  3873. LogWrite(LUA__ERROR, 0, "LUA", "Error in UpdateSpawnScriptData, Query: %s, Error: %s", query2.GetQuery(), query2.GetError());
  3874. else{
  3875. row_id = query2.GetLastInsertedID();
  3876. if(row_id > 0)
  3877. world.AddSpawnScript(row_id, name);
  3878. ret = true;
  3879. }
  3880. }
  3881. else if(spawn_location_id > 0){
  3882. query.RunQuery2(Q_DELETE, "DELETE FROM spawn_scripts where spawn_location_id=%u", spawn_location_id);
  3883. query2.RunQuery2(Q_INSERT, "INSERT into spawn_scripts (spawn_location_id, lua_script) values(%u, '%s')", spawn_location_id, getSafeEscapeString(name).c_str());
  3884. if(query2.GetErrorNumber() && query2.GetError() && query2.GetErrorNumber() < 0xFFFFFFFF)
  3885. LogWrite(LUA__ERROR, 0, "LUA", "Error in UpdateSpawnScriptData, Query: %s, Error: %s", query2.GetQuery(), query2.GetError());
  3886. else{
  3887. row_id = query2.GetLastInsertedID();
  3888. if(row_id > 0)
  3889. world.AddSpawnLocationScript(row_id, name);
  3890. ret = true;
  3891. }
  3892. }
  3893. else if(spawnentry_id > 0){
  3894. query.RunQuery2(Q_DELETE, "DELETE FROM spawn_scripts where spawnentry_id=%u", spawnentry_id);
  3895. query2.RunQuery2(Q_INSERT, "INSERT into spawn_scripts (spawnentry_id, lua_script) values(%u, '%s')", spawnentry_id, getSafeEscapeString(name).c_str());
  3896. if(query2.GetErrorNumber() && query2.GetError() && query2.GetErrorNumber() < 0xFFFFFFFF)
  3897. LogWrite(LUA__ERROR, 0, "LUA", "Error in UpdateSpawnScriptData, Query: %s, Error: %s", query2.GetQuery(), query2.GetError());
  3898. else{
  3899. row_id = query2.GetLastInsertedID();
  3900. if(row_id > 0)
  3901. world.AddSpawnEntryScript(row_id, name);
  3902. ret = true;
  3903. }
  3904. }
  3905. }
  3906. return ret;
  3907. }
  3908. void WorldDatabase::LoadSpawnScriptData() {
  3909. int32 total = 0;
  3910. Query query;
  3911. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT spawn_id, spawnentry_id, spawn_location_id, lua_script FROM spawn_scripts");
  3912. if(result && mysql_num_rows(result) > 0)
  3913. {
  3914. MYSQL_ROW row;
  3915. int32 spawn_id = 0;
  3916. int32 spawnentry_id = 0;
  3917. int32 spawn_location_id = 0;
  3918. while(result && (row = mysql_fetch_row(result)))
  3919. {
  3920. spawn_id = atoul(row[0]);
  3921. spawnentry_id = atoul(row[1]);
  3922. spawn_location_id = atoul(row[2]);
  3923. string spawn_script = string(row[3]);
  3924. if(spawnentry_id > 0)
  3925. {
  3926. world.AddSpawnEntryScript(spawnentry_id, row[3]);
  3927. total++;
  3928. }
  3929. else if(spawn_location_id > 0)
  3930. {
  3931. world.AddSpawnLocationScript(spawn_location_id, row[3]);
  3932. total++;
  3933. }
  3934. else if(spawn_id > 0)
  3935. {
  3936. world.AddSpawnScript(spawn_id, row[3]);
  3937. total++;
  3938. }
  3939. else {
  3940. if(row[3])
  3941. LogWrite(LUA__ERROR, 0, "LUA", "Invalid Entry in spawn_scripts table for lua_script '%s' (spawn_id, spawnentry_id and spawn_location_id are all 0)", row[3]);
  3942. else
  3943. LogWrite(LUA__ERROR, 0, "LUA", "Invalid Entry in spawn_scripts table.");
  3944. }
  3945. spawn_id = 0;
  3946. spawnentry_id = 0;
  3947. spawn_location_id = 0;
  3948. }
  3949. }
  3950. LogWrite(LUA__DEBUG, 0, "LUA", "\tLoaded %u SpawnScript%s", total, total == 1 ? "" : "s");
  3951. }
  3952. void WorldDatabase::LoadZoneScriptData() {
  3953. Query query;
  3954. int32 total = 0;
  3955. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `id`, `lua_script` FROM `zones`");
  3956. if (result && mysql_num_rows(result) > 0) {
  3957. MYSQL_ROW row;
  3958. while(result && (row = mysql_fetch_row(result))) {
  3959. if (row[1]) {
  3960. int32 zone_id = atoul(row[0]);
  3961. string zone_script = string(row[1]);
  3962. if (zone_id > 0 && zone_script.length() > 0) {
  3963. LogWrite(LUA__DEBUG, 5, "LUA", "ZoneScript: %s loaded.", zone_script.c_str());
  3964. world.AddZoneScript(zone_id, zone_script.c_str());
  3965. total++;
  3966. }
  3967. else if (zone_id > 0) {
  3968. string tmpScript;
  3969. tmpScript.append("ZoneScripts/");
  3970. string zonename = GetZoneName(zone_id);
  3971. tmpScript.append(zonename);
  3972. tmpScript.append(".lua");
  3973. struct stat buffer;
  3974. bool fileExists = (stat(tmpScript.c_str(), &buffer) == 0);
  3975. if (fileExists)
  3976. {
  3977. LogWrite(LUA__INFO, 0, "LUA", "No zonescript file described in the database, overriding with ZoneScript %s for Zone ID %u", (char*)tmpScript.c_str(), zone_id);
  3978. world.AddZoneScript(zone_id, tmpScript.c_str());
  3979. }
  3980. }
  3981. }
  3982. }
  3983. }
  3984. LogWrite(LUA__DEBUG, 0, "LUA", "\tLoaded %u ZoneScript%s", total, total == 1 ? "" : "s");
  3985. }
  3986. int32 WorldDatabase::LoadSpellScriptData() {
  3987. Query query;
  3988. MYSQL_ROW row;
  3989. int32 count;
  3990. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `lua_script` FROM `spells`"); // WHERE is_active = 1
  3991. while (result && (row = mysql_fetch_row(result))) {
  3992. if (row[0] && strlen(row[0]) > 0) {
  3993. if (lua_interface->LoadLuaSpell(row[0]))
  3994. LogWrite(SPELL__DEBUG, 5, "Spells", "SpellScript: %s loaded.", row[0]);
  3995. }
  3996. }
  3997. count = mysql_num_rows(result);
  3998. LogWrite(SPELL__DEBUG, 0, "Spells", "\tLoaded %i SpellScript%s", count, count == 1 ? "" : "s");
  3999. return count;
  4000. }
  4001. void WorldDatabase::LoadFactionList() {
  4002. int32 total = 0;
  4003. Query query;
  4004. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, name, type, description, default_level, negative_change, positive_change FROM factions");
  4005. if(result && mysql_num_rows(result) > 0) {
  4006. MYSQL_ROW row;
  4007. Faction* faction = 0;
  4008. while(result && (row = mysql_fetch_row(result))){
  4009. faction = new Faction;
  4010. faction->id = atoul(row[0]);
  4011. faction->name = string(row[1]);
  4012. faction->type = string(row[2]);
  4013. faction->description = string(row[3]);
  4014. faction->default_value = atoi(row[4]);
  4015. faction->negative_change = atoi(row[5]);
  4016. faction->positive_change = atoi(row[6]);
  4017. master_faction_list.AddFaction(faction);
  4018. total++;
  4019. LogWrite(FACTION__DEBUG, 5, "Faction", "---Loading Faction '%s' (%u)", faction->name.c_str(), faction->id);
  4020. }
  4021. }
  4022. LogWrite(FACTION__DEBUG, 3, "Faction", "--Loaded %u Faction%s", total, total == 1 ? "" : "s");
  4023. LoadFactionAlliances();
  4024. }
  4025. void WorldDatabase::SavePlayerFactions(Client* client){
  4026. LogWrite(PLAYER__DEBUG, 3, "Player", "Saving Player Factions...");
  4027. Query query;
  4028. map<int32, sint32>* factions = client->GetPlayer()->GetFactions()->GetFactionValues();
  4029. map<int32, sint32>::iterator itr;
  4030. for(itr = factions->begin(); itr != factions->end(); itr++)
  4031. query.AddQueryAsync(client->GetCharacterID(), this,Q_INSERT, "insert into character_factions (char_id, faction_id, faction_level) values(%u, %u, %i) ON DUPLICATE KEY UPDATE faction_level=%i", client->GetCharacterID(), itr->first, itr->second, itr->second);
  4032. }
  4033. bool WorldDatabase::LoadPlayerFactions(Client* client) {
  4034. LogWrite(PLAYER__DEBUG, 0, "Player", "Loading Player Factions...");
  4035. Query query;
  4036. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT faction_id, faction_level FROM character_factions where char_id=%i", client->GetCharacterID());
  4037. if(result && mysql_num_rows(result) > 0) {
  4038. MYSQL_ROW row;
  4039. while(result && (row = mysql_fetch_row(result))){
  4040. client->GetPlayer()->GetFactions()->SetFactionValue(atoul(row[0]), atol(row[1]));
  4041. }
  4042. }
  4043. if(query.GetErrorNumber())
  4044. return false;
  4045. return true;
  4046. }
  4047. void WorldDatabase::SavePlayerMail(Mail* mail) {
  4048. Query query_update;
  4049. Query query_insert;
  4050. if (mail) {
  4051. if(mail->mail_id > 0)
  4052. query_update.RunQuery2(Q_UPDATE, "UPDATE `character_mail` SET `already_read`=%u, `coin_copper`=%u, `coin_silver`=%u, `coin_gold`=%u, `coin_plat`=%u, `char_item_id`=%u, `stack`=%u WHERE `id`=%u", mail->already_read, mail->coin_copper, mail->coin_silver, mail->coin_gold, mail->coin_plat, mail->char_item_id, mail->stack, mail->mail_id);
  4053. else if (mail->mail_id == 0 || query_update.GetAffectedRows() == 0)
  4054. {
  4055. query_insert.RunQuery2(Q_INSERT, "INSERT INTO `character_mail` (`player_to_id`, `player_from`, `subject`, `mail_body`, `already_read`, `mail_type`, `coin_copper`, `coin_silver`, `coin_gold`, `coin_plat`, `stack`, `postage_cost`, `attachment_cost`, `char_item_id`, `time_sent`, `expire_time`) VALUES (%u, '%s', '%s', '%s', %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u)", mail->player_to_id, mail->player_from.c_str(), getSafeEscapeString(mail->subject.c_str()).c_str(), getSafeEscapeString(mail->mail_body.c_str()).c_str(), mail->already_read, mail->mail_type, mail->coin_copper, mail->coin_silver, mail->coin_gold, mail->coin_plat, mail->stack, mail->postage_cost, mail->attachment_cost, mail->char_item_id, mail->time_sent, mail->expire_time);
  4056. if(!mail->mail_id)
  4057. mail->mail_id = query_insert.GetLastInsertedID();
  4058. }
  4059. mail->save_needed = false;
  4060. }
  4061. }
  4062. void WorldDatabase::SavePlayerMail(Client* client) {
  4063. if (client) {
  4064. MutexMap<int32, Mail*>* mail_list = client->GetPlayer()->GetMail();
  4065. MutexMap<int32, Mail*>::iterator itr = mail_list->begin();
  4066. while (itr.Next()) {
  4067. Mail* mail = itr->second;
  4068. if (mail->save_needed)
  4069. SavePlayerMail(mail);
  4070. }
  4071. }
  4072. }
  4073. void WorldDatabase::LoadPlayerMail(Client* client, bool new_only) {
  4074. LogWrite(PLAYER__DEBUG, 0, "Player", "Loading Player Mail...");
  4075. if (client) {
  4076. Query query;
  4077. MYSQL_RES* result;
  4078. if (new_only)
  4079. result = query.RunQuery2(Q_SELECT, "SELECT `id`, `player_to_id`, `player_from`, `subject`, `mail_body`, `already_read`, `mail_type`, `coin_copper`, `coin_silver`, `coin_gold`, `coin_plat`, `stack`, `postage_cost`, `attachment_cost`, `char_item_id`, `time_sent`, `expire_time` FROM `character_mail` WHERE `player_to_id`=%u AND `unread`=1", client->GetCharacterID());
  4080. else
  4081. result = query.RunQuery2(Q_SELECT, "SELECT `id`, `player_to_id`, `player_from`, `subject`, `mail_body`, `already_read`, `mail_type`, `coin_copper`, `coin_silver`, `coin_gold`, `coin_plat`, `stack`, `postage_cost`, `attachment_cost`, `char_item_id`, `time_sent`, `expire_time` FROM `character_mail` WHERE `player_to_id`=%u", client->GetCharacterID());
  4082. if (result && mysql_num_rows(result) > 0) {
  4083. MYSQL_ROW row;
  4084. bool hasMail = false;
  4085. while (result && (row = mysql_fetch_row(result))) {
  4086. int32 time_sent = atoul(row[15]);
  4087. if ( time_sent > Timer::GetUnixTimeStamp() )
  4088. continue; // should have not been received yet
  4089. hasMail = true;
  4090. Mail* mail = new Mail;
  4091. mail->mail_id = atoul(row[0]);
  4092. mail->player_to_id = atoul(row[1]);
  4093. mail->player_from = string(row[2]);
  4094. mail->subject = string(row[3]);
  4095. if (row[4])
  4096. mail->mail_body = string(row[4]);
  4097. mail->already_read = atoi(row[5]);
  4098. mail->mail_type = atoi(row[6]);
  4099. mail->coin_copper = atoul(row[7]);
  4100. mail->coin_silver = atoul(row[8]);
  4101. mail->coin_gold = atoul(row[9]);
  4102. mail->coin_plat = atoul(row[10]);
  4103. mail->stack = atoi(row[11]);
  4104. mail->postage_cost = atoul(row[12]);
  4105. mail->attachment_cost = atoul(row[13]);
  4106. mail->char_item_id = atoul(row[14]);
  4107. mail->time_sent = time_sent;
  4108. mail->expire_time = atoul(row[16]);
  4109. mail->save_needed = false;
  4110. client->GetPlayer()->AddMail(mail);
  4111. LogWrite(PLAYER__DEBUG, 5, "Player", "Loaded Mail ID %i, to: %i, from: %s", atoul(row[0]), atoul(row[1]), string(row[2]).c_str());
  4112. }
  4113. if(hasMail)
  4114. client->SimpleMessage(CHANNEL_NARRATIVE, "You've got mail! :)");
  4115. }
  4116. }
  4117. }
  4118. void WorldDatabase::DeletePlayerMail(Mail* mail) {
  4119. Query query;
  4120. if (mail)
  4121. query.RunQuery2(Q_DELETE, "DELETE FROM `character_mail` WHERE `id`=%u", mail->mail_id);
  4122. LogWrite(PLAYER__DEBUG, 0, "Player", "Delete Player Mail...");
  4123. }
  4124. vector<int32>* WorldDatabase::GetAllPlayerIDs() {
  4125. Query query;
  4126. vector<int32>* ids = 0;
  4127. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `id` FROM `characters`");
  4128. MYSQL_ROW row;
  4129. while (result && (row = mysql_fetch_row(result))) {
  4130. if (ids == 0)
  4131. ids = new vector<int32>;
  4132. ids->push_back(atoul(row[0]));
  4133. }
  4134. return ids;
  4135. }
  4136. void WorldDatabase::GetPetNames(ZoneServer* zone)
  4137. {
  4138. DatabaseResult result;
  4139. int32 total = 0;
  4140. if( database_new.Select(&result, "SELECT pet_name FROM spawn_pet_names") )
  4141. {
  4142. while(result.Next())
  4143. {
  4144. zone->pet_names.push_back(result.GetStringStr("pet_name"));
  4145. total++;
  4146. LogWrite(PET__DEBUG, 5, "Pet", "---Loading Pet Name: '%s'", result.GetStringStr("pet_name"));
  4147. }
  4148. LogWrite(PET__DEBUG, 0, "Pet", "--Loaded %u Pet Names", total);
  4149. }
  4150. }
  4151. int32 WorldDatabase::GetMaxHotBarID(){
  4152. Query query;
  4153. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT max(id) FROM character_skillbar");
  4154. int32 ret = 0;
  4155. if(result && mysql_num_rows(result) > 0) {
  4156. MYSQL_ROW row;
  4157. row = mysql_fetch_row(result);
  4158. if(row && row[0])
  4159. ret = strtoul(row[0], NULL, 0);
  4160. }
  4161. return ret;
  4162. }
  4163. void WorldDatabase::SaveQuickBar(int32 char_id, vector<QuickBarItem*>* quickbar_items){
  4164. vector<QuickBarItem*>::iterator itr;
  4165. QuickBarItem* qbi = 0;
  4166. for(itr = quickbar_items->begin(); itr != quickbar_items->end(); itr++){
  4167. qbi = *itr;
  4168. if(!qbi)
  4169. continue;
  4170. if(qbi->deleted == false){
  4171. Query query;
  4172. if(qbi->text.size > 0){
  4173. query.AddQueryAsync(char_id, this, Q_REPLACE, "replace into character_skillbar (id, hotbar, slot, char_id, spell_id, type, text_val, tier) values(%u, %u, %u, %u, %u, %i, '%s', %i)",
  4174. qbi->unique_id, qbi->hotbar, qbi->slot, char_id, qbi->id, qbi->type, getSafeEscapeString(qbi->text.data.c_str()).c_str(), qbi->tier);
  4175. }
  4176. else{
  4177. query.AddQueryAsync(char_id, this, Q_REPLACE, "replace into character_skillbar (id, hotbar, slot, char_id, spell_id, type, text_val, tier) values(%u, %u, %u, %u, %u, %i, 'Unused', %i)",
  4178. qbi->unique_id, qbi->hotbar, qbi->slot, char_id, qbi->id, qbi->type, qbi->tier);
  4179. }
  4180. }
  4181. else{
  4182. Query query;
  4183. query.AddQueryAsync(char_id, this, Q_DELETE, "delete FROM character_skillbar where hotbar=%u and slot=%u and char_id=%u", qbi->hotbar, qbi->slot, char_id);
  4184. }
  4185. }
  4186. }
  4187. map<int32, vector<LevelArray*> >* WorldDatabase::LoadSpellClasses(){
  4188. map<int32, vector<LevelArray*> >* ret = new map<int32, vector<LevelArray*> >();
  4189. Query query;
  4190. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT spell_id, adventure_class_id, tradeskill_class_id, level FROM spell_classes");
  4191. MYSQL_ROW row;
  4192. LevelArray* level = 0;
  4193. while(result && (row = mysql_fetch_row(result))){
  4194. level = new LevelArray();
  4195. level->adventure_class = atoi(row[1]);
  4196. level->tradeskill_class = atoi(row[2]);
  4197. level->spell_level = atoi(row[3]);
  4198. (*ret)[atoul(row[0])].push_back(level);
  4199. }
  4200. return ret;
  4201. }
  4202. void WorldDatabase::LoadTraits(){
  4203. Query query;
  4204. MYSQL_ROW row;
  4205. TraitData* trait;
  4206. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `spell_id`, `level`, `class_req`, `race_req`, `isTrait`,`isInate`, `isFocusEffect`, `isTraining`,`tier`, `group`, `item_id` FROM spell_traits where is_active = 1");
  4207. while (result && (row = mysql_fetch_row(result))){
  4208. trait = new TraitData;
  4209. int8 i = 0;
  4210. trait->spellID = strtoul(row[0], NULL, 0);
  4211. trait->level = atoi(row[(++i)]);
  4212. trait->classReq = atoi(row[(++i)]);
  4213. trait->raceReq = atoi(row[(++i)]);
  4214. trait->isTrait = (atoi(row[(++i)]) == 0) ? false : true;
  4215. trait->isInate = (atoi(row[(++i)]) == 0) ? false : true;
  4216. trait->isFocusEffect = (atoi(row[(++i)]) == 0) ? false : true;
  4217. trait->isTraining = (atoi(row[(++i)]) == 0) ? false : true;
  4218. trait->tier = atoi(row[(++i)]);
  4219. trait->group = atoi(row[(++i)]);
  4220. trait->item_id = atoul(row[(++i)]);
  4221. master_trait_list.AddTrait(trait);
  4222. }
  4223. LogWrite(SPELL__INFO, 0, "Traits", "Loaded %u Trait(s)", master_trait_list.Size());
  4224. }
  4225. void WorldDatabase::LoadSpells()
  4226. {
  4227. DatabaseResult result;
  4228. Spell *spell;
  4229. SpellData *data;
  4230. int32 t_now = Timer::GetUnixTimeStamp();
  4231. int32 total = 0;
  4232. map<int32, vector<LevelArray*> >* level_data = LoadSpellClasses();
  4233. if( !database_new.Select(&result, "SELECT s.`id`, ts.spell_id, ts.index, `name`, `description`, `type`, `class_skill`, `min_class_skill_req`, `mastery_skill`, `tier`, `is_aa`,`hp_req`, `power_req`,`power_by_level`, `cast_time`, `recast`, `radius`, `max_aoe_targets`, `req_concentration`, `range`, `duration1`, `duration2`, `resistibility`, `hp_upkeep`, `power_upkeep`, `duration_until_cancel`, `target_type`, `recovery`, `power_req_percent`, `hp_req_percent`, `icon`, `icon_heroic_op`, `icon_backdrop`, `success_message`, `fade_message`, `fade_message_others`, `cast_type`, `lua_script`, `call_frequency`, `interruptable`, `spell_visual`, `effect_message`, `min_range`, `can_effect_raid`, `affect_only_group_members`, `hit_bonus`, `display_spell_tier`, `friendly_spell`, `group_spell`, `spell_book_type`, spell_type+0, s.is_active, savagery_req, savagery_req_percent, savagery_upkeep, dissonance_req, dissonance_req_percent, dissonance_upkeep, linked_timer_id, det_type, incurable, control_effect_type, cast_while_moving, casting_flags, persist_through_death, not_maintained, savage_bar, savage_bar_slot, soe_spell_crc, 0xffffffff-CRC32(s.`name`) as 'spell_name_crc', type_group_spell_id, can_fizzle, given_by "
  4234. "FROM (spells s, spell_tiers st) "
  4235. "LEFT JOIN spell_ts_ability_index ts "
  4236. "ON s.`id` = ts.spell_id "
  4237. "WHERE s.id = st.spell_id AND s.is_active = 1 "
  4238. "ORDER BY s.`id`, `tier`") )
  4239. {
  4240. // error
  4241. }
  4242. else
  4243. {
  4244. while( result.Next() )
  4245. {
  4246. data = new SpellData;
  4247. int32 spell_id = result.GetInt32Str("id");
  4248. string spell_name = result.GetStringStr("name");
  4249. /* General Spell info */
  4250. data->id = spell_id;
  4251. data->inherited_spell_id = spell_id;
  4252. data->soe_spell_crc = result.GetInt32Str("soe_spell_crc");
  4253. data->tier = result.GetInt8Str("tier");
  4254. data->ts_loc_index = result.GetInt8Str("index");
  4255. data->name.data = spell_name.c_str();
  4256. data->name.size = data->name.data.length();
  4257. data->description.data = result.GetStringStr("description");
  4258. data->description.size = data->description.data.length();
  4259. data->icon = result.GetSInt16Str("icon");
  4260. data->icon_heroic_op = result.GetInt16Str("icon_heroic_op");
  4261. data->icon_backdrop = result.GetInt16Str("icon_backdrop");
  4262. data->spell_visual = result.GetInt32Str("spell_visual");
  4263. data->type = result.GetInt16Str("type");
  4264. data->target_type = result.GetInt8Str("target_type");
  4265. data->cast_type = result.GetInt8Str("cast_type");
  4266. data->spell_book_type = result.GetInt32Str("spell_book_type");
  4267. data->det_type = result.GetInt8Str("det_type");
  4268. data->incurable = (result.GetInt8Str("incurable") == 1);
  4269. data->control_effect_type = result.GetInt8Str("control_effect_type");
  4270. data->casting_flags = result.GetInt32Str("casting_flags");
  4271. data->savage_bar = result.GetInt8Str("savage_bar");
  4272. data->savage_bar_slot = result.GetInt8Str("savage_bar_slot");
  4273. data->spell_type = result.IsNullStr("spell_type+0") ? 0 : result.GetInt8Str("spell_type+0");
  4274. /* Toggles */
  4275. data->interruptable = ( result.GetInt8Str("interruptable") == 1);
  4276. data->duration_until_cancel = ( result.GetInt8Str("duration_until_cancel") == 1);
  4277. data->can_effect_raid = result.GetInt8Str("can_effect_raid");
  4278. data->affect_only_group_members = result.GetInt8Str("affect_only_group_members");
  4279. data->display_spell_tier = result.GetInt8Str("display_spell_tier");
  4280. data->friendly_spell = result.GetInt8Str("friendly_spell");
  4281. data->group_spell = result.GetInt8Str("group_spell");
  4282. data->is_active = result.GetInt8Str("is_active");
  4283. data->persist_through_death = ( result.GetInt8Str("persist_through_death") == 1);
  4284. data->cast_while_moving = ( result.GetInt8Str("cast_while_moving") == 1);
  4285. data->not_maintained = ( result.GetInt8Str("not_maintained") == 1);
  4286. data->is_aa = (result.GetInt8Str("is_aa") == 1);
  4287. /* Skill Requirements */
  4288. data->class_skill = result.GetInt32Str("class_skill");
  4289. data->min_class_skill_req = result.GetInt16Str("min_class_skill_req");
  4290. data->mastery_skill = result.GetInt32Str("mastery_skill");
  4291. /* Cost */
  4292. data->req_concentration = result.GetInt16Str("req_concentration");
  4293. data->hp_req = result.GetInt16Str("hp_req");
  4294. data->hp_upkeep = result.GetInt16Str("hp_upkeep");
  4295. data->hp_req_percent = result.GetInt8Str("hp_req_percent");
  4296. data->power_req = result.GetFloatStr("power_req");
  4297. data->power_by_level = ( result.GetInt8Str("power_by_level") == 0)? false : true;
  4298. data->power_upkeep = result.GetInt16Str("power_upkeep");
  4299. data->power_req_percent = result.GetInt8Str("power_req_percent");
  4300. data->savagery_req = result.GetInt16Str("savagery_req");
  4301. data->savagery_upkeep = result.GetInt16Str("savagery_upkeep");
  4302. data->savagery_req_percent = result.GetInt8Str("savagery_req_percent");
  4303. data->dissonance_req = result.GetInt16Str("dissonance_req");
  4304. data->dissonance_upkeep = result.GetInt16Str("dissonance_upkeep");
  4305. data->dissonance_req_percent = result.GetInt8Str("dissonance_req_percent");
  4306. /* Spell Parameters */
  4307. data->call_frequency = result.GetInt32Str("call_frequency");
  4308. data->orig_cast_time = result.GetInt16Str("cast_time");
  4309. data->cast_time = result.GetInt16Str("cast_time");
  4310. data->duration1 = result.GetInt32Str("duration1");
  4311. data->duration2 = result.GetInt32Str("duration2");
  4312. data->hit_bonus = result.GetFloatStr("hit_bonus");
  4313. data->max_aoe_targets = result.GetInt16Str("max_aoe_targets");
  4314. data->min_range = result.GetFloatStr("min_range");
  4315. data->radius = result.GetFloatStr("radius");
  4316. data->range = result.GetFloatStr("range");
  4317. data->recast = result.GetFloatStr("recast");
  4318. data->recovery = result.GetFloatStr("recovery");
  4319. data->resistibility = result.GetFloatStr("resistibility");
  4320. data->linked_timer = result.GetInt32Str("linked_timer_id");
  4321. data->spell_name_crc = result.GetInt32Str("spell_name_crc");
  4322. data->type_group_spell_id = result.GetSInt32Str("type_group_spell_id");
  4323. data->can_fizzle = ( result.GetInt8Str("can_fizzle") == 1);
  4324. string given_by = result.GetStringStr("given_by");
  4325. data->given_by.data = given_by.c_str();
  4326. data->given_by.size = data->given_by.data.length();
  4327. std::string givenType(given_by);
  4328. boost::algorithm::to_lower(givenType);
  4329. if(givenType == "unset" || givenType.length() < 1) {
  4330. data->given_by_type == GivenByType::GivenBy_Unset;
  4331. }
  4332. else if(givenType == "tradeskillclass") {
  4333. data->given_by_type == GivenByType::GivenBy_TradeskillClass;
  4334. }
  4335. else if(givenType == "spellscroll") {
  4336. data->given_by_type == GivenByType::GivenBy_SpellScroll;
  4337. }
  4338. else if(givenType == "alternateadvancement") {
  4339. data->given_by_type == GivenByType::GivenBy_AltAdvancement;
  4340. }
  4341. else if(givenType == "race") {
  4342. data->given_by_type == GivenByType::GivenBy_Race;
  4343. }
  4344. else if(givenType == "racialinnate") {
  4345. data->given_by_type == GivenByType::GivenBy_RacialInnate;
  4346. }
  4347. else if(givenType == "racialtradition") {
  4348. data->given_by_type == GivenByType::GivenBy_RacialTradition;
  4349. }
  4350. else if(givenType == "class") {
  4351. data->given_by_type == GivenByType::GivenBy_Class;
  4352. }
  4353. else if(givenType == "charactertrait") {
  4354. data->given_by_type == GivenByType::GivenBy_CharacterTrait;
  4355. }
  4356. else if(givenType == "focusabilities") {
  4357. data->given_by_type == GivenByType::GivenBy_FocusAbility;
  4358. }
  4359. else if(givenType == "classtraining") {
  4360. data->given_by_type == GivenByType::GivenBy_ClassTraining;
  4361. }
  4362. else if(givenType == "warderspell") {
  4363. data->given_by_type == GivenByType::GivenBy_WarderSpell;
  4364. }
  4365. else {
  4366. data->given_by_type == GivenByType::GivenBy_Unset;
  4367. }
  4368. /* Cast Messaging */
  4369. string message = result.GetStringStr("success_message");
  4370. if( message.length() > 0 )
  4371. data->success_message = message;
  4372. message = result.GetStringStr("fade_message");
  4373. if( message.length() > 0 )
  4374. data->fade_message = string(message);
  4375. message = result.GetStringStr("fade_message_others");
  4376. if (message.length() > 0)
  4377. data->fade_message_others = string(message);
  4378. message = result.GetStringStr("effect_message");
  4379. if( message.length() > 0 )
  4380. data->effect_message = string(message);
  4381. string lua_script = result.GetStringStr("lua_script");
  4382. if( lua_script.length() > 0 )
  4383. data->lua_script = string(lua_script);
  4384. /* Load spell level data */
  4385. spell = new Spell(data);
  4386. if(level_data && level_data->count(data->id) > 0)
  4387. {
  4388. vector<LevelArray*>* level_array = &((*level_data)[data->id]);
  4389. for(int8 i=0; i<level_array->size(); i++)
  4390. {
  4391. spell->AddSpellLevel(level_array->at(i)->adventure_class, level_array->at(i)->tradeskill_class, level_array->at(i)->spell_level*10);
  4392. }
  4393. }
  4394. /* Add spell to master list */
  4395. master_spell_list.AddSpell(data->id, data->tier, spell);
  4396. total++;
  4397. if( lua_script.length() > 0 )
  4398. LogWrite(SPELL__DEBUG, 5, "Spells", "\t%i. %s (Tier: %i) - '%s'", spell_id, spell_name.c_str(), data->tier, lua_script.c_str());
  4399. else if(data->is_active)
  4400. LogWrite(SPELL__WARNING, 1, "Spells", "\tSpell %s (%u, Tier: %i) set 'Active', but missing LUAScript", spell_name.c_str(), spell_id, data->tier);
  4401. } // end while
  4402. } // end else
  4403. LogWrite(SPELL__DEBUG, 0, "Spells", "Loading Spell Effects...");
  4404. LoadSpellEffects();
  4405. LogWrite(SPELL__DEBUG, 0, "Spells", "Loading Spell LUA Data...");
  4406. LoadSpellLuaData();
  4407. if(lua_interface)
  4408. {
  4409. LogWrite(SPELL__DEBUG, 0, "Spells", "Loading Spells Scripts...");
  4410. LoadSpellScriptData();
  4411. }
  4412. if (level_data) {
  4413. map<int32, vector<LevelArray*> >::iterator map_itr;
  4414. vector<LevelArray*>::iterator level_itr;
  4415. for(map_itr = level_data->begin(); map_itr != level_data->end(); map_itr++)
  4416. {
  4417. for(level_itr = map_itr->second.begin(); level_itr != map_itr->second.end(); level_itr++)
  4418. {
  4419. safe_delete(*level_itr);
  4420. }
  4421. }
  4422. }
  4423. safe_delete(level_data);
  4424. LogWrite(SPELL__INFO, 0, "Spells", "Loaded %u Spell%s (took %u seconds)", total, total == 1 ? "" : "s", Timer::GetUnixTimeStamp() - t_now);
  4425. }
  4426. void WorldDatabase::LoadSpellLuaData(){
  4427. Spell *spell;
  4428. Query query;
  4429. MYSQL_ROW row;
  4430. int32 total = 0;
  4431. MYSQL_RES *result = query.RunQuery2(Q_SELECT, "SELECT `spell_id`,`tier`,`value_type`,`value`,`value2`,`dynamic_helper` "
  4432. "FROM `spell_data` "
  4433. "ORDER BY `index_field`");
  4434. while (result && (row = mysql_fetch_row(result))) {
  4435. if ((spell = master_spell_list.GetSpell(atoul(row[0]), atoi(row[1]))) && row[2] && row[3] && row[4] && row[4]) {
  4436. LogWrite(SPELL__DEBUG, 5, "Spells", "\tLoading Spell LUA Data for spell_id: %u", atoul(row[0]));
  4437. if (!strcmp(row[2], "INT"))
  4438. spell->AddSpellLuaDataInt(atoi(row[3]), atoi(row[4]), string(row[5]));
  4439. else if (!strcmp(row[2], "FLOAT"))
  4440. spell->AddSpellLuaDataFloat(atof(row[3]), atof(row[4]),string(row[5]));
  4441. else if (!strcmp(row[2], "BOOL"))
  4442. spell->AddSpellLuaDataBool(!(strncasecmp(row[3], "true", 4)), string(row[5]));
  4443. else if (!strcmp(row[2], "STRING"))
  4444. spell->AddSpellLuaDataString(string(row[3]), string(row[4]), string(row[5]));
  4445. else
  4446. LogWrite(SPELL__ERROR, 0, "Spells", "Invalid Lua Spell data '%s' for Spell ID: %u", row[2], spell->GetSpellID());
  4447. total++;
  4448. }
  4449. }
  4450. LogWrite(SPELL__DEBUG, 0, "Spells", "\tLoaded %i Spell LUA Data entr%s.", total, total == 1 ? "y" : "ies");
  4451. }
  4452. void WorldDatabase::LoadSpellEffects() {
  4453. Spell *spell;
  4454. Query query;
  4455. MYSQL_ROW row;
  4456. int32 total = 0;
  4457. MYSQL_RES *result = query.RunQuery2(Q_SELECT, "SELECT `spell_id`,`tier`,`percentage`,`bullet`,`description` "
  4458. "FROM `spell_display_effects` "
  4459. "ORDER BY `spell_id`,`id` ASC");
  4460. while (result && (row = mysql_fetch_row(result))) {
  4461. if ((spell = master_spell_list.GetSpell(atoul(row[0]), atoi(row[1]))) && row[4]) {
  4462. LogWrite(SPELL__DEBUG, 5, "Spells", "\tLoading Spell Effects for spell_id: %u", atoul(row[0]));
  4463. spell->AddSpellEffect(atoi(row[2]), atoi(row[3]), row[4]);
  4464. total++;
  4465. }
  4466. }
  4467. LogWrite(SPELL__DEBUG, 0, "Spells", "\tLoaded %u Spell Effect%s.", total, total == 1 ? "" : "s");
  4468. }
  4469. int32 WorldDatabase::LoadPlayerSkillbar(Client* client){
  4470. client->GetPlayer()->ClearQuickbarItems();
  4471. Query query;
  4472. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, type, spell_id, slot, text_val, hotbar, tier FROM character_skillbar where char_id = %u", client->GetCharacterID());
  4473. MYSQL_ROW row;
  4474. int32 count = 0;
  4475. while(result && (row = mysql_fetch_row(result))){
  4476. count++;
  4477. int8 tier = atoi(row[6]);
  4478. Spell* spell = master_spell_list.GetSpell(atoul(row[2]), tier);
  4479. if(spell)
  4480. client->GetPlayer()->AddQuickbarItem(atoul(row[5]), atoul(row[3]), atoul(row[1]), spell->GetSpellIcon(), spell->GetSpellIconBackdrop(), spell->GetSpellID(), spell->GetSpellTier(), atoul(row[0]), row[4], false);
  4481. else if(atoul(row[1]) == QUICKBAR_MACRO)
  4482. client->GetPlayer()->AddQuickbarItem(atoul(row[5]), atoul(row[3]), atoul(row[1]), client->GetPlayer()->macro_icons[atoul(row[2])], 0xFFFF, atoul(row[2]), 0, atoul(row[0]), row[4], false);
  4483. else
  4484. client->GetPlayer()->AddQuickbarItem(atoul(row[5]), atoul(row[3]), atoul(row[1]), 0, 0, atoul(row[2]), 0, atoul(row[0]), row[4], false);
  4485. }
  4486. return count;
  4487. }
  4488. bool WorldDatabase::DeleteCharacter(int32 account_id, int32 character_id){
  4489. Guild *guild;
  4490. if((guild = guild_list.GetGuild(GetGuildIDByCharacterID(character_id))))
  4491. guild->RemoveGuildMember(character_id);
  4492. Query query;
  4493. //devn00b: Update this whole thing we were missing many tables. This is ugly but swapped 99% of the delete to async to lighten server load.
  4494. //Do character delete immediately.
  4495. query.RunQuery2(Q_DELETE, "DELETE FROM characters WHERE id=%u AND account_id=%u", character_id, account_id);
  4496. //if no character then we shouldn't bother with the rest.
  4497. if (!query.GetAffectedRows())
  4498. {
  4499. //No error just in case ppl try doing stupid stuff
  4500. return false;
  4501. }
  4502. //Async
  4503. query.AddQueryAsync(character_id, this, Q_DELETE, "DELETE FROM character_languages WHERE char_id=%u", character_id);
  4504. query.AddQueryAsync(character_id, this, Q_DELETE, "DELETE FROM character_quest_rewards WHERE char_id=%u", character_id);
  4505. query.AddQueryAsync(character_id, this, Q_DELETE, "DELETE FROM character_quest_temporary_rewards WHERE char_id=%u", character_id);
  4506. query.AddQueryAsync(character_id, this, Q_DELETE, "DELETE FROM character_claim_items where char_id=%u", character_id);
  4507. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from charactersproperties where charid = %u", character_id);
  4508. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_aa where char_id = %u", character_id);
  4509. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_achievements where char_id = %u", character_id);
  4510. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_achievements_items where char_id = %u", character_id);
  4511. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_buyback where char_id = %u", character_id);
  4512. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_collections where char_id = %u", character_id);
  4513. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_collection_items where char_id = %u", character_id);
  4514. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_details where char_id = %u", character_id);
  4515. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_factions where char_id = %u", character_id);
  4516. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_history where char_id = %u", character_id);
  4517. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_houses where char_id = %u", character_id);
  4518. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_instances where char_id = %u", character_id);
  4519. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_items where char_id = %u", character_id);
  4520. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_items_group_members where character_id = %u", character_id);
  4521. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_lua_history where char_id = %u", character_id);
  4522. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_macros where char_id = %u", character_id);
  4523. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_pictures where char_id = %u", character_id);
  4524. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_properties where charid = %u", character_id);
  4525. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_quests where char_id = %u", character_id);
  4526. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_quest_progress where char_id = %u", character_id);
  4527. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_recipes where char_id = %u", character_id);
  4528. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_recipe_books where char_id = %u", character_id);
  4529. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_skillbar where char_id = %u", character_id);
  4530. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_skills where char_id = %u", character_id);
  4531. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_social where char_id = %u", character_id);
  4532. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_spells where char_id = %u", character_id);
  4533. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_spell_effects where caster_char_id = %u or target_char_id = %u", character_id, character_id);
  4534. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_spell_effect_targets where caster_char_id = %u or target_char_id = %u", character_id, character_id);
  4535. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_spirit_shards where charid = %u", character_id);
  4536. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from character_titles where char_id = %u", character_id);
  4537. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from char_colors where char_id = %u", character_id);
  4538. query.AddQueryAsync(character_id, this, Q_DELETE, "delete from statistics where char_id = %u", character_id);
  4539. return true;
  4540. }
  4541. void WorldDatabase::DeleteCharacterSpell(int32 character_id, int32 spell_id) {
  4542. if (character_id > 0 && spell_id > 0) {
  4543. Query query;
  4544. query.RunQuery2(Q_DELETE, "DELETE FROM character_spells WHERE char_id=%u AND spell_id=%u", character_id, spell_id);
  4545. }
  4546. }
  4547. bool WorldDatabase::GetItemResultsToClient (Client* client, const char* varSearch, int maxResults) {
  4548. Query query;
  4549. MYSQL_ROW row;
  4550. int results = 0;
  4551. if( maxResults > 10 && client->GetAdminStatus ( ) < 100 )
  4552. maxResults = 10;
  4553. else if( maxResults > 20 )
  4554. maxResults = 20;
  4555. client->Message(CHANNEL_COLOR_YELLOW, "Item Search Results");
  4556. client->Message(CHANNEL_COLOR_YELLOW, "ResultNum) [ItemID] ItemName");
  4557. string itemsearch_query = string("SELECT id, name FROM items where name like '%%%s%%' limit %i");
  4558. MYSQL_RES* result = query.RunQuery2(Q_SELECT, itemsearch_query.c_str(),getSafeEscapeString(varSearch).c_str(),maxResults);
  4559. while(result && (row = mysql_fetch_row(result))){
  4560. results++;
  4561. client->Message(CHANNEL_COLOR_YELLOW, "%i) [%s] %s",results,row[0],row[1]);
  4562. }
  4563. if(results == 0)
  4564. {
  4565. client->Message(CHANNEL_COLOR_YELLOW, "No Items Found.");
  4566. return false;
  4567. }
  4568. client->Message(CHANNEL_COLOR_YELLOW, "%i Items Found.",results);
  4569. return true;
  4570. }
  4571. void WorldDatabase::SaveWorldTime(WorldTime* time){
  4572. Query query;
  4573. query.RunQuery2(Q_REPLACE, "replace into variables (variable_name, variable_value) values('gametime', '%i/%i/%i %i:%i')", time->month, time->day, time->year, time->hour, time->minute);
  4574. }
  4575. void WorldDatabase::SaveBugReport(const char* category, const char* subcategory, const char* causes_crash, const char* reproducible, const char* summary, const char* description, const char* version, const char* player, int32 account_id, const char* spawn_name, int32 spawn_id, int32 zone_id){
  4576. Query query;
  4577. int32 dbVersion = rule_manager.GetGlobalRule(R_World, DatabaseVersion)->GetInt32();
  4578. string bug_report = string("insert into bugs (category, subcategory, causes_crash, reproducible, summary, description, version, player, account_id, spawn_name, spawn_id, zone_id, dbversion, worldversion) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %u, '%s', %u, %u, %u, '%s')");
  4579. query.RunQuery2(Q_INSERT, bug_report.c_str(), getSafeEscapeString(category).c_str(), getSafeEscapeString(subcategory).c_str(),
  4580. getSafeEscapeString(causes_crash).c_str(), getSafeEscapeString(reproducible).c_str(), getSafeEscapeString(summary).c_str(),
  4581. getSafeEscapeString(description).c_str(), getSafeEscapeString(version).c_str(), getSafeEscapeString(player).c_str(), account_id,
  4582. getSafeEscapeString(spawn_name).c_str(), spawn_id, zone_id, dbVersion, CURRENT_VERSION);
  4583. FixBugReport();
  4584. FixBugReport();
  4585. FixBugReport();
  4586. }
  4587. void WorldDatabase::FixBugReport(){
  4588. Query query;
  4589. string bug_report = string("update bugs set description = REPLACE(description,SUBSTRING(description,INSTR(description,'%'), 3),char(CONV(SUBSTRING(description,INSTR(description,'%')+1, 2), 16, 10))), summary = REPLACE(summary,SUBSTRING(summary,INSTR(summary,'%'), 3),char(CONV(SUBSTRING(summary,INSTR(summary,'%')+1, 2), 16, 10)))");
  4590. query.RunQuery2(bug_report.c_str(), Q_UPDATE);
  4591. }
  4592. int32 WorldDatabase::LoadQuests(){
  4593. Query query;
  4594. MYSQL_ROW row;
  4595. std::string querystr = std::string("SELECT `quest_id`, `name`, `type`, `zone`, `level`, `enc_level`, `description`, `lua_script`, `completed_text`, `spawn_id`, `shareable_flag`, `deleteable` FROM `quests`");
  4596. MYSQL_RES* result = query.RunQuery2(Q_SELECT, querystr.c_str());
  4597. Quest* quest = 0;
  4598. char* name = 0;
  4599. char* type = 0;
  4600. char* zone = 0;
  4601. int8 level = 0;
  4602. int8 enc_level = 0;
  4603. char* description = 0;
  4604. char* script = 0;
  4605. int32 total = 0;
  4606. int32 id = 0;
  4607. char* completed_description = 0;
  4608. int32 return_npc_id = 0;
  4609. if(result){
  4610. while(result && (row = mysql_fetch_row(result))){
  4611. id = atoul(row[0]);
  4612. name = row[1];
  4613. type = row[2];
  4614. zone = row[3];
  4615. level = atoul(row[4]);
  4616. enc_level = atoul(row[5]);
  4617. description = row[6];
  4618. script = row[7];
  4619. completed_description = row[8];
  4620. return_npc_id = atoi(row[9]);
  4621. if(lua_interface) {
  4622. quest = lua_interface->LoadQuest(id, name, type, zone, level, description, script);
  4623. }
  4624. if(quest){
  4625. LogWrite(QUEST__DEBUG, 5, "Quests", "\tLoading Quest: '%s' (%u)", name, id);
  4626. LoadQuestDetails(quest);
  4627. string compDescription;
  4628. if (completed_description == NULL)
  4629. {
  4630. compDescription = string("Missing! Notify Developer");
  4631. LogWrite(QUEST__WARNING, 5, "Quests", "\tLoading Quest MISSING completed_text in quests table for: '%s' (%u)", name, id);
  4632. }
  4633. else
  4634. compDescription = string(completed_description);
  4635. quest->SetCompletedDescription(string(compDescription));
  4636. quest->SetQuestReturnNPC(return_npc_id);
  4637. quest->SetEncounterLevel(enc_level);
  4638. quest->SetQuestShareableFlag(atoul(row[10]));
  4639. quest->SetCanDeleteQuest(atoul(row[11]));
  4640. total++;
  4641. master_quest_list.AddQuest(id, quest);
  4642. }
  4643. else
  4644. {
  4645. LogWrite(QUEST__ERROR, 5, "Quests", "\tFAILED LOADING QUEST: '%s' (%u), check that script file exists/permissions correct: %s", name, id, (script && strlen(script)) ? script : "Not Set, Missing!");
  4646. }
  4647. }
  4648. }
  4649. LogWrite(QUEST__DEBUG, 0, "Quest", "\tLoaded %i Quest(s)", total);
  4650. return total;
  4651. }
  4652. void WorldDatabase::LoadQuestDetails(Quest* quest) {
  4653. Query query;
  4654. MYSQL_ROW row;
  4655. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `type`, `subtype`, `value`, `faction_id`, `quantity` FROM `quest_details` WHERE `quest_id`=%u", quest->GetQuestID());
  4656. string type;
  4657. string subtype;
  4658. sint64 value;
  4659. int32 faction_id;
  4660. int32 quantity;
  4661. while (result && (row = mysql_fetch_row(result))) {
  4662. type = string(row[0]);
  4663. subtype = string(row[1]);
  4664. value = atoi(row[2]);
  4665. faction_id = atoi(row[3]);
  4666. quantity = atoi(row[4]);
  4667. LogWrite(QUEST__DEBUG, 5, "Quests", "\t- Type: %s, SubType: %s, Val: %u, Faction: %u, Qty: %u", type.c_str(), subtype.c_str(), value, faction_id, quantity);
  4668. if (type == "Prereq") {
  4669. if (subtype == "Class")
  4670. quest->AddPrereqClass(value);
  4671. else if (subtype == "Faction")
  4672. quest->AddPrereqFaction(faction_id, value);
  4673. else if (subtype == "Item") {
  4674. Item* master_item = master_item_list.GetItem(value);
  4675. if (master_item) {
  4676. Item* item = new Item(master_item);
  4677. quest->AddPrereqItem(item);
  4678. }
  4679. }
  4680. else if (subtype == "AdvLevel")
  4681. quest->SetPrereqLevel(value);
  4682. else if (subtype == "Quest")
  4683. quest->AddPrereqQuest(value);
  4684. else if (subtype == "Race")
  4685. quest->AddPrereqRace(value);
  4686. else if (subtype == "TSClass")
  4687. quest->AddPrereqTradeskillClass(value);
  4688. else if (subtype == "TSLevel")
  4689. quest->SetPrereqTSLevel(value);
  4690. else if (subtype == "MaxTSLevel")
  4691. quest->SetPrereqMaxTSLevel(value);
  4692. else if (subtype == "MaxAdvLevel")
  4693. quest->SetPrereqMaxLevel(value);
  4694. }
  4695. else if (type == "Reward") {
  4696. if (subtype == "Item") {
  4697. Item* master_item = master_item_list.GetItem(value);
  4698. if (master_item) {
  4699. Item* item = new Item(master_item);
  4700. item->details.count = quantity;
  4701. quest->AddRewardItem(item);
  4702. }
  4703. }
  4704. else if (subtype == "Selectable") {
  4705. Item* master_item = master_item_list.GetItem(value);
  4706. if (master_item) {
  4707. Item* item = new Item(master_item);
  4708. item->details.count = quantity;
  4709. quest->AddSelectableRewardItem(item);
  4710. }
  4711. }
  4712. else if (subtype == "Coin") {
  4713. int32 copper = 0;
  4714. int32 silver = 0;
  4715. int32 gold = 0;
  4716. int32 plat = 0;
  4717. if (value >= 1000000) {
  4718. plat = value / 1000000;
  4719. value -= 1000000 * plat;
  4720. }
  4721. if (value >= 10000) {
  4722. gold = value / 10000;
  4723. value -= 10000 * gold;
  4724. }
  4725. if (value >= 100) {
  4726. silver = value / 100;
  4727. value -= 100 * silver;
  4728. }
  4729. if (value > 0)
  4730. copper = value;
  4731. quest->AddRewardCoins(copper, silver, gold, plat);
  4732. }
  4733. else if (subtype == "MaxCoin") {
  4734. quest->AddRewardCoinsMax(value);
  4735. }
  4736. else if (subtype == "Faction")
  4737. quest->AddRewardFaction(faction_id, value);
  4738. else if (subtype == "Experience")
  4739. quest->SetRewardXP(value);
  4740. else if (subtype == "TSExperience")
  4741. quest->SetRewardTSXP(value);
  4742. }
  4743. }
  4744. }
  4745. void WorldDatabase::LoadMerchantInformation() {
  4746. LogWrite(MERCHANT__DEBUG, 0, "Merchant", "\tClearing Merchant Inventory...");
  4747. world.DeleteMerchantItems();
  4748. LogWrite(MERCHANT__DEBUG, 0, "Merchant", "\tLoading Merchant Inventory...");
  4749. LoadMerchantInventory();
  4750. Query query;
  4751. MYSQL_ROW row;
  4752. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT merchant_id, inventory_id FROM merchants ORDER BY merchant_id");
  4753. int32 total = 0;
  4754. int32 last_merchant_id = 0;
  4755. int32 id = 0;
  4756. MerchantInfo* merchant = 0;
  4757. if(result) {
  4758. while(result && (row = mysql_fetch_row(result))) {
  4759. id = atoul(row[0]);
  4760. LogWrite(MERCHANT__DEBUG, 5, "Merchant", "\tMerchantID: %u, InventoryID: %u", id, atoul(row[1]));
  4761. if(id != last_merchant_id) {
  4762. if(merchant)
  4763. world.AddMerchantInfo(last_merchant_id, merchant);
  4764. merchant = new MerchantInfo;
  4765. last_merchant_id = id;
  4766. total++;
  4767. }
  4768. merchant->inventory_ids.push_back(atoul(row[1]));
  4769. }
  4770. if(merchant)
  4771. world.AddMerchantInfo(last_merchant_id, merchant);
  4772. }
  4773. LogWrite(MERCHANT__DEBUG, 0, "Merchant", "\tLoaded %i Merchant List(s)", total);
  4774. }
  4775. void WorldDatabase::LoadMerchantInventory(){
  4776. Query query;
  4777. MYSQL_ROW row;
  4778. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT inventory_id, item_id, quantity, price_item_id, price_item_qty, price_item2_id, price_item2_qty, price_status, price_coins, price_stationcash FROM merchant_inventory ORDER BY inventory_id");
  4779. int32 total = 0;
  4780. int32 id;
  4781. if(result) {
  4782. while(result && (row = mysql_fetch_row(result))) {
  4783. MerchantItemInfo ItemInfo;
  4784. id = atoul(row[0]);
  4785. ItemInfo.item_id = atoul(row[1]);
  4786. ItemInfo.quantity = atoi(row[2]);
  4787. ItemInfo.price_item_id = atoul(row[3]);
  4788. ItemInfo.price_item_qty = atoi(row[4]);
  4789. ItemInfo.price_item2_id = atoul(row[5]);
  4790. ItemInfo.price_item2_qty = atoi(row[6]);
  4791. ItemInfo.price_status = atoul(row[7]);
  4792. ItemInfo.price_coins = atoul(row[8]);
  4793. ItemInfo.price_stationcash = atoul(row[9]);
  4794. LogWrite(MERCHANT__DEBUG, 5, "Merchant", "\tInventoryID: %u, ItemID: %u, Qty: %u", id, ItemInfo.item_id, ItemInfo.quantity);
  4795. world.AddMerchantItem(id, ItemInfo);
  4796. total++;
  4797. }
  4798. }
  4799. LogWrite(MERCHANT__DEBUG, 0, "Merchant", "\tLoaded %i Merchant Inventory Item(s)", total);
  4800. }
  4801. string WorldDatabase::GetMerchantDescription(int32 merchant_id) {
  4802. Query query;
  4803. MYSQL_ROW row;
  4804. string description;
  4805. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `description` FROM `merchants` WHERE `merchant_id`=%u", merchant_id);
  4806. if (result && (row = mysql_fetch_row(result)))
  4807. description = string(row[0]);
  4808. return description;
  4809. }
  4810. void WorldDatabase::LoadTransporters(ZoneServer* zone){
  4811. int32 total = 0;
  4812. zone->DeleteGlobalTransporters();
  4813. Query query;
  4814. MYSQL_ROW row;
  4815. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT transport_id, transport_type, display_name, message, destination_zone_id, destination_x, destination_y, destination_z, destination_heading, trigger_location_zone_id, trigger_location_x, trigger_location_y, trigger_location_z, trigger_radius, cost, id, min_level, max_level, quest_req, quest_step_req, quest_completed, map_x, map_y, expansion_flag, holiday_flag, min_client_version, max_client_version, flight_path_id, mount_id, mount_red_color, mount_green_color, mount_blue_color FROM transporters ORDER BY transport_id");
  4816. if(result){
  4817. while(result && (row = mysql_fetch_row(result))){
  4818. LogWrite(TRANSPORT__DEBUG, 5, "Transport", "---Loading Transporter ID: %u, transport_type: %s", row[0], row[1]);
  4819. LogWrite(TRANSPORT__DEBUG, 7, "Transport", "---display_name: %s, message: %s", row[2], row[3]);
  4820. LogWrite(TRANSPORT__DEBUG, 7, "Transport", "---destination_zone_id: %s", row[4]);
  4821. LogWrite(TRANSPORT__DEBUG, 7, "Transport", "---destination_x: %s, destination_y: %s, destination_z: %s, destination_heading: %s", row[5], row[6], row[7], row[8]);
  4822. LogWrite(TRANSPORT__DEBUG, 7, "Transport", "---trigger_location_zone_id: %s", row[9]);
  4823. LogWrite(TRANSPORT__DEBUG, 7, "Transport", "---trigger_location_x: %s, trigger_location_y: %s, trigger_location_z: %s", row[10], row[11], row[12], row[13]);
  4824. LogWrite(TRANSPORT__DEBUG, 7, "Transport", "---trigger_radius: %s, cost: %s, id: %s", row[14], row[15]);
  4825. string name = "";
  4826. if(row[2])
  4827. name = string(row[2]);
  4828. string message = "";
  4829. if(row[3])
  4830. message = string(row[3]);
  4831. if(row[1] && strcmp(row[1], "Zone") == 0)
  4832. zone->AddTransporter(atoul(row[0]), TRANSPORT_TYPE_ZONE, name, message, atoul(row[4]), atof(row[5]), atof(row[6]), atof(row[7]), atof(row[8]), atoul(row[14]), atoul(row[15]), atoi(row[16]), atoi(row[17]), atoul(row[18]), atoi(row[19]), atoul(row[20]), atoul(row[21]), atoul(row[22]), atoul(row[23]), atoul(row[24]), atoul(row[25]), atoul(row[26]), atoul(row[27]), atoul(row[28]), atoul(row[29]), atoul(row[30]), atoul(row[31]));
  4833. else if (row[1] && strcmp(row[1], "Flight") == 0)
  4834. zone->AddTransporter(atoul(row[0]), TRANSPORT_TYPE_FLIGHT, name, message, atoul(row[4]), atof(row[5]), atof(row[6]), atof(row[7]), atof(row[8]), atoul(row[14]), atoul(row[15]), atoi(row[16]), atoi(row[17]), atoul(row[18]), atoi(row[19]), atoul(row[20]), atoul(row[21]), atoul(row[22]), atoul(row[23]), atoul(row[24]), atoul(row[25]), atoul(row[26]), atoul(row[27]), atoul(row[28]), atoul(row[29]), atoul(row[30]), atoul(row[31]));
  4835. else if(row[1] && strcmp(row[1], "Location") == 0)
  4836. zone->AddLocationTransporter(atoul(row[9]), message, atof(row[10]), atof(row[11]), atof(row[12]), atof(row[13]), atoul(row[4]), atof(row[5]), atof(row[6]), atof(row[7]), atof(row[8]), atoul(row[14]), atoul(row[15]));
  4837. else
  4838. zone->AddTransporter(atoul(row[0]), TRANSPORT_TYPE_GENERIC, "", message, atoul(row[4]), atof(row[5]), atof(row[6]), atof(row[7]), atof(row[8]), atoul(row[14]), atoul(row[15]), atoi(row[16]), atoi(row[17]), atoul(row[18]), atoi(row[19]), atoul(row[20]), atoul(row[21]), atoul(row[22]), atoul(row[23]), atoul(row[24]), atoul(row[25]), atoul(row[26]), atoul(row[27]), atoul(row[28]), atoul(row[29]), atoul(row[30]), atoul(row[31]));
  4839. total++;
  4840. }
  4841. }
  4842. LogWrite(TRANSPORT__DEBUG, 0, "Transport", "--Loaded %i Transporter(s)", total);
  4843. LoadTransportMaps(zone);
  4844. }
  4845. void WorldDatabase::LoadFogInit(string zone, PacketStruct* packet)
  4846. {
  4847. LogWrite(WORLD__TRACE, 9, "World", "Enter: %s", __FUNCTION__);
  4848. if(!packet || zone.length() == 0)
  4849. return;
  4850. Query query;
  4851. MYSQL_ROW row;
  4852. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT highest, lowest, zone_name, explored_map_name, unexplored_map_name, bounds1_x, bounds1_z, bounds2_x, bounds2_z, bounds3_x, bounds3_z, bounds4_x, bounds4_z, explored_key, unexplored_key, map_id FROM map_data where zone_name like '%s%%'", getSafeEscapeString(&zone).c_str());
  4853. if(result){
  4854. int count = mysql_num_rows(result);
  4855. int i=0;
  4856. int64 explored_key;
  4857. int64 unexplored_key;
  4858. packet->setArrayLengthByName("num_maps", count);
  4859. while(result && (row = mysql_fetch_row(result))){
  4860. packet->setDataByName("highest_z", atof(row[0]));
  4861. packet->setDataByName("lowest_z", atof(row[1]));
  4862. packet->setDataByName("map_id", atoul(row[15]));
  4863. packet->setArrayDataByName("unknown7", 1600, i);
  4864. packet->setArrayDataByName("unknown8", 1200, i);
  4865. packet->setArrayDataByName("zone_name", row[2], i);
  4866. packet->setArrayDataByName("explored_map_name", row[3], i);
  4867. packet->setArrayDataByName("unexplored_map_name", row[4], i);
  4868. packet->setArrayDataByName("map_bounds1_x", atof(row[5]), i);
  4869. packet->setArrayDataByName("map_bounds1_z", atof(row[6]), i);
  4870. packet->setArrayDataByName("map_bounds2_x", atof(row[7]), i);
  4871. packet->setArrayDataByName("map_bounds2_z", atof(row[8]), i);
  4872. packet->setArrayDataByName("map_bounds3_x", atof(row[9]), i);
  4873. packet->setArrayDataByName("map_bounds3_z", atof(row[10]), i);
  4874. packet->setArrayDataByName("map_bounds4_x", atof(row[11]), i);
  4875. packet->setArrayDataByName("map_bounds4_z", atof(row[12]), i);
  4876. #ifdef WIN32
  4877. explored_key = _strtoui64(row[13], NULL, 10);
  4878. unexplored_key = _strtoui64(row[14], NULL, 10);
  4879. #else
  4880. explored_key = strtoull(row[13], 0, 10);
  4881. unexplored_key = strtoull(row[14], 0, 10);
  4882. #endif
  4883. packet->setArrayDataByName("explored_key", explored_key, i);
  4884. packet->setArrayDataByName("unexplored_key", unexplored_key, i);
  4885. i++;
  4886. }
  4887. }
  4888. LogWrite(WORLD__TRACE, 9, "World", "Exit: %s", __FUNCTION__);
  4889. }
  4890. string WorldDatabase::GetColumnNames(char* name){
  4891. Query query;
  4892. MYSQL_ROW row;
  4893. string columns = "";
  4894. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "show columns FROM %s", name);
  4895. if(result && mysql_num_rows(result) > 0){
  4896. int16 i = 0;
  4897. while((row = mysql_fetch_row(result))){
  4898. if(strcmp(row[0], "table_data_version") != 0){
  4899. if(i>0)
  4900. columns.append(",");
  4901. columns.append(row[0]);
  4902. i++;
  4903. }
  4904. }
  4905. }
  4906. columns.append("");
  4907. return columns;
  4908. }
  4909. void WorldDatabase::ToggleCharacterOnline() {
  4910. Query query;
  4911. query.RunQuery2(Q_UPDATE, "UPDATE characters SET is_online = 0;");
  4912. }
  4913. void WorldDatabase::ToggleCharacterOnline(Client* client, int8 toggle) {
  4914. if (client) {
  4915. Query query;
  4916. Player* player = client->GetPlayer();
  4917. //if(!player->CheckPlayerInfo())
  4918. // return;
  4919. if (player)
  4920. {
  4921. LogWrite(PLAYER__DEBUG, 0, "Player", "Toggling Character %s", toggle ? "ONLINE!" : "OFFLINE!");
  4922. query.RunQuery2(Q_UPDATE, "UPDATE characters SET is_online=%i WHERE id = %u;", toggle, client->GetCharacterID());
  4923. }
  4924. }
  4925. }
  4926. void WorldDatabase::LoadPlayerStatistics(Player* player, int32 char_id) {
  4927. Query query;
  4928. MYSQL_ROW row;
  4929. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT stat_id, stat_value, stat_date FROM statistics WHERE char_id=%i", char_id);
  4930. while (result && (row = mysql_fetch_row(result))) {
  4931. int32 stat_id = atoi(row[0]);
  4932. sint32 stat_value = atoi(row[1]);
  4933. int32 stat_date = atoi(row[2]);
  4934. player->AddPlayerStatistic(stat_id, stat_value, stat_date);
  4935. }
  4936. }
  4937. void WorldDatabase::WritePlayerStatistic(Player *player, Statistic* stat) {
  4938. if (player && player->GetCharacterID() > 0 && stat) {
  4939. Query query;
  4940. query.RunQuery2(Q_INSERT, "INSERT INTO statistics (char_id, guild_id, stat_id, stat_value, stat_date) VALUES(%i, %i, %i, %i, %i) ON DUPLICATE KEY UPDATE stat_value = %i, stat_date = %i;",
  4941. player->GetCharacterID(), 0, stat->stat_id, stat->stat_value, stat->stat_date,
  4942. stat->stat_value, stat->stat_date);
  4943. }
  4944. }
  4945. void WorldDatabase::LoadServerStatistics()
  4946. {
  4947. Query query;
  4948. MYSQL_ROW row;
  4949. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT stat_id, stat_value, stat_date FROM statistics WHERE char_id=0 AND guild_id=0");
  4950. while (result && (row = mysql_fetch_row(result))) {
  4951. int32 stat_id = atoi(row[0]);
  4952. sint32 stat_value = atoi(row[1]);
  4953. int32 stat_date = atoi(row[2]);
  4954. world.AddServerStatistic(stat_id, stat_value, stat_date);
  4955. LogWrite(INIT__DEBUG, 5, "Stats", "Loading Stat ID %i, value: %i", stat_id, stat_value);
  4956. }
  4957. }
  4958. void WorldDatabase::WriteServerStatistic(Statistic* stat) {
  4959. if (stat) {
  4960. Query query;
  4961. query.RunQuery2(Q_INSERT, "INSERT INTO statistics (char_id, guild_id, stat_id, stat_value, stat_date) VALUES(0, 0, %i, %i, %i) ON DUPLICATE KEY UPDATE stat_value = %i, stat_date = %i;",
  4962. stat->stat_id, stat->stat_value, stat->stat_date,
  4963. stat->stat_value, stat->stat_date);
  4964. }
  4965. }
  4966. void WorldDatabase::WriteServerStatistic(int32 stat_id, sint32 stat_value) {
  4967. Query query;
  4968. query.RunQuery2(Q_INSERT, "INSERT INTO statistics (char_id, guild_id, stat_id, stat_value, stat_date) VALUES(0, 0, %i, %i, %i) ON DUPLICATE KEY UPDATE stat_value = %i, stat_date = %i;",
  4969. stat_id, stat_value, Timer::GetUnixTimeStamp(),
  4970. stat_value, Timer::GetUnixTimeStamp());
  4971. }
  4972. void WorldDatabase::WriteServerStatisticsNeededQueries() {
  4973. Query query1, query2, query3;
  4974. MYSQL_ROW row1, row2, row3;
  4975. // Number of unique accounts
  4976. MYSQL_RES* result1 = query1.RunQuery2(Q_SELECT, "SELECT COUNT(DISTINCT account_id) FROM characters");
  4977. if (result1 && (row1 = mysql_fetch_row(result1)) && row1[0] != NULL)
  4978. WriteServerStatistic(STAT_SERVER_NUM_ACCOUNTS, atoi(row1[0]));
  4979. else
  4980. WriteServerStatistic(STAT_SERVER_NUM_ACCOUNTS, 0);
  4981. // Number of characters
  4982. MYSQL_RES* result2 = query2.RunQuery2(Q_SELECT, "SELECT COUNT(id) FROM characters");
  4983. if (result2 && (row2 = mysql_fetch_row(result2)) && row2[0] != NULL)
  4984. WriteServerStatistic(STAT_SERVER_NUM_CHARACTERS, atoi(row2[0]));
  4985. else
  4986. WriteServerStatistic(STAT_SERVER_NUM_CHARACTERS, 0);
  4987. // Average character level
  4988. MYSQL_RES* result3 = query3.RunQuery2(Q_SELECT, "SELECT ROUND(AVG(level)) FROM characters");
  4989. if (result3 && (row3 = mysql_fetch_row(result3)) && row3[0] != NULL)
  4990. WriteServerStatistic(STAT_SERVER_AVG_CHAR_LEVEL, atoi(row3[0]));
  4991. else
  4992. WriteServerStatistic(STAT_SERVER_AVG_CHAR_LEVEL, 0);
  4993. }
  4994. map<int32,int32>* WorldDatabase::GetInstanceRemovedSpawns(int32 instance_id, int8 type)
  4995. {
  4996. DatabaseResult result;
  4997. map<int32,int32>* ret = NULL;
  4998. LogWrite(SPAWN__TRACE, 1, "Spawn", "Enter %s", __FUNCTION__);
  4999. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Loading removed spawns for instance_id: %u, spawn_type: %i", instance_id, type);
  5000. if( !database_new.Select(&result, "SELECT spawn_location_entry_id, respawn_time FROM instance_spawns_removed WHERE instance_id = %i AND spawn_type = %i", instance_id, type) )
  5001. {
  5002. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in GetInstanceRemovedSpawns() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5003. return ret;
  5004. }
  5005. else
  5006. {
  5007. if( result.GetNumRows() > 0 )
  5008. {
  5009. ret = new map<int32,int32>;
  5010. while( result.Next() )
  5011. {
  5012. int32 spawn_location_entry_id = result.GetInt32Str("spawn_location_entry_id");
  5013. /*
  5014. respawnTime == 0 - never respawn
  5015. respawnTime = 1 - spawn now
  5016. respawnTime > 1 (continue timer)
  5017. */
  5018. int32 respawntime = result.GetInt32Str("respawn_time");
  5019. LogWrite(INSTANCE__DEBUG, 5, "Instance", "Found spawn point: %u, respawn time: %i", spawn_location_entry_id, respawntime);
  5020. ret->insert(make_pair(spawn_location_entry_id, respawntime));
  5021. }
  5022. }
  5023. else
  5024. LogWrite(INSTANCE__DEBUG, 0, "Instance", "No removed spawns found for instance_id: %u, spawn_type: %i", instance_id, type);
  5025. }
  5026. LogWrite(SPAWN__TRACE, 1, "Spawn", "Exit %s", __FUNCTION__);
  5027. return ret;
  5028. }
  5029. bool WorldDatabase::CheckVectorForValue(vector<int32>* vector, int32 value) {
  5030. if ( vector != NULL )
  5031. {
  5032. for(int32 i=0;i<vector->size();i++)
  5033. {
  5034. int32 compare = vector->at(i);
  5035. if ( compare == value )
  5036. return true;
  5037. }
  5038. }
  5039. return false;
  5040. }
  5041. int32 WorldDatabase::CheckSpawnRemoveInfo(map<int32,int32>* inmap, int32 spawn_location_entry_id)
  5042. {
  5043. LogWrite(SPAWN__TRACE, 0, "Spawn", "Enter %s", __FUNCTION__);
  5044. map<int32, int32>::iterator iter;
  5045. if ( inmap != NULL )
  5046. {
  5047. for(iter=inmap->begin();iter!=inmap->end();iter++)
  5048. {
  5049. if ( iter->first == spawn_location_entry_id )
  5050. return (int32)iter->second;
  5051. }
  5052. }
  5053. return 1;
  5054. }
  5055. int32 WorldDatabase::AddCharacterInstance(int32 char_id, int32 instance_id, string zone_name, int8 instance_type, int32 last_success, int32 last_failure, int32 success_lockout, int32 failure_lockout)
  5056. {
  5057. int32 ret = 0;
  5058. if( !database_new.Query("INSERT INTO character_instances (char_id, instance_id, instance_zone_name, instance_type, last_success_timestamp, last_failure_timestamp, success_lockout_time, failure_lockout_time) VALUES (%u, %u, '%s', %i, %u, %u, %u, %u) ", char_id, instance_id, database_new.EscapeStr(zone_name).c_str(), instance_type, last_success, last_failure, success_lockout, failure_lockout) )
  5059. {
  5060. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in AddCharacterInstance() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5061. return 0;
  5062. }
  5063. ret = database_new.LastInsertID();
  5064. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Adding character %u to instance: %u", char_id, instance_id);
  5065. //LogWrite(INSTANCE__DEBUG, 1, "Instance", "-- Reenter: %u, Reset: %u, Lockout: %u", grant_reenter_time_left, grant_reset_time_left, lockout_time);
  5066. return ret;
  5067. }
  5068. bool WorldDatabase::UpdateCharacterInstanceTimers(int32 char_id, int32 instance_id, int32 lockout_time, int32 reset_time, int32 reenter_time )
  5069. {
  5070. if ( lockout_time > 0 && reset_time > 0 && reenter_time > 0 )
  5071. database_new.Query("UPDATE character_instances SET lockout_time = %i, grant_reset_time_left = %i, grant_reenter_time_left = %i WHERE char_id = %i AND instance_id = %i", lockout_time, reset_time, reenter_time, char_id, instance_id);
  5072. else if ( lockout_time > 0 && reset_time > 0 )
  5073. database_new.Query("UPDATE character_instances SET lockout_time = %i, grant_reset_time_left = %i WHERE char_id = %i AND instance_id = %i", lockout_time, reset_time, char_id, instance_id);
  5074. else if ( reset_time > 0 && reenter_time > 0 )
  5075. database_new.Query("UPDATE character_instances SET grant_reset_time_left = %i, grant_reenter_time_left = %i WHERE char_id = %i AND instance_id = %i",reset_time, reenter_time, char_id, instance_id);
  5076. else if ( lockout_time > 0 && reenter_time > 0 )
  5077. database_new.Query("UPDATE character_instances SET lockout_time = %i, grant_reenter_time_left = %i WHERE char_id = %i AND instance_id = %i", lockout_time, reenter_time, char_id, instance_id);
  5078. else if ( lockout_time > 0 )
  5079. database_new.Query("UPDATE character_instances SET lockout_time = %i WHERE char_id = %i AND instance_id = %i", lockout_time, char_id, instance_id);
  5080. else if ( reset_time > 0 )
  5081. database_new.Query("UPDATE character_instances SET grant_reset_time_left = %i WHERE char_id = %i AND instance_id = %i", reset_time, char_id, instance_id);
  5082. else if ( reenter_time > 0 )
  5083. database_new.Query("UPDATE character_instances SET grant_reenter_time_left = %i WHERE char_id = %i AND instance_id = %i", reenter_time, char_id, instance_id);
  5084. if( database_new.GetError() )
  5085. {
  5086. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in UpdateCharacterInstanceTimers() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5087. return false;
  5088. }
  5089. else
  5090. {
  5091. if ( database_new.AffectedRows() > 0 )
  5092. {
  5093. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Updating instance timers for character %u to instance: %u", char_id, instance_id);
  5094. LogWrite(INSTANCE__DEBUG, 1, "Instance", "-- Reenter: %u, Reset: %u, Lockout: %u", reenter_time, reset_time, lockout_time);
  5095. return true;
  5096. }
  5097. else
  5098. return false;
  5099. }
  5100. }
  5101. bool WorldDatabase::UpdateCharacterInstance(int32 char_id, string zone_name, int32 instance_id, int8 type, int32 timestamp) {
  5102. // type = 1 = success timestamp
  5103. // type = 2 = failure timestamp
  5104. if (instance_id > 0) {
  5105. if (type == 1) {
  5106. database_new.Query("UPDATE character_instances SET instance_id = %u, last_success_timestamp = %u WHERE char_id = %u AND instance_zone_name = '%s'", instance_id, timestamp, char_id, database_new.EscapeStr(zone_name).c_str());
  5107. }
  5108. else if (type == 2) {
  5109. database_new.Query("UPDATE character_instances SET instance_id = %u, last_failure_timestamp = %u WHERE char_id = %u AND instance_zone_name = '%s'", instance_id, timestamp, char_id, database_new.EscapeStr(zone_name).c_str());
  5110. }
  5111. else {
  5112. database_new.Query("UPDATE character_instances SET instance_id = %u WHERE char_id = %u AND instance_zone_name = '%s'", instance_id, char_id, database_new.EscapeStr(zone_name).c_str());
  5113. }
  5114. }
  5115. else {
  5116. if (type == 1) {
  5117. database_new.Query("UPDATE character_instances SET last_success_timestamp = %u WHERE char_id = %u AND instance_zone_name = '%s'", timestamp, char_id, database_new.EscapeStr(zone_name).c_str());
  5118. }
  5119. else if (type == 2) {
  5120. database_new.Query("UPDATE character_instances SET last_failure_timestamp = %u WHERE char_id = %u AND instance_zone_name = '%s'", timestamp, char_id, database_new.EscapeStr(zone_name).c_str());
  5121. }
  5122. }
  5123. if (database_new.GetError()) {
  5124. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in UpdateCharacterInstance() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5125. return false;
  5126. }
  5127. return true;
  5128. }
  5129. bool WorldDatabase::VerifyInstanceID(int32 char_id, int32 instance_id) {
  5130. DatabaseResult result;
  5131. database_new.Select(&result, "SELECT COUNT(id) as num_instances FROM instances WHERE id = %u", instance_id);
  5132. if (result.Next() && result.GetInt32Str("num_instances") == 0) {
  5133. DeleteCharacterFromInstance(char_id, instance_id);
  5134. return false;
  5135. }
  5136. return true;
  5137. }
  5138. bool WorldDatabase::UpdateInstancedSpawnRemoved(int32 spawn_location_entry_id, int32 spawn_type, int32 respawn_time, int32 instance_id )
  5139. {
  5140. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Updating removed spawns for instance_id: %u", instance_id);
  5141. LogWrite(INSTANCE__DEBUG, 1, "Instance", "-- Spawn Location Entry ID: %u, Type: %u, Respawn: %u", spawn_location_entry_id, spawn_type, respawn_time);
  5142. if( !database_new.Query("UPDATE instance_spawns_removed SET respawn_time = %i WHERE spawn_location_entry_id = %i AND spawn_type = %i AND instance_id = %i", respawn_time, spawn_location_entry_id, spawn_type, instance_id) )
  5143. {
  5144. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in UpdateInstancedSpawnRemoved() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5145. return false;
  5146. }
  5147. if ( database_new.AffectedRows() > 0 )
  5148. {
  5149. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Updated removed spawns for instance_id: %u", instance_id);
  5150. return true;
  5151. }
  5152. else
  5153. return false;
  5154. }
  5155. int32 WorldDatabase::CreateNewInstance(int32 zone_id)
  5156. {
  5157. int32 ret = 0;
  5158. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Creating new instance for zone: %u ", zone_id);
  5159. if( !database_new.Query("INSERT INTO instances (zone_id) VALUES (%u)", zone_id) )
  5160. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in CreateNewInstance() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5161. else
  5162. ret = database_new.LastInsertID();
  5163. if( ret > 0 )
  5164. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Created new instance_id %u for zone: %u ", ret, zone_id);
  5165. return ret;
  5166. }
  5167. int32 WorldDatabase::CreateInstanceSpawnRemoved(int32 spawn_location_entry_id, int32 spawn_type, int32 respawn_time, int32 instance_id )
  5168. {
  5169. int32 ret = 0;
  5170. LogWrite(INSTANCE__DEBUG, 3, "Instance", "Creating new instance spawn removed entries for instance_id: %u ", instance_id);
  5171. LogWrite(INSTANCE__DEBUG, 5, "Instance", "-- Spawn Location Entry ID: %u, Type: %u, Respawn: %u", spawn_location_entry_id, spawn_type, respawn_time);
  5172. if( !database_new.Query("INSERT INTO instance_spawns_removed (spawn_location_entry_id, spawn_type, instance_id, respawn_time) values(%u, %u, %u, %u)", spawn_location_entry_id, spawn_type, instance_id, respawn_time) )
  5173. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in CreateInstanceSpawnRemoved() query '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5174. else
  5175. ret = database_new.LastInsertID();
  5176. // potentially spammy, if it calls for every spawn added. Set to level 3 or 5?
  5177. if( ret > 0 )
  5178. LogWrite(INSTANCE__DEBUG, 5, "Instance", "Created new spawn removed entry: %u for instance_id %u", ret, instance_id);
  5179. return ret;
  5180. }
  5181. bool WorldDatabase::DeleteInstance(int32 instance_id)
  5182. {
  5183. if( !database_new.Query("DELETE FROM instances WHERE id = %u", instance_id) )
  5184. {
  5185. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in DeleteInstance() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5186. return false;
  5187. }
  5188. /* JA: should not need this delete with FK/Constraints
  5189. if( !database_new.Query("DELETE FROM instance_spawns_removed WHERE instance_id = %u", instance_id) )
  5190. {
  5191. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in DeleteInstance() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5192. return false;
  5193. }
  5194. */
  5195. // Remove the instance from the character_instances table
  5196. database_new.Query("UPDATE `character_instances` SET `instance_id` = 0 WHERE `instance_id` = %u", instance_id);
  5197. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Deleted instance_id %u", instance_id);
  5198. return true;
  5199. }
  5200. bool WorldDatabase::DeleteInstanceSpawnRemoved(int32 instance_id, int32 spawn_location_entry_id)
  5201. {
  5202. if( !database_new.Query("DELETE FROM instance_spawns_removed WHERE instance_id = %u AND spawn_location_entry_id = %u", instance_id, spawn_location_entry_id) )
  5203. {
  5204. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in DeleteInstanceSpawnRemoved() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5205. return false;
  5206. }
  5207. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Deleted removed spawn: %u for instance_id %u", spawn_location_entry_id, instance_id);
  5208. return true;
  5209. }
  5210. bool WorldDatabase::DeleteCharacterFromInstance(int32 char_id, int32 instance_id)
  5211. {
  5212. LogWrite(INSTANCE__DEBUG, 0, "Instance", "Delete character %u from instance_id %u.", char_id, instance_id);
  5213. if( !database_new.Query("UPDATE `character_instances` SET `instance_id` = 0 WHERE `instance_id` = %u AND `char_id` = %u", instance_id, char_id) )
  5214. {
  5215. LogWrite(INSTANCE__ERROR, 0, "Instance", "Error in DeleteCharacterFromInstance() '%s': %i", database_new.GetErrorMsg(), database_new.GetError());
  5216. return false;
  5217. }
  5218. if ( database_new.AffectedRows() == 0 ) // didn't find an instance to delete
  5219. {
  5220. LogWrite(INSTANCE__DEBUG, 1, "Instance", "No instance_id %u for character %u to delete.", instance_id, char_id);
  5221. return false;
  5222. }
  5223. else
  5224. {
  5225. // delete entire instance if the last player has left
  5226. DatabaseResult result;
  5227. database_new.Select(&result, "SELECT count(id) as num_instances FROM character_instances where instance_id = %u",instance_id);
  5228. if(result.Next() && result.GetInt32Str("num_instances") == 0)
  5229. {
  5230. LogWrite(INSTANCE__DEBUG, 0, "Instance", "No characters in instance: Delete instance_id %u.", instance_id);
  5231. DeleteInstance(instance_id);
  5232. }
  5233. }
  5234. return true;
  5235. }
  5236. bool WorldDatabase::LoadCharacterInstances(Client* client)
  5237. {
  5238. DatabaseResult result;
  5239. DatabaseResult result2;
  5240. bool addedInstance = false;
  5241. database_new.Select(&result, "SELECT `id`, `instance_id`, `instance_zone_name`, `instance_type`, `last_success_timestamp`, `last_failure_timestamp`, `success_lockout_time`, `failure_lockout_time` FROM `character_instances` WHERE `char_id` = %u", client->GetCharacterID());
  5242. if( result.GetNumRows() > 0 )
  5243. {
  5244. while( result.Next() )
  5245. {
  5246. int32 zone_id = 0;
  5247. int32 instance_id = result.GetInt32Str("instance_id");
  5248. // If `instance_id` is greater then 0 then get the zone id with it, else get the zone id from the zone name
  5249. if (instance_id != 0) {
  5250. if (database_new.Select(&result2, "SELECT `zone_id` FROM `instances` WHERE `id` = %u", instance_id)) {
  5251. if (result2.Next())
  5252. zone_id = result2.GetInt32Str("zone_id");
  5253. }
  5254. }
  5255. if (zone_id == 0)
  5256. zone_id = GetZoneID(result.GetStringStr("instance_zone_name"));
  5257. client->GetPlayer()->GetCharacterInstances()->AddInstance(
  5258. result.GetInt32Str("id"),
  5259. instance_id,
  5260. result.GetInt32Str("last_success_timestamp"),
  5261. result.GetInt32Str("last_failure_timestamp"),
  5262. result.GetInt32Str("success_lockout_time"),
  5263. result.GetInt32Str("failure_lockout_time"),
  5264. zone_id,
  5265. result.GetInt8Str("instance_type"),
  5266. string(result.GetStringStr("instance_zone_name"))
  5267. );
  5268. addedInstance = true;
  5269. }
  5270. }
  5271. return addedInstance;
  5272. }
  5273. void WorldDatabase::UpdateLoginEquipment()
  5274. {
  5275. LogWrite(INIT__LOGIN_DEBUG, 0, "Login", "Updating `character_items` CRC in %s", __FUNCTION__);
  5276. database_new.Query("UPDATE character_items SET login_checksum = CRC32(CRC32(type) + CRC32(slot) + CRC32(item_id)) WHERE `type` = 'EQUIPPED' AND ( slot <= 8 OR slot = 19 )");
  5277. }
  5278. MutexMap<int32, LoginEquipmentUpdate>* WorldDatabase::GetEquipmentUpdates()
  5279. {
  5280. DatabaseResult result;
  5281. MutexMap<int32, LoginEquipmentUpdate>* ret = 0;
  5282. LoginEquipmentUpdate update;
  5283. int32 count = 0;
  5284. LogWrite(INIT__LOGIN_DEBUG, 0, "Login", "Looking for Login Appearance Updates...");
  5285. // TODO: Someday store the equipment colors in character_items, for custom colorization of gear (?)
  5286. if( database_new.Select(&result, "SELECT ci.id, ci.char_id, ia.equip_type, ia.red, ia.green, ia.blue, ia.highlight_red, ia.highlight_green, ia.highlight_blue, ci.slot FROM characters c JOIN character_items ci ON c.id = ci.char_id JOIN item_appearances ia ON ci.item_id = ia.item_id WHERE c.deleted = 0 AND ci.type = 'EQUIPPED' AND ( ci.slot <= 8 OR ci.slot = 19 ) AND ci.login_checksum <> CRC32(CRC32(`ci`.`type`) + CRC32(ci.slot) + CRC32(ci.item_id)) ORDER BY ci.char_id, ci.slot") )
  5287. {
  5288. while( result.Next() )
  5289. {
  5290. LogWrite(INIT__LOGIN_DEBUG, 5, "Login", "Found update for char_id %i!", result.GetInt32Str("char_id"));
  5291. if(!ret)
  5292. ret = new MutexMap<int32, LoginEquipmentUpdate>();
  5293. update.world_char_id = result.GetInt32Str("char_id");
  5294. update.equip_type = result.GetInt16Str("equip_type");
  5295. update.red = result.GetInt8Str("red");
  5296. update.green = result.GetInt8Str("green");
  5297. update.blue = result.GetInt8Str("blue");
  5298. update.highlight_red = result.GetInt8Str("highlight_red");
  5299. update.highlight_green = result.GetInt8Str("highlight_green");
  5300. update.highlight_blue = result.GetInt8Str("highlight_blue");
  5301. update.slot = result.GetInt8Str("slot");
  5302. ret->Put(result.GetInt32Str("id"), update);
  5303. count++;
  5304. }
  5305. }
  5306. if(count)
  5307. LogWrite(INIT__LOGIN_DEBUG, 0, "Login", "Found %i Login Appearance Update%s...", count, count == 1 ? "" : "s");
  5308. return ret;
  5309. }
  5310. MutexMap<int32, LoginEquipmentUpdate>* WorldDatabase::GetEquipmentUpdates(int32 char_id)
  5311. {
  5312. DatabaseResult result;
  5313. MutexMap<int32, LoginEquipmentUpdate>* ret = 0;
  5314. LoginEquipmentUpdate update;
  5315. int32 count = 0;
  5316. LogWrite(INIT__LOGIN_DEBUG, 0, "Login", "Looking for Login Appearance Updates for char_id: %u", char_id);
  5317. // TODO: Someday store the equipment colors in character_items, for custom colorization of gear (?)
  5318. if( database_new.Select(&result, "SELECT ci.id, ci.char_id, ia.equip_type, ia.red, green, ia.blue, ia.highlight_red, ia.highlight_green, ia.highlight_blue, ci.slot FROM characters c JOIN character_items ci ON c.id = ci.char_id JOIN item_appearances ia ON ci.item_id = ia.item_id WHERE c.deleted = 0 AND ci.type = 'EQUIPPED' AND ( ci.slot <= 8 OR ci.slot = 19 ) AND ci.login_checksum <> CRC32(CRC32(ci.type) + CRC32(ci.slot) + CRC32(ci.item_id)) AND ci.char_id = %u ORDER BY ci.slot", char_id) )
  5319. {
  5320. while( result.Next() )
  5321. {
  5322. LogWrite(INIT__LOGIN_DEBUG, 5, "Login", "Found update for char_id %i!", result.GetInt32Str("char_id"));
  5323. if(!ret)
  5324. ret = new MutexMap<int32, LoginEquipmentUpdate>();
  5325. update.world_char_id = char_id;
  5326. update.equip_type = result.GetInt16Str("equip_type");
  5327. update.red = result.GetInt8Str("red");
  5328. update.green = result.GetInt8Str("green");
  5329. update.blue = result.GetInt8Str("blue");
  5330. update.highlight_red = result.GetInt8Str("highlight_red");
  5331. update.highlight_green = result.GetInt8Str("highlight_green");
  5332. update.highlight_blue = result.GetInt8Str("highlight_blue");
  5333. update.slot = result.GetInt8Str("slot");
  5334. ret->Put(result.GetInt32Str("id"), update);
  5335. count++;
  5336. }
  5337. }
  5338. if(count)
  5339. LogWrite(INIT__LOGIN_DEBUG, 0, "Login", "Found %i Login Appearance Update%s...", count, count == 1 ? "" : "s");
  5340. return ret;
  5341. }
  5342. void WorldDatabase::UpdateLoginZones() {
  5343. Query query;
  5344. LogWrite(INIT__LOGIN_DEBUG, 0, "Login", "Updating `zones` CRC in %s", __FUNCTION__);
  5345. query.RunQuery2("UPDATE zones SET login_checksum = CRC32(CRC32(id) + CRC32(`name`) + CRC32(`file`) + CRC32(description))", Q_UPDATE);
  5346. }
  5347. MutexMap<int32, LoginZoneUpdate>* WorldDatabase::GetZoneUpdates() {
  5348. LogWrite(INIT__LOGIN_DEBUG, 0, "Login", "Looking for Login Zone Updates...");
  5349. MutexMap<int32, LoginZoneUpdate>* ret = 0;
  5350. LoginZoneUpdate update;
  5351. Query query;
  5352. MYSQL_ROW row;
  5353. int32 count = 0;
  5354. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, name, description FROM zones where login_checksum != crc32(crc32(id) + crc32(name) + crc32(file) + crc32(description))");
  5355. while(result && (row = mysql_fetch_row(result))) {
  5356. if(row[0] && row[1]) {
  5357. LogWrite(INIT__LOGIN_DEBUG, 5, "Login", "Found update for zone_id %i!", atoi(row[0]));
  5358. if(!ret)
  5359. ret = new MutexMap<int32, LoginZoneUpdate>();
  5360. update.name = string(row[1]);
  5361. if(row[2])
  5362. update.description = string(row[2]);
  5363. else
  5364. update.description = "";
  5365. ret->Put(atoi(row[0]), update);
  5366. count++;
  5367. }
  5368. }
  5369. if(count)
  5370. LogWrite(INIT__LOGIN_DEBUG, 0, "Login", "Found %i Login Zone Update%s...", count, count == 1 ? "" : "s");
  5371. return ret;
  5372. }
  5373. void WorldDatabase::LoadLocationGrids(ZoneServer* zone) {
  5374. if (zone) {
  5375. Query query;
  5376. MYSQL_ROW row;
  5377. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `id`, `grid_id`, `name`, `include_y`, `discovery` FROM `locations` WHERE `zone_id`=%u", zone->GetZoneID());
  5378. while (result && (row = mysql_fetch_row(result))) {
  5379. LocationGrid* grid = new LocationGrid;
  5380. grid->id = atoul(row[0]);
  5381. grid->grid_id = atoul(row[1]);
  5382. grid->name = string(row[2]);
  5383. grid->include_y = (atoi(row[3]) == 1);
  5384. grid->discovery = (atoi(row[4]) == 1);
  5385. if (LoadLocationGridLocations(grid))
  5386. zone->AddLocationGrid(grid);
  5387. else
  5388. safe_delete(grid);
  5389. }
  5390. }
  5391. }
  5392. bool WorldDatabase::LoadLocationGridLocations(LocationGrid* grid) {
  5393. bool ret = false;
  5394. if (grid) {
  5395. Query query;
  5396. int row_count = 0;
  5397. MYSQL_ROW row;
  5398. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `id`, `x`, `y`, `z` FROM `location_details` WHERE `location_id`=%u", grid->id);
  5399. if (result) {
  5400. while (result && (row = mysql_fetch_row(result))) {
  5401. row_count++;
  5402. Location* location = new Location;
  5403. location->id = atoul(row[0]);
  5404. location->x = atof(row[1]);
  5405. location->y = atof(row[2]);
  5406. location->z = atof(row[3]);
  5407. grid->locations.Add(location);
  5408. }
  5409. ret = true;
  5410. }
  5411. if(row_count > 0 && row_count < 3)
  5412. LogWrite(WORLD__WARNING, 0, "World", "Grid '%s' only has %u location(s). A minimum of 3 is needed for a proper location based grid.", grid->name.c_str(), row_count);
  5413. }
  5414. return ret;
  5415. }
  5416. int32 WorldDatabase::CreateLocation(int32 zone_id, int32 grid_id, const char* name, bool include_y) {
  5417. int32 ret = 0;
  5418. if (name && strlen(name) > 0) {
  5419. Query query;
  5420. query.RunQuery2(Q_INSERT, "INSERT INTO `locations` (`zone_id`, `grid_id`, `name`, `include_y`) VALUES (%u, %u, '%s', %u)", zone_id, grid_id, name, include_y == true ? 1 : 0);
  5421. ret = query.GetLastInsertedID();
  5422. }
  5423. return ret;
  5424. }
  5425. bool WorldDatabase::AddLocationPoint(int32 location_id, float x, float y, float z) {
  5426. bool ret = false;
  5427. if (LocationExists(location_id)) {
  5428. Query query;
  5429. query.RunQuery2(Q_INSERT, "INSERT INTO `location_details` (`location_id`, `x`, `y`, `z`) VALUES (%u, %f, %f, %f)", location_id, x, y, z);
  5430. ret = true;
  5431. }
  5432. return ret;
  5433. }
  5434. bool WorldDatabase::DeleteLocation(int32 location_id) {
  5435. bool ret = false;
  5436. if (LocationExists(location_id)) {
  5437. Query query;
  5438. query.RunQuery2(Q_DELETE, "DELETE FROM `locations` WHERE `id`=%u", location_id);
  5439. ret = true;
  5440. }
  5441. return ret;
  5442. }
  5443. bool WorldDatabase::DeleteLocationPoint(int32 location_point_id) {
  5444. Query query;
  5445. query.RunQuery2(Q_DELETE, "DELETE FROM `location_details` WHERE `id`=%u", location_point_id);
  5446. return true;
  5447. }
  5448. void WorldDatabase::ListLocations(Client* client) {
  5449. if (client) {
  5450. Query query;
  5451. MYSQL_ROW row;
  5452. client->SimpleMessage(CHANNEL_COLOR_YELLOW, "Listing all locations:");
  5453. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `id`, `zone_id`, `grid_id`, `name` FROM `locations`");
  5454. while (result && (row = mysql_fetch_row(result))) {
  5455. int32 id = atoul(row[0]);
  5456. int32 zone_id = atoul(row[1]);
  5457. int32 grid_id = atoul(row[2]);
  5458. const char* name = row[3];
  5459. client->Message(CHANNEL_COLOR_YELLOW, "%u) Zone ID: %u Grid ID:%u Name: '%s'", id, zone_id, grid_id, name);
  5460. }
  5461. }
  5462. }
  5463. void WorldDatabase::ListLocationPoints(Client* client, int32 location_id) {
  5464. if (client) {
  5465. if (LocationExists(location_id)) {
  5466. Query query;
  5467. client->Message(CHANNEL_COLOR_YELLOW, "Listing all points for location ID %u:", location_id);
  5468. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `id`, `x`, `y`, `z` FROM `location_details` WHERE `location_id`=%u", location_id);
  5469. MYSQL_ROW row;
  5470. while (result && (row = mysql_fetch_row(result))) {
  5471. int32 id = atoul(row[0]);
  5472. float x = atof(row[1]);
  5473. float y = atof(row[2]);
  5474. float z = atof(row[3]);
  5475. client->Message(CHANNEL_COLOR_YELLOW, "%u) (%f, %f, %f)", id, x, y, z);
  5476. }
  5477. }
  5478. else
  5479. client->Message(CHANNEL_COLOR_YELLOW, "A location with ID %u does not exist", location_id);
  5480. }
  5481. }
  5482. bool WorldDatabase::LocationExists(int32 location_id) {
  5483. bool ret = false;
  5484. Query query;
  5485. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT COUNT(id) FROM `locations` WHERE `id`=%u", location_id);
  5486. MYSQL_ROW row;
  5487. if (result && (row = mysql_fetch_row(result))) {
  5488. if (atoul(row[0]) > 0)
  5489. ret = true;
  5490. }
  5491. return ret;
  5492. }
  5493. bool WorldDatabase::QueriesFromFile(const char * file) {
  5494. return database_new.QueriesFromFile(file);
  5495. }
  5496. bool WorldDatabase::CheckBannedIPs(const char* loginIP)
  5497. {
  5498. // til you build the table, all IPs are allowed
  5499. return false;
  5500. }
  5501. sint32 WorldDatabase::AddMasterTitle(const char* titleName, int8 isPrefix)
  5502. {
  5503. if(titleName == nullptr || strlen(titleName) < 1)
  5504. {
  5505. LogWrite(DATABASE__ERROR, 0, "DBNew", "AddMasterTitle called with missing titleName");
  5506. return -1;
  5507. }
  5508. Query query;
  5509. Title* title = master_titles_list.GetTitleByName(titleName);
  5510. if(title)
  5511. return title->GetID();
  5512. query.RunQuery2(Q_INSERT, "INSERT INTO titles set title='%s', prefix=%u", titleName, isPrefix);
  5513. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  5514. LogWrite(DATABASE__ERROR, 0, "Database", "Error in AddMasterTitle query '%s': %s", query.GetQuery(), query.GetError());
  5515. return false;
  5516. }
  5517. int32 last_insert_id = query.GetLastInsertedID();
  5518. if(last_insert_id > 0)
  5519. {
  5520. title = new Title;
  5521. title->SetID(last_insert_id);
  5522. title->SetName(titleName);
  5523. title->SetPrefix(isPrefix);
  5524. master_titles_list.AddTitle(title);
  5525. return (sint32)last_insert_id;
  5526. }
  5527. return -1;
  5528. }
  5529. void WorldDatabase::LoadTitles(){
  5530. Query query;
  5531. MYSQL_ROW row;
  5532. int32 count = 0;
  5533. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, title, prefix FROM titles");
  5534. if(result && mysql_num_rows(result) > 0){
  5535. Title* title = 0;
  5536. while(result && (row = mysql_fetch_row(result))){
  5537. sint32 idx = atoi(row[0]);
  5538. LogWrite(WORLD__DEBUG, 5, "World", "\tLoading Title '%s' (%u), Prefix: %i, Index: %u", row[1], idx, atoi(row[2]), count);
  5539. title = new Title;
  5540. title->SetID(idx);
  5541. title->SetName(row[1]);
  5542. title->SetPrefix(atoi(row[2]));
  5543. master_titles_list.AddTitle(title);
  5544. count++;
  5545. }
  5546. }
  5547. LogWrite(WORLD__DEBUG, 0, "World", "\tLoaded %u Title%s", count, count == 1 ? "" : "s");
  5548. }
  5549. sint32 WorldDatabase::LoadCharacterTitles(int32 char_id, Player *player){
  5550. LogWrite(WORLD__DEBUG, 0, "World", "Loading Titles for player '%s'...", player->GetName());
  5551. Query query;
  5552. MYSQL_ROW row;
  5553. sint32 index = 0;
  5554. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT title_id, title, prefix FROM character_titles, titles WHERE character_titles.title_id = titles.id AND character_titles.char_id = %u", char_id);
  5555. if(result && mysql_num_rows(result) > 0){
  5556. while(result && (row = mysql_fetch_row(result))){
  5557. LogWrite(WORLD__DEBUG, 5, "World", "\tLoading Title ID: %u, Title: '%s' Index: %u", atoul(row[0]), row[1], index);
  5558. player->AddTitle(index, row[1], atoi(row[2]));
  5559. index++;
  5560. }
  5561. }
  5562. return index;
  5563. }
  5564. sint32 WorldDatabase::GetCharPrefixIndex(int32 char_id, Player *player){
  5565. LogWrite(PLAYER__DEBUG, 0, "Player", "Getting current title index for player '%s'...", player->GetName());
  5566. Query query;
  5567. MYSQL_ROW row;
  5568. sint32 ret = 0;
  5569. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT prefix_title FROM character_details WHERE char_id = %u", char_id);
  5570. if(result && mysql_num_rows(result) > 0)
  5571. while(result && (row = mysql_fetch_row(result))){
  5572. ret = atoi(row[0]);
  5573. LogWrite(PLAYER__DEBUG, 5, "Player", "\tPrefix Index: %i", ret);
  5574. }
  5575. return ret;
  5576. }
  5577. sint32 WorldDatabase::GetCharSuffixIndex(int32 char_id, Player *player){
  5578. LogWrite(PLAYER__DEBUG, 0, "Player", "Getting current title index for player '%s'...", player->GetName());
  5579. Query query;
  5580. MYSQL_ROW row;
  5581. sint32 ret = 0;
  5582. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT suffix_title FROM character_details WHERE char_id = %u", char_id);
  5583. if(result && mysql_num_rows(result) > 0)
  5584. while(result && (row = mysql_fetch_row(result))){
  5585. ret = atoi(row[0]);
  5586. LogWrite(PLAYER__DEBUG, 5, "Player", "\tSuffix Index: %i", ret);
  5587. }
  5588. return ret;
  5589. }
  5590. void WorldDatabase::SaveCharPrefixIndex(sint32 index, int32 char_id){
  5591. Query query;
  5592. query.RunQuery2(Q_UPDATE, "UPDATE character_details SET prefix_title = %i WHERE char_id = %u", index, char_id);
  5593. LogWrite(PLAYER__DEBUG, 0, "Player", "Saving Prefix Index %i for character id '%u'...", index, char_id);
  5594. }
  5595. void WorldDatabase::SaveCharSuffixIndex(sint32 index, int32 char_id){
  5596. Query query;
  5597. query.RunQuery2(Q_SELECT, "UPDATE character_details SET suffix_title = %i WHERE char_id = %u", index, char_id);
  5598. LogWrite(PLAYER__DEBUG, 0, "Player", "Saving Suffix Index %i for character id %u...", index, char_id);
  5599. }
  5600. sint32 WorldDatabase::AddCharacterTitle(sint32 index, int32 char_id, Spawn* player) {
  5601. if(!player || !player->IsPlayer())
  5602. {
  5603. LogWrite(DATABASE__ERROR, 0, "DBNew", "AddCharacterTitle spawn is not a player: %s", player ? player->GetName() : "Unset");
  5604. return -1;
  5605. }
  5606. Title* title = master_titles_list.GetTitle(index);
  5607. if(!title)
  5608. {
  5609. LogWrite(DATABASE__ERROR, 0, "DBNew", "AddCharacterTitle title index %u missing from master_titles_list for player: %s (%u)", index, player ? player->GetName() : "Unset", char_id);
  5610. return -1;
  5611. }
  5612. Query query;
  5613. LogWrite(PLAYER__DEBUG, 0, "Player", "Adding titles for char_id: %u, index: %i", char_id, index);
  5614. query.RunQuery2(Q_INSERT, "INSERT IGNORE INTO character_titles (char_id, title_id) VALUES (%u, %i)", char_id, index);
  5615. sint32 curIndex = (sint32)((Player*)player)->GetPlayerTitles()->Size();
  5616. ((Player*)player)->AddTitle(curIndex++, title->GetName(), title->GetPrefix(), title->GetSaveNeeded());
  5617. return curIndex;
  5618. }
  5619. void WorldDatabase::LoadLanguages()
  5620. {
  5621. int32 count = 0;
  5622. Query query;
  5623. MYSQL_ROW row;
  5624. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, language FROM languages");
  5625. if(result && mysql_num_rows(result) > 0)
  5626. {
  5627. Language* language = 0;
  5628. while(result && (row = mysql_fetch_row(result)))
  5629. {
  5630. LogWrite(WORLD__DEBUG, 5, "World", "\tLoading language '%s' , ID: %u", row[1], atoul(row[0]));
  5631. language = new Language;
  5632. language->SetID(atoul(row[0]));
  5633. language->SetName(row[1]);
  5634. master_languages_list.AddLanguage(language);
  5635. count++;
  5636. }
  5637. }
  5638. LogWrite(WORLD__DEBUG, 0, "World", "\tLoaded %u Language%s", count, count == 1 ? "" : "s");
  5639. }
  5640. int32 WorldDatabase::LoadCharacterLanguages(int32 char_id, Player *player)
  5641. {
  5642. LogWrite(WORLD__DEBUG, 0, "World", "Loading Languages for player '%s'...", player->GetName());
  5643. Query query;
  5644. MYSQL_ROW row;
  5645. int32 count = 0;
  5646. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT language_id, language FROM character_languages, languages WHERE character_languages.language_id = languages.id AND character_languages.char_id = %u", char_id);
  5647. if(result && mysql_num_rows(result) > 0)
  5648. {
  5649. while(result && (row = mysql_fetch_row(result)))
  5650. {
  5651. LogWrite(WORLD__DEBUG, 5, "World", "\tLoading Language ID: %u, Language: '%s'", atoul(row[0]), row[1]);
  5652. player->AddLanguage(atoul(row[0]), row[1]);
  5653. count++;
  5654. }
  5655. }
  5656. return count;
  5657. }
  5658. int16 WorldDatabase::GetCharacterCurrentLang(int32 char_id, Player *player)
  5659. {
  5660. LogWrite(PLAYER__DEBUG, 0, "Player", "Getting current language for player '%s'...", player->GetName());
  5661. Query query;
  5662. MYSQL_ROW row;
  5663. int16 ret = 0;
  5664. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT current_language FROM character_details WHERE char_id = %u", char_id);
  5665. if(result && mysql_num_rows(result) > 0)
  5666. while(result && (row = mysql_fetch_row(result)))
  5667. {
  5668. ret = atoi(row[0]);
  5669. LogWrite(PLAYER__DEBUG, 5, "Player", "\tLanguage ID: %i", ret);
  5670. }
  5671. return ret;
  5672. }
  5673. void WorldDatabase::SaveCharacterCurrentLang(int32 id, int32 char_id, Client *client)
  5674. {
  5675. Query query;
  5676. query.RunQuery2(Q_UPDATE, "UPDATE character_details SET current_language = %i WHERE char_id = %u", id, char_id);
  5677. LogWrite(PLAYER__DEBUG, 3, "Player", "Saving current language ID %i for player '%s'...", id, client->GetPlayer()->GetName());
  5678. }
  5679. void WorldDatabase::SaveCharacterLang(int32 char_id, int32 lang_id) {
  5680. if (!database_new.Query("INSERT INTO character_languages (char_id, language_id) VALUES (%u, %u)", char_id, lang_id))
  5681. LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error %u: %s", database_new.GetError(), database_new.GetErrorMsg());
  5682. }
  5683. // JA - this is not used yet, lots more to consider for storing player history
  5684. void WorldDatabase::LoadCharacterHistory(int32 char_id, Player *player)
  5685. {
  5686. DatabaseResult result;
  5687. // Use -1 on type and subtype to turn the enum into an int and make it a 0 index
  5688. if (!database_new.Select(&result, "SELECT type-1, subtype-1, value, value2, location, event_id, event_date FROM character_history WHERE char_id = %u", char_id)) {
  5689. LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error %u: %s", database_new.GetError(), database_new.GetErrorMsg());
  5690. return;
  5691. }
  5692. while (result.Next()) {
  5693. int8 type = result.GetInt8(0);
  5694. int8 subtype = result.GetInt8(1);
  5695. HistoryData* hd = new HistoryData;
  5696. hd->Value = result.GetInt32(2);
  5697. hd->Value2 = result.GetInt32(3);
  5698. strcpy(hd->Location, result.GetString(4));
  5699. // skipped event id as use for it has not been determined yet
  5700. hd->EventDate = result.GetInt32(6);
  5701. hd->needs_save = false;
  5702. player->LoadPlayerHistory(type, subtype, hd);
  5703. }
  5704. }
  5705. void WorldDatabase::LoadSpellErrors() {
  5706. Query query;
  5707. MYSQL_ROW row;
  5708. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `version`, `error_index`, `value` FROM `spell_error_versions`");
  5709. if (result && mysql_num_rows(result) > 0) {
  5710. while ((row = mysql_fetch_row(result))) {
  5711. master_spell_list.AddSpellError(atoi(row[0]), atoi(row[1]), atoi(row[2]));
  5712. }
  5713. }
  5714. }
  5715. void WorldDatabase::SaveCharacterHistory(Player* player, int8 type, int8 subtype, int32 value, int32 value2, char* location, int32 event_date) {
  5716. string str_type("");
  5717. string str_subtype("");
  5718. switch (type) {
  5719. case HISTORY_TYPE_NONE:
  5720. str_type = "None";
  5721. break;
  5722. case HISTORY_TYPE_DEATH:
  5723. str_type = "Death";
  5724. break;
  5725. case HISTORY_TYPE_DISCOVERY:
  5726. str_type = "Discovery";
  5727. break;
  5728. case HISTORY_TYPE_XP:
  5729. str_type = "XP";
  5730. break;
  5731. default:
  5732. LogWrite(PLAYER__ERROR, 0, "Player", "WorldDatabase::SaveCharacterHistory() - Invalid history type given (%i) with subtype (%i), character history NOT saved.", type, subtype);
  5733. return;
  5734. }
  5735. switch (subtype) {
  5736. case HISTORY_SUBTYPE_NONE:
  5737. str_subtype = "None";
  5738. break;
  5739. case HISTORY_SUBTYPE_ADVENTURE:
  5740. str_subtype = "Adventure";
  5741. break;
  5742. case HISTORY_SUBTYPE_TRADESKILL:
  5743. str_subtype = "Tradeskill";
  5744. break;
  5745. case HISTORY_SUBTYPE_QUEST:
  5746. str_subtype = "Quest";
  5747. break;
  5748. case HISTORY_SUBTYPE_AA:
  5749. str_subtype = "AA";
  5750. break;
  5751. case HISTORY_SUBTYPE_ITEM:
  5752. str_subtype = "Item";
  5753. break;
  5754. case HISTORY_SUBTYPE_LOCATION:
  5755. str_subtype = "Location";
  5756. break;
  5757. default:
  5758. LogWrite(PLAYER__ERROR, 0, "Player", "WorldDatabase::SaveCharacterHistory() - Invalid history sub type given (%i) with type (%i), character history NOT saved.", subtype, type);
  5759. return;
  5760. }
  5761. LogWrite(PLAYER__DEBUG, 1, "Player", "Saving character history, type = %s (%i) subtype = %s (%i)", (char*)str_type.c_str(), type, (char*)str_subtype.c_str(), subtype);
  5762. Query query;
  5763. query.AddQueryAsync(player->GetCharacterID(), this, Q_REPLACE, "replace into character_history (char_id, type, subtype, value, value2, location, event_date) values (%u, '%s', '%s', %i, %i, '%s', %u)",
  5764. player->GetCharacterID(), str_type.c_str(), str_subtype.c_str(), value, value2, getSafeEscapeString(location).c_str(), event_date);
  5765. }
  5766. void WorldDatabase::LoadTransportMaps(ZoneServer* zone) {
  5767. int32 total = 0;
  5768. LogWrite(TRANSPORT__DEBUG, 0, "Transport", "-Loading Transporter Maps...");
  5769. zone->DeleteTransporterMaps();
  5770. Query query;
  5771. MYSQL_ROW row;
  5772. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT `transport_id`, `map_name` FROM `transport_maps`");
  5773. if(result) {
  5774. while(result && (row = mysql_fetch_row(result))){
  5775. zone->AddTransportMap(atoul(row[0]), string(row[1]));
  5776. total++;
  5777. }
  5778. }
  5779. LogWrite(TRANSPORT__DEBUG, 0, "Transport", "--Loaded %i Transporter Maps", total);
  5780. }
  5781. bool WorldDatabase::LoadSign(ZoneServer* zone, int32 spawn_id) {
  5782. Sign* sign = 0;
  5783. int32 id = 0;
  5784. DatabaseResult result;
  5785. database_new.Select(&result, "SELECT ss.spawn_id, s.name, s.model_type, s.size, s.show_command_icon, ss.widget_id, ss.widget_x, ss.widget_y, ss.widget_z, s.command_primary, s.command_secondary, s.collision_radius, ss.icon, ss.type, ss.title, ss.description, ss.sign_distance, ss.zone_id, ss.zone_x, ss.zone_y, ss.zone_z, ss.zone_heading, ss.include_heading, ss.include_location, s.transport_id, s.size_offset, s.display_hand_icon, s.visual_state, s.disable_sounds, s.merchant_min_level, s.merchant_max_level, s.aaxp_rewards, s.loot_tier, s.loot_drop_type, ss.language\n"
  5786. "FROM spawn s\n"
  5787. "INNER JOIN spawn_signs ss\n"
  5788. "ON ss.spawn_id = s.id\n"
  5789. "WHERE s.id = %u\n",
  5790. spawn_id);
  5791. if (result.GetNumRows() > 0 && result.Next()) {
  5792. id = result.GetInt32(0);
  5793. sign = new Sign();
  5794. sign->SetDatabaseID(id);
  5795. strcpy(sign->appearance.name, result.GetString(1));
  5796. sign->appearance.model_type = result.GetInt16(2);
  5797. sign->SetSize(result.GetInt16(3));
  5798. sign->appearance.show_command_icon = result.GetInt8(4);
  5799. sign->SetWidgetID(result.GetInt32(5));
  5800. sign->SetWidgetX(result.GetFloat(6));
  5801. sign->SetWidgetY(result.GetFloat(7));
  5802. sign->SetWidgetZ(result.GetFloat(8));
  5803. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(result.GetInt32(9));
  5804. if(primary_command_list){
  5805. sign->SetPrimaryCommands(primary_command_list);
  5806. sign->primary_command_list_id = result.GetInt32(9);
  5807. }
  5808. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(result.GetInt32(10));
  5809. if (secondary_command_list) {
  5810. sign->SetSecondaryCommands(secondary_command_list);
  5811. sign->secondary_command_list_id = result.GetInt32(10);
  5812. }
  5813. sign->appearance.pos.collision_radius = result.GetInt16(11);
  5814. sign->SetSignIcon(result.GetInt8(12));
  5815. if(strncasecmp(result.GetString(13), "Generic", 7) == 0)
  5816. sign->SetSignType(SIGN_TYPE_GENERIC);
  5817. else if(strncasecmp(result.GetString(13), "Zone", 4) == 0)
  5818. sign->SetSignType(SIGN_TYPE_ZONE);
  5819. sign->SetSignTitle(result.GetString(14));
  5820. sign->SetSignDescription(result.GetString(15));
  5821. sign->SetSignDistance(result.GetFloat(16));
  5822. sign->SetSignZoneID(result.GetInt32(17));
  5823. sign->SetSignZoneX(result.GetFloat(18));
  5824. sign->SetSignZoneY(result.GetFloat(19));
  5825. sign->SetSignZoneZ(result.GetFloat(20));
  5826. sign->SetSignZoneHeading(result.GetFloat(21));
  5827. sign->SetIncludeHeading(result.GetInt8(22) == 1);
  5828. sign->SetIncludeLocation(result.GetInt8(23) == 1);
  5829. sign->SetTransporterID(result.GetInt32(24));
  5830. sign->SetSizeOffset(result.GetInt8(25));
  5831. sign->appearance.display_hand_icon = result.GetInt8(26);
  5832. sign->SetVisualState(result.GetInt16(27));
  5833. sign->SetSoundsDisabled(result.GetInt8(28));
  5834. sign->SetMerchantLevelRange(result.GetInt32(29), result.GetInt32(30));
  5835. sign->SetAAXPRewards(result.GetInt32(31));
  5836. sign->SetLootTier(result.GetInt32(32));
  5837. sign->SetLootDropType(result.GetInt32(33));
  5838. sign->SetLanguage(result.GetInt8(34));
  5839. zone->AddSign(id, sign);
  5840. LogWrite(SIGN__DEBUG, 0, "Sign", "Loaded Sign: '%s' (%u).", sign->appearance.name, spawn_id);
  5841. return true;
  5842. }
  5843. LogWrite(SIGN__DEBUG, 0, "Sign", "Unable to find a sign for spawn id of %u", spawn_id);
  5844. return false;
  5845. }
  5846. bool WorldDatabase::LoadWidget(ZoneServer* zone, int32 spawn_id) {
  5847. Widget* widget = 0;
  5848. int32 id = 0;
  5849. DatabaseResult result;
  5850. database_new.Select(&result, "SELECT sw.spawn_id, s.name, s.model_type, s.size, s.show_command_icon, sw.widget_id, sw.widget_x, sw.widget_y, sw.widget_z, s.command_primary, s.command_secondary, s.collision_radius, sw.include_heading, sw.include_location, sw.icon, sw.type, sw.open_heading, sw.open_y, sw.action_spawn_id, sw.open_sound_file, sw.close_sound_file, sw.open_duration, sw.closed_heading, sw.linked_spawn_id, sw.close_y, s.transport_id, s.size_offset, sw.house_id, sw.open_x, sw.open_z, sw.close_x, sw.close_z, s.display_hand_icon, s.disable_sounds, s.merchant_min_level, s.merchant_max_level, s.aaxp_rewards, s.loot_tier, s.loot_drop_type\n"
  5851. "FROM spawn s\n"
  5852. "INNER JOIN spawn_widgets sw\n"
  5853. "ON sw.spawn_id = s.id\n"
  5854. "WHERE s.id = %u",
  5855. spawn_id);
  5856. if (result.GetNumRows() > 0 && result.Next()) {
  5857. id = result.GetInt32(0);
  5858. widget = new Widget();
  5859. widget->SetDatabaseID(id);
  5860. strcpy(widget->appearance.name, result.GetString(1));
  5861. widget->appearance.model_type = result.GetInt16(2);
  5862. widget->SetSize(result.GetInt16(3));
  5863. widget->appearance.show_command_icon = result.GetInt8(4);
  5864. widget->SetWidgetID(result.GetInt32(5));
  5865. widget->SetWidgetX(result.GetFloat(6));
  5866. widget->SetWidgetY(result.GetFloat(7));
  5867. widget->SetWidgetZ(result.GetFloat(8));
  5868. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(result.GetInt32(9));
  5869. if(primary_command_list){
  5870. widget->SetPrimaryCommands(primary_command_list);
  5871. widget->primary_command_list_id = result.GetInt32(9);
  5872. }
  5873. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(result.GetInt32(10));
  5874. if (secondary_command_list) {
  5875. widget->SetSecondaryCommands(secondary_command_list);
  5876. widget->secondary_command_list_id = result.GetInt32(10);
  5877. }
  5878. widget->appearance.pos.collision_radius = result.GetInt16(11);
  5879. widget->SetIncludeHeading(result.GetInt8(12) == 1);
  5880. widget->SetIncludeLocation(result.GetInt8(13) == 1);
  5881. widget->SetWidgetIcon(result.GetInt8(14));
  5882. if(strncasecmp(result.GetString(15),"Generic", 7) == 0)
  5883. widget->SetWidgetType(WIDGET_TYPE_GENERIC);
  5884. else if(strncasecmp(result.GetString(15),"Door", 4) == 0)
  5885. widget->SetWidgetType(WIDGET_TYPE_DOOR);
  5886. widget->SetOpenHeading(result.GetFloat(16));
  5887. widget->SetOpenY(result.GetFloat(17));
  5888. widget->SetActionSpawnID(result.GetInt32(18));
  5889. if(!result.IsNull(19) && strlen(result.GetString(19)) > 5)
  5890. widget->SetOpenSound(result.GetString(19));
  5891. if(!result.IsNull(20) && strlen(result.GetString(20)) > 5)
  5892. widget->SetCloseSound(result.GetString(20));
  5893. widget->SetOpenDuration(result.GetInt16(21));
  5894. widget->SetClosedHeading(result.GetFloat(22));
  5895. widget->SetLinkedSpawnID(result.GetInt32(23));
  5896. widget->SetCloseY(result.GetFloat(24));
  5897. widget->SetTransporterID(result.GetInt32(25));
  5898. widget->SetSizeOffset(result.GetInt8(26));
  5899. widget->SetHouseID(result.GetInt32(27));
  5900. widget->SetOpenX(result.GetFloat(28));
  5901. widget->SetOpenZ(result.GetFloat(29));
  5902. widget->SetCloseX(result.GetFloat(30));
  5903. widget->SetCloseZ(result.GetFloat(31));
  5904. widget->appearance.display_hand_icon = result.GetInt8(32);
  5905. widget->SetSoundsDisabled(result.GetInt8(33));
  5906. widget->SetMerchantLevelRange(result.GetInt32(34), result.GetInt32(35));
  5907. widget->SetAAXPRewards(result.GetInt32(36));
  5908. widget->SetLootTier(result.GetInt32(37));
  5909. widget->SetLootDropType(result.GetInt32(38));
  5910. zone->AddWidget(id, widget);
  5911. LogWrite(WIDGET__DEBUG, 0, "Widget", "Loaded Widget: '%s' (%u).", widget->appearance.name, spawn_id);
  5912. return true;
  5913. }
  5914. LogWrite(WIDGET__DEBUG, 0, "Widget", "Unable to find a widget for spawn id of %u", spawn_id);
  5915. return false;
  5916. }
  5917. bool WorldDatabase::LoadObject(ZoneServer* zone, int32 spawn_id) {
  5918. Object* object = 0;
  5919. int32 id = 0;
  5920. DatabaseResult result;
  5921. database_new.Select(&result, "SELECT so.spawn_id, s.name, s.race, s.model_type, s.command_primary, s.command_secondary, s.targetable, s.size, s.show_name, s.visual_state, s.attackable, s.show_level, s.show_command_icon, s.display_hand_icon, s.faction_id, s.collision_radius, s.transport_id, s.size_offset, so.device_id, s.disable_sounds, s.merchant_min_level, s.merchant_max_level, s.aaxp_rewards, s.loot_tier, s.loot_drop_type\n"
  5922. "FROM spawn s\n"
  5923. "INNER JOIN spawn_objects so\n"
  5924. "ON so.spawn_id = s.id\n"
  5925. "WHERE s.id = %u",
  5926. spawn_id);
  5927. if (result.GetNumRows() > 0 && result.Next()) {
  5928. id = result.GetInt32(0);
  5929. object = new Object();
  5930. object->SetDatabaseID(id);
  5931. strcpy(object->appearance.name, result.GetString(1));
  5932. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(result.GetInt32(4));
  5933. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(result.GetInt32(5));
  5934. if(primary_command_list){
  5935. object->SetPrimaryCommands(primary_command_list);
  5936. object->primary_command_list_id = result.GetInt32(4);
  5937. }
  5938. if(secondary_command_list){
  5939. object->SetSecondaryCommands(secondary_command_list);
  5940. object->secondary_command_list_id = result.GetInt32(5);
  5941. }
  5942. object->appearance.race = result.GetInt8(2);
  5943. object->appearance.model_type = result.GetInt16(3);
  5944. object->appearance.targetable = result.GetInt8(6);
  5945. object->size = result.GetInt16(7);
  5946. object->appearance.display_name = result.GetInt8(8);
  5947. object->appearance.visual_state = result.GetInt16(9);
  5948. object->appearance.attackable = result.GetInt8(10);
  5949. object->appearance.show_level = result.GetInt8(11);
  5950. object->appearance.show_command_icon = result.GetInt8(12);
  5951. object->appearance.display_hand_icon = result.GetInt8(13);
  5952. object->faction_id = result.GetInt32(14);
  5953. object->appearance.pos.collision_radius = result.GetInt16(15);
  5954. object->SetTransporterID(result.GetInt32(16));
  5955. object->SetSizeOffset(result.GetInt8(17));
  5956. object->SetDeviceID(result.GetInt8(18));
  5957. object->SetSoundsDisabled(result.GetInt8(19));
  5958. object->SetMerchantLevelRange(result.GetInt32(20), result.GetInt32(21));
  5959. object->SetAAXPRewards(result.GetInt32(22));
  5960. object->SetLootTier(result.GetInt32(23));
  5961. object->SetLootDropType(result.GetInt32(24));
  5962. zone->AddObject(id, object);
  5963. LogWrite(OBJECT__DEBUG, 0, "Object", "Loaded Object: '%s' (%u).", object->appearance.name, spawn_id);
  5964. return true;
  5965. }
  5966. LogWrite(OBJECT__DEBUG, 0, "Object", "Unable to find an object for spawn id of %u", spawn_id);
  5967. return false;
  5968. }
  5969. bool WorldDatabase::LoadGroundSpawn(ZoneServer* zone, int32 spawn_id) {
  5970. GroundSpawn* spawn = 0;
  5971. int32 id = 0;
  5972. DatabaseResult result;
  5973. database_new.Select(&result, "SELECT sg.spawn_id, s.name, s.race, s.model_type, s.command_primary, s.command_secondary, s.targetable, s.size, s.show_name, s.visual_state, s.attackable, s.show_level, s.show_command_icon, s.display_hand_icon, s.faction_id, s.collision_radius, sg.number_harvests, sg.num_attempts_per_harvest, sg.groundspawn_id, sg.collection_skill, s.size_offset, s.disable_sounds, s.aaxp_rewards, s.loot_tier, s.loot_drop_type, sg.randomize_heading\n"
  5974. "FROM spawn s\n"
  5975. "INNER JOIN spawn_ground sg\n"
  5976. "ON sg.spawn_id = s.id\n"
  5977. "WHERE s.id = %u",
  5978. spawn_id);
  5979. if (result.GetNumRows() > 0 && result.Next()) {
  5980. id = result.GetInt32(0);
  5981. spawn = new GroundSpawn();
  5982. spawn->SetDatabaseID(id);
  5983. strcpy(spawn->appearance.name, result.GetString(1));
  5984. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(result.GetInt32(4));
  5985. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(result.GetInt32(5));
  5986. if(primary_command_list){
  5987. spawn->SetPrimaryCommands(primary_command_list);
  5988. spawn->primary_command_list_id = result.GetInt32(4);
  5989. }
  5990. if(secondary_command_list){
  5991. spawn->SetSecondaryCommands(secondary_command_list);
  5992. spawn->secondary_command_list_id = result.GetInt32(5);
  5993. }
  5994. spawn->appearance.race = result.GetInt8(2);
  5995. spawn->appearance.model_type = result.GetInt16(3);
  5996. spawn->appearance.targetable = result.GetInt8(6);
  5997. spawn->size = result.GetInt16(7);
  5998. spawn->appearance.display_name = result.GetInt8(8);
  5999. spawn->appearance.visual_state = result.GetInt16(9);
  6000. spawn->appearance.attackable = result.GetInt8(10);
  6001. spawn->appearance.show_level = result.GetInt8(11);
  6002. spawn->appearance.show_command_icon = result.GetInt8(12);
  6003. spawn->appearance.display_hand_icon = result.GetInt8(13);
  6004. spawn->faction_id = result.GetInt32(14);
  6005. spawn->appearance.pos.collision_radius = result.GetInt16(15);
  6006. spawn->SetNumberHarvests(result.GetInt8(16));
  6007. spawn->SetAttemptsPerHarvest(result.GetInt8(17));
  6008. spawn->SetGroundSpawnEntryID(result.GetInt32(18));
  6009. spawn->SetCollectionSkill(result.GetString(19));
  6010. spawn->SetSizeOffset(result.GetInt8(20));
  6011. spawn->SetSoundsDisabled(result.GetInt8(21));
  6012. spawn->SetAAXPRewards(result.GetInt32(22));
  6013. spawn->SetLootTier(result.GetInt32(23));
  6014. spawn->SetLootDropType(result.GetInt32(24));
  6015. spawn->SetRandomizeHeading(result.GetInt32(25));
  6016. zone->AddGroundSpawn(id, spawn);
  6017. if (!zone->GetGroundSpawnEntries(spawn->GetGroundSpawnEntryID()))
  6018. LoadGroundSpawnEntry(zone, spawn->GetGroundSpawnEntryID());
  6019. LogWrite(GROUNDSPAWN__DEBUG, 0, "GSpawn", "Loaded Ground Spawn: '%s' (%u).", spawn->appearance.name, spawn_id);
  6020. return true;
  6021. }
  6022. LogWrite(GROUNDSPAWN__DEBUG, 0, "GSpawn", "Unable to find a ground spawn for spawn id of %u", spawn_id);
  6023. return false;
  6024. }
  6025. void WorldDatabase::LoadGroundSpawnItems(ZoneServer* zone, int32 entry_id) {
  6026. DatabaseResult result;
  6027. database_new.Select(&result, "SELECT item_id, is_rare, grid_id\n"
  6028. "FROM groundspawn_items\n"
  6029. "WHERE groundspawn_id = %u",
  6030. entry_id);
  6031. if (result.GetNumRows() > 0 && result.Next()) {
  6032. zone->AddGroundSpawnItem(entry_id, result.GetInt32(0), result.GetInt8(1), result.GetInt32(2));
  6033. LogWrite(GROUNDSPAWN__DEBUG, 5, "GSpawn", "---Loading GroundSpawn Items: ID: %u\n", entry_id);
  6034. LogWrite(GROUNDSPAWN__DEBUG, 5, "GSpawn", "---item: %ul, rare: %i, grid: %ul", result.GetInt32(0), result.GetInt8(1), result.GetInt32(2));
  6035. }
  6036. }
  6037. void WorldDatabase::LoadGroundSpawnEntry(ZoneServer* zone, int32 entry_id) {
  6038. DatabaseResult result;
  6039. database_new.Select(&result, "SELECT min_skill_level, min_adventure_level, bonus_table, harvest1, harvest3, harvest5, harvest_imbue, harvest_rare, harvest10, harvest_coin\n"
  6040. "FROM groundspawns\n"
  6041. "WHERE enabled = 1 AND groundspawn_id = %u",
  6042. entry_id);
  6043. if (result.GetNumRows() > 0 && result.Next()) {
  6044. // this is getting ridonkulous...
  6045. LogWrite(GROUNDSPAWN__DEBUG, 5, "GSpawn", "---Loading GroundSpawn ID: %u\n" \
  6046. "---min_skill_level: %i, min_adventure_level: %i, bonus_table: %i\n" \
  6047. "---harvest1: %.2f, harvest3: %.2f, harvest5: %.2f\n" \
  6048. "---harvest_imbue: %.2f, harvest_rare: %.2f, harvest10: %.2f\n" \
  6049. "---harvest_coin: %u", entry_id, result.GetInt16(0), result.GetInt16(1), result.GetInt8(2), result.GetFloat(3), result.GetFloat(4), result.GetFloat(5), result.GetFloat(6), result.GetFloat(7), result.GetFloat(8), result.GetInt32(9));
  6050. zone->AddGroundSpawnEntry(entry_id, result.GetInt16(0), result.GetInt16(1), result.GetInt8(2), result.GetFloat(3), result.GetFloat(4), result.GetFloat(5), result.GetFloat(6), result.GetFloat(7), result.GetFloat(8), result.GetInt32(9));
  6051. LoadGroundSpawnItems(zone, entry_id);
  6052. }
  6053. }
  6054. bool WorldDatabase::LoadNPC(ZoneServer* zone, int32 spawn_id) {
  6055. NPC* npc = nullptr;
  6056. int32 id = 0;
  6057. DatabaseResult result;
  6058. database_new.Select(&result, "SELECT npc.spawn_id, s.name, npc.min_level, npc.max_level, npc.enc_level, s.race, s.model_type, npc.class_, npc.gender, s.command_primary, s.command_secondary, s.show_name, npc.min_group_size, npc.max_group_size, npc.hair_type_id, npc.facial_hair_type_id, npc.wing_type_id, npc.chest_type_id, npc.legs_type_id, npc.soga_hair_type_id, npc.soga_facial_hair_type_id, s.attackable, s.show_level, s.targetable, s.show_command_icon, s.display_hand_icon, s.hp, s.power, s.size, s.collision_radius, npc.action_state, s.visual_state, npc.mood_state, npc.initial_state, npc.activity_status, s.faction_id, s.sub_title, s.merchant_id, s.merchant_type, s.size_offset, npc.attack_type, npc.ai_strategy+0, npc.spell_list_id, npc.secondary_spell_list_id, npc.skill_list_id, npc.secondary_skill_list_id, npc.equipment_list_id, npc.str, npc.sta, npc.wis, npc.intel, npc.agi, npc.heat, npc.cold, npc.magic, npc.mental, npc.divine, npc.disease, npc.poison, npc.aggro_radius, npc.cast_percentage, npc.randomize, npc.soga_model_type, npc.heroic_flag, npc.alignment, npc.elemental, npc.arcane, npc.noxious, s.savagery, s.dissonance, npc.hide_hood, npc.emote_state, s.prefix, s.suffix, s.last_name, s.disable_sounds, s.merchant_min_level, s.merchant_max_level, s.aaxp_rewards, s.loot_tier, s.loot_drop_type, npc.scared_by_strong_players, npc.action_state_str\n"
  6059. "FROM spawn s\n"
  6060. "INNER JOIN spawn_npcs npc\n"
  6061. "ON npc.spawn_id = s.id\n"
  6062. "WHERE s.id = %u",
  6063. spawn_id);
  6064. if (result.GetNumRows() > 0 && result.Next()) {
  6065. id = result.GetInt32(0);
  6066. npc = new NPC();
  6067. npc->SetDatabaseID(id);
  6068. strcpy(npc->appearance.name, result.GetString(1));
  6069. vector<EntityCommand*>* primary_command_list = zone->GetEntityCommandList(result.GetInt32(9));
  6070. vector<EntityCommand*>* secondary_command_list = zone->GetEntityCommandList(result.GetInt32(10));
  6071. if(primary_command_list){
  6072. npc->SetPrimaryCommands(primary_command_list);
  6073. npc->primary_command_list_id = result.GetInt32(9);
  6074. }
  6075. if(secondary_command_list){
  6076. npc->SetSecondaryCommands(secondary_command_list);
  6077. npc->secondary_command_list_id = result.GetInt32(10);
  6078. }
  6079. npc->appearance.min_level = result.GetInt8(2);
  6080. npc->appearance.max_level = result.GetInt8(3);
  6081. npc->appearance.level = result.GetInt8(2);
  6082. npc->appearance.difficulty = result.GetInt8(4);
  6083. npc->appearance.race = result.GetInt8(5);
  6084. npc->appearance.model_type = result.GetInt16(6);
  6085. npc->appearance.soga_model_type = result.GetInt16(62);
  6086. npc->appearance.adventure_class = result.GetInt8(7);
  6087. npc->appearance.gender = result.GetInt8(8);
  6088. npc->appearance.display_name = result.GetInt8(11);
  6089. npc->features.hair_type = result.GetInt16(14);
  6090. npc->features.hair_face_type = result.GetInt16(15);
  6091. npc->features.wing_type = result.GetInt16(16);
  6092. npc->features.chest_type = result.GetInt16(17);
  6093. npc->features.legs_type = result.GetInt16(18);
  6094. npc->features.soga_hair_type = result.GetInt16(19);
  6095. npc->features.soga_hair_face_type = result.GetInt16(20);
  6096. npc->appearance.attackable = result.GetInt8(21);
  6097. npc->appearance.show_level = result.GetInt8(22);
  6098. npc->appearance.targetable = result.GetInt8(23);
  6099. npc->appearance.show_command_icon = result.GetInt8(24);
  6100. npc->appearance.display_hand_icon = result.GetInt8(25);
  6101. npc->appearance.hide_hood = result.GetInt8(70);
  6102. npc->appearance.randomize = result.GetInt32(61);
  6103. npc->SetTotalHP(result.GetInt32(26));
  6104. npc->SetTotalPower(result.GetInt32(27));
  6105. npc->SetHP(npc->GetTotalHP());
  6106. npc->SetPower(npc->GetTotalPower());
  6107. if(npc->GetTotalHP() == 0){
  6108. npc->SetTotalHP(15*npc->GetLevel() + 1);
  6109. npc->SetHP(15*npc->GetLevel() + 1);
  6110. }
  6111. if(npc->GetTotalPower() == 0){
  6112. npc->SetTotalPower(15*npc->GetLevel() + 1);
  6113. npc->SetPower(15*npc->GetLevel() + 1);
  6114. }
  6115. npc->size = result.GetInt16(28);
  6116. npc->appearance.pos.collision_radius = result.GetInt16(29);
  6117. npc->appearance.action_state = result.GetInt16(30);
  6118. npc->appearance.visual_state = result.GetInt16(31);
  6119. npc->appearance.mood_state = result.GetInt16(32);
  6120. npc->appearance.emote_state = result.GetInt16(71);
  6121. npc->appearance.pos.state = result.GetInt16(33);
  6122. npc->appearance.activity_status = result.GetInt16(34);
  6123. npc->faction_id = result.GetInt32(35);
  6124. if(!result.IsNull(36)){
  6125. std::string sub_title = std::string(result.GetString(36));
  6126. if(sub_title.find("Collector") != std::string::npos) {
  6127. npc->SetCollector(true);
  6128. }
  6129. if(strlen(result.GetString(36)) < sizeof(npc->appearance.sub_title))
  6130. strcpy(npc->appearance.sub_title, result.GetString(36));
  6131. else
  6132. strncpy(npc->appearance.sub_title, result.GetString(36), sizeof(npc->appearance.sub_title));
  6133. }
  6134. npc->SetMerchantID(result.GetInt32(37));
  6135. npc->SetMerchantType(result.GetInt8(38));
  6136. npc->SetSizeOffset(result.GetInt8(39));
  6137. npc->SetAIStrategy(result.GetInt8(41));
  6138. npc->SetPrimarySpellList(result.GetInt32(42));
  6139. npc->SetSecondarySpellList(result.GetInt32(43));
  6140. npc->SetPrimarySkillList(result.GetInt32(44));
  6141. npc->SetSecondarySkillList(result.GetInt32(45));
  6142. npc->SetEquipmentListID(result.GetInt32(46));
  6143. InfoStruct* info = npc->GetInfoStruct();
  6144. info->set_attack_type(result.GetInt8(40));
  6145. info->set_str_base(result.GetInt16(47));
  6146. info->set_sta_base(result.GetInt16(48));
  6147. info->set_wis_base(result.GetInt16(49));
  6148. info->set_intel_base(result.GetInt16(50));
  6149. info->set_agi_base(result.GetInt16(51));
  6150. info->set_heat_base(result.GetInt16(52));
  6151. info->set_cold_base(result.GetInt16(53));
  6152. info->set_magic_base(result.GetInt16(54));
  6153. info->set_mental_base(result.GetInt16(55));
  6154. info->set_divine_base(result.GetInt16(56));
  6155. info->set_disease_base(result.GetInt16(57));
  6156. info->set_poison_base(result.GetInt16(58));
  6157. info->set_alignment(result.GetSInt8(64));
  6158. npc->SetAggroRadius(result.GetFloat(59));
  6159. npc->SetCastPercentage(result.GetInt8(60));
  6160. npc->appearance.heroic_flag = result.GetInt8(63);
  6161. info->set_elemental_base(result.GetInt16(65));
  6162. info->set_arcane_base(result.GetInt16(66));
  6163. info->set_noxious_base(result.GetInt16(67));
  6164. npc->SetTotalSavagery(result.GetInt32(68));
  6165. npc->SetTotalDissonance(result.GetInt32(69));
  6166. npc->SetSavagery(npc->GetTotalSavagery());
  6167. npc->SetDissonance(npc->GetTotalDissonance());
  6168. if(npc->GetTotalSavagery() == 0){
  6169. npc->SetTotalSavagery(15*npc->GetLevel() + 1);
  6170. npc->SetSavagery(15*npc->GetLevel() + 1);
  6171. }
  6172. if(npc->GetTotalDissonance() == 0){
  6173. npc->SetTotalDissonance(15*npc->GetLevel() + 1);
  6174. npc->SetDissonance(15*npc->GetLevel() + 1);
  6175. }
  6176. npc->SetPrefixTitle(result.GetString(72));
  6177. npc->SetSuffixTitle(result.GetString(73));
  6178. npc->SetLastName(result.GetString(74));
  6179. npc->SetSoundsDisabled(result.GetInt8(75));
  6180. npc->SetMerchantLevelRange(result.GetInt32(76), result.GetInt32(77));
  6181. npc->SetAAXPRewards(result.GetInt32(78));
  6182. npc->SetLootTier(result.GetInt32(79));
  6183. npc->SetLootDropType(result.GetInt32(80));
  6184. npc->SetScaredByStrongPlayers(result.GetInt32(81));
  6185. if(!result.IsNull(82)){
  6186. std::string action_state_str = std::string(result.GetString(82));
  6187. npc->GetInfoStruct()->set_action_state(action_state_str);
  6188. }
  6189. zone->AddNPC(id, npc);
  6190. //skipped spells/skills/equipment as it is all loaded, the following rely on a spawn to load
  6191. LoadAppearance(zone, spawn_id);
  6192. LoadNPCAppearanceEquipmentData(zone, spawn_id);
  6193. LogWrite(NPC__DEBUG, 0, "NPC", "Loaded NPC: '%s' (%u).", npc->appearance.name, spawn_id);
  6194. return true;
  6195. }
  6196. LogWrite(NPC__DEBUG, 0, "NPC", "Unable to find a npc for spawn id of %u", spawn_id);
  6197. return false;
  6198. }
  6199. void WorldDatabase::LoadAppearance(ZoneServer* zone, int32 spawn_id) {
  6200. Entity* entity = zone->GetNPC(spawn_id);
  6201. if (!entity)
  6202. return;
  6203. DatabaseResult result, result2;
  6204. map<string, int8> appearance_types;
  6205. map<int32, map<int8, EQ2_Color> > appearance_colors;
  6206. EQ2_Color color;
  6207. color.red = 0;
  6208. color.green = 0;
  6209. color.blue = 0;
  6210. string type;
  6211. database_new.Select(&result2, "SELECT distinct `type`\n"
  6212. "FROM npc_appearance\n"
  6213. "WHERE length(`type`) > 0 AND `spawn_id` = %u",
  6214. spawn_id);
  6215. while(result2.Next()) {
  6216. type = string(result2.GetString(0));
  6217. appearance_types[type] = GetAppearanceType(type);
  6218. if(appearance_types[type] == 255)
  6219. LogWrite(WORLD__ERROR, 0, "Appearance", "Unknown appearance type '%s' in LoadAppearances.", type.c_str());
  6220. }
  6221. database_new.Select(&result, "SELECT `type`, `signed_value`, `red`, `green`, `blue`\n"
  6222. "FROM npc_appearance\n"
  6223. "WHERE length(`type`) > 0 AND `spawn_id` = %u",
  6224. spawn_id);
  6225. while(result.Next()) {
  6226. if(appearance_types[result.GetString(0)] < APPEARANCE_SOGA_EBT){
  6227. color.red = result.GetInt8(2);
  6228. color.green = result.GetInt8(3);
  6229. color.blue = result.GetInt8(4);
  6230. }
  6231. switch(appearance_types[result.GetString(0)]){
  6232. case APPEARANCE_SOGA_HFHC:{
  6233. entity->features.soga_hair_face_highlight_color = color;
  6234. break;
  6235. }
  6236. case APPEARANCE_SOGA_HTHC:{
  6237. entity->features.soga_hair_type_highlight_color = color;
  6238. break;
  6239. }
  6240. case APPEARANCE_SOGA_HFC:{
  6241. entity->features.soga_hair_face_color = color;
  6242. break;
  6243. }
  6244. case APPEARANCE_SOGA_HTC:{
  6245. entity->features.soga_hair_type_color = color;
  6246. break;
  6247. }
  6248. case APPEARANCE_SOGA_HH:{
  6249. entity->features.soga_hair_highlight_color = color;
  6250. break;
  6251. }
  6252. case APPEARANCE_SOGA_HC1:{
  6253. entity->features.soga_hair_color1 = color;
  6254. break;
  6255. }
  6256. case APPEARANCE_SOGA_HC2:{
  6257. entity->features.soga_hair_color2 = color;
  6258. break;
  6259. }
  6260. case APPEARANCE_SOGA_SC:{
  6261. entity->features.soga_skin_color = color;
  6262. break;
  6263. }
  6264. case APPEARANCE_SOGA_EC:{
  6265. entity->features.soga_eye_color = color;
  6266. break;
  6267. }
  6268. case APPEARANCE_HTHC:{
  6269. entity->features.hair_type_highlight_color = color;
  6270. break;
  6271. }
  6272. case APPEARANCE_HFHC:{
  6273. entity->features.hair_face_highlight_color = color;
  6274. break;
  6275. }
  6276. case APPEARANCE_HTC:{
  6277. entity->features.hair_type_color = color;
  6278. break;
  6279. }
  6280. case APPEARANCE_HFC:{
  6281. entity->features.hair_face_color = color;
  6282. break;
  6283. }
  6284. case APPEARANCE_HH:{
  6285. entity->features.hair_highlight_color = color;
  6286. break;
  6287. }
  6288. case APPEARANCE_HC1:{
  6289. entity->features.hair_color1 = color;
  6290. break;
  6291. }
  6292. case APPEARANCE_HC2:{
  6293. entity->features.hair_color2 = color;
  6294. break;
  6295. }
  6296. case APPEARANCE_WC1:{
  6297. entity->features.wing_color1 = color;
  6298. break;
  6299. }
  6300. case APPEARANCE_WC2:{
  6301. entity->features.wing_color2 = color;
  6302. break;
  6303. }
  6304. case APPEARANCE_SC:{
  6305. entity->features.skin_color = color;
  6306. break;
  6307. }
  6308. case APPEARANCE_EC:{
  6309. entity->features.eye_color = color;
  6310. break;
  6311. }
  6312. case APPEARANCE_SOGA_EBT:{
  6313. for(int i=0;i<3;i++)
  6314. entity->features.soga_eye_brow_type[i] = result.GetInt8(2+i);
  6315. break;
  6316. }
  6317. case APPEARANCE_SOGA_CHEEKT:{
  6318. for(int i=0;i<3;i++)
  6319. entity->features.soga_cheek_type[i] = result.GetInt8(2+i);
  6320. break;
  6321. }
  6322. case APPEARANCE_SOGA_NT:{
  6323. for(int i=0;i<3;i++)
  6324. entity->features.soga_nose_type[i] = result.GetInt8(2+i);
  6325. break;
  6326. }
  6327. case APPEARANCE_SOGA_CHINT:{
  6328. for(int i=0;i<3;i++)
  6329. entity->features.soga_chin_type[i] = result.GetInt8(2+i);
  6330. break;
  6331. }
  6332. case APPEARANCE_SOGA_LT:{
  6333. for(int i=0;i<3;i++)
  6334. entity->features.soga_lip_type[i] = result.GetInt8(2+i);
  6335. break;
  6336. }
  6337. case APPEARANCE_SOGA_EART:{
  6338. for(int i=0;i<3;i++)
  6339. entity->features.soga_ear_type[i] = result.GetInt8(2+i);
  6340. break;
  6341. }
  6342. case APPEARANCE_SOGA_EYET:{
  6343. for(int i=0;i<3;i++)
  6344. entity->features.soga_eye_type[i] = result.GetInt8(2+i);
  6345. break;
  6346. }
  6347. case APPEARANCE_EBT:{
  6348. for(int i=0;i<3;i++)
  6349. entity->features.eye_brow_type[i] = result.GetInt8(2+i);
  6350. break;
  6351. }
  6352. case APPEARANCE_CHEEKT:{
  6353. for(int i=0;i<3;i++)
  6354. entity->features.cheek_type[i] = result.GetInt8(2+i);
  6355. break;
  6356. }
  6357. case APPEARANCE_NT:{
  6358. for(int i=0;i<3;i++)
  6359. entity->features.nose_type[i] = result.GetInt8(2+i);
  6360. break;
  6361. }
  6362. case APPEARANCE_CHINT:{
  6363. for(int i=0;i<3;i++)
  6364. entity->features.chin_type[i] = result.GetInt8(2+i);
  6365. break;
  6366. }
  6367. case APPEARANCE_EART:{
  6368. for(int i=0;i<3;i++)
  6369. entity->features.ear_type[i] = result.GetInt8(2+i);
  6370. break;
  6371. }
  6372. case APPEARANCE_EYET:{
  6373. for(int i=0;i<3;i++)
  6374. entity->features.eye_type[i] = result.GetInt8(2+i);
  6375. break;
  6376. }
  6377. case APPEARANCE_LT:{
  6378. for(int i=0;i<3;i++)
  6379. entity->features.lip_type[i] = result.GetInt8(2+i);
  6380. break;
  6381. }
  6382. case APPEARANCE_SHIRT:{
  6383. entity->features.shirt_color = color;
  6384. break;
  6385. }
  6386. case APPEARANCE_UCC:{
  6387. break;
  6388. }
  6389. case APPEARANCE_PANTS:{
  6390. entity->features.pants_color = color;
  6391. break;
  6392. }
  6393. case APPEARANCE_ULC:{
  6394. break;
  6395. }
  6396. case APPEARANCE_U9:{
  6397. break;
  6398. }
  6399. case APPEARANCE_BODY_SIZE:{
  6400. entity->features.body_size = color.red;
  6401. break;
  6402. }
  6403. case APPEARANCE_SOGA_WC1:{
  6404. break;
  6405. }
  6406. case APPEARANCE_SOGA_WC2:{
  6407. break;
  6408. }
  6409. case APPEARANCE_SOGA_SHIRT:{
  6410. break;
  6411. }
  6412. case APPEARANCE_SOGA_UCC:{
  6413. break;
  6414. }
  6415. case APPEARANCE_SOGA_PANTS:{
  6416. break;
  6417. }
  6418. case APPEARANCE_SOGA_ULC:{
  6419. break;
  6420. }
  6421. case APPEARANCE_SOGA_U13:{
  6422. break;
  6423. }
  6424. case APPEARANCE_BODY_AGE: {
  6425. entity->features.body_age = color.red;
  6426. break;
  6427. }
  6428. case APPEARANCE_MC:{
  6429. entity->features.model_color = color;
  6430. break;
  6431. }
  6432. case APPEARANCE_SMC:{
  6433. entity->features.soga_model_color = color;
  6434. break;
  6435. }
  6436. case APPEARANCE_SBS: {
  6437. entity->features.soga_body_size = color.red;
  6438. break;
  6439. }
  6440. case APPEARANCE_SBA: {
  6441. entity->features.soga_body_age = color.red;
  6442. break;
  6443. }
  6444. }
  6445. }
  6446. entity->info_changed = true;
  6447. }
  6448. void WorldDatabase::LoadNPCAppearanceEquipmentData(ZoneServer* zone, int32 spawn_id) {
  6449. NPC* npc = zone->GetNPC(spawn_id);
  6450. if(!npc) {
  6451. LogWrite(NPC__ERROR, 0, "NPC", "Unable to get a valid npc (%u) in %s", spawn_id, __FUNCTION__);
  6452. return;
  6453. }
  6454. DatabaseResult result;
  6455. int8 slot = 0;
  6456. if (!database_new.Select(&result, "SELECT slot_id, equip_type, red, green, blue, highlight_red, highlight_green, highlight_blue\n"
  6457. "FROM npc_appearance_equip\n"
  6458. "WHERE spawn_id = %u\n",
  6459. spawn_id))
  6460. {
  6461. LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error %u: %s", database_new.GetError(), database_new.GetErrorMsg());
  6462. return;
  6463. }
  6464. while (result.Next()) {
  6465. slot = result.GetInt8(0);
  6466. if(slot < NUM_SLOTS) {
  6467. npc->SetEquipment(slot, result.GetInt16(1), result.GetInt8(2), result.GetInt8(3), result.GetInt8(4), result.GetInt8(5), result.GetInt8(6), result.GetInt8(7));
  6468. }
  6469. }
  6470. }
  6471. void WorldDatabase::SaveCharacterPicture(int32 characterID, int8 type, uchar* picture, int32 picture_size) {
  6472. stringstream ss_hex;
  6473. stringstream ss_query;
  6474. ss_hex.flags(ios::hex);
  6475. for (int32 i = 0; i < picture_size; i++)
  6476. ss_hex << setfill('0') << setw(2) << (int32)picture[i];
  6477. ss_query << "INSERT INTO `character_pictures` (`char_id`, `pic_type`, `picture`) VALUES (" << characterID << ", " << (int32)type << ", '" << ss_hex.str() << "') ON DUPLICATE KEY UPDATE `picture` = '" << ss_hex.str() << "'";
  6478. Query query;
  6479. query.RunQuery2(ss_query.str(), Q_REPLACE);
  6480. if (query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF)
  6481. LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error: in SaveCharacterPicture! Error Message: ", query.GetError());
  6482. }
  6483. void WorldDatabase::LoadZoneFlightPaths(ZoneServer* zone) {
  6484. DatabaseResult result;
  6485. int32 total = 0;
  6486. if (!database_new.Select(&result, "SELECT id, speed, flying, early_dismount FROM flight_paths WHERE zone_id = %u", zone->GetZoneID())) {
  6487. LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error %u: %s", database_new.GetError(), database_new.GetErrorMsg());
  6488. return;
  6489. }
  6490. while (result.Next()) {
  6491. FlightPathInfo* info = new FlightPathInfo;
  6492. int32 id = result.GetInt32(0);
  6493. info->speed = result.GetFloat(1);
  6494. info->flying = result.GetInt8(2) == 1 ? true : false;
  6495. info->dismount = result.GetInt8(3) == 1 ? true : false;
  6496. zone->AddFlightPath(id, info);
  6497. total++;
  6498. }
  6499. LogWrite(ZONE__DEBUG, 0, "Zone", "Loaded %u flight paths for %s", total, zone->GetZoneDescription());
  6500. LoadZoneFlightPathLocations(zone);
  6501. }
  6502. void WorldDatabase::LoadZoneFlightPathLocations(ZoneServer* zone) {
  6503. DatabaseResult result;
  6504. int32 total = 0;
  6505. if (!database_new.Select(&result, "SELECT loc.flight_path, loc.x, loc.y, loc.z FROM flight_paths_locations loc\n"
  6506. "INNER JOIN flight_paths path\n"
  6507. "ON loc.flight_path = path.id\n"
  6508. "WHERE path.zone_id = %u\n"
  6509. "ORDER BY loc.id",
  6510. zone->GetZoneID()))
  6511. {
  6512. LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error %u: %s", database_new.GetError(), database_new.GetErrorMsg());
  6513. return;
  6514. }
  6515. while (result.Next()) {
  6516. FlightPathLocation* loc = new FlightPathLocation;
  6517. int32 id = result.GetInt32(0);
  6518. loc->X = result.GetFloat(1);
  6519. loc->Y = result.GetFloat(2);
  6520. loc->Z = result.GetFloat(3);
  6521. zone->AddFlightPathLocation(id, loc);
  6522. total++;
  6523. }
  6524. LogWrite(ZONE__DEBUG, 0, "Zone", "Loaded %u flight path locations for %s", total, zone->GetZoneDescription());
  6525. }
  6526. void WorldDatabase::SaveCharacterLUAHistory(Player* player, int32 event_id, int32 value, int32 value2) {
  6527. Query query;
  6528. query.AddQueryAsync(player->GetCharacterID(), this, Q_REPLACE, "REPLACE INTO character_lua_history(char_id, event_id, value, value2) VALUES(% u, % u, % u, % u)", player->GetCharacterID(), event_id, value, value2);
  6529. // if (!database_new.Query("REPLACE INTO character_lua_history (char_id, event_id, value, value2) VALUES (%u, %u, %u, %u)", player->GetCharacterID(), event_id, value, value2))
  6530. // LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error %u: %s", database_new.GetError(), database_new.GetErrorMsg());
  6531. }
  6532. void WorldDatabase::LoadCharacterLUAHistory(int32 char_id, Player* player) {
  6533. DatabaseResult result;
  6534. int32 total = 0;
  6535. if (!database_new.Select(&result, "SELECT event_id, value, value2 FROM character_lua_history WHERE char_id = %u", char_id)) {
  6536. LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error %u: %s", database_new.GetError(), database_new.GetErrorMsg());
  6537. return;
  6538. }
  6539. while (result.Next()) {
  6540. int32 id = result.GetInt32(0);
  6541. LUAHistory* hd = new LUAHistory;
  6542. hd->Value = result.GetInt32(1);
  6543. hd->Value2 = result.GetInt32(2);
  6544. hd->SaveNeeded = false;
  6545. player->LoadLUAHistory(id, hd);
  6546. total++;
  6547. }
  6548. LogWrite(PLAYER__DEBUG, 0, "Player", "Loaded %u LUA history for %s", total, player->GetName());
  6549. }
  6550. void WorldDatabase::FindSpell(Client* client, char* findString)
  6551. {
  6552. char* find_escaped = getEscapeString(findString);
  6553. DatabaseResult result;
  6554. if (!database_new.Select(&result, "SELECT s.`id`, ts.spell_id, ts.index, `name`, `tier` "
  6555. "FROM (spells s, spell_tiers st) "
  6556. "LEFT JOIN spell_ts_ability_index ts "
  6557. "ON s.`id` = ts.spell_id "
  6558. "WHERE s.id = st.spell_id and s.name like '%%%s%%' AND s.is_active = 1 "
  6559. "ORDER BY s.`id`, `tier` limit 50", find_escaped))
  6560. {
  6561. // error
  6562. }
  6563. else
  6564. {
  6565. client->Message(CHANNEL_COLOR_YELLOW, "SpellID (SpellTier): SpellName for %s", findString);
  6566. while (result.Next())
  6567. {
  6568. int32 spell_id = result.GetInt32Str("id");
  6569. string spell_name = result.GetStringStr("name");
  6570. int8 tier = result.GetInt8Str("tier");
  6571. client->Message(CHANNEL_COLOR_YELLOW, "%i (%i): %s", spell_id, tier, spell_name.c_str());
  6572. }
  6573. client->Message(CHANNEL_COLOR_YELLOW, "End Spell Results for %s", find_escaped);
  6574. }
  6575. safe_delete_array(find_escaped);
  6576. }
  6577. void WorldDatabase::LoadChestTraps() {
  6578. chest_trap_list.Clear();
  6579. int32 index = 0;
  6580. Query query;
  6581. MYSQL_ROW row;
  6582. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, applicable_zone_id, chest_min_difficulty, chest_max_difficulty, spell_id, spell_tier FROM chest_traps");
  6583. if (result && mysql_num_rows(result) > 0) {
  6584. Title* title = 0;
  6585. while (result && (row = mysql_fetch_row(result))) {
  6586. int32 dbid = atoul(row[0]);
  6587. sint32 applicable_zone_id = atoi(row[1]);
  6588. int32 mindifficulty = atoul(row[2]);
  6589. int32 maxdifficulty = atoul(row[3]);
  6590. int32 spellid = atoul(row[4]);
  6591. int32 tier = atoul(row[5]);
  6592. ChestTrap* trap = new ChestTrap(dbid,applicable_zone_id,mindifficulty,maxdifficulty,spellid,tier);
  6593. chest_trap_list.AddChestTrap(trap);
  6594. }
  6595. }
  6596. }
  6597. bool WorldDatabase::CheckExpansionFlags(ZoneServer* zone, int32 spawnXpackFlag)
  6598. {
  6599. if (spawnXpackFlag == 0)
  6600. return true;
  6601. int32 globalXpackFlag = rule_manager.GetGlobalRule(R_Expansion, GlobalExpansionFlag)->GetInt32();
  6602. int32 zoneXpackFlag = zone->GetExpansionFlag();
  6603. // zone expansion flag takes priority
  6604. if (zoneXpackFlag > 0 && (spawnXpackFlag & zoneXpackFlag) == 0)
  6605. return false;
  6606. // zone expansion flag fails, then if global expansion flag set, we see if that bit operand doesn't match, skip mob then
  6607. else if (zoneXpackFlag == 0 && globalXpackFlag > 0 && (spawnXpackFlag & globalXpackFlag) == 0)
  6608. return false;
  6609. return true;
  6610. }
  6611. bool WorldDatabase::CheckHolidayFlags(ZoneServer* zone, int32 spawnHolidayFlag)
  6612. {
  6613. if (spawnHolidayFlag == 0)
  6614. return true;
  6615. int32 globalHolidayFlag = rule_manager.GetGlobalRule(R_Expansion, GlobalHolidayFlag)->GetInt32();
  6616. int32 zoneHolidayFlag = zone->GetHolidayFlag();
  6617. // zone holiday flag takes priority
  6618. if (zoneHolidayFlag > 0 && (spawnHolidayFlag & zoneHolidayFlag) == 0)
  6619. return false;
  6620. // zone holiday flag fails, then if global expansion flag set, we see if that bit operand doesn't match, skip mob then
  6621. else if (zoneHolidayFlag == 0 && globalHolidayFlag > 0 && (spawnHolidayFlag & globalHolidayFlag) == 0)
  6622. return false;
  6623. return true;
  6624. }
  6625. void WorldDatabase::GetHouseSpawnInstanceData(ZoneServer* zone, Spawn* spawn)
  6626. {
  6627. if (!spawn)
  6628. return;
  6629. if (zone->house_object_database_lookup.count(spawn->GetModelType()) < 1)
  6630. zone->house_object_database_lookup.Put(spawn->GetModelType(), spawn->GetDatabaseID());
  6631. DatabaseResult result;
  6632. database_new.Select(&result, "SELECT pickup_item_id, pickup_unique_item_id\n"
  6633. " FROM spawn_instance_data\n"
  6634. " WHERE spawn_id = %u and spawn_location_id = %u",
  6635. spawn->GetDatabaseID(),spawn->GetSpawnLocationID());
  6636. if (result.GetNumRows() > 0 && result.Next()) {
  6637. spawn->SetPickupItemID(result.GetInt32(0));
  6638. spawn->SetPickupUniqueItemID(result.GetInt32(1));
  6639. if (spawn->GetZone() != nullptr && spawn->GetMap() != nullptr && spawn->GetMap()->IsMapLoaded())
  6640. {
  6641. auto loc = glm::vec3(spawn->GetX(),spawn->GetZ(),spawn->GetY());
  6642. uint32 GridID = 0;
  6643. float new_z = spawn->FindBestZ(loc, nullptr, &GridID);
  6644. spawn->SetPos(&(spawn->appearance.pos.grid_id), GridID);
  6645. }
  6646. }
  6647. }
  6648. int32 WorldDatabase::FindHouseInstanceSpawn(Spawn* spawn)
  6649. {
  6650. DatabaseResult result;
  6651. database_new.Select(&result, "SELECT id\n"
  6652. " FROM spawn\n"
  6653. " WHERE model_type = %u and is_instanced_spawn=1 limit 1",
  6654. spawn->GetModelType());
  6655. if (result.GetNumRows() > 0 && result.Next()) {
  6656. return result.GetInt32(0);
  6657. }
  6658. return 0;
  6659. }
  6660. void WorldDatabase::LoadStartingSkills(World* world)
  6661. {
  6662. world->MStartingLists.writelock();
  6663. int32 total = 0;
  6664. Query query;
  6665. MYSQL_ROW row;
  6666. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT race_id, class_id, skill_id, current_val, max_val, progress FROM starting_skills");
  6667. if (result)
  6668. {
  6669. if (mysql_num_rows(result) > 0)
  6670. {
  6671. Skill* skill = 0;
  6672. while (result && (row = mysql_fetch_row(result)))
  6673. {
  6674. StartingSkill skill;
  6675. skill.header.race_id = atoul(row[0]);
  6676. skill.header.class_id = atoul(row[1]);
  6677. skill.skill_id = atoul(row[2]);
  6678. skill.current_val = atoul(row[3]);
  6679. skill.max_val = atoul(row[4]);
  6680. if (!world->starting_skills.count(skill.header.race_id))
  6681. {
  6682. multimap<int8, StartingSkill>* skills = new multimap<int8, StartingSkill>();
  6683. skills->insert(make_pair(skill.header.class_id, skill));
  6684. world->starting_skills.insert(make_pair(skill.header.race_id, skills));
  6685. }
  6686. else
  6687. {
  6688. multimap<int8, multimap<int8, StartingSkill>*>::const_iterator skills = world->starting_skills.find(skill.header.race_id);
  6689. skills->second->insert(make_pair(skill.header.class_id, skill));
  6690. }
  6691. total++;
  6692. }
  6693. }
  6694. }
  6695. LogWrite(WORLD__DEBUG, 3, "World", "--Loaded %u Starting Skill(s)", total);
  6696. world->MStartingLists.releasewritelock();
  6697. }
  6698. void WorldDatabase::LoadVoiceOvers(World* world)
  6699. {
  6700. int32 total = 0;
  6701. Query query;
  6702. MYSQL_ROW row;
  6703. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT type_id, id, indexed, mp3_string, text_string, emote_string, key1, key2, garbled, garble_link_id FROM voiceovers");
  6704. if (result)
  6705. {
  6706. if (mysql_num_rows(result) > 0)
  6707. {
  6708. Skill* skill = 0;
  6709. while (result && (row = mysql_fetch_row(result)))
  6710. {
  6711. VoiceOverStruct vos;
  6712. vos.mp3_string = std::string(row[3]);
  6713. vos.text_string = std::string(row[4]);
  6714. vos.emote_string = std::string(row[5]);
  6715. vos.key1 = atoul(row[6]);
  6716. vos.key2 = atoul(row[7]);
  6717. vos.is_garbled = atoul(row[8]);
  6718. vos.garble_link_id = atoul(row[9]);
  6719. int8 type = atoul(row[0]);
  6720. int32 id = atoul(row[1]);
  6721. int16 index = atoul(row[2]);
  6722. world->AddVoiceOver(type, id, index, &vos);
  6723. total++;
  6724. }
  6725. }
  6726. }
  6727. LogWrite(WORLD__DEBUG, 3, "World", "--Loaded %u Voiceover(s)", total);
  6728. }
  6729. void WorldDatabase::LoadStartingSpells(World* world)
  6730. {
  6731. world->MStartingLists.writelock();
  6732. int32 total = 0;
  6733. Query query;
  6734. MYSQL_ROW row;
  6735. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT race_id, class_id, spell_id, tier, knowledge_slot FROM starting_spells");
  6736. if (result)
  6737. {
  6738. if (mysql_num_rows(result) > 0)
  6739. {
  6740. Skill* skill = 0;
  6741. while (result && (row = mysql_fetch_row(result)))
  6742. {
  6743. StartingSpell spell;
  6744. spell.header.race_id = atoul(row[0]);
  6745. spell.header.class_id = atoul(row[1]);
  6746. spell.spell_id = atoul(row[2]);
  6747. spell.tier = atoul(row[3]);
  6748. spell.knowledge_slot = atoul(row[4]);
  6749. if (!world->starting_spells.count(spell.header.race_id))
  6750. {
  6751. multimap<int8, StartingSpell>* spells = new multimap<int8, StartingSpell>();
  6752. spells->insert(make_pair(spell.header.class_id, spell));
  6753. world->starting_spells.insert(make_pair(spell.header.race_id, spells));
  6754. }
  6755. else
  6756. {
  6757. multimap<int8, multimap<int8, StartingSpell>*>::iterator spells = world->starting_spells.find(spell.header.race_id);
  6758. spells->second->insert(make_pair(spell.header.class_id, spell));
  6759. }
  6760. total++;
  6761. }
  6762. }
  6763. }
  6764. LogWrite(WORLD__DEBUG, 3, "World", "--Loaded %u Starting Spell(s)", total);
  6765. world->MStartingLists.releasewritelock();
  6766. }
  6767. bool WorldDatabase::DeleteSpiritShard(int32 id){
  6768. Query query;
  6769. query.RunQuery2(Q_DELETE, "delete FROM character_spirit_shards where id=%u",id);
  6770. if(query.GetErrorNumber() && query.GetError() && query.GetErrorNumber() < 0xFFFFFFFF){
  6771. LogWrite(WORLD__ERROR, 0, "World", "Error in DeleteSpiritShard query '%s': %s", query.GetQuery(), query.GetError());
  6772. return false;
  6773. }
  6774. return true;
  6775. }
  6776. int32 WorldDatabase::CreateSpiritShard(const char* name, int32 level, int8 race, int8 gender, int8 adventure_class,
  6777. int16 model_type, int16 soga_model_type, int16 hair_type, int16 hair_face_type, int16 wing_type,
  6778. int16 chest_type, int16 legs_type, int16 soga_hair_type, int16 soga_hair_face_type, int8 hide_hood,
  6779. int16 size, int16 collision_radius, int16 action_state, int16 visual_state, int16 mood_state, int16 emote_state,
  6780. int16 pos_state, int16 activity_status, char* sub_title, char* prefix_title, char* suffix_title, char* lastname,
  6781. float x, float y, float z, float heading, int32 gridid, int32 charid, int32 zoneid, int32 instanceid)
  6782. {
  6783. LogWrite(WORLD__INFO, 3, "World", "Saving Spirit Shard %s %u", name, charid);
  6784. Query query;
  6785. char* name_escaped = getEscapeString(name);
  6786. if(!sub_title)
  6787. sub_title = "";
  6788. char* subtitle_escaped = getEscapeString(sub_title);
  6789. char* prefix_escaped = getEscapeString(prefix_title);
  6790. char* suffix_escaped = getEscapeString(suffix_title);
  6791. char* lastname_escaped = getEscapeString(lastname);
  6792. string insert = string("INSERT INTO character_spirit_shards (name, level, race, gender, adventure_class, model_type, soga_model_type, hair_type, hair_face_type, wing_type, chest_type, legs_type, soga_hair_type, soga_hair_face_type, hide_hood, size, collision_radius, action_state, visual_state, mood_state, emote_state, pos_state, activity_status, sub_title, prefix_title, suffix_title, lastname, x, y, z, heading, gridid, charid, zoneid, instanceid) VALUES ('%s', %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, '%s', '%s', '%s', '%s', %f, %f, %f, %f, %u, %u, %u, %u)");
  6793. query.RunQuery2(Q_INSERT, insert.c_str(), name_escaped, level, race, gender, adventure_class, model_type, soga_model_type,
  6794. hair_type, hair_face_type, wing_type, chest_type, legs_type, soga_hair_type,
  6795. soga_hair_face_type, hide_hood, size, collision_radius, action_state, visual_state,
  6796. mood_state, emote_state, pos_state, activity_status, subtitle_escaped, prefix_escaped, suffix_escaped,
  6797. lastname_escaped, x, y, z, heading, gridid, charid, zoneid, instanceid);
  6798. safe_delete_array(name_escaped);
  6799. safe_delete_array(subtitle_escaped);
  6800. safe_delete_array(prefix_escaped);
  6801. safe_delete_array(suffix_escaped);
  6802. safe_delete_array(lastname_escaped);
  6803. return query.GetLastInsertedID();
  6804. }
  6805. void WorldDatabase::LoadCharacterSpellEffects(int32 char_id, Client* client, int8 db_spell_type)
  6806. {
  6807. SpellProcess* spellProcess = client->GetCurrentZone()->GetSpellProcess();
  6808. Player* player = client->GetPlayer();
  6809. if(!spellProcess)
  6810. return;
  6811. DatabaseResult result;
  6812. multimap<LuaSpell*, Entity*> restoreSpells;
  6813. // Use -1 on type and subtype to turn the enum into an int and make it a 0 index
  6814. if (!database_new.Select(&result, "SELECT name, caster_char_id, target_char_id, target_type, spell_id, effect_slot, slot_pos, icon, icon_backdrop, conc_used, tier, total_time, expire_timestamp, lua_file, custom_spell, damage_remaining, effect_bitmask, num_triggers, had_triggers, cancel_after_triggers, crit, last_spellattack_hit, interrupted, resisted, has_damaged, custom_function FROM character_spell_effects WHERE charid = %u and db_effect_type = %u", char_id, db_spell_type)) {
  6815. LogWrite(DATABASE__ERROR, 0, "DBNew", "MySQL Error %u: %s", database_new.GetError(), database_new.GetErrorMsg());
  6816. return;
  6817. }
  6818. InfoStruct* info = player->GetInfoStruct();
  6819. while (result.Next()) {
  6820. //result.GetInt8Str
  6821. char spell_name[60];
  6822. strncpy(spell_name, result.GetStringStr("name"), 60);
  6823. int32 caster_char_id = result.GetInt32Str("caster_char_id");
  6824. int32 target_char_id = result.GetInt32Str("target_char_id");
  6825. int8 target_type = result.GetInt8Str("target_type");
  6826. int32 spell_id = result.GetInt32Str("spell_id");
  6827. int32 effect_slot = result.GetInt32Str("effect_slot");
  6828. int32 slot_pos = result.GetInt32Str("slot_pos");
  6829. int16 icon = result.GetInt32Str("icon");
  6830. int16 icon_backdrop = result.GetInt32Str("icon_backdrop");
  6831. int8 conc_used = result.GetInt32Str("conc_used");
  6832. int8 tier = result.GetInt32Str("tier");
  6833. float total_time = result.GetFloatStr("total_time");
  6834. int32 expire_timestamp = result.GetInt32Str("expire_timestamp");
  6835. string lua_file (result.GetStringStr("lua_file"));
  6836. int8 custom_spell = result.GetInt32Str("custom_spell");
  6837. int32 damage_remaining = result.GetInt32Str("damage_remaining");
  6838. int32 effect_bitmask = result.GetInt32Str("effect_bitmask");
  6839. int16 num_triggers = result.GetInt32Str("num_triggers");
  6840. int8 had_triggers = result.GetInt32Str("had_triggers");
  6841. int8 cancel_after_triggers = result.GetInt32Str("cancel_after_triggers");
  6842. int8 crit = result.GetInt32Str("crit");
  6843. int8 last_spellattack_hit = result.GetInt32Str("last_spellattack_hit");
  6844. int8 interrupted = result.GetInt32Str("interrupted");
  6845. int8 resisted = result.GetInt32Str("resisted");
  6846. int8 has_damaged = result.GetInt32Str("has_damaged");
  6847. std::string custom_function = std::string(result.GetStringStr("custom_function"));
  6848. LuaSpell* lua_spell = 0;
  6849. if(custom_spell)
  6850. {
  6851. if((lua_spell = lua_interface->GetSpell(lua_file.c_str())) == nullptr)
  6852. {
  6853. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: GetSpell(%u, %u, '%s'), custom lua script not loaded, when attempting to load.", spell_id, tier, lua_file.c_str());
  6854. lua_interface->LoadLuaSpell(lua_file);
  6855. }
  6856. }
  6857. Spell* spell = master_spell_list.GetSpell(spell_id, tier);
  6858. if(!spell)
  6859. {
  6860. LogWrite(LUA__ERROR, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: GetSpell(%u, %u), spell could not be found!", spell_id, tier);
  6861. spell = master_spell_list.GetSpell(spell_id, 0);
  6862. if(spell)
  6863. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: GetSpell(%u, %u), identified tier 0 as replacement since the GetSpell failed!", spell_id, tier);
  6864. else
  6865. continue;
  6866. }
  6867. bool isMaintained = false;
  6868. bool isExistingLuaSpell = false;
  6869. MaintainedEffects* effect = nullptr;
  6870. Client* tmpCaster = nullptr;
  6871. if(caster_char_id == player->GetCharacterID() && (target_char_id == 0xFFFFFFFF || target_char_id == player->GetCharacterID()) && (effect = player->GetMaintainedSpell(spell_id)) != nullptr)
  6872. {
  6873. safe_delete(lua_spell);
  6874. lua_spell = effect->spell;
  6875. if(lua_spell)
  6876. spell = lua_spell->spell;
  6877. isMaintained = true;
  6878. isExistingLuaSpell = true;
  6879. }
  6880. else if ( caster_char_id != player->GetCharacterID() && (tmpCaster = zone_list.GetClientByCharID(caster_char_id)) != nullptr
  6881. && tmpCaster->GetPlayer() && (effect = tmpCaster->GetPlayer()->GetMaintainedSpell(spell_id)) != nullptr)
  6882. {
  6883. if(effect->spell && effect->spell_id == spell_id)
  6884. {
  6885. safe_delete(lua_spell);
  6886. if(tmpCaster->GetCurrentZone() == player->GetZone())
  6887. spellProcess->AddLuaSpellTarget(effect->spell, client->GetPlayer()->GetID());
  6888. lua_spell = effect->spell;
  6889. spell = effect->spell->spell;
  6890. isExistingLuaSpell = true;
  6891. isMaintained = true;
  6892. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: GetSpell(%u, %u, '%s'), effect spell id %u maintained spell recovered from %s", spell_id, tier, spell_name, effect ? effect->spell_id : 0, (tmpCaster && tmpCaster->GetPlayer()) ? tmpCaster->GetPlayer()->GetName() : "?");
  6893. }
  6894. else
  6895. {
  6896. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: GetSpell(%u, %u, '%s'), something went wrong loading another characters maintained spell. Effect has spell id %u", spell_id, tier, lua_file.c_str(), effect ? effect->spell_id : 0);
  6897. safe_delete(lua_spell);
  6898. continue;
  6899. }
  6900. }
  6901. else if(custom_spell && lua_spell)
  6902. {
  6903. lua_spell->spell = new Spell(spell);
  6904. lua_interface->AddCustomSpell(lua_spell);
  6905. }
  6906. else if(db_spell_type == DB_TYPE_MAINTAINEDEFFECTS)
  6907. {
  6908. safe_delete(lua_spell);
  6909. if(!target_char_id)
  6910. continue;
  6911. lua_spell = lua_interface->GetSpell(spell->GetSpellData()->lua_script.c_str());
  6912. if(lua_spell)
  6913. lua_spell->spell = spell;
  6914. }
  6915. if(!lua_spell)
  6916. {
  6917. LogWrite(LUA__ERROR, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: GetSpell(%u, %u, '%s'), lua_spell FAILED, when attempting to load.", spell_id, tier, lua_file.c_str());
  6918. continue;
  6919. }
  6920. SpellScriptTimer* timer = nullptr;
  6921. if(!isExistingLuaSpell && expire_timestamp != 0xFFFFFFFF && custom_function.size() > 0)
  6922. {
  6923. timer = new SpellScriptTimer;
  6924. timer->caster = 0;
  6925. timer->deleteWhenDone = false;
  6926. timer->target = 0;
  6927. timer->time = expire_timestamp;
  6928. timer->customFunction = string(custom_function); // TODO
  6929. timer->spell = lua_spell;
  6930. timer->caster = (caster_char_id == player->GetCharacterID()) ? player->GetID() : 0;
  6931. if(target_char_id == 0xFFFFFFFF && player->HasPet())
  6932. timer->target = player->GetPet()->GetID();
  6933. else
  6934. timer->target = (target_char_id == player->GetCharacterID()) ? player->GetID() : 0;
  6935. if(!timer->target && target_char_id)
  6936. {
  6937. Client* tmpClient = zone_list.GetClientByCharID(target_char_id);
  6938. if(tmpClient && tmpClient->GetPlayer() && tmpClient->GetPlayer()->GetZone() == player->GetZone())
  6939. timer->target = tmpClient->GetPlayer()->GetID();
  6940. }
  6941. }
  6942. if(!isExistingLuaSpell)
  6943. {
  6944. lua_spell->crit = crit;
  6945. lua_spell->damage_remaining = damage_remaining;
  6946. lua_spell->effect_bitmask = effect_bitmask;
  6947. lua_spell->had_dmg_remaining = (damage_remaining>0) ? true : false;
  6948. lua_spell->had_triggers = had_triggers;
  6949. lua_spell->initial_caster_char_id = caster_char_id;
  6950. lua_spell->initial_target = (target_char_id == player->GetCharacterID()) ? player->GetID() : 0;
  6951. lua_spell->initial_target_char_id = target_char_id;
  6952. lua_spell->interrupted = interrupted;
  6953. lua_spell->last_spellattack_hit = last_spellattack_hit;
  6954. lua_spell->num_triggers = num_triggers;
  6955. lua_spell->has_damaged = has_damaged;
  6956. lua_spell->is_damage_spell = has_damaged;
  6957. }
  6958. if(lua_spell->initial_target == 0 && target_char_id == 0xFFFFFFFF && player->HasPet())
  6959. {
  6960. lua_spell->initial_target = player->GetPet()->GetID();
  6961. lua_spell->initial_target_char_id = target_char_id;
  6962. }
  6963. //lua_spell->num_calls ??
  6964. //if(target_char_id == player->GetCharacterID())
  6965. // lua_spell->targets.push_back(player->GetID());
  6966. if(db_spell_type == DB_TYPE_SPELLEFFECTS)
  6967. {
  6968. if (caster_char_id != player->GetCharacterID() && lua_spell->spell->GetSpellData()->group_spell && lua_spell->spell->GetSpellData()->friendly_spell)
  6969. {
  6970. if(!isExistingLuaSpell)
  6971. safe_delete(lua_spell);
  6972. continue;
  6973. }
  6974. player->MSpellEffects.writelock();
  6975. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: %s lua_spell caster %s (%u), caster char id: %u.", lua_spell->spell->GetName(), lua_spell->caster ? lua_spell->caster->GetName() : "", lua_spell->caster ? lua_spell->caster->GetID() : 0, caster_char_id);
  6976. if(lua_spell->caster && (rule_manager.GetGlobalRule(R_Spells,EnableCrossZoneTargetBuffs)->GetInt8() || (!rule_manager.GetGlobalRule(R_Spells,EnableCrossZoneTargetBuffs)->GetInt8() && lua_spell->caster->GetZone() == player->GetZone())))
  6977. info->spell_effects[effect_slot].caster = lua_spell->caster;
  6978. else if(caster_char_id != player->GetCharacterID())
  6979. {
  6980. Client* tmpCaster = zone_list.GetClientByCharID(caster_char_id);
  6981. if(tmpCaster)
  6982. {
  6983. if((rule_manager.GetGlobalRule(R_Spells,EnableCrossZoneTargetBuffs)->GetInt8() || (!rule_manager.GetGlobalRule(R_Spells,EnableCrossZoneTargetBuffs)->GetInt8() && lua_spell->caster->GetZone() == player->GetZone())))
  6984. {
  6985. info->spell_effects[effect_slot].caster = tmpCaster->GetPlayer();
  6986. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: %s lua_spell caster %s (%u), caster char id: %u, found player %s.", lua_spell->spell->GetName(), lua_spell->caster ? lua_spell->caster->GetName() : "", lua_spell->caster ? lua_spell->caster->GetID() : 0, caster_char_id, tmpCaster->GetPlayer()->GetName());
  6987. }
  6988. else
  6989. {
  6990. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: %s lua_spell caster %s (%u), caster char id: %u, found player %s, SKIPPED due to R_Spells, EnableCrossZoneTargetBuffs.", lua_spell->spell->GetName(), lua_spell->caster ? lua_spell->caster->GetName() : "", lua_spell->caster ? lua_spell->caster->GetID() : 0, caster_char_id, tmpCaster->GetPlayer()->GetName());
  6991. if(!isExistingLuaSpell)
  6992. {
  6993. safe_delete(lua_spell);
  6994. }
  6995. else
  6996. {
  6997. lua_spell->MSpellTargets.writelock(__FUNCTION__, __LINE__);
  6998. lua_spell->char_id_targets.insert(make_pair(player->GetCharacterID(),0));
  6999. lua_spell->MSpellTargets.releasewritelock(__FUNCTION__, __LINE__);
  7000. }
  7001. player->MSpellEffects.releasewritelock();
  7002. continue;
  7003. }
  7004. }
  7005. }
  7006. else if(caster_char_id == player->GetCharacterID())
  7007. info->spell_effects[effect_slot].caster = player;
  7008. else
  7009. {
  7010. LogWrite(LUA__ERROR, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: %s lua_spell caster %s (%u), caster char id: %u, failed to find caster will delete: %u", lua_spell->spell->GetName(), lua_spell->caster ? lua_spell->caster->GetName() : "", lua_spell->caster ? lua_spell->caster->GetID() : 0, caster_char_id, isExistingLuaSpell);
  7011. if(!isExistingLuaSpell)
  7012. safe_delete(lua_spell);
  7013. continue;
  7014. }
  7015. if(spell->GetSpellData()->duration_until_cancel)
  7016. info->spell_effects[effect_slot].expire_timestamp = 0xFFFFFFFF;
  7017. else
  7018. info->spell_effects[effect_slot].expire_timestamp = Timer::GetCurrentTime2() + expire_timestamp;
  7019. info->spell_effects[effect_slot].icon = icon;
  7020. info->spell_effects[effect_slot].icon_backdrop = icon_backdrop;
  7021. info->spell_effects[effect_slot].spell_id = spell_id;
  7022. info->spell_effects[effect_slot].tier = tier;
  7023. info->spell_effects[effect_slot].total_time = total_time;
  7024. info->spell_effects[effect_slot].spell = lua_spell;
  7025. lua_spell->MSpellTargets.writelock(__FUNCTION__, __LINE__);
  7026. multimap<int32,int8>::iterator entries;
  7027. while((entries = lua_spell->char_id_targets.find(player->GetCharacterID())) != lua_spell->char_id_targets.end())
  7028. {
  7029. lua_spell->char_id_targets.erase(entries);
  7030. }
  7031. lua_spell->MSpellTargets.releasewritelock(__FUNCTION__, __LINE__);
  7032. lua_spell->slot_pos = slot_pos;
  7033. if(!isExistingLuaSpell)
  7034. lua_spell->caster = player; // TODO: get actual player
  7035. player->MSpellEffects.releasewritelock();
  7036. if(!isMaintained)
  7037. spellProcess->ProcessSpell(lua_spell, true, "cast", timer);
  7038. else
  7039. {
  7040. // track target id when caster isnt in zone somehow
  7041. }
  7042. }
  7043. else if ( db_spell_type == DB_TYPE_MAINTAINEDEFFECTS )
  7044. {
  7045. player->MMaintainedSpells.writelock();
  7046. DatabaseResult targets;
  7047. // Use -1 on type and subtype to turn the enum into an int and make it a 0 index
  7048. if (database_new.Select(&targets, "SELECT target_char_id, target_type, db_effect_type, spell_id from character_spell_effect_targets where caster_char_id = %u and effect_slot = %u and slot_pos = %u", char_id, effect_slot, slot_pos)) {
  7049. while (targets.Next()) {
  7050. int32 target_char = targets.GetInt32Str("target_char_id");
  7051. int8 maintained_target_type = targets.GetInt32Str("target_type");
  7052. int32 in_spell_id = targets.GetInt32Str("spell_id");
  7053. if(spell_id != in_spell_id)
  7054. continue;
  7055. int32 idToAdd = 0;
  7056. if(target_char == 0xFFFFFFFF)
  7057. {
  7058. if( player->HasPet() )
  7059. {
  7060. restoreSpells.insert(make_pair(lua_spell, player->GetPet()));
  7061. // target added via restoreSpells
  7062. }
  7063. }
  7064. else
  7065. {
  7066. Client* client2 = zone_list.GetClientByCharID(target_char);
  7067. if(client2 && client2->GetPlayer() && client2->GetCurrentZone() == client->GetCurrentZone())
  7068. {
  7069. if(maintained_target_type > 0)
  7070. {
  7071. if(client != client2)
  7072. {
  7073. lua_spell->MSpellTargets.writelock(__FUNCTION__, __LINE__);
  7074. if(client2->GetPlayer()->GetPet() && maintained_target_type == PET_TYPE_COMBAT)
  7075. {
  7076. restoreSpells.insert(make_pair(lua_spell, client2->GetPlayer()->GetPet()));
  7077. // target added via restoreSpells
  7078. }
  7079. if(client2->GetPlayer()->GetCharmedPet() && maintained_target_type == PET_TYPE_CHARMED)
  7080. {
  7081. restoreSpells.insert(make_pair(lua_spell, client2->GetPlayer()->GetCharmedPet()));
  7082. // target added via restoreSpells
  7083. }
  7084. lua_spell->MSpellTargets.releasewritelock(__FUNCTION__, __LINE__);
  7085. }
  7086. } // end of pet clause
  7087. else if(client != client2) // maintained type must be 0, so client
  7088. restoreSpells.insert(make_pair(lua_spell, client2->GetPlayer()));
  7089. lua_spell->MSpellTargets.writelock(__FUNCTION__, __LINE__);
  7090. multimap<int32,int8>::iterator entries;
  7091. for(entries = lua_spell->char_id_targets.begin(); entries != lua_spell->char_id_targets.end(); entries++)
  7092. {
  7093. int32 ent_char_id = entries->first;
  7094. int8 ent_target_type = entries->second;
  7095. if(ent_char_id == target_char && ent_target_type == maintained_target_type)
  7096. entries = lua_spell->char_id_targets.erase(entries);
  7097. }
  7098. lua_spell->MSpellTargets.releasewritelock(__FUNCTION__, __LINE__);
  7099. }
  7100. else
  7101. {
  7102. lua_spell->MSpellTargets.writelock(__FUNCTION__, __LINE__);
  7103. lua_spell->char_id_targets.insert(make_pair(target_char,maintained_target_type));
  7104. lua_spell->MSpellTargets.releasewritelock(__FUNCTION__, __LINE__);
  7105. }
  7106. }
  7107. }
  7108. }
  7109. Client* tmpClient = 0;
  7110. int32 targetID = 0;
  7111. if(target_char_id == 0xFFFFFFFF && player->HasPet())
  7112. targetID = player->GetPet()->GetID();
  7113. else if(target_char_id == player->GetCharacterID())
  7114. {
  7115. targetID = player->GetID();
  7116. tmpClient = player->GetClient();
  7117. }
  7118. else if((tmpClient = zone_list.GetClientByCharID(target_char_id)) != nullptr && tmpClient->GetPlayer())
  7119. targetID = tmpClient->GetPlayer()->GetID();
  7120. info->maintained_effects[effect_slot].conc_used = conc_used;
  7121. strncpy(info->maintained_effects[effect_slot].name, spell_name, 60);
  7122. info->maintained_effects[effect_slot].slot_pos = slot_pos;
  7123. info->maintained_effects[effect_slot].target = targetID;
  7124. info->maintained_effects[effect_slot].target_type = target_type;
  7125. if(spell->GetSpellData()->duration_until_cancel)
  7126. info->maintained_effects[effect_slot].expire_timestamp = 0xFFFFFFFF;
  7127. else
  7128. info->maintained_effects[effect_slot].expire_timestamp = Timer::GetCurrentTime2() + expire_timestamp;
  7129. info->maintained_effects[effect_slot].icon = icon;
  7130. info->maintained_effects[effect_slot].icon_backdrop = icon_backdrop;
  7131. info->maintained_effects[effect_slot].spell_id = spell_id;
  7132. info->maintained_effects[effect_slot].tier = tier;
  7133. info->maintained_effects[effect_slot].total_time = total_time;
  7134. info->maintained_effects[effect_slot].spell = lua_spell;
  7135. if(!isExistingLuaSpell)
  7136. lua_spell->caster = player;
  7137. player->MMaintainedSpells.releasewritelock();
  7138. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: %s process spell caster %s (%u), caster char id: %u, target id %u (%s).", lua_spell->spell->GetName(), lua_spell->caster ? lua_spell->caster->GetName() : "",
  7139. lua_spell->caster ? lua_spell->caster->GetID() : 0, caster_char_id, targetID, tmpClient ? tmpClient->GetPlayer()->GetName() : "");
  7140. if(tmpClient && lua_spell->initial_target_char_id == tmpClient->GetCharacterID())
  7141. {
  7142. lua_spell->initial_target = tmpClient->GetPlayer()->GetID();
  7143. spellProcess->AddLuaSpellTarget(lua_spell, lua_spell->initial_target, false);
  7144. }
  7145. spellProcess->ProcessSpell(lua_spell, true, "cast", timer);
  7146. }
  7147. if(!isExistingLuaSpell && expire_timestamp != 0xFFFFFFFF && !isMaintained)
  7148. {
  7149. lua_spell->timer.SetTimer(expire_timestamp);
  7150. lua_spell->timer.SetAtTrigger(lua_spell->spell->GetSpellData()->duration1 * 100);
  7151. lua_spell->timer.Start();
  7152. }
  7153. if(target_char_id == player->GetCharacterID() && lua_spell->spell->GetSpellData()->det_type)
  7154. player->AddDetrimentalSpell(lua_spell, expire_timestamp);
  7155. if(!isExistingLuaSpell)
  7156. {
  7157. if(timer)
  7158. spellProcess->AddSpellScriptTimer(timer);
  7159. lua_spell->num_calls = 1;
  7160. lua_spell->restored = true;
  7161. }
  7162. if(!lua_spell->resisted && (lua_spell->spell->GetSpellDuration() > 0 || lua_spell->spell->GetSpellData()->duration_until_cancel))
  7163. spellProcess->AddActiveSpell(lua_spell);
  7164. if ( db_spell_type == DB_TYPE_MAINTAINEDEFFECTS )
  7165. {
  7166. // restore concentration on zoning/reloading characters maintained effects
  7167. spellProcess->AddConcentration(lua_spell);
  7168. if (num_triggers > 0)
  7169. ClientPacketFunctions::SendMaintainedExamineUpdate(client, slot_pos, num_triggers, 0);
  7170. if (damage_remaining > 0)
  7171. ClientPacketFunctions::SendMaintainedExamineUpdate(client, slot_pos, damage_remaining, 1);
  7172. }
  7173. }
  7174. if(db_spell_type == DB_TYPE_SPELLEFFECTS)
  7175. {
  7176. // if the cross_zone_target_buff option is disabled then we check for all possible targets within the current zone
  7177. // if cross_zone_target_buff is enabled, we only check to restore pets, the players get restored by their own spell effects (we don't directly track the pets, indirectly we do through the player casting and their targets)
  7178. int8 cross_zone_target_buff = rule_manager.GetGlobalRule(R_Spells,EnableCrossZoneTargetBuffs)->GetInt8();
  7179. DatabaseResult targets;
  7180. if (
  7181. (!cross_zone_target_buff && database_new.Select(&targets, "SELECT caster_char_id, target_type, spell_id from character_spell_effect_targets where target_char_id = %u", player->GetCharacterID())) ||
  7182. (database_new.Select(&targets, "SELECT caster_char_id, target_type, spell_id from character_spell_effect_targets where target_char_id = %u and target_type > 0", player->GetCharacterID())))
  7183. {
  7184. while (targets.Next()) {
  7185. int32 caster_char_id = targets.GetInt32Str("caster_char_id");
  7186. int8 prev_target_type = targets.GetInt32Str("target_type");
  7187. int32 in_spell_id = targets.GetInt32Str("spell_id");
  7188. Client* tmpCaster = nullptr;
  7189. MaintainedEffects* effect = nullptr;
  7190. if (caster_char_id != player->GetCharacterID() && (tmpCaster = zone_list.GetClientByCharID(caster_char_id)) != nullptr && (cross_zone_target_buff ||
  7191. tmpCaster->GetCurrentZone() == player->GetZone()) && tmpCaster->GetPlayer() && (effect = tmpCaster->GetPlayer()->GetMaintainedSpell(in_spell_id)) != nullptr)
  7192. {
  7193. if(prev_target_type > 0)
  7194. {
  7195. if(player->HasPet())
  7196. {
  7197. if(player->GetPet() && prev_target_type == PET_TYPE_COMBAT)
  7198. restoreSpells.insert(make_pair(effect->spell, player->GetPet()));
  7199. if(player->GetCharmedPet() && prev_target_type == PET_TYPE_CHARMED)
  7200. restoreSpells.insert(make_pair(effect->spell, player->GetCharmedPet()));
  7201. }
  7202. }
  7203. else if(!player->GetSpellEffect(effect->spell_id, tmpCaster->GetPlayer()))
  7204. {
  7205. if(effect->spell->initial_target_char_id == player->GetCharacterID())
  7206. effect->spell->initial_target = player->GetID();
  7207. restoreSpells.insert(make_pair(effect->spell, player));
  7208. }
  7209. }
  7210. }
  7211. }
  7212. }
  7213. multimap<LuaSpell*, Entity*>::const_iterator itr;
  7214. for (itr = restoreSpells.begin(); itr != restoreSpells.end(); itr++)
  7215. {
  7216. LuaSpell* tmpSpell = itr->first;
  7217. Entity* target = itr->second;
  7218. if(!target)
  7219. {
  7220. target = client->GetPlayer()->GetPet();
  7221. if(!target)
  7222. continue;
  7223. }
  7224. Entity* caster = tmpSpell->caster;
  7225. if(!caster)
  7226. caster = client->GetPlayer();
  7227. int32 group_id_target = target->group_id;
  7228. if(target->IsPet() && target->GetOwner())
  7229. group_id_target = target->GetOwner()->group_id;
  7230. if(caster != target && caster->GetPet() != target &&
  7231. tmpSpell->spell->GetSpellData()->group_spell && tmpSpell->spell->GetSpellData()->friendly_spell && (caster->group_id == 0 || group_id_target == 0 || caster->group_id != group_id_target))
  7232. {
  7233. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: %s player no longer grouped with %s to reload bonuses for spell %s (target_groupid: %u, caster_groupid: %u).", target->GetName(), caster ? caster->GetName() : "?", tmpSpell->spell->GetName(), group_id_target, caster->group_id);
  7234. continue;
  7235. }
  7236. LogWrite(LUA__WARNING, 0, "LUA", "WorldDatabase::LoadCharacterSpellEffects: %s using caster %s to reload bonuses for spell %s.", player->GetName(), caster ? caster->GetName() : "?", tmpSpell->spell->GetName());
  7237. spellProcess->AddLuaSpellTarget(tmpSpell, target->GetID());
  7238. target->AddSpellEffect(tmpSpell, tmpSpell->timer.GetRemainingTime() != 0 ? tmpSpell->timer.GetRemainingTime() : 0);
  7239. vector<BonusValues*>* sb_list = caster->GetAllSpellBonuses(tmpSpell);
  7240. for (int32 x = 0; x < sb_list->size(); x++) {
  7241. BonusValues* bv = sb_list->at(x);
  7242. target->AddSpellBonus(tmpSpell, bv->type, bv->value, bv->class_req, bv->race_req, bv->faction_req);
  7243. }
  7244. sb_list->clear();
  7245. safe_delete(sb_list);
  7246. // look for a skill bonus on the caster's spell
  7247. if(caster->IsPlayer())
  7248. {
  7249. SkillBonus* sb = ((Player*)caster)->GetSkillBonus(tmpSpell->spell->GetSpellID());
  7250. if (sb) {
  7251. map<int32, SkillBonusValue*>::iterator itr_skills;
  7252. for (itr_skills = sb->skills.begin(); itr_skills != sb->skills.end(); itr_skills++)
  7253. target->AddSkillBonus(sb->spell_id, (*itr_skills).second->skill_id, (*itr_skills).second->value);
  7254. }
  7255. }
  7256. }
  7257. }
  7258. //devn00b: We need to handle non-found factions so the subtraction/addition works on 1st kill. Need to find a better way to handle this, but for now..
  7259. bool WorldDatabase::VerifyFactionID(int32 char_id, int32 faction_id) {
  7260. DatabaseResult result;
  7261. database_new.Select(&result, "SELECT COUNT(id) as faction_exists from character_factions where faction_id=%u and char_id=%u", faction_id, char_id);
  7262. if (result.Next() && result.GetInt32Str("faction_exists") == 0)
  7263. return false;
  7264. return true;
  7265. }
  7266. //using int/32 for starting city, should be large enough to support future zones (LOL). TODO: Will probably need more support bolted on, to support PVP and such.
  7267. void WorldDatabase::UpdateStartingLanguage(int32 char_id, uint8 race_id, int32 starting_city)
  7268. {
  7269. int8 rule = rule_manager.GetGlobalRule(R_World, StartingZoneLanguages)->GetInt8();
  7270. //this should never need to be done but lets make sure we got all the stuff we need. char_id at min since used for both.
  7271. if(!char_id || (rule == 0 && !race_id) || (rule == 1 && !starting_city))
  7272. return;
  7273. std::string query_string = "SELECT language_id FROM starting_languages ";
  7274. //check the rule, and that they gave us a race, if so use default entries to match live.
  7275. if(rule == 0 && race_id >= 0) {
  7276. query_string.append("WHERE race=" + std::to_string(race_id));
  7277. }
  7278. //if we have a starting city supplied, and the rule is set to use it, deal with it
  7279. else if(rule == 1) {
  7280. query_string.append("WHERE starting_city=" + std::to_string(starting_city) + " or (starting_city=0 and race_id=" + std::to_string(race_id) + ")");
  7281. }
  7282. Query query;
  7283. MYSQL_ROW row;
  7284. MYSQL_RES* result = query.RunQuery2(Q_SELECT,query_string.c_str());
  7285. LogWrite(PLAYER__DEBUG, 0, "Player", "Adding Languages for starting_city: %i based on rule R_World:StartingZoneLanguages value %u", starting_city, rule);
  7286. if (result) {
  7287. if (mysql_num_rows(result) > 0) {
  7288. while (result && (row = mysql_fetch_row(result))){
  7289. //add custom languages to the character_languages db.
  7290. Query query2;
  7291. query2.RunQuery2(Q_INSERT, "INSERT IGNORE INTO character_languages (char_id, language_id) VALUES (%u,%u)",char_id, atoul(row[0]));
  7292. }
  7293. }
  7294. }
  7295. }
  7296. //devn00b: load the items the server has into a character_ db for easy access. Should be done on char create.
  7297. void WorldDatabase::LoadClaimItems(int32 char_id)
  7298. {
  7299. if (!char_id) {
  7300. LogWrite(WORLD__DEBUG, 3, "World", "-- There was an error in LoadClaimItems (missing char_id)");
  7301. return;
  7302. }
  7303. int16 total = 0;
  7304. Query query;
  7305. MYSQL_ROW row;
  7306. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT id, item_id, max_claim, one_per_char, veteran_reward_time from claim_items");
  7307. if (result)
  7308. {
  7309. if (mysql_num_rows(result) > 0)
  7310. {
  7311. while (result && (row = mysql_fetch_row(result)))
  7312. {
  7313. int32 item_id = atoul(row[1]);
  7314. int16 max_claim = atoul(row[2]);
  7315. int16 curr_claim = max_claim;
  7316. int8 one_per_char = atoul(row[3]);
  7317. int64 vet_reward_time = atoi64(row[4]);
  7318. int32 acct_id = GetCharacterAccountID(char_id);
  7319. if (one_per_char == 1) {
  7320. max_claim = 1;
  7321. curr_claim = 1;
  7322. }
  7323. Query query2;
  7324. MYSQL_RES* res = query2.RunQuery2(Q_INSERT, "insert ignore into character_claim_items (char_id, item_id, max_claim, curr_claim, one_per_char, veteran_reward_time, account_id) values (%i, %i, %i, %i, %i, %I64i, %i)", char_id, item_id, max_claim, curr_claim, one_per_char, vet_reward_time, acct_id);
  7325. total++;
  7326. }
  7327. }
  7328. }
  7329. LogWrite(WORLD__DEBUG, 3, "World", "--Loaded %u Claim Item(s)", total);
  7330. }
  7331. int16 WorldDatabase::CountCharClaimItems(int32 char_id) {
  7332. Query query;
  7333. MYSQL_ROW row;
  7334. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT count(*) from character_claim_items where char_id=%i and curr_claim >0", char_id);
  7335. if (result && mysql_num_rows(result) > 0) {
  7336. MYSQL_ROW row;
  7337. row = mysql_fetch_row(result);
  7338. return atoi(row[0]); // Return count
  7339. }
  7340. return 0;
  7341. }
  7342. vector<ClaimItems> WorldDatabase::LoadCharacterClaimItems(int32 char_id) {
  7343. vector<ClaimItems> claim;
  7344. //make sure we have a charID shouldn't need this but adding anyway.
  7345. if (!char_id)
  7346. return claim;
  7347. int32 acct_id = GetCharacterAccountID(char_id);
  7348. Query query;
  7349. MYSQL_ROW row;
  7350. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT item_id, max_claim, curr_claim, one_per_char, last_claim, veteran_reward_time from character_claim_items where char_id=%u and curr_claim > 0", char_id);
  7351. int16 i = 0;
  7352. if (result)
  7353. {
  7354. if (mysql_num_rows(result) > 0)
  7355. {
  7356. while (result && (row = mysql_fetch_row(result)))
  7357. {
  7358. ClaimItems c;
  7359. int8 max_claim = atoi(row[1]);
  7360. int8 curr_claim = atoi(row[2]);
  7361. //if one per char is set set max/cur to 1.
  7362. if (atoi(row[3]) == 1) {
  7363. max_claim = 1;
  7364. curr_claim = 1;
  7365. }
  7366. if (atoi(row[3]) == 0) {
  7367. //handle getting lowest claim amt from table, to prevent new chars skewing.
  7368. Query query2;
  7369. MYSQL_ROW row2;
  7370. MYSQL_RES* result2 = query2.RunQuery2(Q_SELECT, "SELECT min(curr_claim) AS min_claim FROM character_claim_items WHERE account_id=%i and item_id=%i", acct_id, atoi(row[0]));
  7371. //our current claim is now the lowest.
  7372. if (result2 && (row2 = mysql_fetch_row(result2)) && row2[0] != NULL) {
  7373. int8 curr_claim = atoi(row2[0]);
  7374. }
  7375. }
  7376. c.item_id = atoi(row[0]);
  7377. c.max_claim = max_claim;
  7378. c.curr_claim = curr_claim;
  7379. c.one_per_char = atoi(row[3]);
  7380. c.vet_reward_time = atoi(row[5]);
  7381. claim.push_back(c);
  7382. i++;
  7383. }
  7384. return claim;
  7385. }
  7386. }
  7387. return claim;
  7388. }
  7389. void WorldDatabase::ClaimItem(int32 char_id, int32 item_id, Client* client) {
  7390. if (!client || !item_id || !char_id) {
  7391. return;
  7392. }
  7393. Query query;
  7394. MYSQL_ROW row;
  7395. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT item_id, max_claim, curr_claim, one_per_char, last_claim, veteran_reward_time, one_per_char from character_claim_items where char_id=%u and item_id=%u", char_id, item_id);
  7396. if (result)
  7397. {
  7398. if (mysql_num_rows(result) > 0)
  7399. {
  7400. while (result && (row = mysql_fetch_row(result)))
  7401. {
  7402. Item* item = master_item_list.GetItem(item_id);
  7403. Player* player = client->GetPlayer();
  7404. InfoStruct* info = player->GetInfoStruct();
  7405. int32 item_id = atoi(row[0]);
  7406. int8 max_claim = atoi(row[1]);
  7407. int8 min_claim = 0;
  7408. int8 curr_claim = atoi(row[2]);
  7409. int32 vet_reward_req = atoi(row[5]);
  7410. int8 one_per_char = atoi(row[6]);
  7411. int32 acct_id = GetCharacterAccountID(char_id);
  7412. char claim_msg[512] = { 0 };
  7413. //no claims left.
  7414. if (curr_claim == 0) {
  7415. client->Message(CHANNEL_COLOR_RED, "You have nothing to claim.");
  7416. return;
  7417. }
  7418. //On live, characters must wait 6 seconds between claims. So..Lots of stuff here.
  7419. uint32 last_claim = info->get_last_claim_time(); //load our last claim
  7420. time_t now = time(0); //get the current epoc time
  7421. uint32 curr_time = now; // current time.
  7422. uint32 total_time = curr_time - last_claim; //Time since last claim (Current time - last claim)
  7423. if (total_time < 6) {
  7424. uint32 ttw = 6 - total_time;
  7425. char tmp[64] = { 0 };
  7426. sprintf(tmp, "You must wait %u more seconds.", ttw);
  7427. client->Message(CHANNEL_COLOR_RED, tmp);
  7428. return;
  7429. }
  7430. //handle the 2 different messages found from live (11/2022)
  7431. if (item->generic_info.item_type == 18) {
  7432. sprintf(claim_msg, "You have consumed the item\nYou have chosen to give this character a %s", item->name.c_str());
  7433. }
  7434. else {
  7435. sprintf(claim_msg, "You have consumed the item");
  7436. }
  7437. //not one per char, so remove 1 from account.
  7438. if (one_per_char == 0) {
  7439. Query query3;
  7440. MYSQL_ROW row3;
  7441. MYSQL_RES* result3 = query3.RunQuery2(Q_SELECT, "SELECT min(curr_claim) AS min_claim FROM character_claim_items WHERE account_id=%i and item_id=%i", acct_id, item_id);
  7442. if (result3 && (row3 = mysql_fetch_row(result3)) && row3[0] != NULL) {
  7443. int16 min_claim = atoi(row3[0]);
  7444. //remove 1 from claim on one per char
  7445. int32 acct_id = GetCharacterAccountID(char_id);
  7446. Query query2;
  7447. query2.RunQuery2(Q_UPDATE, "UPDATE `character_claim_items` SET curr_claim=(SELECT min(curr_claim) AS min_claim FROM character_claim_items WHERE account_id=%i and item_id=%i) - 1 , `last_claim`=%u WHERE account_id=%i and item_id=%i AND curr_claim > 0", acct_id, item_id, curr_time, acct_id, item_id);
  7448. //give the item to the player, and update last claim time.
  7449. bool item_added = client->AddItem(item_id);
  7450. if (item_added == 0) {
  7451. return;
  7452. }
  7453. info->set_last_claim_time(curr_time);
  7454. client->Message(CHANNEL_COLOR_YELLOW, claim_msg);
  7455. //reload the window to show new count.
  7456. client->ShowClaimWindow();
  7457. return;
  7458. }
  7459. }
  7460. Query query4;
  7461. query4.RunQuery2(Q_UPDATE, "UPDATE `character_claim_items` SET `curr_claim`=0 , `last_claim`=%u WHERE char_id=%i and item_id=%i", curr_time, char_id, item_id);
  7462. //give the item to the player, and update last claim time.
  7463. //client->AddItem(item_id);
  7464. bool item_added = client->AddItem(item_id);
  7465. if (item_added == 0) {
  7466. return;
  7467. }
  7468. info->set_last_claim_time(curr_time);
  7469. client->Message(CHANNEL_COLOR_YELLOW, claim_msg);
  7470. //reload the window to show new count.
  7471. client->ShowClaimWindow();
  7472. return;
  7473. }
  7474. }
  7475. }
  7476. return;
  7477. }
  7478. //returns account age in seconds
  7479. int32 WorldDatabase::GetAccountAge(int32 account_id) {
  7480. if (!account_id)
  7481. return 0;
  7482. int32 acct_age = 0;
  7483. int32 acct_created = 0;
  7484. time_t now = time(0); //get the current epoc time
  7485. uint32 curr_time = now; // current time.
  7486. Query query;
  7487. //order by created date and grab the oldest one.
  7488. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT UNIX_TIMESTAMP(created_date) FROM characters WHERE account_id=%i ORDER BY created_date LIMIT 1", account_id);
  7489. if (result && mysql_num_rows(result) > 0) {
  7490. MYSQL_ROW row = mysql_fetch_row(result);
  7491. acct_created = atoi(row[0]);
  7492. }
  7493. if (!curr_time || !acct_created)
  7494. return 0;
  7495. acct_age = curr_time - acct_created;
  7496. return acct_age;
  7497. }
  7498. void WorldDatabase::SaveSignMark(int32 char_id, int32 sign_id, char* char_name, Client* client) {
  7499. if (!database_new.Query("update spawn_signs set char_id=%u, char_name='%s' where widget_id=%u", char_id, char_name, sign_id)) {
  7500. LogWrite(SIGN__DEBUG, 0, "Sign", "ERROR in WorldDatabase::SaveSignMark");
  7501. return;
  7502. }
  7503. }
  7504. string WorldDatabase::GetSignMark(int32 char_id, int32 sign_id, char* char_name) {
  7505. Query query;
  7506. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "SELECT char_name from spawn_signs where widget_id=%u", sign_id);
  7507. char* charname = 0;
  7508. if (result && mysql_num_rows(result) > 0) {
  7509. MYSQL_ROW row = mysql_fetch_row(result);
  7510. charname = new char[strlen(row[0]) + 1];
  7511. memset(charname, 0, strlen(row[0]) + 1);
  7512. strcpy(charname, row[0]);
  7513. }
  7514. return charname;
  7515. }