commonobject.class.php 315 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2019 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/core/class/commonobject.class.php
  34. * \ingroup core
  35. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  36. */
  37. /**
  38. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  39. */
  40. abstract class CommonObject
  41. {
  42. /**
  43. * @var DoliDb Database handler (result of a new DoliDB)
  44. */
  45. public $db;
  46. /**
  47. * @var int The object identifier
  48. */
  49. public $id;
  50. /**
  51. * @var int The environment ID when using a multicompany module
  52. */
  53. public $entity;
  54. /**
  55. * @var string Error string
  56. * @see $errors
  57. */
  58. public $error;
  59. /**
  60. * @var string Error string that is hidden but can be used to store complementatry technical code.
  61. */
  62. public $errorhidden;
  63. /**
  64. * @var string[] Array of error strings
  65. */
  66. public $errors = array();
  67. /**
  68. * @var string ID to identify managed object
  69. */
  70. public $element;
  71. /**
  72. * @var string Name of table without prefix where object is stored
  73. */
  74. public $table_element;
  75. /**
  76. * @var string Name of subtable line
  77. */
  78. public $table_element_line = '';
  79. /**
  80. * @var string Key value used to track if data is coming from import wizard
  81. */
  82. public $import_key;
  83. /**
  84. * @var mixed Contains data to manage extrafields
  85. */
  86. public $array_options = array();
  87. /**
  88. * @var mixed Array to store alternative languages values of object
  89. */
  90. public $array_languages = null; // Value is array() when load already tried
  91. /**
  92. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  93. */
  94. public $linkedObjectsIds;
  95. /**
  96. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  97. */
  98. public $linkedObjects;
  99. /**
  100. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  101. */
  102. public $oldcopy;
  103. /**
  104. * @var string Column name of the ref field.
  105. */
  106. protected $table_ref_field = '';
  107. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  108. /**
  109. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  110. */
  111. public $context = array();
  112. /**
  113. * @var string Contains canvas name if record is an alternative canvas record
  114. */
  115. public $canvas;
  116. /**
  117. * @var Project The related project
  118. * @see fetch_projet()
  119. */
  120. public $project;
  121. /**
  122. * @var int The related project ID
  123. * @see setProject(), project
  124. */
  125. public $fk_project;
  126. /**
  127. * @deprecated
  128. * @see project
  129. */
  130. public $projet;
  131. /**
  132. * @var Contact a related contact
  133. * @see fetch_contact()
  134. */
  135. public $contact;
  136. /**
  137. * @var int The related contact ID
  138. * @see fetch_contact()
  139. */
  140. public $contact_id;
  141. /**
  142. * @var Societe A related thirdparty
  143. * @see fetch_thirdparty()
  144. */
  145. public $thirdparty;
  146. /**
  147. * @var User A related user
  148. * @see fetch_user()
  149. */
  150. public $user;
  151. /**
  152. * @var string The type of originating object ('commande', 'facture', ...)
  153. * @see fetch_origin()
  154. */
  155. public $origin;
  156. /**
  157. * @var int The id of originating object
  158. * @see fetch_origin()
  159. */
  160. public $origin_id;
  161. /**
  162. * @var string The object's reference
  163. */
  164. public $ref;
  165. /**
  166. * @var string An external reference for the object
  167. */
  168. public $ref_ext;
  169. /**
  170. * @var string The object's previous reference
  171. */
  172. public $ref_previous;
  173. /**
  174. * @var string The object's next reference
  175. */
  176. public $ref_next;
  177. /**
  178. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  179. */
  180. public $newref;
  181. /**
  182. * @var int The object's status
  183. * @see setStatut()
  184. */
  185. public $statut;
  186. /**
  187. * @var int The object's status
  188. * @see setStatut()
  189. */
  190. public $status;
  191. /**
  192. * @var string
  193. * @see getFullAddress()
  194. */
  195. public $country;
  196. /**
  197. * @var int
  198. * @see getFullAddress(), country
  199. */
  200. public $country_id;
  201. /**
  202. * @var string
  203. * @see getFullAddress(), isInEEC(), country
  204. */
  205. public $country_code;
  206. /**
  207. * @var string
  208. * @see getFullAddress()
  209. */
  210. public $state;
  211. /**
  212. * @var int
  213. * @see getFullAddress(), state
  214. */
  215. public $state_id;
  216. /**
  217. * @var string
  218. * @see getFullAddress(), $state
  219. */
  220. public $state_code;
  221. /**
  222. * @var int
  223. * @see getFullAddress(), $region_code, $region
  224. */
  225. public $region_id;
  226. /**
  227. * @var string
  228. * @see getFullAddress(), $region_id, $region
  229. */
  230. public $region_code;
  231. /**
  232. * @var string
  233. * @see getFullAddress(), $region_id, $region_code
  234. */
  235. public $region;
  236. /**
  237. * @var int
  238. * @see fetch_barcode()
  239. */
  240. public $barcode_type;
  241. /**
  242. * @var string
  243. * @see fetch_barcode(), barcode_type
  244. */
  245. public $barcode_type_code;
  246. /**
  247. * @var string
  248. * @see fetch_barcode(), barcode_type
  249. */
  250. public $barcode_type_label;
  251. /**
  252. * @var string
  253. * @see fetch_barcode(), barcode_type
  254. */
  255. public $barcode_type_coder;
  256. /**
  257. * @var int Payment method ID (cheque, cash, ...)
  258. * @see setPaymentMethods()
  259. */
  260. public $mode_reglement_id;
  261. /**
  262. * @var int Payment terms ID
  263. * @see setPaymentTerms()
  264. */
  265. public $cond_reglement_id;
  266. /**
  267. * @var int Demand reason ID
  268. */
  269. public $demand_reason_id;
  270. /**
  271. * @var int Transport mode ID (For module intracomm report)
  272. * @see setTransportMode()
  273. */
  274. public $transport_mode_id;
  275. /**
  276. * @var int Payment terms ID
  277. * @deprecated Kept for compatibility
  278. * @see cond_reglement_id;
  279. */
  280. public $cond_reglement;
  281. /**
  282. * @var int Delivery address ID
  283. * @see setDeliveryAddress()
  284. * @deprecated
  285. */
  286. public $fk_delivery_address;
  287. /**
  288. * @var int Shipping method ID
  289. * @see setShippingMethod()
  290. */
  291. public $shipping_method_id;
  292. /**
  293. * @var string
  294. * @see SetDocModel()
  295. */
  296. public $model_pdf;
  297. /**
  298. * @var string
  299. * @deprecated
  300. * @see $model_pdf
  301. */
  302. public $modelpdf;
  303. /**
  304. * @var string
  305. * Contains relative path of last generated main file
  306. */
  307. public $last_main_doc;
  308. /**
  309. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  310. * @deprecated
  311. * @see $fk_account
  312. */
  313. public $fk_bank;
  314. /**
  315. * @var int Bank account ID
  316. * @see SetBankAccount()
  317. */
  318. public $fk_account;
  319. /**
  320. * @var string Open ID
  321. */
  322. public $openid;
  323. /**
  324. * @var string Public note
  325. * @see update_note()
  326. */
  327. public $note_public;
  328. /**
  329. * @var string Private note
  330. * @see update_note()
  331. */
  332. public $note_private;
  333. /**
  334. * @deprecated
  335. * @see $note_private
  336. */
  337. public $note;
  338. /**
  339. * @var float Total amount before taxes
  340. * @see update_price()
  341. */
  342. public $total_ht;
  343. /**
  344. * @var float Total VAT amount
  345. * @see update_price()
  346. */
  347. public $total_tva;
  348. /**
  349. * @var float Total local tax 1 amount
  350. * @see update_price()
  351. */
  352. public $total_localtax1;
  353. /**
  354. * @var float Total local tax 2 amount
  355. * @see update_price()
  356. */
  357. public $total_localtax2;
  358. /**
  359. * @var float Total amount with taxes
  360. * @see update_price()
  361. */
  362. public $total_ttc;
  363. /**
  364. * @var CommonObjectLine[]
  365. */
  366. public $lines;
  367. /**
  368. * @var mixed Contains comments
  369. * @see fetchComments()
  370. */
  371. public $comments = array();
  372. /**
  373. * @var string The name
  374. */
  375. public $name;
  376. /**
  377. * @var string The lastname
  378. */
  379. public $lastname;
  380. /**
  381. * @var string The firstname
  382. */
  383. public $firstname;
  384. /**
  385. * @var string The civility code, not an integer
  386. */
  387. public $civility_id;
  388. // Dates
  389. /**
  390. * @var integer|string date_creation
  391. */
  392. public $date_creation;
  393. /**
  394. * @var integer|string $date_validation;
  395. */
  396. public $date_validation; // Date validation
  397. /**
  398. * @var integer|string $date_modification;
  399. */
  400. public $date_modification; // Date last change (tms field)
  401. public $next_prev_filter;
  402. /**
  403. * @var int 1 if object is specimen
  404. */
  405. public $specimen = 0;
  406. /**
  407. * @var int Id of contact to send object (used by the trigger of module Agenda)
  408. */
  409. public $sendtoid;
  410. /**
  411. * @var float Amount already paid (used to show correct status)
  412. */
  413. public $alreadypaid;
  414. /**
  415. * @var array List of child tables. To test if we can delete object.
  416. */
  417. protected $childtables = array();
  418. /**
  419. * @var array List of child tables. To know object to delete on cascade.
  420. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  421. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  422. */
  423. protected $childtablesoncascade = array();
  424. // No constructor as it is an abstract class
  425. /**
  426. * Check an object id/ref exists
  427. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  428. *
  429. * @param string $element String of element ('product', 'facture', ...)
  430. * @param int $id Id of object
  431. * @param string $ref Ref of object to check
  432. * @param string $ref_ext Ref ext of object to check
  433. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  434. */
  435. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  436. {
  437. global $db, $conf;
  438. $sql = "SELECT rowid, ref, ref_ext";
  439. $sql .= " FROM ".MAIN_DB_PREFIX.$element;
  440. $sql .= " WHERE entity IN (".getEntity($element).")";
  441. if ($id > 0) {
  442. $sql .= " AND rowid = ".((int) $id);
  443. } elseif ($ref) {
  444. $sql .= " AND ref = '".$db->escape($ref)."'";
  445. } elseif ($ref_ext) {
  446. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  447. } else {
  448. $error = 'ErrorWrongParameters';
  449. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  450. return -1;
  451. }
  452. if ($ref || $ref_ext) {
  453. $sql .= " AND entity = ".((int) $conf->entity);
  454. }
  455. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  456. $resql = $db->query($sql);
  457. if ($resql) {
  458. $num = $db->num_rows($resql);
  459. if ($num > 0) {
  460. return 1;
  461. } else {
  462. return 0;
  463. }
  464. }
  465. return -1;
  466. }
  467. /**
  468. * Method to output saved errors
  469. *
  470. * @return string String with errors
  471. */
  472. public function errorsToString()
  473. {
  474. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  475. }
  476. /**
  477. * Return customer ref for screen output.
  478. *
  479. * @param string $objref Customer ref
  480. * @return string Customer ref formated
  481. */
  482. public function getFormatedCustomerRef($objref)
  483. {
  484. global $hookmanager;
  485. $parameters = array('objref'=>$objref);
  486. $action = '';
  487. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  488. if ($reshook > 0) {
  489. return $hookmanager->resArray['objref'];
  490. }
  491. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  492. }
  493. /**
  494. * Return supplier ref for screen output.
  495. *
  496. * @param string $objref Supplier ref
  497. * @return string Supplier ref formated
  498. */
  499. public function getFormatedSupplierRef($objref)
  500. {
  501. global $hookmanager;
  502. $parameters = array('objref'=>$objref);
  503. $action = '';
  504. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  505. if ($reshook > 0) {
  506. return $hookmanager->resArray['objref'];
  507. }
  508. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  509. }
  510. /**
  511. * Return full name (civility+' '+name+' '+lastname)
  512. *
  513. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  514. * @param int $option 0=No option, 1=Add civility
  515. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  516. * @param int $maxlen Maximum length
  517. * @return string String with full name
  518. */
  519. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  520. {
  521. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  522. $lastname = $this->lastname;
  523. $firstname = $this->firstname;
  524. if (empty($lastname)) {
  525. $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
  526. }
  527. $ret = '';
  528. if (!empty($option) && !empty($this->civility_code)) {
  529. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  530. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  531. } else {
  532. $ret .= $this->civility_code.' ';
  533. }
  534. }
  535. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  536. return dol_trunc($ret, $maxlen);
  537. }
  538. /**
  539. * Set to upper or ucwords/lower if needed
  540. *
  541. * @return void;
  542. */
  543. public function setUpperOrLowerCase()
  544. {
  545. global $conf;
  546. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  547. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  548. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  549. $this->name = dol_ucwords(dol_strtolower($this->name));
  550. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  551. }
  552. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  553. $this->lastname = dol_strtoupper($this->lastname);
  554. $this->name = dol_strtoupper($this->name);
  555. $this->name_alias = dol_strtoupper($this->name_alias);
  556. }
  557. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  558. $this->address = dol_strtoupper($this->address);
  559. $this->town = dol_strtoupper($this->town);
  560. }
  561. }
  562. /**
  563. * Return clicable link of object (with eventually picto)
  564. *
  565. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  566. * @return string HTML Code for Kanban thumb.
  567. */
  568. public function getKanbanView($option = '')
  569. {
  570. $return = '<div class="box-flex-item">';
  571. $return .= '<div class="info-box info-box-sm">';
  572. $return .= '<span class="info-box-icon bg-infobox-action">';
  573. $return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  574. $return .= '</span>';
  575. $return .= '<div class="info-box-content">';
  576. $return .= '<span class="info-box-title">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  577. $return .= '</div>';
  578. $return .= '</div>';
  579. $return .= '</div>';
  580. return $return;
  581. }
  582. /**
  583. * Return full address of contact
  584. *
  585. * @param int $withcountry 1=Add country into address string
  586. * @param string $sep Separator to use to build string
  587. * @param int $withregion 1=Add region into address string
  588. * @param string $extralangcode User extralanguages as value
  589. * @return string Full address string
  590. */
  591. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  592. {
  593. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  594. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  595. $tmparray = getCountry($this->country_id, 'all');
  596. $this->country_code = $tmparray['code'];
  597. $this->country = $tmparray['label'];
  598. }
  599. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  600. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  601. $tmparray = getState($this->state_id, 'all', 0, 1);
  602. $this->state_code = $tmparray['code'];
  603. $this->state = $tmparray['label'];
  604. $this->region_code = $tmparray['region_code'];
  605. $this->region = $tmparray['region'];
  606. }
  607. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  608. }
  609. /**
  610. * Return full address for banner
  611. *
  612. * @param string $htmlkey HTML id to make banner content unique
  613. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  614. * @return string Full address string
  615. */
  616. public function getBannerAddress($htmlkey, $object)
  617. {
  618. global $conf, $langs, $form, $extralanguages;
  619. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  620. $contactid = 0;
  621. $thirdpartyid = 0;
  622. $elementforaltlanguage = $this->element;
  623. if ($this->element == 'societe') {
  624. $thirdpartyid = $this->id;
  625. }
  626. if ($this->element == 'contact') {
  627. $contactid = $this->id;
  628. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  629. }
  630. if ($this->element == 'user') {
  631. $contactid = $this->contact_id;
  632. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  633. }
  634. $out = '';
  635. $outdone = 0;
  636. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  637. if ($coords) {
  638. if (!empty($conf->use_javascript_ajax)) {
  639. // Add picto with tooltip on map
  640. $namecoords = '';
  641. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  642. $namecoords .= $object->name.'<br>';
  643. }
  644. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  645. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  646. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  647. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  648. $out .= '</a> ';
  649. }
  650. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  651. $outdone++;
  652. $outdone++;
  653. // List of extra languages
  654. $arrayoflangcode = array();
  655. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  656. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  657. }
  658. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  659. if (!is_object($extralanguages)) {
  660. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  661. $extralanguages = new ExtraLanguages($this->db);
  662. }
  663. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  664. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  665. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  666. $this->fetchValuesForExtraLanguages();
  667. if (!is_object($form)) {
  668. $form = new Form($this->db);
  669. }
  670. $htmltext = '';
  671. // If there is extra languages
  672. foreach ($arrayoflangcode as $extralangcode) {
  673. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  674. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  675. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  676. }
  677. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  678. }
  679. }
  680. }
  681. if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
  682. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  683. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  684. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  685. } else {
  686. $out .= ($outdone ? ' - ' : '').$this->state;
  687. }
  688. $outdone++;
  689. }
  690. if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) {
  691. $out .= ($outdone ? '<br>' : '');
  692. }
  693. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  694. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  695. $outdone++;
  696. }
  697. if (!empty($this->phone_pro)) {
  698. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  699. $outdone++;
  700. }
  701. if (!empty($this->phone_mobile)) {
  702. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  703. $outdone++;
  704. }
  705. if (!empty($this->phone_perso)) {
  706. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  707. $outdone++;
  708. }
  709. if (!empty($this->office_phone)) {
  710. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  711. $outdone++;
  712. }
  713. if (!empty($this->user_mobile)) {
  714. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  715. $outdone++;
  716. }
  717. if (!empty($this->fax)) {
  718. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  719. $outdone++;
  720. }
  721. if (!empty($this->office_fax)) {
  722. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  723. $outdone++;
  724. }
  725. if ($out) {
  726. $out .= '<div style="clear: both;"></div>';
  727. }
  728. $outdone = 0;
  729. if (!empty($this->email)) {
  730. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  731. $outdone++;
  732. }
  733. if (!empty($this->url)) {
  734. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  735. $out .= dol_print_url($this->url, '_blank', 0, 1);
  736. $outdone++;
  737. }
  738. if (!empty($conf->socialnetworks->enabled)) {
  739. $outsocialnetwork = '';
  740. if (!empty($this->socialnetworks) && is_countable($this->socialnetworks) && count($this->socialnetworks) > 0) {
  741. $socialnetworksdict = getArrayOfSocialNetworks();
  742. foreach ($this->socialnetworks as $key => $value) {
  743. if ($value) {
  744. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  745. }
  746. $outdone++;
  747. }
  748. } else { // Old code to remove
  749. if (!empty($this->skype)) {
  750. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  751. }
  752. $outdone++;
  753. if (!empty($this->jabberid)) {
  754. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  755. }
  756. $outdone++;
  757. if (!empty($this->twitter)) {
  758. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  759. }
  760. $outdone++;
  761. if (!empty($this->facebook)) {
  762. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  763. }
  764. $outdone++;
  765. if (!empty($this->linkedin)) {
  766. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  767. }
  768. $outdone++;
  769. }
  770. if ($outsocialnetwork) {
  771. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  772. }
  773. }
  774. if ($out) {
  775. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  776. } else {
  777. return '';
  778. }
  779. }
  780. /**
  781. * Return the link of last main doc file for direct public download.
  782. *
  783. * @param string $modulepart Module related to document
  784. * @param int $initsharekey Init the share key if it was not yet defined
  785. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  786. * @return string Link or empty string if there is no download link
  787. */
  788. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  789. {
  790. global $user, $dolibarr_main_url_root;
  791. if (empty($this->last_main_doc)) {
  792. return ''; // No way to known which document name to use
  793. }
  794. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  795. $ecmfile = new EcmFiles($this->db);
  796. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  797. if ($result < 0) {
  798. $this->error = $ecmfile->error;
  799. $this->errors = $ecmfile->errors;
  800. return -1;
  801. }
  802. if (empty($ecmfile->id)) {
  803. // Add entry into index
  804. if ($initsharekey) {
  805. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  806. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  807. /*
  808. $ecmfile->filepath = $rel_dir;
  809. $ecmfile->filename = $filename;
  810. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  811. $ecmfile->fullpath_orig = '';
  812. $ecmfile->gen_or_uploaded = 'generated';
  813. $ecmfile->description = ''; // indexed content
  814. $ecmfile->keyword = ''; // keyword content
  815. $ecmfile->share = getRandomPassword(true);
  816. $result = $ecmfile->create($user);
  817. if ($result < 0)
  818. {
  819. $this->error = $ecmfile->error;
  820. $this->errors = $ecmfile->errors;
  821. }
  822. */
  823. } else {
  824. return '';
  825. }
  826. } elseif (empty($ecmfile->share)) {
  827. // Add entry into index
  828. if ($initsharekey) {
  829. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  830. $ecmfile->share = getRandomPassword(true);
  831. $ecmfile->update($user);
  832. } else {
  833. return '';
  834. }
  835. }
  836. // Define $urlwithroot
  837. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  838. // This is to use external domain name found into config file
  839. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  840. //else
  841. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  842. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  843. $forcedownload = 0;
  844. $paramlink = '';
  845. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  846. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  847. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  848. if (!empty($ecmfile->share)) {
  849. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  850. }
  851. if ($forcedownload) {
  852. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  853. }
  854. if ($relativelink) {
  855. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  856. } else {
  857. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  858. }
  859. // Here $ecmfile->share is defined
  860. return $linktoreturn;
  861. }
  862. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  863. /**
  864. * Add a link between element $this->element and a contact
  865. *
  866. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  867. * @param int|string $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
  868. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  869. * @param int $notrigger Disable all triggers
  870. * @return int <0 if KO, 0 if already added, >0 if OK
  871. */
  872. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  873. {
  874. // phpcs:enable
  875. global $user, $langs;
  876. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  877. // Check parameters
  878. if ($fk_socpeople <= 0) {
  879. $langs->load("errors");
  880. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  881. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  882. return -1;
  883. }
  884. if (!$type_contact) {
  885. $langs->load("errors");
  886. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  887. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  888. return -2;
  889. }
  890. $id_type_contact = 0;
  891. if (is_numeric($type_contact)) {
  892. $id_type_contact = $type_contact;
  893. } else {
  894. // We look for id type_contact
  895. $sql = "SELECT tc.rowid";
  896. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  897. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  898. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  899. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  900. //print $sql;
  901. $resql = $this->db->query($sql);
  902. if ($resql) {
  903. $obj = $this->db->fetch_object($resql);
  904. if ($obj) {
  905. $id_type_contact = $obj->rowid;
  906. }
  907. }
  908. }
  909. if ($id_type_contact == 0) {
  910. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  911. dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
  912. return -3;
  913. }
  914. $datecreate = dol_now();
  915. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  916. $TListeContacts = $this->liste_contact(-1, $source);
  917. $already_added = false;
  918. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  919. foreach ($TListeContacts as $array_contact) {
  920. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  921. $already_added = true;
  922. break;
  923. }
  924. }
  925. }
  926. if (!$already_added) {
  927. $this->db->begin();
  928. // Insert into database
  929. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  930. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  931. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  932. $sql .= "'".$this->db->idate($datecreate)."'";
  933. $sql .= ", 4, ".((int) $id_type_contact);
  934. $sql .= ")";
  935. $resql = $this->db->query($sql);
  936. if ($resql) {
  937. if (!$notrigger) {
  938. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  939. if ($result < 0) {
  940. $this->db->rollback();
  941. return -1;
  942. }
  943. }
  944. $this->db->commit();
  945. return 1;
  946. } else {
  947. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  948. $this->error = $this->db->errno();
  949. $this->db->rollback();
  950. return -2;
  951. } else {
  952. $this->error = $this->db->error();
  953. $this->db->rollback();
  954. return -1;
  955. }
  956. }
  957. } else {
  958. return 0;
  959. }
  960. }
  961. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  962. /**
  963. * Copy contact from one element to current
  964. *
  965. * @param CommonObject $objFrom Source element
  966. * @param string $source Nature of contact ('internal' or 'external')
  967. * @return int >0 if OK, <0 if KO
  968. */
  969. public function copy_linked_contact($objFrom, $source = 'internal')
  970. {
  971. // phpcs:enable
  972. $contacts = $objFrom->liste_contact(-1, $source);
  973. foreach ($contacts as $contact) {
  974. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  975. $this->error = $this->db->lasterror();
  976. return -1;
  977. }
  978. }
  979. return 1;
  980. }
  981. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  982. /**
  983. * Update a link to contact line
  984. *
  985. * @param int $rowid Id of line contact-element
  986. * @param int $statut New status of link
  987. * @param int $type_contact_id Id of contact type (not modified if 0)
  988. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  989. * @return int <0 if KO, >= 0 if OK
  990. */
  991. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  992. {
  993. // phpcs:enable
  994. // Insert into database
  995. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  996. $sql .= " statut = ".$statut;
  997. if ($type_contact_id) {
  998. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  999. }
  1000. if ($fk_socpeople) {
  1001. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1002. }
  1003. $sql .= " where rowid = ".((int) $rowid);
  1004. $resql = $this->db->query($sql);
  1005. if ($resql) {
  1006. return 0;
  1007. } else {
  1008. $this->error = $this->db->lasterror();
  1009. return -1;
  1010. }
  1011. }
  1012. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1013. /**
  1014. * Delete a link to contact line
  1015. *
  1016. * @param int $rowid Id of contact link line to delete
  1017. * @param int $notrigger Disable all triggers
  1018. * @return int >0 if OK, <0 if KO
  1019. */
  1020. public function delete_contact($rowid, $notrigger = 0)
  1021. {
  1022. // phpcs:enable
  1023. global $user;
  1024. $this->db->begin();
  1025. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1026. $sql .= " WHERE rowid = ".((int) $rowid);
  1027. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1028. if ($this->db->query($sql)) {
  1029. if (!$notrigger) {
  1030. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1031. if ($result < 0) {
  1032. $this->db->rollback();
  1033. return -1;
  1034. }
  1035. }
  1036. $this->db->commit();
  1037. return 1;
  1038. } else {
  1039. $this->error = $this->db->lasterror();
  1040. $this->db->rollback();
  1041. return -1;
  1042. }
  1043. }
  1044. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1045. /**
  1046. * Delete all links between an object $this and all its contacts
  1047. *
  1048. * @param string $source '' or 'internal' or 'external'
  1049. * @param string $code Type of contact (code or id)
  1050. * @return int >0 if OK, <0 if KO
  1051. */
  1052. public function delete_linked_contact($source = '', $code = '')
  1053. {
  1054. // phpcs:enable
  1055. $temp = array();
  1056. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1057. foreach ($typeContact as $key => $value) {
  1058. array_push($temp, $key);
  1059. }
  1060. $listId = implode(",", $temp);
  1061. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1062. $sql .= " WHERE element_id = ".$this->id;
  1063. if ($listId) {
  1064. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1065. }
  1066. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1067. if ($this->db->query($sql)) {
  1068. return 1;
  1069. } else {
  1070. $this->error = $this->db->lasterror();
  1071. return -1;
  1072. }
  1073. }
  1074. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1075. /**
  1076. * Get array of all contacts for an object
  1077. *
  1078. * @param int $status Status of links to get (-1=all)
  1079. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1080. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1081. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1082. * @return array|int Array of contacts, -1 if error
  1083. */
  1084. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1085. {
  1086. // phpcs:enable
  1087. global $langs;
  1088. $tab = array();
  1089. $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
  1090. if ($source == 'internal') {
  1091. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1092. }
  1093. if ($source == 'external' || $source == 'thirdparty') {
  1094. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1095. }
  1096. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1097. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1098. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1099. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  1100. if ($source == 'internal') {
  1101. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  1102. }
  1103. if ($source == 'external' || $source == 'thirdparty') {
  1104. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  1105. }
  1106. $sql .= " WHERE ec.element_id =".$this->id;
  1107. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1108. $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
  1109. if ($code) {
  1110. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1111. }
  1112. if ($source == 'internal') {
  1113. $sql .= " AND tc.source = 'internal'";
  1114. }
  1115. if ($source == 'external' || $source == 'thirdparty') {
  1116. $sql .= " AND tc.source = 'external'";
  1117. }
  1118. $sql .= " AND tc.active=1";
  1119. if ($status >= 0) {
  1120. $sql .= " AND ec.statut = ".((int) $status);
  1121. }
  1122. $sql .= " ORDER BY t.lastname ASC";
  1123. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1124. $resql = $this->db->query($sql);
  1125. if ($resql) {
  1126. $num = $this->db->num_rows($resql);
  1127. $i = 0;
  1128. while ($i < $num) {
  1129. $obj = $this->db->fetch_object($resql);
  1130. if (!$list) {
  1131. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1132. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1133. $tab[$i] = array(
  1134. 'source' => $obj->source,
  1135. 'socid' => $obj->socid,
  1136. 'id' => $obj->id,
  1137. 'nom' => $obj->lastname, // For backward compatibility
  1138. 'civility' => $obj->civility,
  1139. 'lastname' => $obj->lastname,
  1140. 'firstname' => $obj->firstname,
  1141. 'email'=>$obj->email,
  1142. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1143. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1144. 'statuscontact' => $obj->statuscontact,
  1145. 'rowid' => $obj->rowid,
  1146. 'code' => $obj->code,
  1147. 'libelle' => $libelle_type,
  1148. 'status' => $obj->statuslink,
  1149. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1150. );
  1151. } else {
  1152. $tab[$i] = $obj->id;
  1153. }
  1154. $i++;
  1155. }
  1156. return $tab;
  1157. } else {
  1158. $this->error = $this->db->lasterror();
  1159. dol_print_error($this->db);
  1160. return -1;
  1161. }
  1162. }
  1163. /**
  1164. * Update status of a contact linked to object
  1165. *
  1166. * @param int $rowid Id of link between object and contact
  1167. * @return int <0 if KO, >=0 if OK
  1168. */
  1169. public function swapContactStatus($rowid)
  1170. {
  1171. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1172. $sql .= " tc.code, tc.libelle";
  1173. $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  1174. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1175. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1176. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1177. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1178. $resql = $this->db->query($sql);
  1179. if ($resql) {
  1180. $obj = $this->db->fetch_object($resql);
  1181. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1182. $result = $this->update_contact($rowid, $newstatut);
  1183. $this->db->free($resql);
  1184. return $result;
  1185. } else {
  1186. $this->error = $this->db->error();
  1187. dol_print_error($this->db);
  1188. return -1;
  1189. }
  1190. }
  1191. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1192. /**
  1193. * Return array with list of possible values for type of contacts
  1194. *
  1195. * @param string $source 'internal', 'external' or 'all'
  1196. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1197. * @param int $option 0=Return array id->label, 1=Return array code->label
  1198. * @param int $activeonly 0=all status of contact, 1=only the active
  1199. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1200. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1201. */
  1202. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1203. {
  1204. // phpcs:enable
  1205. global $langs;
  1206. if (empty($order)) {
  1207. $order = 'position';
  1208. }
  1209. if ($order == 'position') {
  1210. $order .= ',code';
  1211. }
  1212. $tab = array();
  1213. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1214. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1215. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1216. if ($activeonly == 1) {
  1217. $sql .= " AND tc.active=1"; // only the active types
  1218. }
  1219. if (!empty($source) && $source != 'all') {
  1220. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1221. }
  1222. if (!empty($code)) {
  1223. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1224. }
  1225. $sql .= $this->db->order($order, 'ASC');
  1226. //print "sql=".$sql;
  1227. $resql = $this->db->query($sql);
  1228. if ($resql) {
  1229. $num = $this->db->num_rows($resql);
  1230. $i = 0;
  1231. while ($i < $num) {
  1232. $obj = $this->db->fetch_object($resql);
  1233. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1234. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1235. if (empty($option)) {
  1236. $tab[$obj->rowid] = $libelle_type;
  1237. } else {
  1238. $tab[$obj->code] = $libelle_type;
  1239. }
  1240. $i++;
  1241. }
  1242. return $tab;
  1243. } else {
  1244. $this->error = $this->db->lasterror();
  1245. //dol_print_error($this->db);
  1246. return null;
  1247. }
  1248. }
  1249. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1250. /**
  1251. * Return array with list of possible values for type of contacts
  1252. *
  1253. * @param string $source 'internal', 'external' or 'all'
  1254. * @param int $option 0=Return array id->label, 1=Return array code->label
  1255. * @param int $activeonly 0=all status of contact, 1=only the active
  1256. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1257. * @param string $element Filter on 1 element type
  1258. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1259. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1260. */
  1261. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1262. {
  1263. // phpcs:enable
  1264. global $langs, $conf;
  1265. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1266. $tab = array();
  1267. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1268. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1269. $sqlWhere = array();
  1270. if (!empty($element)) {
  1271. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1272. }
  1273. if (!empty($excludeelement)) {
  1274. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1275. }
  1276. if ($activeonly == 1) {
  1277. $sqlWhere[] = " tc.active=1"; // only the active types
  1278. }
  1279. if (!empty($source) && $source != 'all') {
  1280. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1281. }
  1282. if (!empty($code)) {
  1283. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1284. }
  1285. if (count($sqlWhere) > 0) {
  1286. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1287. }
  1288. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1289. dol_syslog(__METHOD__, LOG_DEBUG);
  1290. $resql = $this->db->query($sql);
  1291. if ($resql) {
  1292. $num = $this->db->num_rows($resql);
  1293. if ($num > 0) {
  1294. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1295. while ($obj = $this->db->fetch_object($resql)) {
  1296. $modulename = $obj->element;
  1297. if (strpos($obj->element, 'project') !== false) {
  1298. $modulename = 'projet';
  1299. } elseif ($obj->element == 'contrat') {
  1300. $element = 'contract';
  1301. } elseif ($obj->element == 'action') {
  1302. $modulename = 'agenda';
  1303. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1304. $modulename = 'fournisseur';
  1305. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1306. $modulename = 'fournisseur';
  1307. }
  1308. if (!empty($conf->{$modulename}->enabled)) {
  1309. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1310. $tmpelement = $obj->element;
  1311. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1312. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1313. if (empty($option)) {
  1314. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1315. } else {
  1316. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1317. }
  1318. }
  1319. }
  1320. }
  1321. return $tab;
  1322. } else {
  1323. $this->error = $this->db->lasterror();
  1324. return null;
  1325. }
  1326. }
  1327. /**
  1328. * Return id of contacts for a source and a contact code.
  1329. * Example: contact client de facturation ('external', 'BILLING')
  1330. * Example: contact client de livraison ('external', 'SHIPPING')
  1331. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1332. *
  1333. * @param string $source 'external' or 'internal'
  1334. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1335. * @param int $status limited to a certain status
  1336. * @return array List of id for such contacts
  1337. */
  1338. public function getIdContact($source, $code, $status = 0)
  1339. {
  1340. global $conf;
  1341. $result = array();
  1342. $i = 0;
  1343. //cas particulier pour les expeditions
  1344. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1345. $id = $this->origin_id;
  1346. $element = 'commande';
  1347. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1348. $id = $this->origin_id;
  1349. $element = 'order_supplier';
  1350. } else {
  1351. $id = $this->id;
  1352. $element = $this->element;
  1353. }
  1354. $sql = "SELECT ec.fk_socpeople";
  1355. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1356. if ($source == 'internal') {
  1357. $sql .= " ".MAIN_DB_PREFIX."user as c,";
  1358. }
  1359. if ($source == 'external') {
  1360. $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
  1361. }
  1362. $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1363. $sql .= " WHERE ec.element_id = ".((int) $id);
  1364. $sql .= " AND ec.fk_socpeople = c.rowid";
  1365. if ($source == 'internal') {
  1366. $sql .= " AND c.entity IN (".getEntity('user').")";
  1367. }
  1368. if ($source == 'external') {
  1369. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1370. }
  1371. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1372. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1373. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1374. if ($code) {
  1375. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1376. }
  1377. $sql .= " AND tc.active = 1";
  1378. if ($status) {
  1379. $sql .= " AND ec.statut = ".((int) $status);
  1380. }
  1381. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1382. $resql = $this->db->query($sql);
  1383. if ($resql) {
  1384. while ($obj = $this->db->fetch_object($resql)) {
  1385. $result[$i] = $obj->fk_socpeople;
  1386. $i++;
  1387. }
  1388. } else {
  1389. $this->error = $this->db->error();
  1390. return null;
  1391. }
  1392. return $result;
  1393. }
  1394. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1395. /**
  1396. * Load object contact with id=$this->contact_id into $this->contact
  1397. *
  1398. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1399. * @return int <0 if KO, >0 if OK
  1400. */
  1401. public function fetch_contact($contactid = null)
  1402. {
  1403. // phpcs:enable
  1404. if (empty($contactid)) {
  1405. $contactid = $this->contact_id;
  1406. }
  1407. if (empty($contactid)) {
  1408. return 0;
  1409. }
  1410. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1411. $contact = new Contact($this->db);
  1412. $result = $contact->fetch($contactid);
  1413. $this->contact = $contact;
  1414. return $result;
  1415. }
  1416. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1417. /**
  1418. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1419. *
  1420. * @param int $force_thirdparty_id Force thirdparty id
  1421. * @return int <0 if KO, >0 if OK
  1422. */
  1423. public function fetch_thirdparty($force_thirdparty_id = 0)
  1424. {
  1425. // phpcs:enable
  1426. global $conf;
  1427. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1428. return 0;
  1429. }
  1430. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1431. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1432. if ($force_thirdparty_id) {
  1433. $idtofetch = $force_thirdparty_id;
  1434. }
  1435. if ($idtofetch) {
  1436. $thirdparty = new Societe($this->db);
  1437. $result = $thirdparty->fetch($idtofetch);
  1438. if ($result<0) {
  1439. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1440. }
  1441. $this->thirdparty = $thirdparty;
  1442. // Use first price level if level not defined for third party
  1443. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1444. $this->thirdparty->price_level = 1;
  1445. }
  1446. return $result;
  1447. } else {
  1448. return -1;
  1449. }
  1450. }
  1451. /**
  1452. * Looks for an object with ref matching the wildcard provided
  1453. * It does only work when $this->table_ref_field is set
  1454. *
  1455. * @param string $ref Wildcard
  1456. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1457. */
  1458. public function fetchOneLike($ref)
  1459. {
  1460. if (!$this->table_ref_field) {
  1461. return 0;
  1462. }
  1463. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
  1464. $query = $this->db->query($sql);
  1465. if (!$this->db->num_rows($query)) {
  1466. return 0;
  1467. }
  1468. $result = $this->db->fetch_object($query);
  1469. return $this->fetch($result->rowid);
  1470. }
  1471. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1472. /**
  1473. * Load data for barcode into properties ->barcode_type*
  1474. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1475. * if it is not defined, ->element must be defined to know default barcode type.
  1476. *
  1477. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1478. */
  1479. public function fetch_barcode()
  1480. {
  1481. // phpcs:enable
  1482. global $conf;
  1483. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1484. $idtype = $this->barcode_type;
  1485. if (empty($idtype) && $idtype != '0') { // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined
  1486. if ($this->element == 'product') {
  1487. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1488. } elseif ($this->element == 'societe') {
  1489. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1490. } else {
  1491. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1492. }
  1493. }
  1494. if ($idtype > 0) {
  1495. if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) { // If data not already loaded
  1496. $sql = "SELECT rowid, code, libelle as label, coder";
  1497. $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1498. $sql .= " WHERE rowid = ".((int) $idtype);
  1499. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1500. $resql = $this->db->query($sql);
  1501. if ($resql) {
  1502. $obj = $this->db->fetch_object($resql);
  1503. $this->barcode_type = $obj->rowid;
  1504. $this->barcode_type_code = $obj->code;
  1505. $this->barcode_type_label = $obj->label;
  1506. $this->barcode_type_coder = $obj->coder;
  1507. return 1;
  1508. } else {
  1509. dol_print_error($this->db);
  1510. return -1;
  1511. }
  1512. }
  1513. }
  1514. return 0;
  1515. }
  1516. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1517. /**
  1518. * Load the project with id $this->fk_project into this->project
  1519. *
  1520. * @return int <0 if KO, >=0 if OK
  1521. */
  1522. public function fetch_projet()
  1523. {
  1524. // phpcs:enable
  1525. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1526. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1527. $this->fk_project = $this->fk_projet; // For backward compatibility
  1528. }
  1529. if (empty($this->fk_project)) {
  1530. return 0;
  1531. }
  1532. $project = new Project($this->db);
  1533. $result = $project->fetch($this->fk_project);
  1534. $this->projet = $project; // deprecated
  1535. $this->project = $project;
  1536. return $result;
  1537. }
  1538. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1539. /**
  1540. * Load the product with id $this->fk_product into this->product
  1541. *
  1542. * @return int <0 if KO, >=0 if OK
  1543. */
  1544. public function fetch_product()
  1545. {
  1546. // phpcs:enable
  1547. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1548. if (empty($this->fk_product)) {
  1549. return 0;
  1550. }
  1551. $product = new Product($this->db);
  1552. $result = $product->fetch($this->fk_product);
  1553. $this->product = $product;
  1554. return $result;
  1555. }
  1556. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1557. /**
  1558. * Load the user with id $userid into this->user
  1559. *
  1560. * @param int $userid Id du contact
  1561. * @return int <0 if KO, >0 if OK
  1562. */
  1563. public function fetch_user($userid)
  1564. {
  1565. // phpcs:enable
  1566. $user = new User($this->db);
  1567. $result = $user->fetch($userid);
  1568. $this->user = $user;
  1569. return $result;
  1570. }
  1571. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1572. /**
  1573. * Read linked origin object
  1574. *
  1575. * @return void
  1576. */
  1577. public function fetch_origin()
  1578. {
  1579. // phpcs:enable
  1580. if ($this->origin == 'shipping') {
  1581. $this->origin = 'expedition';
  1582. }
  1583. if ($this->origin == 'delivery') {
  1584. $this->origin = 'livraison';
  1585. }
  1586. if ($this->origin == 'order_supplier') {
  1587. $this->origin = 'commandeFournisseur';
  1588. }
  1589. $origin = $this->origin;
  1590. $classname = ucfirst($origin);
  1591. $this->$origin = new $classname($this->db);
  1592. $this->$origin->fetch($this->origin_id);
  1593. }
  1594. /**
  1595. * Load object from specific field
  1596. *
  1597. * @param string $table Table element or element line
  1598. * @param string $field Field selected
  1599. * @param string $key Import key
  1600. * @param string $element Element name
  1601. * @return int <0 if KO, >0 if OK
  1602. */
  1603. public function fetchObjectFrom($table, $field, $key, $element = null)
  1604. {
  1605. global $conf;
  1606. $result = false;
  1607. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1608. $sql .= " WHERE ".$field." = '".$key."'";
  1609. if (!empty($element)) {
  1610. $sql .= " AND entity IN (".getEntity($element).")";
  1611. } else {
  1612. $sql .= " AND entity = ".$conf->entity;
  1613. }
  1614. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1615. $resql = $this->db->query($sql);
  1616. if ($resql) {
  1617. $row = $this->db->fetch_row($resql);
  1618. // Test for avoid error -1
  1619. if ($row[0] > 0) {
  1620. $result = $this->fetch($row[0]);
  1621. }
  1622. }
  1623. return $result;
  1624. }
  1625. /**
  1626. * Getter generic. Load value from a specific field
  1627. *
  1628. * @param string $table Table of element or element line
  1629. * @param int $id Element id
  1630. * @param string $field Field selected
  1631. * @return int <0 if KO, >0 if OK
  1632. */
  1633. public function getValueFrom($table, $id, $field)
  1634. {
  1635. $result = false;
  1636. if (!empty($id) && !empty($field) && !empty($table)) {
  1637. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1638. $sql .= " WHERE rowid = ".((int) $id);
  1639. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1640. $resql = $this->db->query($sql);
  1641. if ($resql) {
  1642. $row = $this->db->fetch_row($resql);
  1643. $result = $row[0];
  1644. }
  1645. }
  1646. return $result;
  1647. }
  1648. /**
  1649. * Setter generic. Update a specific field into database.
  1650. * Warning: Trigger is run only if param trigkey is provided.
  1651. *
  1652. * @param string $field Field to update
  1653. * @param mixed $value New value
  1654. * @param string $table To force other table element or element line (should not be used)
  1655. * @param int $id To force other object id (should not be used)
  1656. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1657. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1658. * @param User|string $fuser Update the user of last update field with this user. If not provided, current user is used except if value is 'none'
  1659. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1660. * @param string $fk_user_field Name of field to save user id making change
  1661. * @return int <0 if KO, >0 if OK
  1662. * @see updateExtraField()
  1663. */
  1664. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1665. {
  1666. global $user, $langs, $conf;
  1667. if (empty($table)) {
  1668. $table = $this->table_element;
  1669. }
  1670. if (empty($id)) {
  1671. $id = $this->id;
  1672. }
  1673. if (empty($format)) {
  1674. $format = 'text';
  1675. }
  1676. if (empty($id_field)) {
  1677. $id_field = 'rowid';
  1678. }
  1679. $error = 0;
  1680. $this->db->begin();
  1681. // Special case
  1682. if ($table == 'product' && $field == 'note_private') {
  1683. $field = 'note';
  1684. }
  1685. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1686. $fk_user_field = 'fk_user_mod';
  1687. }
  1688. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1689. if ($format == 'text') {
  1690. $sql .= $field." = '".$this->db->escape($value)."'";
  1691. } elseif ($format == 'int') {
  1692. $sql .= $field." = ".((int) $value);
  1693. } elseif ($format == 'date') {
  1694. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1695. }
  1696. if ($fk_user_field) {
  1697. if (!empty($fuser) && is_object($fuser)) {
  1698. $sql .= ", ".$fk_user_field." = ".$fuser->id;
  1699. } elseif (empty($fuser) || $fuser != 'none') {
  1700. $sql .= ", ".$fk_user_field." = ".$user->id;
  1701. }
  1702. }
  1703. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1704. dol_syslog(__METHOD__."", LOG_DEBUG);
  1705. $resql = $this->db->query($sql);
  1706. if ($resql) {
  1707. if ($trigkey) {
  1708. // call trigger with updated object values
  1709. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1710. $result = $this->fetch($id);
  1711. } else {
  1712. $result = $this->fetchCommon($id);
  1713. }
  1714. if ($result >= 0) {
  1715. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1716. }
  1717. if ($result < 0) {
  1718. $error++;
  1719. }
  1720. }
  1721. if (!$error) {
  1722. if (property_exists($this, $field)) {
  1723. $this->$field = $value;
  1724. }
  1725. $this->db->commit();
  1726. return 1;
  1727. } else {
  1728. $this->db->rollback();
  1729. return -2;
  1730. }
  1731. } else {
  1732. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1733. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1734. } else {
  1735. $this->error = $this->db->lasterror();
  1736. }
  1737. $this->db->rollback();
  1738. return -1;
  1739. }
  1740. }
  1741. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1742. /**
  1743. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1744. *
  1745. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
  1746. * @param string $fieldid Name of field to use for the select MAX and MIN
  1747. * @param int $nodbprefix Do not include DB prefix to forge table name
  1748. * @return int <0 if KO, >0 if OK
  1749. */
  1750. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1751. {
  1752. // phpcs:enable
  1753. global $conf, $user;
  1754. if (!$this->table_element) {
  1755. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1756. return -1;
  1757. }
  1758. if ($fieldid == 'none') {
  1759. return 1;
  1760. }
  1761. // Security on socid
  1762. $socid = 0;
  1763. if ($user->socid > 0) {
  1764. $socid = $user->socid;
  1765. }
  1766. // this->ismultientitymanaged contains
  1767. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1768. $aliastablesociete = 's';
  1769. if ($this->element == 'societe') {
  1770. $aliastablesociete = 'te'; // te as table_element
  1771. }
  1772. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1773. $sql = "SELECT MAX(te.".$fieldid.")";
  1774. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1775. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1776. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1777. }
  1778. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1779. $tmparray = explode('@', $this->ismultientitymanaged);
  1780. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1781. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1782. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1783. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1784. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1785. }
  1786. if ($restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
  1787. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1788. }
  1789. $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1790. if ($restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
  1791. $sql .= " AND sc.fk_user = ".$user->id;
  1792. }
  1793. if ($restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
  1794. $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1795. }
  1796. if (!empty($filter)) {
  1797. if (!preg_match('/^\s*AND/i', $filter)) {
  1798. $sql .= " AND "; // For backward compatibility
  1799. }
  1800. $sql .= $filter;
  1801. }
  1802. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1803. $tmparray = explode('@', $this->ismultientitymanaged);
  1804. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1805. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1806. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1807. }
  1808. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1809. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1810. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1811. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1812. } else {
  1813. $sql .= " AND ug.fk_user = te.rowid";
  1814. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1815. }
  1816. } else {
  1817. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1818. }
  1819. }
  1820. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1821. $tmparray = explode('@', $this->ismultientitymanaged);
  1822. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1823. }
  1824. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1825. $sql .= ' AND te.fk_soc = '.$socid;
  1826. }
  1827. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1828. $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1829. }
  1830. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1831. $sql .= ' AND te.rowid = '.$socid;
  1832. }
  1833. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1834. $result = $this->db->query($sql);
  1835. if (!$result) {
  1836. $this->error = $this->db->lasterror();
  1837. return -1;
  1838. }
  1839. $row = $this->db->fetch_row($result);
  1840. $this->ref_previous = $row[0];
  1841. $sql = "SELECT MIN(te.".$fieldid.")";
  1842. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1843. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1844. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1845. }
  1846. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1847. $tmparray = explode('@', $this->ismultientitymanaged);
  1848. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1849. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1850. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1851. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1852. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1853. }
  1854. if ($restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
  1855. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1856. }
  1857. $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1858. if ($restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
  1859. $sql .= " AND sc.fk_user = ".$user->id;
  1860. }
  1861. if ($restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
  1862. $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1863. }
  1864. if (!empty($filter)) {
  1865. if (!preg_match('/^\s*AND/i', $filter)) {
  1866. $sql .= " AND "; // For backward compatibility
  1867. }
  1868. $sql .= $filter;
  1869. }
  1870. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1871. $tmparray = explode('@', $this->ismultientitymanaged);
  1872. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1873. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1874. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1875. }
  1876. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1877. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1878. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1879. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1880. } else {
  1881. $sql .= " AND ug.fk_user = te.rowid";
  1882. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1883. }
  1884. } else {
  1885. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1886. }
  1887. }
  1888. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1889. $tmparray = explode('@', $this->ismultientitymanaged);
  1890. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1891. }
  1892. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1893. $sql .= ' AND te.fk_soc = '.$socid;
  1894. }
  1895. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1896. $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1897. }
  1898. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1899. $sql .= ' AND te.rowid = '.$socid;
  1900. }
  1901. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1902. // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null
  1903. $result = $this->db->query($sql);
  1904. if (!$result) {
  1905. $this->error = $this->db->lasterror();
  1906. return -2;
  1907. }
  1908. $row = $this->db->fetch_row($result);
  1909. $this->ref_next = $row[0];
  1910. return 1;
  1911. }
  1912. /**
  1913. * Return list of id of contacts of object
  1914. *
  1915. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1916. * @return array Array of id of contacts (if source=external or internal)
  1917. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1918. */
  1919. public function getListContactId($source = 'external')
  1920. {
  1921. $contactAlreadySelected = array();
  1922. $tab = $this->liste_contact(-1, $source);
  1923. $num = count($tab);
  1924. $i = 0;
  1925. while ($i < $num) {
  1926. if ($source == 'thirdparty') {
  1927. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1928. } else {
  1929. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1930. }
  1931. $i++;
  1932. }
  1933. return $contactAlreadySelected;
  1934. }
  1935. /**
  1936. * Link element with a project
  1937. *
  1938. * @param int $projectid Project id to link element to
  1939. * @return int <0 if KO, >0 if OK
  1940. */
  1941. public function setProject($projectid)
  1942. {
  1943. if (!$this->table_element) {
  1944. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1945. return -1;
  1946. }
  1947. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1948. if (!empty($this->fields['fk_project'])) { // Common case
  1949. if ($projectid) {
  1950. $sql .= ' SET fk_project = '.((int) $projectid);
  1951. } else {
  1952. $sql .= ' SET fk_project = NULL';
  1953. }
  1954. $sql .= ' WHERE rowid = '.((int) $this->id);
  1955. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  1956. if ($projectid) {
  1957. $sql .= ' SET fk_project = '.((int) $projectid);
  1958. } else {
  1959. $sql .= ' SET fk_project = NULL';
  1960. }
  1961. $sql .= ' WHERE id = '.((int) $this->id);
  1962. } else // Special case for old architecture objects
  1963. {
  1964. if ($projectid) {
  1965. $sql .= ' SET fk_projet = '.((int) $projectid);
  1966. } else {
  1967. $sql .= ' SET fk_projet = NULL';
  1968. }
  1969. $sql .= ' WHERE rowid = '.$this->id;
  1970. }
  1971. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1972. if ($this->db->query($sql)) {
  1973. $this->fk_project = ((int) $projectid);
  1974. return 1;
  1975. } else {
  1976. dol_print_error($this->db);
  1977. return -1;
  1978. }
  1979. }
  1980. /**
  1981. * Change the payments methods
  1982. *
  1983. * @param int $id Id of new payment method
  1984. * @return int >0 if OK, <0 if KO
  1985. */
  1986. public function setPaymentMethods($id)
  1987. {
  1988. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1989. if ($this->statut >= 0 || $this->element == 'societe') {
  1990. // TODO uniformize field name
  1991. $fieldname = 'fk_mode_reglement';
  1992. if ($this->element == 'societe') {
  1993. $fieldname = 'mode_reglement';
  1994. }
  1995. if (get_class($this) == 'Fournisseur') {
  1996. $fieldname = 'mode_reglement_supplier';
  1997. }
  1998. if (get_class($this) == 'Tva') {
  1999. $fieldname = 'fk_typepayment';
  2000. }
  2001. if (get_class($this) == 'Salary') {
  2002. $fieldname = 'fk_typepayment';
  2003. }
  2004. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2005. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2006. $sql .= ' WHERE rowid='.((int) $this->id);
  2007. if ($this->db->query($sql)) {
  2008. $this->mode_reglement_id = $id;
  2009. // for supplier
  2010. if (get_class($this) == 'Fournisseur') {
  2011. $this->mode_reglement_supplier_id = $id;
  2012. }
  2013. return 1;
  2014. } else {
  2015. dol_syslog(get_class($this).'::setPaymentMethods Error '.$sql.' - '.$this->db->error());
  2016. $this->error = $this->db->error();
  2017. return -1;
  2018. }
  2019. } else {
  2020. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2021. $this->error = 'Status of the object is incompatible '.$this->statut;
  2022. return -2;
  2023. }
  2024. }
  2025. /**
  2026. * Change the multicurrency code
  2027. *
  2028. * @param string $code multicurrency code
  2029. * @return int >0 if OK, <0 if KO
  2030. */
  2031. public function setMulticurrencyCode($code)
  2032. {
  2033. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2034. if ($this->statut >= 0 || $this->element == 'societe') {
  2035. $fieldname = 'multicurrency_code';
  2036. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2037. $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
  2038. $sql .= ' WHERE rowid='.((int) $this->id);
  2039. if ($this->db->query($sql)) {
  2040. $this->multicurrency_code = $code;
  2041. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2042. if ($rate) {
  2043. $this->setMulticurrencyRate($rate, 2);
  2044. }
  2045. return 1;
  2046. } else {
  2047. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2048. $this->error = $this->db->error();
  2049. return -1;
  2050. }
  2051. } else {
  2052. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2053. $this->error = 'Status of the object is incompatible '.$this->statut;
  2054. return -2;
  2055. }
  2056. }
  2057. /**
  2058. * Change the multicurrency rate
  2059. *
  2060. * @param double $rate multicurrency rate
  2061. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2062. * @return int >0 if OK, <0 if KO
  2063. */
  2064. public function setMulticurrencyRate($rate, $mode = 1)
  2065. {
  2066. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2067. if ($this->statut >= 0 || $this->element == 'societe') {
  2068. $fieldname = 'multicurrency_tx';
  2069. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2070. $sql .= ' SET '.$fieldname.' = '.((float) $rate);
  2071. $sql .= ' WHERE rowid='.((int) $this->id);
  2072. if ($this->db->query($sql)) {
  2073. $this->multicurrency_tx = $rate;
  2074. // Update line price
  2075. if (!empty($this->lines)) {
  2076. foreach ($this->lines as &$line) {
  2077. // Amounts in company currency will be recalculated
  2078. if ($mode == 1) {
  2079. $line->subprice = 0;
  2080. }
  2081. // Amounts in foreign currency will be recalculated
  2082. if ($mode == 2) {
  2083. $line->multicurrency_subprice = 0;
  2084. }
  2085. switch ($this->element) {
  2086. case 'propal':
  2087. $this->updateline(
  2088. $line->id,
  2089. $line->subprice,
  2090. $line->qty,
  2091. $line->remise_percent,
  2092. $line->tva_tx,
  2093. $line->localtax1_tx,
  2094. $line->localtax2_tx,
  2095. ($line->description ? $line->description : $line->desc),
  2096. 'HT',
  2097. $line->info_bits,
  2098. $line->special_code,
  2099. $line->fk_parent_line,
  2100. $line->skip_update_total,
  2101. $line->fk_fournprice,
  2102. $line->pa_ht,
  2103. $line->label,
  2104. $line->product_type,
  2105. $line->date_start,
  2106. $line->date_end,
  2107. $line->array_options,
  2108. $line->fk_unit,
  2109. $line->multicurrency_subprice
  2110. );
  2111. break;
  2112. case 'commande':
  2113. $this->updateline(
  2114. $line->id,
  2115. ($line->description ? $line->description : $line->desc),
  2116. $line->subprice,
  2117. $line->qty,
  2118. $line->remise_percent,
  2119. $line->tva_tx,
  2120. $line->localtax1_tx,
  2121. $line->localtax2_tx,
  2122. 'HT',
  2123. $line->info_bits,
  2124. $line->date_start,
  2125. $line->date_end,
  2126. $line->product_type,
  2127. $line->fk_parent_line,
  2128. $line->skip_update_total,
  2129. $line->fk_fournprice,
  2130. $line->pa_ht,
  2131. $line->label,
  2132. $line->special_code,
  2133. $line->array_options,
  2134. $line->fk_unit,
  2135. $line->multicurrency_subprice
  2136. );
  2137. break;
  2138. case 'facture':
  2139. $this->updateline(
  2140. $line->id,
  2141. ($line->description ? $line->description : $line->desc),
  2142. $line->subprice,
  2143. $line->qty,
  2144. $line->remise_percent,
  2145. $line->date_start,
  2146. $line->date_end,
  2147. $line->tva_tx,
  2148. $line->localtax1_tx,
  2149. $line->localtax2_tx,
  2150. 'HT',
  2151. $line->info_bits,
  2152. $line->product_type,
  2153. $line->fk_parent_line,
  2154. $line->skip_update_total,
  2155. $line->fk_fournprice,
  2156. $line->pa_ht,
  2157. $line->label,
  2158. $line->special_code,
  2159. $line->array_options,
  2160. $line->situation_percent,
  2161. $line->fk_unit,
  2162. $line->multicurrency_subprice
  2163. );
  2164. break;
  2165. case 'supplier_proposal':
  2166. $this->updateline(
  2167. $line->id,
  2168. $line->subprice,
  2169. $line->qty,
  2170. $line->remise_percent,
  2171. $line->tva_tx,
  2172. $line->localtax1_tx,
  2173. $line->localtax2_tx,
  2174. ($line->description ? $line->description : $line->desc),
  2175. 'HT',
  2176. $line->info_bits,
  2177. $line->special_code,
  2178. $line->fk_parent_line,
  2179. $line->skip_update_total,
  2180. $line->fk_fournprice,
  2181. $line->pa_ht,
  2182. $line->label,
  2183. $line->product_type,
  2184. $line->array_options,
  2185. $line->ref_fourn,
  2186. $line->multicurrency_subprice
  2187. );
  2188. break;
  2189. case 'order_supplier':
  2190. $this->updateline(
  2191. $line->id,
  2192. ($line->description ? $line->description : $line->desc),
  2193. $line->subprice,
  2194. $line->qty,
  2195. $line->remise_percent,
  2196. $line->tva_tx,
  2197. $line->localtax1_tx,
  2198. $line->localtax2_tx,
  2199. 'HT',
  2200. $line->info_bits,
  2201. $line->product_type,
  2202. false,
  2203. $line->date_start,
  2204. $line->date_end,
  2205. $line->array_options,
  2206. $line->fk_unit,
  2207. $line->multicurrency_subprice,
  2208. $line->ref_supplier
  2209. );
  2210. break;
  2211. case 'invoice_supplier':
  2212. $this->updateline(
  2213. $line->id,
  2214. ($line->description ? $line->description : $line->desc),
  2215. $line->subprice,
  2216. $line->tva_tx,
  2217. $line->localtax1_tx,
  2218. $line->localtax2_tx,
  2219. $line->qty,
  2220. 0,
  2221. 'HT',
  2222. $line->info_bits,
  2223. $line->product_type,
  2224. $line->remise_percent,
  2225. false,
  2226. $line->date_start,
  2227. $line->date_end,
  2228. $line->array_options,
  2229. $line->fk_unit,
  2230. $line->multicurrency_subprice,
  2231. $line->ref_supplier
  2232. );
  2233. break;
  2234. default:
  2235. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2236. break;
  2237. }
  2238. }
  2239. }
  2240. return 1;
  2241. } else {
  2242. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2243. $this->error = $this->db->error();
  2244. return -1;
  2245. }
  2246. } else {
  2247. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2248. $this->error = 'Status of the object is incompatible '.$this->statut;
  2249. return -2;
  2250. }
  2251. }
  2252. /**
  2253. * Change the payments terms
  2254. *
  2255. * @param int $id Id of new payment terms
  2256. * @return int >0 if OK, <0 if KO
  2257. */
  2258. public function setPaymentTerms($id)
  2259. {
  2260. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  2261. if ($this->statut >= 0 || $this->element == 'societe') {
  2262. // TODO uniformize field name
  2263. $fieldname = 'fk_cond_reglement';
  2264. if ($this->element == 'societe') {
  2265. $fieldname = 'cond_reglement';
  2266. }
  2267. if (get_class($this) == 'Fournisseur') {
  2268. $fieldname = 'cond_reglement_supplier';
  2269. }
  2270. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2271. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2272. $sql .= ' WHERE rowid='.((int) $this->id);
  2273. if ($this->db->query($sql)) {
  2274. $this->cond_reglement_id = $id;
  2275. // for supplier
  2276. if (get_class($this) == 'Fournisseur') {
  2277. $this->cond_reglement_supplier_id = $id;
  2278. }
  2279. $this->cond_reglement = $id; // for compatibility
  2280. return 1;
  2281. } else {
  2282. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2283. $this->error = $this->db->error();
  2284. return -1;
  2285. }
  2286. } else {
  2287. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2288. $this->error = 'Status of the object is incompatible '.$this->statut;
  2289. return -2;
  2290. }
  2291. }
  2292. /**
  2293. * Change the transport mode methods
  2294. *
  2295. * @param int $id Id of transport mode
  2296. * @return int >0 if OK, <0 if KO
  2297. */
  2298. public function setTransportMode($id)
  2299. {
  2300. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2301. if ($this->statut >= 0 || $this->element == 'societe') {
  2302. $fieldname = 'fk_transport_mode';
  2303. if ($this->element == 'societe') {
  2304. $fieldname = 'transport_mode';
  2305. }
  2306. if (get_class($this) == 'Fournisseur') {
  2307. $fieldname = 'transport_mode_supplier';
  2308. }
  2309. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2310. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2311. $sql .= ' WHERE rowid='.((int) $this->id);
  2312. if ($this->db->query($sql)) {
  2313. $this->transport_mode_id = $id;
  2314. // for supplier
  2315. if (get_class($this) == 'Fournisseur') {
  2316. $this->transport_mode_supplier_id = $id;
  2317. }
  2318. return 1;
  2319. } else {
  2320. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2321. $this->error = $this->db->error();
  2322. return -1;
  2323. }
  2324. } else {
  2325. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2326. $this->error = 'Status of the object is incompatible '.$this->statut;
  2327. return -2;
  2328. }
  2329. }
  2330. /**
  2331. * Change the retained warranty payments terms
  2332. *
  2333. * @param int $id Id of new payment terms
  2334. * @return int >0 if OK, <0 if KO
  2335. */
  2336. public function setRetainedWarrantyPaymentTerms($id)
  2337. {
  2338. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2339. if ($this->statut >= 0 || $this->element == 'societe') {
  2340. $fieldname = 'retained_warranty_fk_cond_reglement';
  2341. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2342. $sql .= ' SET '.$fieldname.' = '.((int) $id);
  2343. $sql .= ' WHERE rowid='.((int) $this->id);
  2344. if ($this->db->query($sql)) {
  2345. $this->retained_warranty_fk_cond_reglement = $id;
  2346. return 1;
  2347. } else {
  2348. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2349. $this->error = $this->db->error();
  2350. return -1;
  2351. }
  2352. } else {
  2353. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2354. $this->error = 'Status of the object is incompatible '.$this->statut;
  2355. return -2;
  2356. }
  2357. }
  2358. /**
  2359. * Define delivery address
  2360. * @deprecated
  2361. *
  2362. * @param int $id Address id
  2363. * @return int <0 si ko, >0 si ok
  2364. */
  2365. public function setDeliveryAddress($id)
  2366. {
  2367. $fieldname = 'fk_delivery_address';
  2368. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2369. $fieldname = 'fk_address';
  2370. }
  2371. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".((int) $id);
  2372. $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  2373. if ($this->db->query($sql)) {
  2374. $this->fk_delivery_address = $id;
  2375. return 1;
  2376. } else {
  2377. $this->error = $this->db->error();
  2378. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$sql.' - '.$this->error);
  2379. return -1;
  2380. }
  2381. }
  2382. /**
  2383. * Change the shipping method
  2384. *
  2385. * @param int $shipping_method_id Id of shipping method
  2386. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2387. * @param User $userused Object user
  2388. *
  2389. * @return int 1 if OK, 0 if KO
  2390. */
  2391. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2392. {
  2393. global $user;
  2394. if (empty($userused)) {
  2395. $userused = $user;
  2396. }
  2397. $error = 0;
  2398. if (!$this->table_element) {
  2399. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2400. return -1;
  2401. }
  2402. $this->db->begin();
  2403. if ($shipping_method_id < 0) {
  2404. $shipping_method_id = 'NULL';
  2405. }
  2406. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2407. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2408. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2409. $sql .= " WHERE rowid=".((int) $this->id);
  2410. $resql = $this->db->query($sql);
  2411. if (!$resql) {
  2412. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2413. $this->error = $this->db->lasterror();
  2414. $error++;
  2415. } else {
  2416. if (!$notrigger) {
  2417. // Call trigger
  2418. $this->context = array('shippingmethodupdate'=>1);
  2419. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2420. if ($result < 0) {
  2421. $error++;
  2422. }
  2423. // End call trigger
  2424. }
  2425. }
  2426. if ($error) {
  2427. $this->db->rollback();
  2428. return -1;
  2429. } else {
  2430. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2431. $this->db->commit();
  2432. return 1;
  2433. }
  2434. }
  2435. /**
  2436. * Change the warehouse
  2437. *
  2438. * @param int $warehouse_id Id of warehouse
  2439. * @return int 1 if OK, 0 if KO
  2440. */
  2441. public function setWarehouse($warehouse_id)
  2442. {
  2443. if (!$this->table_element) {
  2444. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2445. return -1;
  2446. }
  2447. if ($warehouse_id < 0) {
  2448. $warehouse_id = 'NULL';
  2449. }
  2450. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2451. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2452. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2453. $sql .= " WHERE rowid=".((int) $this->id);
  2454. if ($this->db->query($sql)) {
  2455. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2456. return 1;
  2457. } else {
  2458. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2459. $this->error = $this->db->error();
  2460. return 0;
  2461. }
  2462. }
  2463. /**
  2464. * Set last model used by doc generator
  2465. *
  2466. * @param User $user User object that make change
  2467. * @param string $modelpdf Modele name
  2468. * @return int <0 if KO, >0 if OK
  2469. */
  2470. public function setDocModel($user, $modelpdf)
  2471. {
  2472. if (!$this->table_element) {
  2473. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2474. return -1;
  2475. }
  2476. $newmodelpdf = dol_trunc($modelpdf, 255);
  2477. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2478. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2479. $sql .= " WHERE rowid = ".$this->id;
  2480. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2481. $resql = $this->db->query($sql);
  2482. if ($resql) {
  2483. $this->model_pdf = $modelpdf;
  2484. $this->modelpdf = $modelpdf; // For bakward compatibility
  2485. return 1;
  2486. } else {
  2487. dol_print_error($this->db);
  2488. return 0;
  2489. }
  2490. }
  2491. /**
  2492. * Change the bank account
  2493. *
  2494. * @param int $fk_account Id of bank account
  2495. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2496. * @param User $userused Object user
  2497. * @return int 1 if OK, 0 if KO
  2498. */
  2499. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2500. {
  2501. global $user;
  2502. if (empty($userused)) {
  2503. $userused = $user;
  2504. }
  2505. $error = 0;
  2506. if (!$this->table_element) {
  2507. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2508. return -1;
  2509. }
  2510. $this->db->begin();
  2511. if ($fk_account < 0) {
  2512. $fk_account = 'NULL';
  2513. }
  2514. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2515. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2516. $sql .= " SET fk_account = ".((int) $fk_account);
  2517. $sql .= " WHERE rowid=".((int) $this->id);
  2518. $resql = $this->db->query($sql);
  2519. if (!$resql) {
  2520. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2521. $this->error = $this->db->lasterror();
  2522. $error++;
  2523. } else {
  2524. if (!$notrigger) {
  2525. // Call trigger
  2526. $this->context = array('bankaccountupdate'=>1);
  2527. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2528. if ($result < 0) {
  2529. $error++;
  2530. }
  2531. // End call trigger
  2532. }
  2533. }
  2534. if ($error) {
  2535. $this->db->rollback();
  2536. return -1;
  2537. } else {
  2538. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2539. $this->db->commit();
  2540. return 1;
  2541. }
  2542. }
  2543. // TODO: Move line related operations to CommonObjectLine?
  2544. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2545. /**
  2546. * Save a new position (field rang) for details lines.
  2547. * You can choose to set position for lines with already a position or lines without any position defined.
  2548. *
  2549. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2550. * @param string $rowidorder ASC or DESC
  2551. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2552. * @return int <0 if KO, >0 if OK
  2553. */
  2554. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2555. {
  2556. // phpcs:enable
  2557. if (!$this->table_element_line) {
  2558. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2559. return -1;
  2560. }
  2561. if (!$this->fk_element) {
  2562. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2563. return -1;
  2564. }
  2565. // Count number of lines to reorder (according to choice $renum)
  2566. $nl = 0;
  2567. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2568. $sql .= ' WHERE '.$this->fk_element.'='.$this->id;
  2569. if (!$renum) {
  2570. $sql .= ' AND rang = 0';
  2571. }
  2572. if ($renum) {
  2573. $sql .= ' AND rang <> 0';
  2574. }
  2575. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2576. $resql = $this->db->query($sql);
  2577. if ($resql) {
  2578. $row = $this->db->fetch_row($resql);
  2579. $nl = $row[0];
  2580. } else {
  2581. dol_print_error($this->db);
  2582. }
  2583. if ($nl > 0) {
  2584. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2585. $rows = array();
  2586. // We first search all lines that are parent lines (for multilevel details lines)
  2587. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2588. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2589. if ($fk_parent_line) {
  2590. $sql .= ' AND fk_parent_line IS NULL';
  2591. }
  2592. $sql .= ' ORDER BY rang ASC, rowid '.$rowidorder;
  2593. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2594. $resql = $this->db->query($sql);
  2595. if ($resql) {
  2596. $i = 0;
  2597. $num = $this->db->num_rows($resql);
  2598. while ($i < $num) {
  2599. $row = $this->db->fetch_row($resql);
  2600. $rows[] = $row[0]; // Add parent line into array rows
  2601. $childrens = $this->getChildrenOfLine($row[0]);
  2602. if (!empty($childrens)) {
  2603. foreach ($childrens as $child) {
  2604. array_push($rows, $child);
  2605. }
  2606. }
  2607. $i++;
  2608. }
  2609. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2610. if (!empty($rows)) {
  2611. foreach ($rows as $key => $row) {
  2612. $this->updateRangOfLine($row, ($key + 1));
  2613. }
  2614. }
  2615. } else {
  2616. dol_print_error($this->db);
  2617. }
  2618. }
  2619. return 1;
  2620. }
  2621. /**
  2622. * Get children of line
  2623. *
  2624. * @param int $id Id of parent line
  2625. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2626. * @return array Array with list of children lines id
  2627. */
  2628. public function getChildrenOfLine($id, $includealltree = 0)
  2629. {
  2630. $rows = array();
  2631. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2632. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2633. $sql .= ' AND fk_parent_line = '.$id;
  2634. $sql .= ' ORDER BY rang ASC';
  2635. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  2636. $resql = $this->db->query($sql);
  2637. if ($resql) {
  2638. if ($this->db->num_rows($resql) > 0) {
  2639. while ($row = $this->db->fetch_row($resql)) {
  2640. $rows[] = $row[0];
  2641. if (!empty($includealltree)) {
  2642. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2643. }
  2644. }
  2645. }
  2646. }
  2647. return $rows;
  2648. }
  2649. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2650. /**
  2651. * Update a line to have a lower rank
  2652. *
  2653. * @param int $rowid Id of line
  2654. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2655. * @return void
  2656. */
  2657. public function line_up($rowid, $fk_parent_line = true)
  2658. {
  2659. // phpcs:enable
  2660. $this->line_order(false, 'ASC', $fk_parent_line);
  2661. // Get rang of line
  2662. $rang = $this->getRangOfLine($rowid);
  2663. // Update position of line
  2664. $this->updateLineUp($rowid, $rang);
  2665. }
  2666. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2667. /**
  2668. * Update a line to have a higher rank
  2669. *
  2670. * @param int $rowid Id of line
  2671. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2672. * @return void
  2673. */
  2674. public function line_down($rowid, $fk_parent_line = true)
  2675. {
  2676. // phpcs:enable
  2677. $this->line_order(false, 'ASC', $fk_parent_line);
  2678. // Get rang of line
  2679. $rang = $this->getRangOfLine($rowid);
  2680. // Get max value for rang
  2681. $max = $this->line_max();
  2682. // Update position of line
  2683. $this->updateLineDown($rowid, $rang, $max);
  2684. }
  2685. /**
  2686. * Update position of line (rang)
  2687. *
  2688. * @param int $rowid Id of line
  2689. * @param int $rang Position
  2690. * @return void
  2691. */
  2692. public function updateRangOfLine($rowid, $rang)
  2693. {
  2694. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2695. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) {
  2696. $fieldposition = 'position';
  2697. }
  2698. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2699. $sql .= ' WHERE rowid = '.((int) $rowid);
  2700. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2701. if (!$this->db->query($sql)) {
  2702. dol_print_error($this->db);
  2703. }
  2704. }
  2705. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2706. /**
  2707. * Update position of line with ajax (rang)
  2708. *
  2709. * @param array $rows Array of rows
  2710. * @return void
  2711. */
  2712. public function line_ajaxorder($rows)
  2713. {
  2714. // phpcs:enable
  2715. $num = count($rows);
  2716. for ($i = 0; $i < $num; $i++) {
  2717. $this->updateRangOfLine($rows[$i], ($i + 1));
  2718. }
  2719. }
  2720. /**
  2721. * Update position of line up (rang)
  2722. *
  2723. * @param int $rowid Id of line
  2724. * @param int $rang Position
  2725. * @return void
  2726. */
  2727. public function updateLineUp($rowid, $rang)
  2728. {
  2729. if ($rang > 1) {
  2730. $fieldposition = 'rang';
  2731. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2732. $fieldposition = 'position';
  2733. }
  2734. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2735. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2736. $sql .= ' AND rang = '.($rang - 1);
  2737. if ($this->db->query($sql)) {
  2738. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) ($rang - 1));
  2739. $sql .= ' WHERE rowid = '.((int) $rowid);
  2740. if (!$this->db->query($sql)) {
  2741. dol_print_error($this->db);
  2742. }
  2743. } else {
  2744. dol_print_error($this->db);
  2745. }
  2746. }
  2747. }
  2748. /**
  2749. * Update position of line down (rang)
  2750. *
  2751. * @param int $rowid Id of line
  2752. * @param int $rang Position
  2753. * @param int $max Max
  2754. * @return void
  2755. */
  2756. public function updateLineDown($rowid, $rang, $max)
  2757. {
  2758. if ($rang < $max) {
  2759. $fieldposition = 'rang';
  2760. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2761. $fieldposition = 'position';
  2762. }
  2763. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2764. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2765. $sql .= ' AND rang = '.((int) ($rang + 1));
  2766. if ($this->db->query($sql)) {
  2767. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) ($rang + 1));
  2768. $sql .= ' WHERE rowid = '.((int) $rowid);
  2769. if (!$this->db->query($sql)) {
  2770. dol_print_error($this->db);
  2771. }
  2772. } else {
  2773. dol_print_error($this->db);
  2774. }
  2775. }
  2776. }
  2777. /**
  2778. * Get position of line (rang)
  2779. *
  2780. * @param int $rowid Id of line
  2781. * @return int Value of rang in table of lines
  2782. */
  2783. public function getRangOfLine($rowid)
  2784. {
  2785. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2786. $sql .= ' WHERE rowid ='.((int) $rowid);
  2787. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2788. $resql = $this->db->query($sql);
  2789. if ($resql) {
  2790. $row = $this->db->fetch_row($resql);
  2791. return $row[0];
  2792. }
  2793. }
  2794. /**
  2795. * Get rowid of the line relative to its position
  2796. *
  2797. * @param int $rang Rang value
  2798. * @return int Rowid of the line
  2799. */
  2800. public function getIdOfLine($rang)
  2801. {
  2802. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2803. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2804. $sql .= ' AND rang = '.((int) $rang);
  2805. $resql = $this->db->query($sql);
  2806. if ($resql) {
  2807. $row = $this->db->fetch_row($resql);
  2808. return $row[0];
  2809. }
  2810. }
  2811. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2812. /**
  2813. * Get max value used for position of line (rang)
  2814. *
  2815. * @param int $fk_parent_line Parent line id
  2816. * @return int Max value of rang in table of lines
  2817. */
  2818. public function line_max($fk_parent_line = 0)
  2819. {
  2820. // phpcs:enable
  2821. $positionfield = 'rang';
  2822. if ($this->table_element == 'bom_bom') {
  2823. $positionfield = 'position';
  2824. }
  2825. // Search the last rang with fk_parent_line
  2826. if ($fk_parent_line) {
  2827. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2828. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2829. $sql .= ' AND fk_parent_line = '.$fk_parent_line;
  2830. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2831. $resql = $this->db->query($sql);
  2832. if ($resql) {
  2833. $row = $this->db->fetch_row($resql);
  2834. if (!empty($row[0])) {
  2835. return $row[0];
  2836. } else {
  2837. return $this->getRangOfLine($fk_parent_line);
  2838. }
  2839. }
  2840. } else {
  2841. // If not, search the last rang of element
  2842. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2843. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2844. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2845. $resql = $this->db->query($sql);
  2846. if ($resql) {
  2847. $row = $this->db->fetch_row($resql);
  2848. return $row[0];
  2849. }
  2850. }
  2851. }
  2852. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2853. /**
  2854. * Update external ref of element
  2855. *
  2856. * @param string $ref_ext Update field ref_ext
  2857. * @return int <0 if KO, >0 if OK
  2858. */
  2859. public function update_ref_ext($ref_ext)
  2860. {
  2861. // phpcs:enable
  2862. if (!$this->table_element) {
  2863. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2864. return -1;
  2865. }
  2866. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2867. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2868. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id;
  2869. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2870. if ($this->db->query($sql)) {
  2871. $this->ref_ext = $ref_ext;
  2872. return 1;
  2873. } else {
  2874. $this->error = $this->db->error();
  2875. return -1;
  2876. }
  2877. }
  2878. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2879. /**
  2880. * Update note of element
  2881. *
  2882. * @param string $note New value for note
  2883. * @param string $suffix '', '_public' or '_private'
  2884. * @return int <0 if KO, >0 if OK
  2885. */
  2886. public function update_note($note, $suffix = '')
  2887. {
  2888. // phpcs:enable
  2889. global $user;
  2890. if (!$this->table_element) {
  2891. $this->error = 'update_note was called on objet with property table_element not defined';
  2892. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2893. return -1;
  2894. }
  2895. if (!in_array($suffix, array('', '_public', '_private'))) {
  2896. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2897. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2898. return -2;
  2899. }
  2900. $newsuffix = $suffix;
  2901. // Special cas
  2902. if ($this->table_element == 'product' && $newsuffix == '_private') {
  2903. $newsuffix = '';
  2904. }
  2905. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  2906. $fieldusermod = "fk_user_mod";
  2907. } elseif ($this->table_element == 'ecm_files') {
  2908. $fieldusermod = "fk_user_m";
  2909. } else {
  2910. $fieldusermod = "fk_user_modif";
  2911. }
  2912. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2913. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2914. $sql .= " ,".$fieldusermod." = ".$user->id;
  2915. $sql .= " WHERE rowid =".$this->id;
  2916. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2917. if ($this->db->query($sql)) {
  2918. if ($suffix == '_public') {
  2919. $this->note_public = $note;
  2920. } elseif ($suffix == '_private') {
  2921. $this->note_private = $note;
  2922. } else {
  2923. $this->note = $note; // deprecated
  2924. $this->note_private = $note;
  2925. }
  2926. return 1;
  2927. } else {
  2928. $this->error = $this->db->lasterror();
  2929. return -1;
  2930. }
  2931. }
  2932. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2933. /**
  2934. * Update public note (kept for backward compatibility)
  2935. *
  2936. * @param string $note New value for note
  2937. * @return int <0 if KO, >0 if OK
  2938. * @deprecated
  2939. * @see update_note()
  2940. */
  2941. public function update_note_public($note)
  2942. {
  2943. // phpcs:enable
  2944. return $this->update_note($note, '_public');
  2945. }
  2946. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2947. /**
  2948. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2949. * Must be called at end of methods addline or updateline.
  2950. *
  2951. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2952. * @param string $roundingadjust 'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total
  2953. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2954. * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object.
  2955. * @return int <0 if KO, >0 if OK
  2956. */
  2957. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  2958. {
  2959. // phpcs:enable
  2960. global $conf, $hookmanager, $action;
  2961. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  2962. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2963. if ($reshook > 0) {
  2964. return 1; // replacement code
  2965. } elseif ($reshook < 0) {
  2966. return -1; // failure
  2967. } // reshook = 0 => execute normal code
  2968. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  2969. $MODULE = "";
  2970. if ($this->element == 'propal') {
  2971. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  2972. } elseif ($this->element == 'commande' || $this->element == 'order') {
  2973. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  2974. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  2975. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  2976. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier') {
  2977. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  2978. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  2979. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  2980. } elseif ($this->element == 'supplier_proposal') {
  2981. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  2982. }
  2983. if (!empty($MODULE)) {
  2984. if (!empty($conf->global->$MODULE)) {
  2985. $modsactivated = explode(',', $conf->global->$MODULE);
  2986. foreach ($modsactivated as $mod) {
  2987. if ($conf->$mod->enabled) {
  2988. return 1; // update was disabled by specific setup
  2989. }
  2990. }
  2991. }
  2992. }
  2993. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2994. if ($roundingadjust == '-1') {
  2995. $roundingadjust = 'auto'; // For backward compatibility
  2996. }
  2997. $forcedroundingmode = $roundingadjust;
  2998. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  2999. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  3000. } elseif ($forcedroundingmode == 'auto') {
  3001. $forcedroundingmode = '0';
  3002. }
  3003. $error = 0;
  3004. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3005. // Define constants to find lines to sum
  3006. $fieldtva = 'total_tva';
  3007. $fieldlocaltax1 = 'total_localtax1';
  3008. $fieldlocaltax2 = 'total_localtax2';
  3009. $fieldup = 'subprice';
  3010. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3011. $fieldtva = 'tva';
  3012. $fieldup = 'pu_ht';
  3013. }
  3014. if ($this->element == 'expensereport') {
  3015. $fieldup = 'value_unit';
  3016. }
  3017. $sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,';
  3018. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3019. if ($this->table_element_line == 'facturedet') {
  3020. $sql .= ', situation_percent';
  3021. }
  3022. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3023. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3024. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  3025. if ($exclspec) {
  3026. $product_field = 'product_type';
  3027. if ($this->table_element_line == 'contratdet') {
  3028. $product_field = ''; // contratdet table has no product_type field
  3029. }
  3030. if ($product_field) {
  3031. $sql .= ' AND '.$product_field.' <> 9';
  3032. }
  3033. }
  3034. $sql .= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used
  3035. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3036. $resql = $this->db->query($sql);
  3037. if ($resql) {
  3038. $this->total_ht = 0;
  3039. $this->total_tva = 0;
  3040. $this->total_localtax1 = 0;
  3041. $this->total_localtax2 = 0;
  3042. $this->total_ttc = 0;
  3043. $total_ht_by_vats = array();
  3044. $total_tva_by_vats = array();
  3045. $total_ttc_by_vats = array();
  3046. $this->multicurrency_total_ht = 0;
  3047. $this->multicurrency_total_tva = 0;
  3048. $this->multicurrency_total_ttc = 0;
  3049. $num = $this->db->num_rows($resql);
  3050. $i = 0;
  3051. while ($i < $num) {
  3052. $obj = $this->db->fetch_object($resql);
  3053. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3054. $parameters = array('fk_element' => $obj->rowid);
  3055. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3056. if (empty($reshook) && $forcedroundingmode == '0') { // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
  3057. // This part of code is to fix data. We should not call it too often.
  3058. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3059. $tmpcal = calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
  3060. $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price adn unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
  3061. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3062. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3063. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3064. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3065. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  3066. dol_syslog('We found unconsistent data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
  3067. $resqlfix = $this->db->query($sqlfix);
  3068. if (!$resqlfix) {
  3069. dol_print_error($this->db, 'Failed to update line');
  3070. }
  3071. $obj->total_tva = $tmpcal[1];
  3072. $obj->total_ttc = $tmpcal[2];
  3073. }
  3074. }
  3075. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3076. $this->total_tva += $obj->total_tva;
  3077. $this->total_localtax1 += $obj->total_localtax1;
  3078. $this->total_localtax2 += $obj->total_localtax2;
  3079. $this->total_ttc += $obj->total_ttc;
  3080. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3081. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3082. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3083. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3084. $total_ht_by_vats[$obj->vatrate] = 0;
  3085. }
  3086. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3087. $total_tva_by_vats[$obj->vatrate] = 0;
  3088. }
  3089. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3090. $total_ttc_by_vats[$obj->vatrate] = 0;
  3091. }
  3092. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3093. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3094. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3095. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3096. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3097. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3098. //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."<br>\n";
  3099. if ($diff) {
  3100. if (abs($diff) > 0.1) {
  3101. $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your line may be corrupted. Try to edit each line manually.';
  3102. dol_syslog($errmsg, LOG_WARNING);
  3103. dol_print_error('', $errmsg);
  3104. exit;
  3105. }
  3106. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid;
  3107. dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
  3108. $resqlfix = $this->db->query($sqlfix);
  3109. if (!$resqlfix) {
  3110. dol_print_error($this->db, 'Failed to update line');
  3111. }
  3112. $this->total_tva -= $diff;
  3113. $this->total_ttc -= $diff;
  3114. $total_tva_by_vats[$obj->vatrate] -= $diff;
  3115. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  3116. }
  3117. }
  3118. $i++;
  3119. }
  3120. // Add revenue stamp to total
  3121. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3122. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3123. // Situations totals
  3124. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3125. $prev_sits = $this->get_prev_sits();
  3126. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3127. $this->total_ht -= $sit->total_ht;
  3128. $this->total_tva -= $sit->total_tva;
  3129. $this->total_localtax1 -= $sit->total_localtax1;
  3130. $this->total_localtax2 -= $sit->total_localtax2;
  3131. $this->total_ttc -= $sit->total_ttc;
  3132. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3133. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3134. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3135. }
  3136. }
  3137. $this->db->free($resql);
  3138. // Now update global field total_ht, total_ttc and tva
  3139. $fieldht = 'total_ht';
  3140. $fieldtva = 'tva';
  3141. $fieldlocaltax1 = 'localtax1';
  3142. $fieldlocaltax2 = 'localtax2';
  3143. $fieldttc = 'total_ttc';
  3144. // Specific code for backward compatibility with old field names
  3145. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3146. $fieldtva = 'total_tva';
  3147. }
  3148. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3149. $fieldtva = 'total_tva';
  3150. }
  3151. if ($this->element == 'propal') {
  3152. $fieldtva = 'total_tva';
  3153. }
  3154. if ($this->element == 'expensereport') {
  3155. $fieldtva = 'total_tva';
  3156. }
  3157. if ($this->element == 'supplier_proposal') {
  3158. $fieldtva = 'total_tva';
  3159. }
  3160. if ($this->element == 'commande') {
  3161. $fieldtva = 'total_tva';
  3162. }
  3163. if ($this->element == 'order_supplier') {
  3164. $fieldtva = 'total_tva';
  3165. }
  3166. if (empty($nodatabaseupdate)) {
  3167. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  3168. $sql .= " ".$fieldht." = ".price2num($this->total_ht).",";
  3169. $sql .= " ".$fieldtva." = ".price2num($this->total_tva).",";
  3170. $sql .= " ".$fieldlocaltax1." = ".price2num($this->total_localtax1).",";
  3171. $sql .= " ".$fieldlocaltax2." = ".price2num($this->total_localtax2).",";
  3172. $sql .= " ".$fieldttc." = ".price2num($this->total_ttc);
  3173. $sql .= ", multicurrency_total_ht = ".price2num($this->multicurrency_total_ht, 'MT', 1);
  3174. $sql .= ", multicurrency_total_tva = ".price2num($this->multicurrency_total_tva, 'MT', 1);
  3175. $sql .= ", multicurrency_total_ttc = ".price2num($this->multicurrency_total_ttc, 'MT', 1);
  3176. $sql .= ' WHERE rowid = '.$this->id;
  3177. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3178. $resql = $this->db->query($sql);
  3179. if (!$resql) {
  3180. $error++;
  3181. $this->error = $this->db->lasterror();
  3182. $this->errors[] = $this->db->lasterror();
  3183. }
  3184. }
  3185. if (!$error) {
  3186. return 1;
  3187. } else {
  3188. return -1;
  3189. }
  3190. } else {
  3191. dol_print_error($this->db, 'Bad request in update_price');
  3192. return -1;
  3193. }
  3194. }
  3195. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3196. /**
  3197. * Add objects linked in llx_element_element.
  3198. *
  3199. * @param string $origin Linked element type
  3200. * @param int $origin_id Linked element id
  3201. * @param User $f_user User that create
  3202. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3203. * @return int <=0 if KO, >0 if OK
  3204. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3205. */
  3206. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3207. {
  3208. // phpcs:enable
  3209. global $user;
  3210. $origin = (!empty($origin) ? $origin : $this->origin);
  3211. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3212. $f_user = isset($f_user) ? $f_user : $user;
  3213. // Special case
  3214. if ($origin == 'order') {
  3215. $origin = 'commande';
  3216. }
  3217. if ($origin == 'invoice') {
  3218. $origin = 'facture';
  3219. }
  3220. if ($origin == 'invoice_template') {
  3221. $origin = 'facturerec';
  3222. }
  3223. if ($origin == 'supplierorder') {
  3224. $origin = 'order_supplier';
  3225. }
  3226. $this->db->begin();
  3227. $error = 0;
  3228. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "element_element (";
  3229. $sql .= "fk_source";
  3230. $sql .= ", sourcetype";
  3231. $sql .= ", fk_target";
  3232. $sql .= ", targettype";
  3233. $sql .= ") VALUES (";
  3234. $sql .= $origin_id;
  3235. $sql .= ", '" . $this->db->escape($origin) . "'";
  3236. $sql .= ", " . $this->id;
  3237. $sql .= ", '" . $this->db->escape($this->element) . "'";
  3238. $sql .= ")";
  3239. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3240. if ($this->db->query($sql)) {
  3241. if (!$notrigger) {
  3242. // Call trigger
  3243. $this->context['link_origin'] = $origin;
  3244. $this->context['link_origin_id'] = $origin_id;
  3245. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3246. if ($result < 0) {
  3247. $error++;
  3248. }
  3249. // End call triggers
  3250. }
  3251. } else {
  3252. $this->error = $this->db->lasterror();
  3253. $error++;
  3254. }
  3255. if (!$error) {
  3256. $this->db->commit();
  3257. return 1;
  3258. } else {
  3259. $this->db->rollback();
  3260. return 0;
  3261. }
  3262. }
  3263. /**
  3264. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3265. * this->linkedObjectsIds array +
  3266. * this->linkedObjects array if $loadalsoobjects = 1
  3267. * Possible usage for parameters:
  3268. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3269. * - source id+type -> will get target list linked to source
  3270. * - target id+type -> will get source list linked to target
  3271. * - source id+type + target type -> will get target list of the type
  3272. * - target id+type + target source -> will get source list of the type
  3273. *
  3274. * @param int $sourceid Object source id (if not defined, id of object)
  3275. * @param string $sourcetype Object source type (if not defined, element name of object)
  3276. * @param int $targetid Object target id (if not defined, id of object)
  3277. * @param string $targettype Object target type (if not defined, elemennt name of object)
  3278. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3279. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3280. * @param string $orderby SQL 'ORDER BY' clause
  3281. * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances)
  3282. * @return int <0 if KO, >0 if OK
  3283. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3284. */
  3285. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3286. {
  3287. global $conf;
  3288. $this->linkedObjectsIds = array();
  3289. $this->linkedObjects = array();
  3290. $justsource = false;
  3291. $justtarget = false;
  3292. $withtargettype = false;
  3293. $withsourcetype = false;
  3294. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3295. $justsource = true; // the source (id and type) is a search criteria
  3296. if (!empty($targettype)) {
  3297. $withtargettype = true;
  3298. }
  3299. }
  3300. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3301. $justtarget = true; // the target (id and type) is a search criteria
  3302. if (!empty($sourcetype)) {
  3303. $withsourcetype = true;
  3304. }
  3305. }
  3306. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3307. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3308. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3309. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3310. /*if (empty($sourceid) && empty($targetid))
  3311. {
  3312. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3313. return -1;
  3314. }*/
  3315. // Links between objects are stored in table element_element
  3316. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  3317. $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
  3318. $sql .= " WHERE ";
  3319. if ($justsource || $justtarget) {
  3320. if ($justsource) {
  3321. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3322. if ($withtargettype) {
  3323. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3324. }
  3325. } elseif ($justtarget) {
  3326. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3327. if ($withsourcetype) {
  3328. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3329. }
  3330. }
  3331. } else {
  3332. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3333. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3334. }
  3335. $sql .= ' ORDER BY '.$orderby;
  3336. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3337. $resql = $this->db->query($sql);
  3338. if ($resql) {
  3339. $num = $this->db->num_rows($resql);
  3340. $i = 0;
  3341. while ($i < $num) {
  3342. $obj = $this->db->fetch_object($resql);
  3343. if ($justsource || $justtarget) {
  3344. if ($justsource) {
  3345. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3346. } elseif ($justtarget) {
  3347. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3348. }
  3349. } else {
  3350. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3351. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3352. }
  3353. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3354. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3355. }
  3356. }
  3357. $i++;
  3358. }
  3359. if (!empty($this->linkedObjectsIds)) {
  3360. $tmparray = $this->linkedObjectsIds;
  3361. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3362. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3363. $module = $element = $subelement = $objecttype;
  3364. $regs = array();
  3365. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3366. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3367. $module = $element = $regs[1];
  3368. $subelement = $regs[2];
  3369. }
  3370. $classpath = $element.'/class';
  3371. // To work with non standard classpath or module name
  3372. if ($objecttype == 'facture') {
  3373. $classpath = 'compta/facture/class';
  3374. } elseif ($objecttype == 'facturerec') {
  3375. $classpath = 'compta/facture/class';
  3376. $module = 'facture';
  3377. } elseif ($objecttype == 'propal') {
  3378. $classpath = 'comm/propal/class';
  3379. } elseif ($objecttype == 'supplier_proposal') {
  3380. $classpath = 'supplier_proposal/class';
  3381. } elseif ($objecttype == 'shipping') {
  3382. $classpath = 'expedition/class';
  3383. $subelement = 'expedition';
  3384. $module = 'expedition_bon';
  3385. } elseif ($objecttype == 'delivery') {
  3386. $classpath = 'delivery/class';
  3387. $subelement = 'delivery';
  3388. $module = 'delivery_note';
  3389. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3390. $classpath = 'fourn/class';
  3391. $module = 'fournisseur';
  3392. } elseif ($objecttype == 'fichinter') {
  3393. $classpath = 'fichinter/class';
  3394. $subelement = 'fichinter';
  3395. $module = 'ficheinter';
  3396. } elseif ($objecttype == 'subscription') {
  3397. $classpath = 'adherents/class';
  3398. $module = 'adherent';
  3399. } elseif ($objecttype == 'contact') {
  3400. $module = 'societe';
  3401. }
  3402. // Set classfile
  3403. $classfile = strtolower($subelement);
  3404. $classname = ucfirst($subelement);
  3405. if ($objecttype == 'order') {
  3406. $classfile = 'commande';
  3407. $classname = 'Commande';
  3408. } elseif ($objecttype == 'invoice_supplier') {
  3409. $classfile = 'fournisseur.facture';
  3410. $classname = 'FactureFournisseur';
  3411. } elseif ($objecttype == 'order_supplier') {
  3412. $classfile = 'fournisseur.commande';
  3413. $classname = 'CommandeFournisseur';
  3414. } elseif ($objecttype == 'supplier_proposal') {
  3415. $classfile = 'supplier_proposal';
  3416. $classname = 'SupplierProposal';
  3417. } elseif ($objecttype == 'facturerec') {
  3418. $classfile = 'facture-rec';
  3419. $classname = 'FactureRec';
  3420. } elseif ($objecttype == 'subscription') {
  3421. $classfile = 'subscription';
  3422. $classname = 'Subscription';
  3423. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3424. $classpath = 'projet/class';
  3425. $classfile = 'project';
  3426. $classname = 'Project';
  3427. } elseif ($objecttype == 'conferenceorboothattendee') {
  3428. $classpath = 'eventorganization/class';
  3429. $classfile = 'conferenceorboothattendee';
  3430. $classname = 'ConferenceOrBoothAttendee';
  3431. $module = 'eventorganization';
  3432. }
  3433. // Here $module, $classfile and $classname are set
  3434. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3435. if ($loadalsoobjects) {
  3436. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3437. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3438. if (class_exists($classname)) {
  3439. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3440. $object = new $classname($this->db);
  3441. $ret = $object->fetch($objectid);
  3442. if ($ret >= 0) {
  3443. $this->linkedObjects[$objecttype][$i] = $object;
  3444. }
  3445. }
  3446. }
  3447. }
  3448. } else {
  3449. unset($this->linkedObjectsIds[$objecttype]);
  3450. }
  3451. }
  3452. }
  3453. return 1;
  3454. } else {
  3455. dol_print_error($this->db);
  3456. return -1;
  3457. }
  3458. }
  3459. /**
  3460. * Update object linked of a current object
  3461. *
  3462. * @param int $sourceid Object source id
  3463. * @param string $sourcetype Object source type
  3464. * @param int $targetid Object target id
  3465. * @param string $targettype Object target type
  3466. * @param User $f_user User that create
  3467. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3468. * @return int >0 if OK, <0 if KO
  3469. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3470. */
  3471. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3472. {
  3473. global $user;
  3474. $updatesource = false;
  3475. $updatetarget = false;
  3476. $f_user = isset($f_user) ? $f_user : $user;
  3477. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3478. $updatesource = true;
  3479. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3480. $updatetarget = true;
  3481. }
  3482. $this->db->begin();
  3483. $error = 0;
  3484. $sql = "UPDATE " . MAIN_DB_PREFIX . "element_element SET ";
  3485. if ($updatesource) {
  3486. $sql .= "fk_source = " . $sourceid;
  3487. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3488. $sql .= " WHERE fk_target = " . $this->id;
  3489. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3490. } elseif ($updatetarget) {
  3491. $sql .= "fk_target = " . $targetid;
  3492. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3493. $sql .= " WHERE fk_source = " . $this->id;
  3494. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3495. }
  3496. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3497. if ($this->db->query($sql)) {
  3498. if (!$notrigger) {
  3499. // Call trigger
  3500. $this->context['link_source_id'] = $sourceid;
  3501. $this->context['link_source_type'] = $sourcetype;
  3502. $this->context['link_target_id'] = $targetid;
  3503. $this->context['link_target_type'] = $targettype;
  3504. $result = $this->call_trigger('OBJECT_LINK_UPDATE', $f_user);
  3505. if ($result < 0) {
  3506. $error++;
  3507. }
  3508. // End call triggers
  3509. }
  3510. } else {
  3511. $this->error = $this->db->lasterror();
  3512. $error++;
  3513. }
  3514. if (!$error) {
  3515. $this->db->commit();
  3516. return 1;
  3517. } else {
  3518. $this->db->rollback();
  3519. return -1;
  3520. }
  3521. }
  3522. /**
  3523. * Delete all links between an object $this
  3524. *
  3525. * @param int $sourceid Object source id
  3526. * @param string $sourcetype Object source type
  3527. * @param int $targetid Object target id
  3528. * @param string $targettype Object target type
  3529. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3530. * @param User $f_user User that create
  3531. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3532. * @return int >0 if OK, <0 if KO
  3533. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3534. */
  3535. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3536. {
  3537. global $user;
  3538. $deletesource = false;
  3539. $deletetarget = false;
  3540. $f_user = isset($f_user) ? $f_user : $user;
  3541. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3542. $deletesource = true;
  3543. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3544. $deletetarget = true;
  3545. }
  3546. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3547. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3548. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3549. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3550. $this->db->begin();
  3551. $error = 0;
  3552. if (!$notrigger) {
  3553. // Call trigger
  3554. $this->context['link_id'] = $rowid;
  3555. $this->context['link_source_id'] = $sourceid;
  3556. $this->context['link_source_type'] = $sourcetype;
  3557. $this->context['link_target_id'] = $targetid;
  3558. $this->context['link_target_type'] = $targettype;
  3559. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3560. if ($result < 0) {
  3561. $error++;
  3562. }
  3563. // End call triggers
  3564. }
  3565. if (!$error) {
  3566. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "element_element";
  3567. $sql .= " WHERE";
  3568. if ($rowid > 0) {
  3569. $sql .= " rowid = " . ((int) $rowid);
  3570. } else {
  3571. if ($deletesource) {
  3572. $sql .= " fk_source = " . $sourceid . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3573. $sql .= " AND fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3574. } elseif ($deletetarget) {
  3575. $sql .= " fk_target = " . $targetid . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3576. $sql .= " AND fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3577. } else {
  3578. $sql .= " (fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3579. $sql .= " OR";
  3580. $sql .= " (fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3581. }
  3582. }
  3583. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3584. if (!$this->db->query($sql)) {
  3585. $this->error = $this->db->lasterror();
  3586. $this->errors[] = $this->error;
  3587. $error++;
  3588. }
  3589. }
  3590. if (!$error) {
  3591. $this->db->commit();
  3592. return 1;
  3593. } else {
  3594. $this->db->rollback();
  3595. return 0;
  3596. }
  3597. }
  3598. /**
  3599. * Function used to get an array with all items linked to an object id in association table
  3600. *
  3601. * @param int $fk_object_where id of object we need to get linked items
  3602. * @param string $field_select name of field we need to get a list
  3603. * @param string $field_where name of field of object we need to get linked items
  3604. * @param string $table_element name of association table
  3605. * @return array Array of record
  3606. */
  3607. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3608. {
  3609. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3610. return -1;
  3611. }
  3612. global $db;
  3613. $sql = 'SELECT '.$field_select.' FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.((int) $fk_object_where);
  3614. $resql = $db->query($sql);
  3615. $TRes = array();
  3616. if (!empty($resql)) {
  3617. while ($res = $db->fetch_object($resql)) {
  3618. $TRes[] = $res->{$field_select};
  3619. }
  3620. }
  3621. return $TRes;
  3622. }
  3623. /**
  3624. * Function used to remove all items linked to an object id in association table
  3625. *
  3626. * @param int $fk_object_where id of object we need to remove linked items
  3627. * @param string $field_where name of field of object we need to delete linked items
  3628. * @param string $table_element name of association table
  3629. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3630. */
  3631. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3632. {
  3633. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3634. return -1;
  3635. }
  3636. global $db;
  3637. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.((int) $fk_object_where);
  3638. $resql = $db->query($sql);
  3639. if (empty($resql)) {
  3640. return 0;
  3641. }
  3642. return 1;
  3643. }
  3644. /**
  3645. * Set status of an object
  3646. *
  3647. * @param int $status Status to set
  3648. * @param int $elementId Id of element to force (use this->id by default)
  3649. * @param string $elementType Type of element to force (use this->table_element by default)
  3650. * @param string $trigkey Trigger key to use for trigger
  3651. * @return int <0 if KO, >0 if OK
  3652. */
  3653. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '')
  3654. {
  3655. global $user, $langs, $conf;
  3656. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3657. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3658. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3659. $this->db->begin();
  3660. $fieldstatus = "fk_statut";
  3661. if ($elementTable == 'facture_rec') {
  3662. $fieldstatus = "suspended";
  3663. }
  3664. if ($elementTable == 'mailing') {
  3665. $fieldstatus = "statut";
  3666. }
  3667. if ($elementTable == 'cronjob') {
  3668. $fieldstatus = "status";
  3669. }
  3670. if ($elementTable == 'user') {
  3671. $fieldstatus = "statut";
  3672. }
  3673. if ($elementTable == 'expensereport') {
  3674. $fieldstatus = "fk_statut";
  3675. }
  3676. if ($elementTable == 'commande_fournisseur_dispatch') {
  3677. $fieldstatus = "status";
  3678. }
  3679. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3680. $fieldstatus = 'status';
  3681. }
  3682. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  3683. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3684. // If status = 1 = validated, update also fk_user_valid
  3685. if ($status == 1 && $elementTable == 'expensereport') {
  3686. $sql .= ", fk_user_valid = ".$user->id;
  3687. }
  3688. $sql .= " WHERE rowid=".((int) $elementId);
  3689. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3690. if ($this->db->query($sql)) {
  3691. $error = 0;
  3692. // Try autoset of trigkey
  3693. if (empty($trigkey)) {
  3694. if ($this->element == 'supplier_proposal' && $status == 2) {
  3695. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3696. }
  3697. if ($this->element == 'supplier_proposal' && $status == 3) {
  3698. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3699. }
  3700. if ($this->element == 'supplier_proposal' && $status == 4) {
  3701. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3702. }
  3703. if ($this->element == 'fichinter' && $status == 3) {
  3704. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3705. }
  3706. if ($this->element == 'fichinter' && $status == 2) {
  3707. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3708. }
  3709. if ($this->element == 'fichinter' && $status == 1) {
  3710. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3711. }
  3712. }
  3713. if ($trigkey) {
  3714. // Call trigger
  3715. $result = $this->call_trigger($trigkey, $user);
  3716. if ($result < 0) {
  3717. $error++;
  3718. }
  3719. // End call triggers
  3720. }
  3721. if (!$error) {
  3722. $this->db->commit();
  3723. if (empty($savElementId)) { // If the element we update was $this (so $elementId is null)
  3724. $this->statut = $status;
  3725. $this->status = $status;
  3726. }
  3727. return 1;
  3728. } else {
  3729. $this->db->rollback();
  3730. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3731. return -1;
  3732. }
  3733. } else {
  3734. $this->error = $this->db->lasterror();
  3735. $this->db->rollback();
  3736. return -1;
  3737. }
  3738. }
  3739. /**
  3740. * Load type of canvas of an object if it exists
  3741. *
  3742. * @param int $id Record id
  3743. * @param string $ref Record ref
  3744. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3745. */
  3746. public function getCanvas($id = 0, $ref = '')
  3747. {
  3748. global $conf;
  3749. if (empty($id) && empty($ref)) {
  3750. return 0;
  3751. }
  3752. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3753. return 0; // To increase speed. Not enabled by default.
  3754. }
  3755. // Clean parameters
  3756. $ref = trim($ref);
  3757. $sql = "SELECT rowid, canvas";
  3758. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3759. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3760. if (!empty($id)) {
  3761. $sql .= " AND rowid = ".((int) $id);
  3762. }
  3763. if (!empty($ref)) {
  3764. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3765. }
  3766. $resql = $this->db->query($sql);
  3767. if ($resql) {
  3768. $obj = $this->db->fetch_object($resql);
  3769. if ($obj) {
  3770. $this->canvas = $obj->canvas;
  3771. return 1;
  3772. } else {
  3773. return 0;
  3774. }
  3775. } else {
  3776. dol_print_error($this->db);
  3777. return -1;
  3778. }
  3779. }
  3780. /**
  3781. * Get special code of a line
  3782. *
  3783. * @param int $lineid Id of line
  3784. * @return int Special code
  3785. */
  3786. public function getSpecialCode($lineid)
  3787. {
  3788. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3789. $sql .= ' WHERE rowid = '.((int) $lineid);
  3790. $resql = $this->db->query($sql);
  3791. if ($resql) {
  3792. $row = $this->db->fetch_row($resql);
  3793. return $row[0];
  3794. }
  3795. }
  3796. /**
  3797. * Function to check if an object is used by others.
  3798. * Check is done into this->childtables. There is no check into llx_element_element.
  3799. *
  3800. * @param int $id Force id of object
  3801. * @return int <0 if KO, 0 if not used, >0 if already used
  3802. */
  3803. public function isObjectUsed($id = 0)
  3804. {
  3805. global $langs;
  3806. if (empty($id)) {
  3807. $id = $this->id;
  3808. }
  3809. // Check parameters
  3810. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3811. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3812. return -1;
  3813. }
  3814. $arraytoscan = $this->childtables;
  3815. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3816. $tmparray = array_keys($this->childtables);
  3817. if (is_numeric($tmparray[0])) {
  3818. $arraytoscan = array_flip($this->childtables);
  3819. }
  3820. // Test if child exists
  3821. $haschild = 0;
  3822. foreach ($arraytoscan as $table => $elementname) {
  3823. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3824. // Check if third party can be deleted
  3825. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3826. $sql .= " WHERE ".$this->fk_element." = ".((int) $id);
  3827. $resql = $this->db->query($sql);
  3828. if ($resql) {
  3829. $obj = $this->db->fetch_object($resql);
  3830. if ($obj->nb > 0) {
  3831. $langs->load("errors");
  3832. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3833. $haschild += $obj->nb;
  3834. if (is_numeric($elementname)) { // old usage
  3835. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
  3836. } else // new usage: $elementname=Translation key
  3837. {
  3838. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
  3839. }
  3840. break; // We found at least one, we stop here
  3841. }
  3842. } else {
  3843. $this->errors[] = $this->db->lasterror();
  3844. return -1;
  3845. }
  3846. }
  3847. if ($haschild > 0) {
  3848. $this->errors[] = "ErrorRecordHasChildren";
  3849. return $haschild;
  3850. } else {
  3851. return 0;
  3852. }
  3853. }
  3854. /**
  3855. * Function to say how many lines object contains
  3856. *
  3857. * @param int $predefined -1=All, 0=Count free product/service only, 1=Count predefined product/service only, 2=Count predefined product, 3=Count predefined service
  3858. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3859. */
  3860. public function hasProductsOrServices($predefined = -1)
  3861. {
  3862. $nb = 0;
  3863. foreach ($this->lines as $key => $val) {
  3864. $qualified = 0;
  3865. if ($predefined == -1) {
  3866. $qualified = 1;
  3867. }
  3868. if ($predefined == 1 && $val->fk_product > 0) {
  3869. $qualified = 1;
  3870. }
  3871. if ($predefined == 0 && $val->fk_product <= 0) {
  3872. $qualified = 1;
  3873. }
  3874. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  3875. $qualified = 1;
  3876. }
  3877. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  3878. $qualified = 1;
  3879. }
  3880. if ($qualified) {
  3881. $nb++;
  3882. }
  3883. }
  3884. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3885. return $nb;
  3886. }
  3887. /**
  3888. * Function that returns the total amount HT of discounts applied for all lines.
  3889. *
  3890. * @return float
  3891. */
  3892. public function getTotalDiscount()
  3893. {
  3894. $total_discount = 0.00;
  3895. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3896. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
  3897. $sql .= " WHERE ".$this->fk_element." = ".$this->id;
  3898. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3899. $resql = $this->db->query($sql);
  3900. if ($resql) {
  3901. $num = $this->db->num_rows($resql);
  3902. $i = 0;
  3903. while ($i < $num) {
  3904. $obj = $this->db->fetch_object($resql);
  3905. $pu_ht = $obj->pu_ht;
  3906. $qty = $obj->qty;
  3907. $total_ht = $obj->total_ht;
  3908. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3909. $total_discount += $total_discount_line;
  3910. $i++;
  3911. }
  3912. }
  3913. //print $total_discount; exit;
  3914. return price2num($total_discount);
  3915. }
  3916. /**
  3917. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3918. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3919. *
  3920. * @return array array('weight'=>...,'volume'=>...)
  3921. */
  3922. public function getTotalWeightVolume()
  3923. {
  3924. $totalWeight = 0;
  3925. $totalVolume = 0;
  3926. // defined for shipment only
  3927. $totalOrdered = '';
  3928. // defined for shipment only
  3929. $totalToShip = '';
  3930. foreach ($this->lines as $line) {
  3931. if (isset($line->qty_asked)) {
  3932. if (empty($totalOrdered)) {
  3933. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  3934. }
  3935. $totalOrdered += $line->qty_asked; // defined for shipment only
  3936. }
  3937. if (isset($line->qty_shipped)) {
  3938. if (empty($totalToShip)) {
  3939. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  3940. }
  3941. $totalToShip += $line->qty_shipped; // defined for shipment only
  3942. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  3943. if (empty($totalToShip)) {
  3944. $totalToShip = 0;
  3945. }
  3946. $totalToShip += $line->qty; // defined for reception only
  3947. }
  3948. // Define qty, weight, volume, weight_units, volume_units
  3949. if ($this->element == 'shipping') {
  3950. // for shipments
  3951. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  3952. } else {
  3953. $qty = $line->qty ? $line->qty : 0;
  3954. }
  3955. $weight = $line->weight ? $line->weight : 0;
  3956. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  3957. $volume = $line->volume ? $line->volume : 0;
  3958. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  3959. $weight_units = $line->weight_units;
  3960. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  3961. $volume_units = $line->volume_units;
  3962. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  3963. $weightUnit = 0;
  3964. $volumeUnit = 0;
  3965. if (!empty($weight_units)) {
  3966. $weightUnit = $weight_units;
  3967. }
  3968. if (!empty($volume_units)) {
  3969. $volumeUnit = $volume_units;
  3970. }
  3971. if (empty($totalWeight)) {
  3972. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  3973. }
  3974. if (empty($totalVolume)) {
  3975. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  3976. }
  3977. //var_dump($line->volume_units);
  3978. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3979. $trueWeightUnit = pow(10, $weightUnit);
  3980. $totalWeight += $weight * $qty * $trueWeightUnit;
  3981. } else {
  3982. if ($weight_units == 99) {
  3983. // conversion 1 Pound = 0.45359237 KG
  3984. $trueWeightUnit = 0.45359237;
  3985. $totalWeight += $weight * $qty * $trueWeightUnit;
  3986. } elseif ($weight_units == 98) {
  3987. // conversion 1 Ounce = 0.0283495 KG
  3988. $trueWeightUnit = 0.0283495;
  3989. $totalWeight += $weight * $qty * $trueWeightUnit;
  3990. } else {
  3991. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  3992. }
  3993. }
  3994. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3995. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  3996. $trueVolumeUnit = pow(10, $volumeUnit);
  3997. //print $line->volume;
  3998. $totalVolume += $volume * $qty * $trueVolumeUnit;
  3999. } else {
  4000. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4001. }
  4002. }
  4003. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4004. }
  4005. /**
  4006. * Set extra parameters
  4007. *
  4008. * @return int <0 if KO, >0 if OK
  4009. */
  4010. public function setExtraParameters()
  4011. {
  4012. $this->db->begin();
  4013. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4014. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  4015. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4016. $sql .= " WHERE rowid = ".$this->id;
  4017. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4018. $resql = $this->db->query($sql);
  4019. if (!$resql) {
  4020. $this->error = $this->db->lasterror();
  4021. $this->db->rollback();
  4022. return -1;
  4023. } else {
  4024. $this->db->commit();
  4025. return 1;
  4026. }
  4027. }
  4028. // --------------------
  4029. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4030. // --------------------
  4031. /* This is to show add lines */
  4032. /**
  4033. * Show add free and predefined products/services form
  4034. *
  4035. * @param int $dateSelector 1=Show also date range input fields
  4036. * @param Societe $seller Object thirdparty who sell
  4037. * @param Societe $buyer Object thirdparty who buy
  4038. * @param string $defaulttpldir Directory where to find the template
  4039. * @return void
  4040. */
  4041. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4042. {
  4043. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4044. global $form;
  4045. // Line extrafield
  4046. if (!is_object($extrafields)) {
  4047. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4048. $extrafields = new ExtraFields($this->db);
  4049. }
  4050. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4051. // Output template part (modules that overwrite templates must declare this into descriptor)
  4052. // Use global variables + $dateSelector + $seller and $buyer
  4053. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4054. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4055. foreach ($dirtpls as $module => $reldir) {
  4056. if (!empty($module)) {
  4057. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4058. } else {
  4059. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4060. }
  4061. if (empty($conf->file->strict_mode)) {
  4062. $res = @include $tpl;
  4063. } else {
  4064. $res = include $tpl; // for debug
  4065. }
  4066. if ($res) {
  4067. break;
  4068. }
  4069. }
  4070. }
  4071. /* This is to show array of line of details */
  4072. /**
  4073. * Return HTML table for object lines
  4074. * TODO Move this into an output class file (htmlline.class.php)
  4075. * If lines are into a template, title must also be into a template
  4076. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4077. *
  4078. * @param string $action Action code
  4079. * @param string $seller Object of seller third party
  4080. * @param string $buyer Object of buyer third party
  4081. * @param int $selected Object line selected
  4082. * @param int $dateSelector 1=Show also date range input fields
  4083. * @param string $defaulttpldir Directory where to find the template
  4084. * @return void
  4085. */
  4086. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4087. {
  4088. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4089. // TODO We should not use global var for this
  4090. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4091. // Define usemargins
  4092. $usemargins = 0;
  4093. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4094. $usemargins = 1;
  4095. }
  4096. $num = count($this->lines);
  4097. // Line extrafield
  4098. if (!is_object($extrafields)) {
  4099. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4100. $extrafields = new ExtraFields($this->db);
  4101. }
  4102. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4103. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4104. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4105. if (empty($reshook)) {
  4106. // Output template part (modules that overwrite templates must declare this into descriptor)
  4107. // Use global variables + $dateSelector + $seller and $buyer
  4108. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4109. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4110. foreach ($dirtpls as $module => $reldir) {
  4111. if (!empty($module)) {
  4112. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4113. } else {
  4114. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4115. }
  4116. if (empty($conf->file->strict_mode)) {
  4117. $res = @include $tpl;
  4118. } else {
  4119. $res = include $tpl; // for debug
  4120. }
  4121. if ($res) {
  4122. break;
  4123. }
  4124. }
  4125. }
  4126. $i = 0;
  4127. print "<!-- begin printObjectLines() --><tbody>\n";
  4128. foreach ($this->lines as $line) {
  4129. //Line extrafield
  4130. $line->fetch_optionals();
  4131. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4132. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4133. if (empty($line->fk_parent_line)) {
  4134. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4135. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4136. } else {
  4137. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line);
  4138. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4139. }
  4140. }
  4141. if (empty($reshook)) {
  4142. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4143. }
  4144. $i++;
  4145. }
  4146. print "</tbody><!-- end printObjectLines() -->\n";
  4147. }
  4148. /**
  4149. * Return HTML content of a detail line
  4150. * TODO Move this into an output class file (htmlline.class.php)
  4151. *
  4152. * @param string $action GET/POST action
  4153. * @param CommonObjectLine $line Selected object line to output
  4154. * @param string $var Is it a an odd line (true)
  4155. * @param int $num Number of line (0)
  4156. * @param int $i I
  4157. * @param int $dateSelector 1=Show also date range input fields
  4158. * @param string $seller Object of seller third party
  4159. * @param string $buyer Object of buyer third party
  4160. * @param int $selected Object line selected
  4161. * @param Extrafields $extrafields Object of extrafields
  4162. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4163. * @return void
  4164. */
  4165. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4166. {
  4167. global $conf, $langs, $user, $object, $hookmanager;
  4168. global $form;
  4169. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4170. $object_rights = $this->getRights();
  4171. $element = $this->element;
  4172. $text = '';
  4173. $description = '';
  4174. // Line in view mode
  4175. if ($action != 'editline' || $selected != $line->id) {
  4176. // Product
  4177. if ($line->fk_product > 0) {
  4178. $product_static = new Product($this->db);
  4179. $product_static->fetch($line->fk_product);
  4180. $product_static->ref = $line->ref; //can change ref in hook
  4181. $product_static->label = $line->label; //can change label in hook
  4182. $text = $product_static->getNomUrl(1);
  4183. // Define output language and label
  4184. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4185. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4186. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4187. return;
  4188. }
  4189. $prod = new Product($this->db);
  4190. $prod->fetch($line->fk_product);
  4191. $outputlangs = $langs;
  4192. $newlang = '';
  4193. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4194. $newlang = GETPOST('lang_id', 'aZ09');
  4195. }
  4196. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4197. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4198. }
  4199. if (!empty($newlang)) {
  4200. $outputlangs = new Translate("", $conf);
  4201. $outputlangs->setDefaultLang($newlang);
  4202. }
  4203. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4204. } else {
  4205. $label = $line->product_label;
  4206. }
  4207. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4208. $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc.
  4209. }
  4210. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4211. // Output template part (modules that overwrite templates must declare this into descriptor)
  4212. // Use global variables + $dateSelector + $seller and $buyer
  4213. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4214. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4215. foreach ($dirtpls as $module => $reldir) {
  4216. if (!empty($module)) {
  4217. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4218. } else {
  4219. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4220. }
  4221. if (empty($conf->file->strict_mode)) {
  4222. $res = @include $tpl;
  4223. } else {
  4224. $res = include $tpl; // for debug
  4225. }
  4226. if ($res) {
  4227. break;
  4228. }
  4229. }
  4230. }
  4231. // Line in update mode
  4232. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4233. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4234. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4235. // Output template part (modules that overwrite templates must declare this into descriptor)
  4236. // Use global variables + $dateSelector + $seller and $buyer
  4237. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4238. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4239. foreach ($dirtpls as $module => $reldir) {
  4240. if (!empty($module)) {
  4241. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4242. } else {
  4243. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4244. }
  4245. if (empty($conf->file->strict_mode)) {
  4246. $res = @include $tpl;
  4247. } else {
  4248. $res = include $tpl; // for debug
  4249. }
  4250. if ($res) {
  4251. break;
  4252. }
  4253. }
  4254. }
  4255. }
  4256. /* This is to show array of line of details of source object */
  4257. /**
  4258. * Return HTML table table of source object lines
  4259. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4260. * If lines are into a template, title must also be into a template
  4261. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4262. *
  4263. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4264. * @param array $selectedLines Array of lines id for selected lines
  4265. * @return void
  4266. */
  4267. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4268. {
  4269. global $langs, $hookmanager, $conf, $form;
  4270. print '<tr class="liste_titre">';
  4271. print '<td>'.$langs->trans('Ref').'</td>';
  4272. print '<td>'.$langs->trans('Description').'</td>';
  4273. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  4274. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  4275. if (!empty($conf->multicurrency->enabled)) {
  4276. print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4277. }
  4278. print '<td class="right">'.$langs->trans('Qty').'</td>';
  4279. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4280. print '<td class="left">'.$langs->trans('Unit').'</td>';
  4281. }
  4282. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  4283. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4284. print '</tr>';
  4285. $i = 0;
  4286. if (!empty($this->lines)) {
  4287. foreach ($this->lines as $line) {
  4288. if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4289. if (empty($line->fk_parent_line)) {
  4290. $parameters = array('line'=>$line, 'i'=>$i);
  4291. $action = '';
  4292. $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4293. }
  4294. } else {
  4295. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4296. }
  4297. $i++;
  4298. }
  4299. }
  4300. }
  4301. /**
  4302. * Return HTML with a line of table array of source object lines
  4303. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4304. * If lines are into a template, title must also be into a template
  4305. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4306. *
  4307. * @param CommonObjectLine $line Line
  4308. * @param string $var Var
  4309. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4310. * @param string $defaulttpldir Directory where to find the template
  4311. * @param array $selectedLines Array of lines id for selected lines
  4312. * @return void
  4313. */
  4314. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4315. {
  4316. global $langs, $conf;
  4317. //var_dump($line);
  4318. if (!empty($line->date_start)) {
  4319. $date_start = $line->date_start;
  4320. } else {
  4321. $date_start = $line->date_debut_prevue;
  4322. if ($line->date_debut_reel) {
  4323. $date_start = $line->date_debut_reel;
  4324. }
  4325. }
  4326. if (!empty($line->date_end)) {
  4327. $date_end = $line->date_end;
  4328. } else {
  4329. $date_end = $line->date_fin_prevue;
  4330. if ($line->date_fin_reel) {
  4331. $date_end = $line->date_fin_reel;
  4332. }
  4333. }
  4334. $this->tpl['id'] = $line->id;
  4335. $this->tpl['label'] = '';
  4336. if (!empty($line->fk_parent_line)) {
  4337. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4338. }
  4339. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4340. $discount = new DiscountAbsolute($this->db);
  4341. $discount->fk_soc = $this->socid;
  4342. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4343. } elseif (!empty($line->fk_product)) {
  4344. $productstatic = new Product($this->db);
  4345. $productstatic->id = $line->fk_product;
  4346. $productstatic->ref = $line->ref;
  4347. $productstatic->type = $line->fk_product_type;
  4348. if (empty($productstatic->ref)) {
  4349. $line->fetch_product();
  4350. $productstatic = $line->product;
  4351. }
  4352. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4353. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4354. // Dates
  4355. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4356. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4357. }
  4358. } else {
  4359. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4360. if (!empty($line->desc)) {
  4361. $this->tpl['label'] .= $line->desc;
  4362. } else {
  4363. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4364. }
  4365. // Dates
  4366. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4367. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4368. }
  4369. }
  4370. if (!empty($line->desc)) {
  4371. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4372. $discount = new DiscountAbsolute($this->db);
  4373. $discount->fetch($line->fk_remise_except);
  4374. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4375. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4376. $discount = new DiscountAbsolute($this->db);
  4377. $discount->fetch($line->fk_remise_except);
  4378. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4379. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4380. $discount = new DiscountAbsolute($this->db);
  4381. $discount->fetch($line->fk_remise_except);
  4382. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4383. } elseif ($line->desc == '(EXCESS PAID)') {
  4384. $discount = new DiscountAbsolute($this->db);
  4385. $discount->fetch($line->fk_remise_except);
  4386. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4387. } else {
  4388. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4389. }
  4390. } else {
  4391. $this->tpl['description'] = '&nbsp;';
  4392. }
  4393. // VAT Rate
  4394. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4395. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4396. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4397. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4398. }
  4399. $this->tpl['price'] = price($line->subprice);
  4400. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4401. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4402. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4403. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4404. }
  4405. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4406. // Is the line strike or not
  4407. $this->tpl['strike'] = 0;
  4408. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4409. $this->tpl['strike'] = 1;
  4410. }
  4411. // Output template part (modules that overwrite templates must declare this into descriptor)
  4412. // Use global variables + $dateSelector + $seller and $buyer
  4413. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4414. foreach ($dirtpls as $module => $reldir) {
  4415. if (!empty($module)) {
  4416. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4417. } else {
  4418. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4419. }
  4420. if (empty($conf->file->strict_mode)) {
  4421. $res = @include $tpl;
  4422. } else {
  4423. $res = include $tpl; // for debug
  4424. }
  4425. if ($res) {
  4426. break;
  4427. }
  4428. }
  4429. }
  4430. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4431. /**
  4432. * Add resources to the current object : add entry into llx_element_resources
  4433. * Need $this->element & $this->id
  4434. *
  4435. * @param int $resource_id Resource id
  4436. * @param string $resource_type 'resource'
  4437. * @param int $busy Busy or not
  4438. * @param int $mandatory Mandatory or not
  4439. * @return int <=0 if KO, >0 if OK
  4440. */
  4441. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4442. {
  4443. // phpcs:enable
  4444. $this->db->begin();
  4445. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  4446. $sql .= "resource_id";
  4447. $sql .= ", resource_type";
  4448. $sql .= ", element_id";
  4449. $sql .= ", element_type";
  4450. $sql .= ", busy";
  4451. $sql .= ", mandatory";
  4452. $sql .= ") VALUES (";
  4453. $sql .= $resource_id;
  4454. $sql .= ", '".$this->db->escape($resource_type)."'";
  4455. $sql .= ", '".$this->db->escape($this->id)."'";
  4456. $sql .= ", '".$this->db->escape($this->element)."'";
  4457. $sql .= ", '".$this->db->escape($busy)."'";
  4458. $sql .= ", '".$this->db->escape($mandatory)."'";
  4459. $sql .= ")";
  4460. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4461. if ($this->db->query($sql)) {
  4462. $this->db->commit();
  4463. return 1;
  4464. } else {
  4465. $this->error = $this->db->lasterror();
  4466. $this->db->rollback();
  4467. return 0;
  4468. }
  4469. }
  4470. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4471. /**
  4472. * Delete a link to resource line
  4473. *
  4474. * @param int $rowid Id of resource line to delete
  4475. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4476. * @param int $notrigger Disable all triggers
  4477. * @return int >0 if OK, <0 if KO
  4478. */
  4479. public function delete_resource($rowid, $element, $notrigger = 0)
  4480. {
  4481. // phpcs:enable
  4482. global $user;
  4483. $this->db->begin();
  4484. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  4485. $sql .= " WHERE rowid = ".((int) $rowid);
  4486. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4487. $resql = $this->db->query($sql);
  4488. if (!$resql) {
  4489. $this->error = $this->db->lasterror();
  4490. $this->db->rollback();
  4491. return -1;
  4492. } else {
  4493. if (!$notrigger) {
  4494. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4495. if ($result < 0) {
  4496. $this->db->rollback();
  4497. return -1;
  4498. }
  4499. }
  4500. $this->db->commit();
  4501. return 1;
  4502. }
  4503. }
  4504. /**
  4505. * Overwrite magic function to solve problem of cloning object that are kept as references
  4506. *
  4507. * @return void
  4508. */
  4509. public function __clone()
  4510. {
  4511. // Force a copy of this->lines, otherwise it will point to same object.
  4512. if (isset($this->lines) && is_array($this->lines)) {
  4513. $nboflines = count($this->lines);
  4514. for ($i = 0; $i < $nboflines; $i++) {
  4515. $this->lines[$i] = clone $this->lines[$i];
  4516. }
  4517. }
  4518. }
  4519. /**
  4520. * Common function for all objects extending CommonObject for generating documents
  4521. *
  4522. * @param string $modelspath Relative folder where generators are placed
  4523. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4524. * @param Translate $outputlangs Output language to use
  4525. * @param int $hidedetails 1 to hide details. 0 by default
  4526. * @param int $hidedesc 1 to hide product description. 0 by default
  4527. * @param int $hideref 1 to hide product reference. 0 by default
  4528. * @param null|array $moreparams Array to provide more information
  4529. * @return int >0 if OK, <0 if KO
  4530. * @see addFileIntoDatabaseIndex()
  4531. */
  4532. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4533. {
  4534. global $conf, $langs, $user, $hookmanager, $action;
  4535. $srctemplatepath = '';
  4536. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4537. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4538. if (empty($reshook)) {
  4539. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4540. if (empty($modele)) {
  4541. $this->error = 'BadValueForParameterModele';
  4542. return -1;
  4543. }
  4544. // Increase limit for PDF build
  4545. $err = error_reporting();
  4546. error_reporting(0);
  4547. @set_time_limit(120);
  4548. error_reporting($err);
  4549. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4550. $tmp = explode(':', $modele, 2);
  4551. if (!empty($tmp[1])) {
  4552. $modele = $tmp[0];
  4553. $srctemplatepath = $tmp[1];
  4554. }
  4555. // Search template files
  4556. $file = '';
  4557. $classname = '';
  4558. $filefound = '';
  4559. $dirmodels = array('/');
  4560. if (is_array($conf->modules_parts['models'])) {
  4561. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4562. }
  4563. foreach ($dirmodels as $reldir) {
  4564. foreach (array('doc', 'pdf') as $prefix) {
  4565. if (in_array(get_class($this), array('Adherent'))) {
  4566. // Member module use prefix_modele.class.php
  4567. $file = $prefix."_".$modele.".class.php";
  4568. } else {
  4569. // Other module use prefix_modele.modules.php
  4570. $file = $prefix."_".$modele.".modules.php";
  4571. }
  4572. // On verifie l'emplacement du modele
  4573. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4574. if (file_exists($file)) {
  4575. $filefound = $file;
  4576. $classname = $prefix.'_'.$modele;
  4577. break;
  4578. }
  4579. }
  4580. if ($filefound) {
  4581. break;
  4582. }
  4583. }
  4584. // If generator was found
  4585. if ($filefound) {
  4586. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4587. require_once $file;
  4588. $obj = new $classname($this->db);
  4589. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4590. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4591. $varfortemplatedir = $obj->scandir;
  4592. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4593. $dirtoscan = $conf->global->$varfortemplatedir;
  4594. $listoffiles = array();
  4595. // Now we add first model found in directories scanned
  4596. $listofdir = explode(',', $dirtoscan);
  4597. foreach ($listofdir as $key => $tmpdir) {
  4598. $tmpdir = trim($tmpdir);
  4599. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4600. if (!$tmpdir) {
  4601. unset($listofdir[$key]);
  4602. continue;
  4603. }
  4604. if (is_dir($tmpdir)) {
  4605. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4606. if (count($tmpfiles)) {
  4607. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4608. }
  4609. }
  4610. }
  4611. if (count($listoffiles)) {
  4612. foreach ($listoffiles as $record) {
  4613. $srctemplatepath = $record['fullname'];
  4614. break;
  4615. }
  4616. }
  4617. }
  4618. if (empty($srctemplatepath)) {
  4619. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4620. return -1;
  4621. }
  4622. }
  4623. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4624. if (!dol_is_file($srctemplatepath)) {
  4625. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4626. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4627. return -1;
  4628. }
  4629. }
  4630. // We save charset_output to restore it because write_file can change it if needed for
  4631. // output format that does not support UTF8.
  4632. $sav_charset_output = $outputlangs->charset_output;
  4633. if (in_array(get_class($this), array('Adherent'))) {
  4634. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  4635. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  4636. } else {
  4637. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4638. }
  4639. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4640. if ($resultwritefile > 0) {
  4641. $outputlangs->charset_output = $sav_charset_output;
  4642. // We delete old preview
  4643. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4644. dol_delete_preview($this);
  4645. // Index file in database
  4646. if (!empty($obj->result['fullpath'])) {
  4647. $destfull = $obj->result['fullpath'];
  4648. $upload_dir = dirname($destfull);
  4649. $destfile = basename($destfull);
  4650. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4651. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4652. $filename = basename($destfile);
  4653. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4654. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4655. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4656. $ecmfile = new EcmFiles($this->db);
  4657. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4658. // Set the public "share" key
  4659. $setsharekey = false;
  4660. if ($this->element == 'propal') {
  4661. $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
  4662. if ($useonlinesignature) {
  4663. $setsharekey = true;
  4664. }
  4665. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4666. $setsharekey = true;
  4667. }
  4668. }
  4669. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4670. $setsharekey = true;
  4671. }
  4672. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4673. $setsharekey = true;
  4674. }
  4675. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4676. $setsharekey = true;
  4677. }
  4678. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4679. $setsharekey = true;
  4680. }
  4681. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4682. $setsharekey = true;
  4683. }
  4684. if ($setsharekey) {
  4685. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4686. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4687. $ecmfile->share = getRandomPassword(true);
  4688. }
  4689. }
  4690. if ($result > 0) {
  4691. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4692. $ecmfile->fullpath_orig = '';
  4693. $ecmfile->gen_or_uploaded = 'generated';
  4694. $ecmfile->description = ''; // indexed content
  4695. $ecmfile->keyword = ''; // keyword content
  4696. $result = $ecmfile->update($user);
  4697. if ($result < 0) {
  4698. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4699. }
  4700. } else {
  4701. $ecmfile->entity = $conf->entity;
  4702. $ecmfile->filepath = $rel_dir;
  4703. $ecmfile->filename = $filename;
  4704. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4705. $ecmfile->fullpath_orig = '';
  4706. $ecmfile->gen_or_uploaded = 'generated';
  4707. $ecmfile->description = ''; // indexed content
  4708. $ecmfile->keyword = ''; // keyword content
  4709. $ecmfile->src_object_type = $this->table_element;
  4710. $ecmfile->src_object_id = $this->id;
  4711. $result = $ecmfile->create($user);
  4712. if ($result < 0) {
  4713. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4714. }
  4715. }
  4716. /*$this->result['fullname']=$destfull;
  4717. $this->result['filepath']=$ecmfile->filepath;
  4718. $this->result['filename']=$ecmfile->filename;*/
  4719. //var_dump($obj->update_main_doc_field);exit;
  4720. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4721. $update_main_doc_field = 0;
  4722. if (!empty($obj->update_main_doc_field)) {
  4723. $update_main_doc_field = 1;
  4724. }
  4725. if ($update_main_doc_field && !empty($this->table_element)) {
  4726. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
  4727. $sql .= ' WHERE rowid = '.$this->id;
  4728. $resql = $this->db->query($sql);
  4729. if (!$resql) {
  4730. dol_print_error($this->db);
  4731. } else {
  4732. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4733. }
  4734. }
  4735. }
  4736. } else {
  4737. dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING);
  4738. }
  4739. // Success in building document. We build meta file.
  4740. dol_meta_create($this);
  4741. return 1;
  4742. } else {
  4743. $outputlangs->charset_output = $sav_charset_output;
  4744. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4745. return -1;
  4746. }
  4747. } else {
  4748. if (!$filefound) {
  4749. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4750. dol_print_error('', $this->error);
  4751. } else {
  4752. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4753. dol_print_error('', $this->error);
  4754. }
  4755. return -1;
  4756. }
  4757. } else {
  4758. return $reshook;
  4759. }
  4760. }
  4761. /**
  4762. * Build thumb
  4763. * @todo Move this into files.lib.php
  4764. *
  4765. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4766. * @return void
  4767. */
  4768. public function addThumbs($file)
  4769. {
  4770. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4771. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4772. $file_osencoded = dol_osencode($file);
  4773. if (file_exists($file_osencoded)) {
  4774. // Create small thumbs for company (Ratio is near 16/9)
  4775. // Used on logon for example
  4776. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4777. // Create mini thumbs for company (Ratio is near 16/9)
  4778. // Used on menu or for setup page for example
  4779. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4780. }
  4781. }
  4782. /* Functions common to commonobject and commonobjectline */
  4783. /* For default values */
  4784. /**
  4785. * Return the default value to use for a field when showing the create form of object.
  4786. * Return values in this order:
  4787. * 1) If parameter is available into POST, we return it first.
  4788. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4789. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4790. * 4) Return value found into database (TODO No yet implemented)
  4791. *
  4792. * @param string $fieldname Name of field
  4793. * @param string $alternatevalue Alternate value to use
  4794. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4795. **/
  4796. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4797. {
  4798. global $conf, $_POST;
  4799. // If param here has been posted, we use this value first.
  4800. if (GETPOSTISSET($fieldname)) {
  4801. return GETPOST($fieldname, 'alphanohtml', 3);
  4802. }
  4803. if (isset($alternatevalue)) {
  4804. return $alternatevalue;
  4805. }
  4806. $newelement = $this->element;
  4807. if ($newelement == 'facture') {
  4808. $newelement = 'invoice';
  4809. }
  4810. if ($newelement == 'commande') {
  4811. $newelement = 'order';
  4812. }
  4813. if (empty($newelement)) {
  4814. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4815. return '';
  4816. }
  4817. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4818. //var_dump($keyforfieldname);
  4819. if (isset($conf->global->$keyforfieldname)) {
  4820. return $conf->global->$keyforfieldname;
  4821. }
  4822. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4823. }
  4824. /* For triggers */
  4825. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4826. /**
  4827. * Call trigger based on this instance.
  4828. * Some context information may also be provided into array property this->context.
  4829. * NB: Error from trigger are stacked in interface->errors
  4830. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4831. *
  4832. * @param string $triggerName trigger's name to execute
  4833. * @param User $user Object user
  4834. * @return int Result of run_triggers
  4835. */
  4836. public function call_trigger($triggerName, $user)
  4837. {
  4838. // phpcs:enable
  4839. global $langs, $conf;
  4840. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4841. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4842. $langs = new Translate('', $conf);
  4843. }
  4844. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4845. $interface = new Interfaces($this->db);
  4846. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4847. if ($result < 0) {
  4848. if (!empty($this->errors)) {
  4849. $this->errors = array_unique(array_merge($this->errors, $interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice.
  4850. } else {
  4851. $this->errors = $interface->errors;
  4852. }
  4853. }
  4854. return $result;
  4855. }
  4856. /* Functions for data in other language */
  4857. /**
  4858. * Function to get alternative languages of a data into $this->array_languages
  4859. * This method is NOT called by method fetch of objects but must be called separately.
  4860. *
  4861. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4862. * @see fetch_optionnals()
  4863. */
  4864. public function fetchValuesForExtraLanguages()
  4865. {
  4866. // To avoid SQL errors. Probably not the better solution though
  4867. if (!$this->element) {
  4868. return 0;
  4869. }
  4870. if (!($this->id > 0)) {
  4871. return 0;
  4872. }
  4873. if (is_array($this->array_languages)) {
  4874. return 1;
  4875. }
  4876. $this->array_languages = array();
  4877. $element = $this->element;
  4878. if ($element == 'categorie') {
  4879. $element = 'categories'; // For compatibility
  4880. }
  4881. // Request to get translation values for object
  4882. $sql = "SELECT rowid, property, lang , value";
  4883. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  4884. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  4885. $sql .= " AND fk_object = ".$this->id;
  4886. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4887. $resql = $this->db->query($sql);
  4888. if ($resql) {
  4889. $numrows = $this->db->num_rows($resql);
  4890. if ($numrows) {
  4891. $i = 0;
  4892. while ($i < $numrows) {
  4893. $obj = $this->db->fetch_object($resql);
  4894. $key = $obj->property;
  4895. $value = $obj->value;
  4896. $codelang = $obj->lang;
  4897. $type = $this->fields[$key]['type'];
  4898. // we can add this attribute to object
  4899. if (preg_match('/date/', $type)) {
  4900. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  4901. } else {
  4902. $this->array_languages[$key][$codelang] = $value;
  4903. }
  4904. $i++;
  4905. }
  4906. }
  4907. $this->db->free($resql);
  4908. if ($numrows) {
  4909. return $numrows;
  4910. } else {
  4911. return 0;
  4912. }
  4913. } else {
  4914. dol_print_error($this->db);
  4915. return -1;
  4916. }
  4917. }
  4918. /**
  4919. * Fill array_options property of object by extrafields value (using for data sent by forms)
  4920. *
  4921. * @param string $onlykey Only the following key is filled. When we make update of only one language field ($action = 'update_languages'), calling page must set this to avoid to have other languages being reset.
  4922. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  4923. */
  4924. public function setValuesForExtraLanguages($onlykey = '')
  4925. {
  4926. global $_POST, $langs;
  4927. // Get extra fields
  4928. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  4929. $tmparray = explode('-', $postfieldkey);
  4930. if ($tmparray[0] != 'field') {
  4931. continue;
  4932. }
  4933. $element = $tmparray[1];
  4934. $key = $tmparray[2];
  4935. $codelang = $tmparray[3];
  4936. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  4937. if (!empty($onlykey) && $key != $onlykey) {
  4938. continue;
  4939. }
  4940. if ($element != $this->element) {
  4941. continue;
  4942. }
  4943. $key_type = $this->fields[$key]['type'];
  4944. $enabled = 1;
  4945. if (isset($this->fields[$key]['enabled'])) {
  4946. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  4947. }
  4948. /*$perms = 1;
  4949. if (isset($this->fields[$key]['perms']))
  4950. {
  4951. $perms = dol_eval($this->fields[$key]['perms'], 1);
  4952. }*/
  4953. if (empty($enabled)) {
  4954. continue;
  4955. }
  4956. //if (empty($perms)) continue;
  4957. if (in_array($key_type, array('date'))) {
  4958. // Clean parameters
  4959. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4960. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4961. } elseif (in_array($key_type, array('datetime'))) {
  4962. // Clean parameters
  4963. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4964. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4965. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  4966. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  4967. if (!empty($value_arr)) {
  4968. $value_key = implode(',', $value_arr);
  4969. } else {
  4970. $value_key = '';
  4971. }
  4972. } elseif (in_array($key_type, array('price', 'double'))) {
  4973. $value_arr = GETPOST($postfieldkey, 'alpha');
  4974. $value_key = price2num($value_arr);
  4975. } else {
  4976. $value_key = GETPOST($postfieldkey);
  4977. if (in_array($key_type, array('link')) && $value_key == '-1') {
  4978. $value_key = '';
  4979. }
  4980. }
  4981. $this->array_languages[$key][$codelang] = $value_key;
  4982. /*if ($nofillrequired) {
  4983. $langs->load('errors');
  4984. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  4985. return -1;
  4986. }*/
  4987. }
  4988. return 1;
  4989. }
  4990. /* Functions for extrafields */
  4991. /**
  4992. * Function to make a fetch but set environment to avoid to load computed values before.
  4993. *
  4994. * @param int $id ID of object
  4995. * @return int >0 if OK, 0 if not found, <0 if KO
  4996. */
  4997. public function fetchNoCompute($id)
  4998. {
  4999. global $conf;
  5000. $savDisableCompute = $conf->disable_compute;
  5001. $conf->disable_compute = 1;
  5002. $ret = $this->fetch($id);
  5003. $conf->disable_compute = $savDisableCompute;
  5004. return $ret;
  5005. }
  5006. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5007. /**
  5008. * Function to get extra fields of an object into $this->array_options
  5009. * This method is in most cases called by method fetch of objects but you can call it separately.
  5010. *
  5011. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5012. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5013. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5014. * @see fetchValuesForExtraLanguages()
  5015. */
  5016. public function fetch_optionals($rowid = null, $optionsArray = null)
  5017. {
  5018. // phpcs:enable
  5019. global $conf, $extrafields;
  5020. if (empty($rowid)) {
  5021. $rowid = $this->id;
  5022. }
  5023. if (empty($rowid) && isset($this->rowid)) {
  5024. $rowid = $this->rowid; // deprecated
  5025. }
  5026. // To avoid SQL errors. Probably not the better solution though
  5027. if (!$this->table_element) {
  5028. return 0;
  5029. }
  5030. $this->array_options = array();
  5031. if (!is_array($optionsArray)) {
  5032. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5033. if (!isset($extrafields) || !is_object($extrafields)) {
  5034. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5035. $extrafields = new ExtraFields($this->db);
  5036. }
  5037. // Load array of extrafields for elementype = $this->table_element
  5038. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5039. $extrafields->fetch_name_optionals_label($this->table_element);
  5040. }
  5041. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5042. } else {
  5043. global $extrafields;
  5044. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5045. }
  5046. $table_element = $this->table_element;
  5047. if ($table_element == 'categorie') {
  5048. $table_element = 'categories'; // For compatibility
  5049. }
  5050. // Request to get complementary values
  5051. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5052. $sql = "SELECT rowid";
  5053. foreach ($optionsArray as $name => $label) {
  5054. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5055. $sql .= ", ".$name;
  5056. }
  5057. }
  5058. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  5059. $sql .= " WHERE fk_object = ".((int) $rowid);
  5060. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5061. $resql = $this->db->query($sql);
  5062. if ($resql) {
  5063. $numrows = $this->db->num_rows($resql);
  5064. if ($numrows) {
  5065. $tab = $this->db->fetch_array($resql);
  5066. foreach ($tab as $key => $value) {
  5067. // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine)
  5068. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5069. // we can add this attribute to object
  5070. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5071. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5072. $this->array_options["options_".$key] = $this->db->jdate($value);
  5073. } else {
  5074. $this->array_options["options_".$key] = $value;
  5075. }
  5076. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5077. }
  5078. }
  5079. // If field is a computed field, value must become result of compute
  5080. foreach ($tab as $key => $value) {
  5081. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5082. //var_dump($conf->disable_compute);
  5083. if (empty($conf->disable_compute)) {
  5084. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  5085. }
  5086. }
  5087. }
  5088. }
  5089. $this->db->free($resql);
  5090. if ($numrows) {
  5091. return $numrows;
  5092. } else {
  5093. return 0;
  5094. }
  5095. } else {
  5096. $this->errors[]=$this->db->lasterror;
  5097. return -1;
  5098. }
  5099. }
  5100. return 0;
  5101. }
  5102. /**
  5103. * Delete all extra fields values for the current object.
  5104. *
  5105. * @return int <0 if KO, >0 if OK
  5106. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5107. */
  5108. public function deleteExtraFields()
  5109. {
  5110. global $conf;
  5111. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5112. return 0;
  5113. }
  5114. $this->db->begin();
  5115. $table_element = $this->table_element;
  5116. if ($table_element == 'categorie') {
  5117. $table_element = 'categories'; // For compatibility
  5118. }
  5119. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  5120. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5121. $resql = $this->db->query($sql_del);
  5122. if (!$resql) {
  5123. $this->error = $this->db->lasterror();
  5124. $this->db->rollback();
  5125. return -1;
  5126. } else {
  5127. $this->db->commit();
  5128. return 1;
  5129. }
  5130. }
  5131. /**
  5132. * Add/Update all extra fields values for the current object.
  5133. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5134. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5135. *
  5136. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5137. * @param User $userused Object user
  5138. * @return int -1=error, O=did nothing, 1=OK
  5139. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5140. */
  5141. public function insertExtraFields($trigger = '', $userused = null)
  5142. {
  5143. global $conf, $langs, $user;
  5144. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5145. return 0;
  5146. }
  5147. if (empty($userused)) {
  5148. $userused = $user;
  5149. }
  5150. $error = 0;
  5151. if (!empty($this->array_options)) {
  5152. // Check parameters
  5153. $langs->load('admin');
  5154. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5155. $extrafields = new ExtraFields($this->db);
  5156. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5157. // Eliminate copied source object extra fields that do not exist in target object
  5158. $new_array_options = array();
  5159. foreach ($this->array_options as $key => $value) {
  5160. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5161. $new_array_options[$key] = $value;
  5162. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5163. $new_array_options['options_'.$key] = $value;
  5164. }
  5165. }
  5166. foreach ($new_array_options as $key => $value) {
  5167. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5168. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5169. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5170. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5171. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5172. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5173. // Similar code than into insertExtraFields
  5174. if ($attributeRequired) {
  5175. $mandatorypb = false;
  5176. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5177. $mandatorypb = true;
  5178. }
  5179. if ($this->array_options[$key] === '') {
  5180. $mandatorypb = true;
  5181. }
  5182. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5183. $mandatorypb = true;
  5184. }
  5185. if ($mandatorypb) {
  5186. dol_syslog("Mandatory extra field ".$key." is empty");
  5187. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5188. return -1;
  5189. }
  5190. }
  5191. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5192. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5193. if (!empty($attrfieldcomputed)) {
  5194. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5195. $value = dol_eval($attrfieldcomputed, 1, 0);
  5196. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5197. $new_array_options[$key] = $value;
  5198. } else {
  5199. $new_array_options[$key] = null;
  5200. }
  5201. }
  5202. switch ($attributeType) {
  5203. case 'int':
  5204. if (!is_numeric($value) && $value != '') {
  5205. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5206. return -1;
  5207. } elseif ($value == '') {
  5208. $new_array_options[$key] = null;
  5209. }
  5210. break;
  5211. case 'price':
  5212. case 'double':
  5213. $value = price2num($value);
  5214. if (!is_numeric($value) && $value != '') {
  5215. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5216. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5217. return -1;
  5218. } elseif ($value == '') {
  5219. $new_array_options[$key] = null;
  5220. }
  5221. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5222. $new_array_options[$key] = $value;
  5223. break;
  5224. /*case 'select': // Not required, we chosed value='0' for undefined values
  5225. if ($value=='-1')
  5226. {
  5227. $this->array_options[$key] = null;
  5228. }
  5229. break;*/
  5230. case 'password':
  5231. $algo = '';
  5232. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5233. // If there is an encryption choice, we use it to crypt data before insert
  5234. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5235. $algo = reset($tmparrays);
  5236. if ($algo != '') {
  5237. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5238. //var_dump($action);
  5239. //var_dump($this->oldcopy);exit;
  5240. if (is_object($this->oldcopy)) { // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
  5241. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5242. if ($this->array_options[$key] == $this->oldcopy->array_options[$key]) { // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
  5243. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5244. } else {
  5245. // var_dump($algo);
  5246. $newvalue = dol_hash($this->array_options[$key], $algo);
  5247. $new_array_options[$key] = $newvalue;
  5248. }
  5249. } else {
  5250. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5251. }
  5252. }
  5253. } else // Common usage
  5254. {
  5255. $new_array_options[$key] = $this->array_options[$key];
  5256. }
  5257. break;
  5258. case 'date':
  5259. case 'datetime':
  5260. // If data is a string instead of a timestamp, we convert it
  5261. if (!is_int($this->array_options[$key])) {
  5262. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5263. }
  5264. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5265. break;
  5266. case 'link':
  5267. $param_list = array_keys($attributeParam['options']);
  5268. // 0 : ObjectName
  5269. // 1 : classPath
  5270. $InfoFieldList = explode(":", $param_list[0]);
  5271. dol_include_once($InfoFieldList[1]);
  5272. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5273. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5274. $new_array_options[$key] = '';
  5275. } elseif ($value) {
  5276. $object = new $InfoFieldList[0]($this->db);
  5277. if (is_numeric($value)) {
  5278. $res = $object->fetch($value); // Common case
  5279. } else {
  5280. $res = $object->fetch('', $value); // For compatibility
  5281. }
  5282. if ($res > 0) {
  5283. $new_array_options[$key] = $object->id;
  5284. } else {
  5285. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5286. $this->db->rollback();
  5287. return -1;
  5288. }
  5289. }
  5290. } else {
  5291. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5292. }
  5293. break;
  5294. }
  5295. }
  5296. $this->db->begin();
  5297. $table_element = $this->table_element;
  5298. if ($table_element == 'categorie') {
  5299. $table_element = 'categories'; // For compatibility
  5300. }
  5301. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5302. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  5303. $this->db->query($sql_del);
  5304. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  5305. foreach ($new_array_options as $key => $value) {
  5306. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5307. // Add field of attribut
  5308. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5309. $sql .= ",".$attributeKey;
  5310. }
  5311. }
  5312. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5313. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5314. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5315. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5316. $sql .= ",".$tmpkey;
  5317. }
  5318. }
  5319. }
  5320. $sql .= ") VALUES (".$this->id;
  5321. foreach ($new_array_options as $key => $value) {
  5322. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5323. // Add field of attribute
  5324. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5325. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5326. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5327. } else {
  5328. $sql .= ",null";
  5329. }
  5330. }
  5331. }
  5332. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5333. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5334. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5335. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5336. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5337. $sql .= ", 0";
  5338. } else {
  5339. $sql .= ", ''";
  5340. }
  5341. }
  5342. }
  5343. }
  5344. $sql .= ")";
  5345. $resql = $this->db->query($sql);
  5346. if (!$resql) {
  5347. $this->error = $this->db->lasterror();
  5348. $error++;
  5349. }
  5350. if (!$error && $trigger) {
  5351. // Call trigger
  5352. $this->context = array('extrafieldaddupdate'=>1);
  5353. $result = $this->call_trigger($trigger, $userused);
  5354. if ($result < 0) {
  5355. $error++;
  5356. }
  5357. // End call trigger
  5358. }
  5359. if ($error) {
  5360. $this->db->rollback();
  5361. return -1;
  5362. } else {
  5363. $this->db->commit();
  5364. return 1;
  5365. }
  5366. } else {
  5367. return 0;
  5368. }
  5369. }
  5370. /**
  5371. * Add/Update all extra fields values for the current object.
  5372. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5373. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5374. *
  5375. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5376. * @param User $userused Object user
  5377. * @return int -1=error, O=did nothing, 1=OK
  5378. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5379. */
  5380. public function insertExtraLanguages($trigger = '', $userused = null)
  5381. {
  5382. global $conf, $langs, $user;
  5383. if (empty($userused)) {
  5384. $userused = $user;
  5385. }
  5386. $error = 0;
  5387. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5388. return 0; // For avoid conflicts if trigger used
  5389. }
  5390. if (is_array($this->array_languages)) {
  5391. $new_array_languages = $this->array_languages;
  5392. foreach ($new_array_languages as $key => $value) {
  5393. $attributeKey = $key;
  5394. $attributeType = $this->fields[$attributeKey]['type'];
  5395. $attributeLabel = $this->fields[$attributeKey]['label'];
  5396. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5397. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5398. switch ($attributeType) {
  5399. case 'int':
  5400. if (!is_numeric($value) && $value != '') {
  5401. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5402. return -1;
  5403. } elseif ($value == '') {
  5404. $new_array_languages[$key] = null;
  5405. }
  5406. break;
  5407. case 'double':
  5408. $value = price2num($value);
  5409. if (!is_numeric($value) && $value != '') {
  5410. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5411. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5412. return -1;
  5413. } elseif ($value == '') {
  5414. $new_array_languages[$key] = null;
  5415. }
  5416. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5417. $new_array_languages[$key] = $value;
  5418. break;
  5419. /*case 'select': // Not required, we chosed value='0' for undefined values
  5420. if ($value=='-1')
  5421. {
  5422. $this->array_options[$key] = null;
  5423. }
  5424. break;*/
  5425. }
  5426. }
  5427. $this->db->begin();
  5428. $table_element = $this->table_element;
  5429. if ($table_element == 'categorie') {
  5430. $table_element = 'categories'; // For compatibility
  5431. }
  5432. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5433. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5434. foreach ($langcodearray as $langcode => $value) {
  5435. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  5436. $sql_del .= " WHERE fk_object = ".$this->id." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5437. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5438. $this->db->query($sql_del);
  5439. if ($value !== '') {
  5440. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  5441. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5442. $sql .= ")";
  5443. $resql = $this->db->query($sql);
  5444. if (!$resql) {
  5445. $this->error = $this->db->lasterror();
  5446. $error++;
  5447. break;
  5448. }
  5449. }
  5450. }
  5451. }
  5452. if (!$error && $trigger) {
  5453. // Call trigger
  5454. $this->context = array('extralanguagesaddupdate'=>1);
  5455. $result = $this->call_trigger($trigger, $userused);
  5456. if ($result < 0) {
  5457. $error++;
  5458. }
  5459. // End call trigger
  5460. }
  5461. if ($error) {
  5462. $this->db->rollback();
  5463. return -1;
  5464. } else {
  5465. $this->db->commit();
  5466. return 1;
  5467. }
  5468. } else {
  5469. return 0;
  5470. }
  5471. }
  5472. /**
  5473. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5474. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5475. *
  5476. * @param string $key Key of the extrafield to update (without starting 'options_')
  5477. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5478. * @param User $userused Object user
  5479. * @return int -1=error, O=did nothing, 1=OK
  5480. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5481. */
  5482. public function updateExtraField($key, $trigger = null, $userused = null)
  5483. {
  5484. global $conf, $langs, $user;
  5485. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5486. return 0;
  5487. }
  5488. if (empty($userused)) {
  5489. $userused = $user;
  5490. }
  5491. $error = 0;
  5492. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5493. // Check parameters
  5494. $langs->load('admin');
  5495. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5496. $extrafields = new ExtraFields($this->db);
  5497. $extrafields->fetch_name_optionals_label($this->table_element);
  5498. $value = $this->array_options["options_".$key];
  5499. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5500. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5501. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5502. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5503. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5504. // Similar code than into insertExtraFields
  5505. if ($attributeRequired) {
  5506. $mandatorypb = false;
  5507. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5508. $mandatorypb = true;
  5509. }
  5510. if ($this->array_options["options_".$key] === '') {
  5511. $mandatorypb = true;
  5512. }
  5513. if ($mandatorypb) {
  5514. dol_syslog("Mandatory extra field options_".$key." is empty");
  5515. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5516. return -1;
  5517. }
  5518. }
  5519. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5520. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5521. if (!empty($attrfieldcomputed)) {
  5522. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5523. $value = dol_eval($attrfieldcomputed, 1, 0);
  5524. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5525. $this->array_options["options_".$key] = $value;
  5526. } else {
  5527. $this->array_options["options_".$key] = null;
  5528. }
  5529. }
  5530. switch ($attributeType) {
  5531. case 'int':
  5532. if (!is_numeric($value) && $value != '') {
  5533. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5534. return -1;
  5535. } elseif ($value === '') {
  5536. $this->array_options["options_".$key] = null;
  5537. }
  5538. break;
  5539. case 'double':
  5540. $value = price2num($value);
  5541. if (!is_numeric($value) && $value != '') {
  5542. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5543. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5544. return -1;
  5545. } elseif ($value === '') {
  5546. $this->array_options["options_".$key] = null;
  5547. }
  5548. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5549. $this->array_options["options_".$key] = $value;
  5550. break;
  5551. /*case 'select': // Not required, we chosed value='0' for undefined values
  5552. if ($value=='-1')
  5553. {
  5554. $this->array_options[$key] = null;
  5555. }
  5556. break;*/
  5557. case 'price':
  5558. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5559. break;
  5560. case 'date':
  5561. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5562. break;
  5563. case 'datetime':
  5564. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5565. break;
  5566. /*
  5567. case 'link':
  5568. $param_list = array_keys($attributeParam['options']);
  5569. // 0 : ObjectName
  5570. // 1 : classPath
  5571. $InfoFieldList = explode(":", $param_list[0]);
  5572. dol_include_once($InfoFieldList[1]);
  5573. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5574. {
  5575. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5576. {
  5577. $new_array_options[$key] = '';
  5578. } elseif ($value) {
  5579. $object = new $InfoFieldList[0]($this->db);
  5580. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5581. else $res = $object->fetch('', $value); // For compatibility
  5582. if ($res > 0) $new_array_options[$key] = $object->id;
  5583. else {
  5584. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5585. $this->db->rollback();
  5586. return -1;
  5587. }
  5588. }
  5589. } else {
  5590. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5591. }
  5592. break;
  5593. */
  5594. }
  5595. $this->db->begin();
  5596. $linealreadyfound = 0;
  5597. // Check if there is already a line for this object (in most cases, it is, but sometimes it is not, for example when extra field has been created after), so we must keep this overload)
  5598. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  5599. $resql = $this->db->query($sql);
  5600. if ($resql) {
  5601. $tmpobj = $this->db->fetch_object($resql);
  5602. if ($tmpobj) {
  5603. $linealreadyfound = $tmpobj->nb;
  5604. }
  5605. }
  5606. if ($linealreadyfound) {
  5607. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5608. $sql .= " WHERE fk_object = ".$this->id;
  5609. } else {
  5610. $result = $this->insertExtraFields('', $user);
  5611. if ($result < 0) {
  5612. $error++;
  5613. }
  5614. }
  5615. $resql = $this->db->query($sql);
  5616. if (!$resql) {
  5617. $error++;
  5618. $this->error = $this->db->lasterror();
  5619. }
  5620. if (!$error && $trigger) {
  5621. // Call trigger
  5622. $this->context = array('extrafieldupdate'=>1);
  5623. $result = $this->call_trigger($trigger, $userused);
  5624. if ($result < 0) {
  5625. $error++;
  5626. }
  5627. // End call trigger
  5628. }
  5629. if ($error) {
  5630. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5631. $this->db->rollback();
  5632. return -1;
  5633. } else {
  5634. $this->db->commit();
  5635. return 1;
  5636. }
  5637. } else {
  5638. return 0;
  5639. }
  5640. }
  5641. /**
  5642. * Update an extra language value for the current object.
  5643. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5644. *
  5645. * @param string $key Key of the extrafield (without starting 'options_')
  5646. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5647. * @param User $userused Object user
  5648. * @return int -1=error, O=did nothing, 1=OK
  5649. * @see updateExtraFields(), insertExtraLanguages()
  5650. */
  5651. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5652. {
  5653. global $conf, $langs, $user;
  5654. if (empty($userused)) {
  5655. $userused = $user;
  5656. }
  5657. $error = 0;
  5658. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5659. return 0; // For avoid conflicts if trigger used
  5660. }
  5661. return 0;
  5662. }
  5663. /**
  5664. * Return HTML string to put an input field into a page
  5665. * Code very similar with showInputField of extra fields
  5666. *
  5667. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5668. * @param string $key Key of attribute
  5669. * @param string|array $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value, for array type must be array)
  5670. * @param string $moreparam To add more parameters on html input tag
  5671. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5672. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5673. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5674. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5675. * @return string
  5676. */
  5677. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5678. {
  5679. global $conf, $langs, $form;
  5680. if (!is_object($form)) {
  5681. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5682. $form = new Form($this->db);
  5683. }
  5684. if (!empty($this->fields)) {
  5685. $val = $this->fields[$key];
  5686. }
  5687. $out = '';
  5688. $type = '';
  5689. $isDependList=0;
  5690. $param = array();
  5691. $param['options'] = array();
  5692. $reg = array();
  5693. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5694. // Because we work on extrafields
  5695. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5696. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5697. $type = 'link';
  5698. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5699. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5700. $type = 'link';
  5701. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5702. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5703. $type = 'link';
  5704. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5705. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5706. $type = 'sellist';
  5707. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5708. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5709. $type = 'sellist';
  5710. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5711. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5712. $type = 'sellist';
  5713. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5714. $param['options'] = array();
  5715. $type = 'varchar';
  5716. $size = $reg[1];
  5717. } elseif (preg_match('/varchar/', $val['type'])) {
  5718. $param['options'] = array();
  5719. $type = 'varchar';
  5720. } else {
  5721. $param['options'] = array();
  5722. $type = $this->fields[$key]['type'];
  5723. }
  5724. // Special case that force options and type ($type can be integer, varchar, ...)
  5725. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5726. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5727. $type = 'select';
  5728. }
  5729. $label = $this->fields[$key]['label'];
  5730. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5731. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5732. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5733. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5734. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5735. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5736. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5737. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5738. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5739. $objectid = $this->id;
  5740. if ($computed) {
  5741. if (!preg_match('/^search_/', $keyprefix)) {
  5742. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5743. } else {
  5744. return '';
  5745. }
  5746. }
  5747. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5748. if (empty($morecss) && !empty($val['css'])) {
  5749. $morecss = $val['css'];
  5750. } elseif (empty($morecss)) {
  5751. if ($type == 'date') {
  5752. $morecss = 'minwidth100imp';
  5753. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5754. $morecss = 'minwidth200imp';
  5755. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5756. $morecss = 'maxwidth75';
  5757. } elseif ($type == 'url') {
  5758. $morecss = 'minwidth400';
  5759. } elseif ($type == 'boolean') {
  5760. $morecss = '';
  5761. } else {
  5762. if (round($size) < 12) {
  5763. $morecss = 'minwidth100';
  5764. } elseif (round($size) <= 48) {
  5765. $morecss = 'minwidth200';
  5766. } else {
  5767. $morecss = 'minwidth400';
  5768. }
  5769. }
  5770. }
  5771. if (in_array($type, array('date'))) {
  5772. $tmp = explode(',', $size);
  5773. $newsize = $tmp[0];
  5774. $showtime = 0;
  5775. // Do not show current date when field not required (see selectDate() method)
  5776. if (!$required && $value == '') {
  5777. $value = '-1';
  5778. }
  5779. // TODO Must also support $moreparam
  5780. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5781. } elseif (in_array($type, array('datetime'))) {
  5782. $tmp = explode(',', $size);
  5783. $newsize = $tmp[0];
  5784. $showtime = 1;
  5785. // Do not show current date when field not required (see selectDate() method)
  5786. if (!$required && $value == '') $value = '-1';
  5787. // TODO Must also support $moreparam
  5788. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  5789. } elseif (in_array($type, array('duration'))) {
  5790. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5791. } elseif (in_array($type, array('int', 'integer'))) {
  5792. $tmp = explode(',', $size);
  5793. $newsize = $tmp[0];
  5794. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5795. } elseif (in_array($type, array('real'))) {
  5796. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5797. } elseif (preg_match('/varchar/', $type)) {
  5798. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5799. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5800. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5801. } elseif (preg_match('/^text/', $type)) {
  5802. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5803. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5804. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5805. $out = $doleditor->Create(1);
  5806. } else {
  5807. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5808. }
  5809. } elseif (preg_match('/^html/', $type)) {
  5810. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5811. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5812. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
  5813. $out = $doleditor->Create(1);
  5814. } else {
  5815. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5816. }
  5817. } elseif ($type == 'boolean') {
  5818. $checked = '';
  5819. if (!empty($value)) {
  5820. $checked = ' checked value="1" ';
  5821. } else {
  5822. $checked = ' value="1" ';
  5823. }
  5824. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5825. } elseif ($type == 'price') {
  5826. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5827. $value = price($value);
  5828. }
  5829. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5830. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5831. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5832. $value = price($value);
  5833. }
  5834. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5835. } elseif ($type == 'select') {
  5836. $out = '';
  5837. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5838. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5839. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5840. }
  5841. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5842. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  5843. $out .= '<option value="0">&nbsp;</option>';
  5844. }
  5845. foreach ($param['options'] as $key => $val) {
  5846. if ((string) $key == '') {
  5847. continue;
  5848. }
  5849. list($val, $parent) = explode('|', $val);
  5850. $out .= '<option value="'.$key.'"';
  5851. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  5852. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5853. $out .= '>'.$val.'</option>';
  5854. }
  5855. $out .= '</select>';
  5856. } elseif ($type == 'sellist') {
  5857. $out = '';
  5858. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5859. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5860. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5861. }
  5862. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5863. if (is_array($param['options'])) {
  5864. $param_list = array_keys($param['options']);
  5865. $InfoFieldList = explode(":", $param_list[0]);
  5866. $parentName = '';
  5867. $parentField = '';
  5868. // 0 : tableName
  5869. // 1 : label field name
  5870. // 2 : key fields name (if differ of rowid)
  5871. // 3 : key field parent (for dependent lists)
  5872. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5873. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5874. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  5875. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5876. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5877. } else {
  5878. $keyList = $InfoFieldList[2].' as rowid';
  5879. }
  5880. }
  5881. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  5882. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5883. $keyList .= ', '.$parentField;
  5884. }
  5885. $fields_label = explode('|', $InfoFieldList[1]);
  5886. if (is_array($fields_label)) {
  5887. $keyList .= ', ';
  5888. $keyList .= implode(', ', $fields_label);
  5889. }
  5890. $sqlwhere = '';
  5891. $sql = 'SELECT '.$keyList;
  5892. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5893. if (!empty($InfoFieldList[4])) {
  5894. // can use SELECT request
  5895. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5896. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5897. }
  5898. // current object id can be use into filter
  5899. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5900. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5901. } else {
  5902. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5903. }
  5904. //We have to join on extrafield table
  5905. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5906. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5907. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5908. } else {
  5909. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5910. }
  5911. } else {
  5912. $sqlwhere .= ' WHERE 1=1';
  5913. }
  5914. // Some tables may have field, some other not. For the moment we disable it.
  5915. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  5916. $sqlwhere .= ' AND entity = '.$conf->entity;
  5917. }
  5918. $sql .= $sqlwhere;
  5919. //print $sql;
  5920. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  5921. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  5922. $resql = $this->db->query($sql);
  5923. if ($resql) {
  5924. $out .= '<option value="0">&nbsp;</option>';
  5925. $num = $this->db->num_rows($resql);
  5926. $i = 0;
  5927. while ($i < $num) {
  5928. $labeltoshow = '';
  5929. $obj = $this->db->fetch_object($resql);
  5930. // Several field into label (eq table:code|libelle:rowid)
  5931. $notrans = false;
  5932. $fields_label = explode('|', $InfoFieldList[1]);
  5933. if (count($fields_label) > 1) {
  5934. $notrans = true;
  5935. foreach ($fields_label as $field_toshow) {
  5936. $labeltoshow .= $obj->$field_toshow.' ';
  5937. }
  5938. } else {
  5939. $labeltoshow = $obj->{$InfoFieldList[1]};
  5940. }
  5941. $labeltoshow = dol_trunc($labeltoshow, 45);
  5942. if ($value == $obj->rowid) {
  5943. foreach ($fields_label as $field_toshow) {
  5944. $translabel = $langs->trans($obj->$field_toshow);
  5945. if ($translabel != $obj->$field_toshow) {
  5946. $labeltoshow = dol_trunc($translabel, 18).' ';
  5947. } else {
  5948. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5949. }
  5950. }
  5951. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5952. } else {
  5953. if (!$notrans) {
  5954. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5955. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5956. $labeltoshow = dol_trunc($translabel, 18);
  5957. } else {
  5958. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5959. }
  5960. }
  5961. if (empty($labeltoshow)) {
  5962. $labeltoshow = '(not defined)';
  5963. }
  5964. if ($value == $obj->rowid) {
  5965. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5966. }
  5967. if (!empty($InfoFieldList[3]) && $parentField) {
  5968. $parent = $parentName.':'.$obj->{$parentField};
  5969. $isDependList=1;
  5970. }
  5971. $out .= '<option value="'.$obj->rowid.'"';
  5972. $out .= ($value == $obj->rowid ? ' selected' : '');
  5973. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5974. $out .= '>'.$labeltoshow.'</option>';
  5975. }
  5976. $i++;
  5977. }
  5978. $this->db->free($resql);
  5979. } else {
  5980. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5981. }
  5982. }
  5983. $out .= '</select>';
  5984. } elseif ($type == 'checkbox') {
  5985. $value_arr = explode(',', $value);
  5986. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  5987. } elseif ($type == 'radio') {
  5988. $out = '';
  5989. foreach ($param['options'] as $keyopt => $val) {
  5990. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  5991. $out .= ' value="'.$keyopt.'"';
  5992. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  5993. $out .= ($value == $keyopt ? 'checked' : '');
  5994. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  5995. }
  5996. } elseif ($type == 'chkbxlst') {
  5997. if (is_array($value)) {
  5998. $value_arr = $value;
  5999. } else {
  6000. $value_arr = explode(',', $value);
  6001. }
  6002. if (is_array($param['options'])) {
  6003. $param_list = array_keys($param['options']);
  6004. $InfoFieldList = explode(":", $param_list[0]);
  6005. $parentName = '';
  6006. $parentField = '';
  6007. // 0 : tableName
  6008. // 1 : label field name
  6009. // 2 : key fields name (if differ of rowid)
  6010. // 3 : key field parent (for dependent lists)
  6011. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6012. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6013. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6014. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6015. $keyList .= ', '.$parentField;
  6016. }
  6017. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6018. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6019. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6020. } else {
  6021. $keyList = $InfoFieldList[2].' as rowid';
  6022. }
  6023. }
  6024. $fields_label = explode('|', $InfoFieldList[1]);
  6025. if (is_array($fields_label)) {
  6026. $keyList .= ', ';
  6027. $keyList .= implode(', ', $fields_label);
  6028. }
  6029. $sqlwhere = '';
  6030. $sql = 'SELECT '.$keyList;
  6031. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6032. if (!empty($InfoFieldList[4])) {
  6033. // can use SELECT request
  6034. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6035. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6036. }
  6037. // current object id can be use into filter
  6038. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6039. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6040. } else {
  6041. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6042. }
  6043. // We have to join on extrafield table
  6044. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6045. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  6046. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  6047. } else {
  6048. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  6049. }
  6050. } else {
  6051. $sqlwhere .= ' WHERE 1=1';
  6052. }
  6053. // Some tables may have field, some other not. For the moment we disable it.
  6054. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6055. $sqlwhere .= ' AND entity = '.$conf->entity;
  6056. }
  6057. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6058. // print $sql;
  6059. $sql .= $sqlwhere;
  6060. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6061. $resql = $this->db->query($sql);
  6062. if ($resql) {
  6063. $num = $this->db->num_rows($resql);
  6064. $i = 0;
  6065. $data = array();
  6066. while ($i < $num) {
  6067. $labeltoshow = '';
  6068. $obj = $this->db->fetch_object($resql);
  6069. $notrans = false;
  6070. // Several field into label (eq table:code|libelle:rowid)
  6071. $fields_label = explode('|', $InfoFieldList[1]);
  6072. if (count($fields_label) > 1) {
  6073. $notrans = true;
  6074. foreach ($fields_label as $field_toshow) {
  6075. $labeltoshow .= $obj->$field_toshow.' ';
  6076. }
  6077. } else {
  6078. $labeltoshow = $obj->{$InfoFieldList[1]};
  6079. }
  6080. $labeltoshow = dol_trunc($labeltoshow, 45);
  6081. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6082. foreach ($fields_label as $field_toshow) {
  6083. $translabel = $langs->trans($obj->$field_toshow);
  6084. if ($translabel != $obj->$field_toshow) {
  6085. $labeltoshow = dol_trunc($translabel, 18).' ';
  6086. } else {
  6087. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6088. }
  6089. }
  6090. $data[$obj->rowid] = $labeltoshow;
  6091. } else {
  6092. if (!$notrans) {
  6093. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6094. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6095. $labeltoshow = dol_trunc($translabel, 18);
  6096. } else {
  6097. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6098. }
  6099. }
  6100. if (empty($labeltoshow)) {
  6101. $labeltoshow = '(not defined)';
  6102. }
  6103. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6104. $data[$obj->rowid] = $labeltoshow;
  6105. }
  6106. if (!empty($InfoFieldList[3]) && $parentField) {
  6107. $parent = $parentName.':'.$obj->{$parentField};
  6108. $isDependList=1;
  6109. }
  6110. $data[$obj->rowid] = $labeltoshow;
  6111. }
  6112. $i++;
  6113. }
  6114. $this->db->free($resql);
  6115. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6116. } else {
  6117. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6118. }
  6119. }
  6120. } elseif ($type == 'link') {
  6121. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]'
  6122. $param_list_array = explode(':', $param_list[0]);
  6123. $showempty = (($required && $default != '') ? 0 : 1);
  6124. if (!preg_match('/search_/', $keyprefix)) {
  6125. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6126. if (!empty($this->fields[$key]['picto'])) {
  6127. $morecss .= ' widthcentpercentminusxx';
  6128. } else {
  6129. $morecss .= ' widthcentpercentminusx';
  6130. }
  6131. } else {
  6132. if (!empty($this->fields[$key]['picto'])) {
  6133. $morecss .= ' widthcentpercentminusx';
  6134. }
  6135. }
  6136. }
  6137. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6138. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6139. if (!GETPOSTISSET('backtopage') && empty($val['disabled']) && empty($nonewbutton)) { // To avoid to open several times the 'Create Object' button and to avoid to have button if field is protected by a "disabled".
  6140. list($class, $classfile) = explode(':', $param_list[0]);
  6141. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6142. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6143. } else {
  6144. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6145. }
  6146. $paramforthenewlink = '';
  6147. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6148. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6149. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6150. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6151. $out .= '<a class="butActionNew" title="'.$langs->trans("New").'" href="'.$url_path.'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF'].($paramforthenewlink ? '?'.$paramforthenewlink : '')).'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6152. }
  6153. }
  6154. } elseif ($type == 'password') {
  6155. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6156. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6157. } elseif ($type == 'array') {
  6158. $newval = $val;
  6159. $newval['type'] = 'varchar(256)';
  6160. $out = '';
  6161. if (!empty($value)) {
  6162. foreach ($value as $option) {
  6163. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6164. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6165. }
  6166. }
  6167. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6168. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6169. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6170. if (!empty($conf->use_javascript_ajax)) {
  6171. $out .= '
  6172. <script>
  6173. $(document).ready(function() {
  6174. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6175. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6176. });
  6177. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6178. $(this).parent().remove();
  6179. });
  6180. });
  6181. </script>';
  6182. }
  6183. }
  6184. if (!empty($hidden)) {
  6185. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6186. }
  6187. if ($isDependList==1) {
  6188. $out .= $this->getJSListDependancies('_common');
  6189. }
  6190. /* Add comments
  6191. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6192. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6193. */
  6194. return $out;
  6195. }
  6196. /**
  6197. * Return HTML string to show a field into a page
  6198. * Code very similar with showOutputField of extra fields
  6199. *
  6200. * @param array $val Array of properties of field to show
  6201. * @param string $key Key of attribute
  6202. * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value)
  6203. * @param string $moreparam To add more parametes on html input tag
  6204. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6205. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6206. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6207. * @return string
  6208. */
  6209. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6210. {
  6211. global $conf, $langs, $form;
  6212. if (!is_object($form)) {
  6213. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6214. $form = new Form($this->db);
  6215. }
  6216. $objectid = $this->id; // Not used ???
  6217. $label = empty($val['label']) ? '' : $val['label'];
  6218. $type = empty($val['type']) ? '' : $val['type'];
  6219. $size = empty($val['css']) ? '' : $val['css'];
  6220. $reg = array();
  6221. // Convert var to be able to share same code than showOutputField of extrafields
  6222. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6223. $type = 'varchar'; // convert varchar(xx) int varchar
  6224. $size = $reg[1];
  6225. } elseif (preg_match('/varchar/', $type)) {
  6226. $type = 'varchar'; // convert varchar(xx) int varchar
  6227. }
  6228. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6229. $type = 'select';
  6230. }
  6231. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6232. $type = 'link';
  6233. }
  6234. $default = empty($val['default']) ? '' : $val['default'];
  6235. $computed = empty($val['computed']) ? '' : $val['computed'];
  6236. $unique = empty($val['unique']) ? '' : $val['unique'];
  6237. $required = empty($val['required']) ? '' : $val['required'];
  6238. $param = array();
  6239. $param['options'] = array();
  6240. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6241. $param['options'] = $val['arrayofkeyval'];
  6242. }
  6243. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6244. $type = 'link';
  6245. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6246. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6247. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6248. $type = 'sellist';
  6249. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6250. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6251. $type = 'sellist';
  6252. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6253. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6254. $type = 'sellist';
  6255. }
  6256. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6257. $list = (empty($val['list']) ? '' : $val['list']);
  6258. $help = (empty($val['help']) ? '' : $val['help']);
  6259. $hidden = (($val['visible'] == 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
  6260. if ($hidden) {
  6261. return '';
  6262. }
  6263. // If field is a computed field, value must become result of compute
  6264. if ($computed) {
  6265. // Make the eval of compute string
  6266. //var_dump($computed);
  6267. $value = dol_eval($computed, 1, 0);
  6268. }
  6269. if (empty($morecss)) {
  6270. if ($type == 'date') {
  6271. $morecss = 'minwidth100imp';
  6272. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6273. $morecss = 'minwidth200imp';
  6274. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6275. $morecss = 'maxwidth75';
  6276. } elseif ($type == 'url') {
  6277. $morecss = 'minwidth400';
  6278. } elseif ($type == 'boolean') {
  6279. $morecss = '';
  6280. } else {
  6281. if (is_numeric($size) && round($size) < 12) {
  6282. $morecss = 'minwidth100';
  6283. } elseif (is_numeric($size) && round($size) <= 48) {
  6284. $morecss = 'minwidth200';
  6285. } else {
  6286. $morecss = 'minwidth400';
  6287. }
  6288. }
  6289. }
  6290. // Format output value differently according to properties of field
  6291. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6292. $value = $this->getNomUrl(1, '', 0, '', 1);
  6293. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6294. $value = $this->getLibStatut(3);
  6295. } elseif ($type == 'date') {
  6296. if (!empty($value)) {
  6297. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6298. } else {
  6299. $value = '';
  6300. }
  6301. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6302. if (!empty($value)) {
  6303. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6304. } else {
  6305. $value = '';
  6306. }
  6307. } elseif ($type == 'duration') {
  6308. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6309. if (!is_null($value) && $value !== '') {
  6310. $value = convertSecondToTime($value, 'allhourmin');
  6311. }
  6312. } elseif ($type == 'double' || $type == 'real') {
  6313. if (!is_null($value) && $value !== '') {
  6314. $value = price($value);
  6315. }
  6316. } elseif ($type == 'boolean') {
  6317. $checked = '';
  6318. if (!empty($value)) {
  6319. $checked = ' checked ';
  6320. }
  6321. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6322. } elseif ($type == 'mail') {
  6323. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6324. } elseif ($type == 'url') {
  6325. $value = dol_print_url($value, '_blank', 32, 1);
  6326. } elseif ($type == 'phone') {
  6327. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6328. } elseif ($type == 'price') {
  6329. if (!is_null($value) && $value !== '') {
  6330. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6331. }
  6332. } elseif ($type == 'select') {
  6333. $value = $param['options'][$value];
  6334. } elseif ($type == 'sellist') {
  6335. $param_list = array_keys($param['options']);
  6336. $InfoFieldList = explode(":", $param_list[0]);
  6337. $selectkey = "rowid";
  6338. $keyList = 'rowid';
  6339. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6340. $selectkey = $InfoFieldList[2];
  6341. $keyList = $InfoFieldList[2].' as rowid';
  6342. }
  6343. $fields_label = explode('|', $InfoFieldList[1]);
  6344. if (is_array($fields_label)) {
  6345. $keyList .= ', ';
  6346. $keyList .= implode(', ', $fields_label);
  6347. }
  6348. $sql = 'SELECT '.$keyList;
  6349. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6350. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6351. $sql .= ' as main';
  6352. }
  6353. if ($selectkey == 'rowid' && empty($value)) {
  6354. $sql .= " WHERE ".$selectkey." = 0";
  6355. } elseif ($selectkey == 'rowid') {
  6356. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6357. } else {
  6358. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6359. }
  6360. //$sql.= ' AND entity = '.$conf->entity;
  6361. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6362. $resql = $this->db->query($sql);
  6363. if ($resql) {
  6364. $value = ''; // value was used, so now we reste it to use it to build final output
  6365. $obj = $this->db->fetch_object($resql);
  6366. // Several field into label (eq table:code|libelle:rowid)
  6367. $fields_label = explode('|', $InfoFieldList[1]);
  6368. if (is_array($fields_label) && count($fields_label) > 1) {
  6369. foreach ($fields_label as $field_toshow) {
  6370. $translabel = '';
  6371. if (!empty($obj->$field_toshow)) {
  6372. $translabel = $langs->trans($obj->$field_toshow);
  6373. }
  6374. if ($translabel != $field_toshow) {
  6375. $value .= dol_trunc($translabel, 18).' ';
  6376. } else {
  6377. $value .= $obj->$field_toshow.' ';
  6378. }
  6379. }
  6380. } else {
  6381. $translabel = '';
  6382. if (!empty($obj->{$InfoFieldList[1]})) {
  6383. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6384. }
  6385. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6386. $value = dol_trunc($translabel, 18);
  6387. } else {
  6388. $value = $obj->{$InfoFieldList[1]};
  6389. }
  6390. }
  6391. } else {
  6392. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6393. }
  6394. } elseif ($type == 'radio') {
  6395. $value = $param['options'][$value];
  6396. } elseif ($type == 'checkbox') {
  6397. $value_arr = explode(',', $value);
  6398. $value = '';
  6399. if (is_array($value_arr) && count($value_arr) > 0) {
  6400. $toprint = array();
  6401. foreach ($value_arr as $keyval => $valueval) {
  6402. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6403. }
  6404. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6405. }
  6406. } elseif ($type == 'chkbxlst') {
  6407. $value_arr = explode(',', $value);
  6408. $param_list = array_keys($param['options']);
  6409. $InfoFieldList = explode(":", $param_list[0]);
  6410. $selectkey = "rowid";
  6411. $keyList = 'rowid';
  6412. if (count($InfoFieldList) >= 3) {
  6413. $selectkey = $InfoFieldList[2];
  6414. $keyList = $InfoFieldList[2].' as rowid';
  6415. }
  6416. $fields_label = explode('|', $InfoFieldList[1]);
  6417. if (is_array($fields_label)) {
  6418. $keyList .= ', ';
  6419. $keyList .= implode(', ', $fields_label);
  6420. }
  6421. $sql = 'SELECT '.$keyList;
  6422. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6423. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6424. $sql .= ' as main';
  6425. }
  6426. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6427. // $sql.= ' AND entity = '.$conf->entity;
  6428. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6429. $resql = $this->db->query($sql);
  6430. if ($resql) {
  6431. $value = ''; // value was used, so now we reste it to use it to build final output
  6432. $toprint = array();
  6433. while ($obj = $this->db->fetch_object($resql)) {
  6434. // Several field into label (eq table:code|libelle:rowid)
  6435. $fields_label = explode('|', $InfoFieldList[1]);
  6436. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6437. if (is_array($fields_label) && count($fields_label) > 1) {
  6438. foreach ($fields_label as $field_toshow) {
  6439. $translabel = '';
  6440. if (!empty($obj->$field_toshow)) {
  6441. $translabel = $langs->trans($obj->$field_toshow);
  6442. }
  6443. if ($translabel != $field_toshow) {
  6444. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6445. } else {
  6446. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6447. }
  6448. }
  6449. } else {
  6450. $translabel = '';
  6451. if (!empty($obj->{$InfoFieldList[1]})) {
  6452. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6453. }
  6454. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6455. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6456. } else {
  6457. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6458. }
  6459. }
  6460. }
  6461. }
  6462. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6463. } else {
  6464. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6465. }
  6466. } elseif ($type == 'link') {
  6467. $out = '';
  6468. // only if something to display (perf)
  6469. if ($value) {
  6470. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6471. $InfoFieldList = explode(":", $param_list[0]);
  6472. $classname = $InfoFieldList[0];
  6473. $classpath = $InfoFieldList[1];
  6474. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6475. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6476. if (!empty($classpath)) {
  6477. dol_include_once($InfoFieldList[1]);
  6478. if ($classname && class_exists($classname)) {
  6479. $object = new $classname($this->db);
  6480. $object->fetch($value);
  6481. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6482. }
  6483. } else {
  6484. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6485. return 'Error bad setup of extrafield';
  6486. }
  6487. } else {
  6488. $value = '';
  6489. }
  6490. } elseif (preg_match('/^(text|html)/', $type)) {
  6491. $value = dol_htmlentitiesbr($value);
  6492. } elseif ($type == 'password') {
  6493. $value = preg_replace('/./i', '*', $value);
  6494. } elseif ($type == 'array') {
  6495. $value = implode('<br>', $value);
  6496. }
  6497. //print $type.'-'.$size.'-'.$value;
  6498. $out = $value;
  6499. return $out;
  6500. }
  6501. /**
  6502. * Function to show lines of extrafields with output datas.
  6503. * This function is responsible to output the <tr> and <td> according to correct number of columns received into $params['colspan'] or <div> according to $display_type
  6504. *
  6505. * @param Extrafields $extrafields Extrafield Object
  6506. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6507. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6508. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6509. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6510. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6511. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6512. * @return string
  6513. */
  6514. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6515. {
  6516. global $db, $conf, $langs, $action, $form, $hookmanager;
  6517. if (!is_object($form)) {
  6518. $form = new Form($db);
  6519. }
  6520. $out = '';
  6521. $parameters = array();
  6522. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6523. if (empty($reshook)) {
  6524. if (key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  6525. $out .= "\n";
  6526. $out .= '<!-- showOptionals --> ';
  6527. $out .= "\n";
  6528. $extrafields_collapse_num = '';
  6529. $e = 0;
  6530. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6531. // Show only the key field in params
  6532. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6533. continue;
  6534. }
  6535. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6536. $enabled = 1;
  6537. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6538. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  6539. }
  6540. if (empty($enabled)) {
  6541. continue;
  6542. }
  6543. $visibility = 1;
  6544. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6545. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  6546. }
  6547. $perms = 1;
  6548. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6549. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  6550. }
  6551. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  6552. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6553. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  6554. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6555. } elseif ($mode == 'view' && empty($visibility)) {
  6556. continue;
  6557. }
  6558. if (empty($perms)) {
  6559. continue;
  6560. }
  6561. // Load language if required
  6562. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6563. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6564. }
  6565. $colspan = '';
  6566. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  6567. if (array_key_exists('cols', $params)) {
  6568. $colspan = $params['cols'];
  6569. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6570. $reg = array();
  6571. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6572. $colspan = $reg[1];
  6573. } else {
  6574. $colspan = $params['colspan'];
  6575. }
  6576. }
  6577. }
  6578. switch ($mode) {
  6579. case "view":
  6580. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6581. break;
  6582. case "create":
  6583. case "edit":
  6584. // We get the value of property found with GETPOST so it takes into account:
  6585. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6586. $check = 'alphanohtml';
  6587. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6588. $check = 'restricthtml';
  6589. }
  6590. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6591. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6592. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  6593. if (is_array($getposttemp)) {
  6594. // $getposttemp is an array but following code expects a comma separated string
  6595. $value = implode(",", $getposttemp);
  6596. } else {
  6597. $value = $getposttemp;
  6598. }
  6599. } else {
  6600. $value = (!empty($this->array_options["options_".$key]) ? $this->array_options["options_".$key] : ''); // No GET, no POST, no default value, so we take value of object.
  6601. }
  6602. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6603. break;
  6604. }
  6605. // Output value of the current field
  6606. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  6607. $extrafields_collapse_num = '';
  6608. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6609. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6610. $extrafield_param_list = array_keys($extrafield_param['options']);
  6611. if (count($extrafield_param_list) > 0) {
  6612. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6613. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6614. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6615. }
  6616. }
  6617. }
  6618. $out .= $extrafields->showSeparator($key, $this, ($colspan + 1), $display_type);
  6619. } else {
  6620. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6621. $csstyle = '';
  6622. if (is_array($params) && count($params) > 0) {
  6623. if (array_key_exists('class', $params)) {
  6624. $class .= $params['class'].' ';
  6625. }
  6626. if (array_key_exists('style', $params)) {
  6627. $csstyle = $params['style'];
  6628. }
  6629. }
  6630. // add html5 elements
  6631. $domData = ' data-element="extrafield"';
  6632. $domData .= ' data-targetelement="'.$this->element.'"';
  6633. $domData .= ' data-targetid="'.$this->id.'"';
  6634. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6635. if ($display_type=='card') {
  6636. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  6637. $colspan = '0';
  6638. }
  6639. if ($action == 'selectlines') {
  6640. $colspan++;
  6641. }
  6642. }
  6643. // Convert date into timestamp format (value in memory must be a timestamp)
  6644. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  6645. $datenotinstring = $this->array_options['options_'.$key];
  6646. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6647. $datenotinstring = $this->db->jdate($datenotinstring);
  6648. }
  6649. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(12, 0, 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3)) : $datenotinstring;
  6650. }
  6651. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  6652. $datenotinstring = $this->array_options['options_'.$key];
  6653. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6654. $datenotinstring = $this->db->jdate($datenotinstring);
  6655. }
  6656. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."sec", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3), 'tzuserrel') : $datenotinstring;
  6657. }
  6658. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  6659. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  6660. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  6661. }
  6662. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  6663. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  6664. if ($action == 'create') {
  6665. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  6666. }
  6667. }
  6668. $labeltoshow = $langs->trans($label);
  6669. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  6670. if ($display_type == 'card') {
  6671. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldcreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  6672. $out .= '<td class="wordbreak';
  6673. } elseif ($display_type == 'line') {
  6674. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldlinecreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  6675. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  6676. }
  6677. //$out .= "titlefield";
  6678. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  6679. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  6680. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  6681. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  6682. $out .= '">';
  6683. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6684. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6685. } else {
  6686. $out .= $labeltoshow;
  6687. }
  6688. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6689. $out .= '&nbsp;<font color="red">*</font>';
  6690. }
  6691. } else {
  6692. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6693. $out .= ' fieldrequired';
  6694. }
  6695. $out .= '">';
  6696. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6697. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6698. } else {
  6699. $out .= $labeltoshow;
  6700. }
  6701. }
  6702. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  6703. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  6704. if ($display_type == 'card') {
  6705. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  6706. } elseif ($display_type == 'line') {
  6707. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="'.$this->element.'_extras_'.$key.'">';
  6708. }
  6709. switch ($mode) {
  6710. case "view":
  6711. $out .= $extrafields->showOutputField($key, $value);
  6712. break;
  6713. case "create":
  6714. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6715. break;
  6716. case "edit":
  6717. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6718. break;
  6719. }
  6720. $out .= ($display_type=='card' ? '</td>' : '</div>');
  6721. /*for($ii = 0; $ii < ($colspan - 1); $ii++)
  6722. {
  6723. $out .='<td class="'.$this->element.'_extras_'.$key.'"></td>';
  6724. }*/
  6725. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  6726. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  6727. } else {
  6728. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  6729. }
  6730. $e++;
  6731. }
  6732. }
  6733. $out .= "\n";
  6734. // Add code to manage list depending on others
  6735. if (!empty($conf->use_javascript_ajax)) {
  6736. $out .= $this->getJSListDependancies();
  6737. }
  6738. $out .= '<!-- /showOptionals --> '."\n";
  6739. }
  6740. }
  6741. $out .= $hookmanager->resPrint;
  6742. return $out;
  6743. }
  6744. /**
  6745. * @param string $type Type for prefix
  6746. * @return string Javacript code to manage dependency
  6747. */
  6748. public function getJSListDependancies($type = '_extra')
  6749. {
  6750. $out = '
  6751. <script>
  6752. jQuery(document).ready(function() {
  6753. function showOptions'.$type.'(child_list, parent_list, orig_select)
  6754. {
  6755. var val = $("select[name=\""+parent_list+"\"]").val();
  6756. var parentVal = parent_list + ":" + val;
  6757. if(typeof val == "string"){
  6758. if(val != "") {
  6759. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  6760. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6761. $("select[name=\""+child_list+"\"]").append(options);
  6762. } else {
  6763. var options = orig_select.find("option[parent]").clone();
  6764. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6765. $("select[name=\""+child_list+"\"]").append(options);
  6766. }
  6767. } else if(val > 0) {
  6768. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  6769. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6770. $("select[name=\""+child_list+"\"]").append(options);
  6771. } else {
  6772. var options = orig_select.find("option[parent]").clone();
  6773. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6774. $("select[name=\""+child_list+"\"]").append(options);
  6775. }
  6776. }
  6777. function setListDependencies'.$type.'() {
  6778. jQuery("select option[parent]").parent().each(function() {
  6779. var orig_select = {};
  6780. var child_list = $(this).attr("name");
  6781. orig_select[child_list] = $(this).clone();
  6782. var parent = $(this).find("option[parent]:first").attr("parent");
  6783. var infos = parent.split(":");
  6784. var parent_list = infos[0];
  6785. //Hide daughters lists
  6786. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  6787. $("#"+child_list).hide();
  6788. //Show mother lists
  6789. } else if ($("#"+parent_list).val() != 0){
  6790. $("#"+parent_list).show();
  6791. }
  6792. //Show the child list if the parent list value is selected
  6793. $("select[name=\""+parent_list+"\"]").click(function() {
  6794. if ($(this).val() != 0){
  6795. $("#"+child_list).show()
  6796. }
  6797. });
  6798. //When we change parent list
  6799. $("select[name=\""+parent_list+"\"]").change(function() {
  6800. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  6801. //Select the value 0 on child list after a change on the parent list
  6802. $("#"+child_list).val(0).trigger("change");
  6803. //Hide child lists if the parent value is set to 0
  6804. if ($(this).val() == 0){
  6805. $("#"+child_list).hide();
  6806. }
  6807. });
  6808. });
  6809. }
  6810. setListDependencies'.$type.'();
  6811. });
  6812. </script>'."\n";
  6813. return $out;
  6814. }
  6815. /**
  6816. * Returns the rights used for this class
  6817. * @return stdClass
  6818. */
  6819. public function getRights()
  6820. {
  6821. global $user;
  6822. $element = $this->element;
  6823. if ($element == 'facturerec') {
  6824. $element = 'facture';
  6825. }
  6826. return $user->rights->{$element};
  6827. }
  6828. /**
  6829. * Function used to replace a thirdparty id with another one.
  6830. * This function is meant to be called from replaceThirdparty with the appropiate tables
  6831. * Column name fk_soc MUST be used to identify thirdparties
  6832. *
  6833. * @param DoliDB $db Database handler
  6834. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  6835. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  6836. * @param string[] $tables Tables that need to be changed
  6837. * @param int $ignoreerrors Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old thirdparty may already exists on new one)
  6838. * @return bool True if success, False if error
  6839. */
  6840. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  6841. {
  6842. foreach ($tables as $table) {
  6843. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  6844. if (!$db->query($sql)) {
  6845. if ($ignoreerrors) {
  6846. return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B.
  6847. }
  6848. //$this->errors = $db->lasterror();
  6849. return false;
  6850. }
  6851. }
  6852. return true;
  6853. }
  6854. /**
  6855. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  6856. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  6857. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  6858. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  6859. * else set min buy price as buy price
  6860. *
  6861. * @param float $unitPrice Product unit price
  6862. * @param float $discountPercent Line discount percent
  6863. * @param int $fk_product Product id
  6864. * @return float <0 if KO, buyprice if OK
  6865. */
  6866. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  6867. {
  6868. global $conf;
  6869. $buyPrice = 0;
  6870. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  6871. // When ForceBuyingPriceIfNull is set
  6872. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  6873. } else {
  6874. // Get cost price for margin calculation
  6875. if (!empty($fk_product)) {
  6876. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  6877. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6878. $product = new Product($this->db);
  6879. $result = $product->fetch($fk_product);
  6880. if ($result <= 0) {
  6881. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6882. return -1;
  6883. }
  6884. if ($product->cost_price > 0) {
  6885. $buyPrice = $product->cost_price;
  6886. } elseif ($product->pmp > 0) {
  6887. $buyPrice = $product->pmp;
  6888. }
  6889. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  6890. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6891. $product = new Product($this->db);
  6892. $result = $product->fetch($fk_product);
  6893. if ($result <= 0) {
  6894. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6895. return -1;
  6896. }
  6897. if ($product->pmp > 0) {
  6898. $buyPrice = $product->pmp;
  6899. }
  6900. }
  6901. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  6902. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6903. $productFournisseur = new ProductFournisseur($this->db);
  6904. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  6905. $buyPrice = $productFournisseur->fourn_unitprice;
  6906. } elseif ($result < 0) {
  6907. $this->errors[] = $productFournisseur->error;
  6908. return -2;
  6909. }
  6910. }
  6911. }
  6912. }
  6913. return $buyPrice;
  6914. }
  6915. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6916. /**
  6917. * Show photos of an object (nbmax maximum), into several columns
  6918. *
  6919. * @param string $modulepart 'product', 'ticket', ...
  6920. * @param string $sdir Directory to scan (full absolute path)
  6921. * @param int $size 0=original size, 1='small' use thumbnail if possible
  6922. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  6923. * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1.
  6924. * @param int $showfilename 1=Show filename
  6925. * @param int $showaction 1=Show icon with action links (resize, delete)
  6926. * @param int $maxHeight Max height of original image when size='small' (so we can use original even if small requested). If 0, always use 'small' thumb image.
  6927. * @param int $maxWidth Max width of original image when size='small'
  6928. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  6929. * @param int $notitle Do not add title tag on image
  6930. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  6931. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  6932. */
  6933. public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $notitle = 0, $usesharelink = 0)
  6934. {
  6935. // phpcs:enable
  6936. global $conf, $user, $langs;
  6937. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6938. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  6939. $sortfield = 'position_name';
  6940. $sortorder = 'asc';
  6941. $dir = $sdir.'/';
  6942. $pdir = '/';
  6943. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  6944. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  6945. // For backward compatibility
  6946. if ($modulepart == 'product') {
  6947. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  6948. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6949. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6950. }
  6951. }
  6952. // Defined relative dir to DOL_DATA_ROOT
  6953. $relativedir = '';
  6954. if ($dir) {
  6955. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  6956. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  6957. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  6958. }
  6959. $dirthumb = $dir.'thumbs/';
  6960. $pdirthumb = $pdir.'thumbs/';
  6961. $return = '<!-- Photo -->'."\n";
  6962. $nbphoto = 0;
  6963. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  6964. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  6965. {
  6966. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  6967. $filearray=array_merge($filearray, $filearrayold);
  6968. }*/
  6969. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  6970. if (count($filearray)) {
  6971. if ($sortfield && $sortorder) {
  6972. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  6973. }
  6974. foreach ($filearray as $key => $val) {
  6975. $photo = '';
  6976. $file = $val['name'];
  6977. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  6978. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  6979. if (image_format_supported($file) >= 0) {
  6980. $nbphoto++;
  6981. $photo = $file;
  6982. $viewfilename = $file;
  6983. if ($size == 1 || $size == 'small') { // Format vignette
  6984. // Find name of thumb file
  6985. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  6986. if (!dol_is_file($dirthumb.$photo_vignette)) {
  6987. $photo_vignette = '';
  6988. }
  6989. // Get filesize of original file
  6990. $imgarray = dol_getImageSize($dir.$photo);
  6991. if ($nbbyrow > 0) {
  6992. if ($nbphoto == 1) {
  6993. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  6994. }
  6995. if ($nbphoto % $nbbyrow == 1) {
  6996. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  6997. }
  6998. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  6999. } elseif ($nbbyrow < 0) {
  7000. $return .= '<div class="inline-block">';
  7001. }
  7002. $return .= "\n";
  7003. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7004. if (empty($nolink)) {
  7005. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7006. if ($urladvanced) {
  7007. $return .= '<a href="'.$urladvanced.'">';
  7008. } else {
  7009. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
  7010. }
  7011. }
  7012. // Show image (width height=$maxHeight)
  7013. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7014. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7015. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7016. if ($notitle) {
  7017. $alt = '';
  7018. }
  7019. if ($usesharelink) {
  7020. if ($val['share']) {
  7021. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7022. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7023. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7024. } else {
  7025. $return .= '<!-- Show original file -->';
  7026. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7027. }
  7028. } else {
  7029. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7030. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7031. }
  7032. } else {
  7033. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7034. $return .= '<!-- Show thumb -->';
  7035. $return .= '<img class="photo photowithmargin maxwidth150onsmartphone" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7036. } else {
  7037. $return .= '<!-- Show original file -->';
  7038. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7039. }
  7040. }
  7041. if (empty($nolink)) {
  7042. $return .= '</a>';
  7043. }
  7044. $return .= "\n";
  7045. if ($showfilename) {
  7046. $return .= '<br>'.$viewfilename;
  7047. }
  7048. if ($showaction) {
  7049. $return .= '<br>';
  7050. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7051. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7052. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=addthumb&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7053. }
  7054. // Special cas for product
  7055. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7056. // Link to resize
  7057. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7058. // Link to delete
  7059. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  7060. $return .= img_delete().'</a>';
  7061. }
  7062. }
  7063. $return .= "\n";
  7064. if ($nbbyrow > 0) {
  7065. $return .= '</td>';
  7066. if (($nbphoto % $nbbyrow) == 0) {
  7067. $return .= '</tr>';
  7068. }
  7069. } elseif ($nbbyrow < 0) {
  7070. $return .= '</div>';
  7071. }
  7072. }
  7073. if (empty($size)) { // Format origine
  7074. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7075. if ($showfilename) {
  7076. $return .= '<br>'.$viewfilename;
  7077. }
  7078. if ($showaction) {
  7079. // Special case for product
  7080. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7081. // Link to resize
  7082. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7083. // Link to delete
  7084. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  7085. $return .= img_delete().'</a>';
  7086. }
  7087. }
  7088. }
  7089. // On continue ou on arrete de boucler ?
  7090. if ($nbmax && $nbphoto >= $nbmax) {
  7091. break;
  7092. }
  7093. }
  7094. }
  7095. if ($size == 1 || $size == 'small') {
  7096. if ($nbbyrow > 0) {
  7097. // Ferme tableau
  7098. while ($nbphoto % $nbbyrow) {
  7099. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7100. $nbphoto++;
  7101. }
  7102. if ($nbphoto) {
  7103. $return .= '</table>';
  7104. }
  7105. }
  7106. }
  7107. }
  7108. $this->nbphoto = $nbphoto;
  7109. return $return;
  7110. }
  7111. /**
  7112. * Function test if type is array
  7113. *
  7114. * @param array $info content informations of field
  7115. * @return bool true if array
  7116. */
  7117. protected function isArray($info)
  7118. {
  7119. if (is_array($info)) {
  7120. if (isset($info['type']) && $info['type'] == 'array') {
  7121. return true;
  7122. } else {
  7123. return false;
  7124. }
  7125. }
  7126. return false;
  7127. }
  7128. /**
  7129. * Function test if type is date
  7130. *
  7131. * @param array $info content informations of field
  7132. * @return bool true if date
  7133. */
  7134. public function isDate($info)
  7135. {
  7136. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7137. return true;
  7138. }
  7139. return false;
  7140. }
  7141. /**
  7142. * Function test if type is duration
  7143. *
  7144. * @param array $info content informations of field
  7145. * @return bool true if field of type duration
  7146. */
  7147. public function isDuration($info)
  7148. {
  7149. if (is_array($info)) {
  7150. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7151. return true;
  7152. } else {
  7153. return false;
  7154. }
  7155. } else {
  7156. return false;
  7157. }
  7158. }
  7159. /**
  7160. * Function test if type is integer
  7161. *
  7162. * @param array $info content informations of field
  7163. * @return bool true if integer
  7164. */
  7165. public function isInt($info)
  7166. {
  7167. if (is_array($info)) {
  7168. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7169. return true;
  7170. } else {
  7171. return false;
  7172. }
  7173. } else {
  7174. return false;
  7175. }
  7176. }
  7177. /**
  7178. * Function test if type is float
  7179. *
  7180. * @param array $info content informations of field
  7181. * @return bool true if float
  7182. */
  7183. public function isFloat($info)
  7184. {
  7185. if (is_array($info)) {
  7186. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7187. return true;
  7188. } else {
  7189. return false;
  7190. }
  7191. }
  7192. return false;
  7193. }
  7194. /**
  7195. * Function test if type is text
  7196. *
  7197. * @param array $info content informations of field
  7198. * @return bool true if type text
  7199. */
  7200. public function isText($info)
  7201. {
  7202. if (is_array($info)) {
  7203. if (isset($info['type']) && $info['type'] == 'text') {
  7204. return true;
  7205. } else {
  7206. return false;
  7207. }
  7208. }
  7209. return false;
  7210. }
  7211. /**
  7212. * Function test if field can be null
  7213. *
  7214. * @param array $info content informations of field
  7215. * @return bool true if it can be null
  7216. */
  7217. protected function canBeNull($info)
  7218. {
  7219. if (is_array($info)) {
  7220. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7221. return true;
  7222. } else {
  7223. return false;
  7224. }
  7225. }
  7226. return true;
  7227. }
  7228. /**
  7229. * Function test if field is forced to null if zero or empty
  7230. *
  7231. * @param array $info content informations of field
  7232. * @return bool true if forced to null
  7233. */
  7234. protected function isForcedToNullIfZero($info)
  7235. {
  7236. if (is_array($info)) {
  7237. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7238. return true;
  7239. } else {
  7240. return false;
  7241. }
  7242. }
  7243. return false;
  7244. }
  7245. /**
  7246. * Function test if is indexed
  7247. *
  7248. * @param array $info content informations of field
  7249. * @return bool
  7250. */
  7251. protected function isIndex($info)
  7252. {
  7253. if (is_array($info)) {
  7254. if (isset($info['index']) && $info['index'] == true) {
  7255. return true;
  7256. } else {
  7257. return false;
  7258. }
  7259. }
  7260. return false;
  7261. }
  7262. /**
  7263. * Function to prepare a part of the query for insert.
  7264. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7265. * $this->${field} should be a clean value. The page can run
  7266. *
  7267. * @return array
  7268. */
  7269. protected function setSaveQuery()
  7270. {
  7271. global $conf;
  7272. $queryarray = array();
  7273. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7274. // Depending on field type ('datetime', ...)
  7275. if ($this->isDate($info)) {
  7276. if (empty($this->{$field})) {
  7277. $queryarray[$field] = null;
  7278. } else {
  7279. $queryarray[$field] = $this->db->idate($this->{$field});
  7280. }
  7281. } elseif ($this->isArray($info)) {
  7282. if (!empty($this->{$field})) {
  7283. if (!is_array($this->{$field})) {
  7284. $this->{$field} = array($this->{$field});
  7285. }
  7286. $queryarray[$field] = serialize($this->{$field});
  7287. } else {
  7288. $queryarray[$field] = null;
  7289. }
  7290. } elseif ($this->isDuration($info)) {
  7291. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7292. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7293. if (!isset($this->{$field})) {
  7294. $queryarray[$field] = 0;
  7295. } else {
  7296. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7297. }
  7298. } else {
  7299. $queryarray[$field] = null;
  7300. }
  7301. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7302. if ($field == 'entity' && is_null($this->{$field})) {
  7303. $queryarray[$field] = $conf->entity;
  7304. } else {
  7305. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7306. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7307. if (!isset($this->{$field})) {
  7308. $queryarray[$field] = 0;
  7309. } elseif ($this->isInt($info)) {
  7310. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7311. } elseif ($this->isFloat($info)) {
  7312. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7313. }
  7314. } else {
  7315. $queryarray[$field] = null;
  7316. }
  7317. }
  7318. } else {
  7319. $queryarray[$field] = $this->{$field};
  7320. }
  7321. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7322. unset($queryarray[$field]);
  7323. }
  7324. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7325. $queryarray[$field] = null; // May force 0 to null
  7326. }
  7327. }
  7328. return $queryarray;
  7329. }
  7330. /**
  7331. * Function to load data from a SQL pointer into properties of current object $this
  7332. *
  7333. * @param stdClass $obj Contain data of object from database
  7334. * @return void
  7335. */
  7336. public function setVarsFromFetchObj(&$obj)
  7337. {
  7338. global $db;
  7339. foreach ($this->fields as $field => $info) {
  7340. if ($this->isDate($info)) {
  7341. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7342. $this->{$field} = '';
  7343. } else {
  7344. $this->{$field} = $db->jdate($obj->{$field});
  7345. }
  7346. } elseif ($this->isArray($info)) {
  7347. if (!empty($obj->{$field})) {
  7348. $this->{$field} = @unserialize($obj->{$field});
  7349. // Hack for data not in UTF8
  7350. if ($this->{$field } === false) {
  7351. @unserialize(utf8_decode($obj->{$field}));
  7352. }
  7353. } else {
  7354. $this->{$field} = array();
  7355. }
  7356. } elseif ($this->isInt($info)) {
  7357. if ($field == 'rowid') {
  7358. $this->id = (int) $obj->{$field};
  7359. } else {
  7360. if ($this->isForcedToNullIfZero($info)) {
  7361. if (empty($obj->{$field})) {
  7362. $this->{$field} = null;
  7363. } else {
  7364. $this->{$field} = (double) $obj->{$field};
  7365. }
  7366. } else {
  7367. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7368. $this->{$field} = (int) $obj->{$field};
  7369. } else {
  7370. $this->{$field} = null;
  7371. }
  7372. }
  7373. }
  7374. } elseif ($this->isFloat($info)) {
  7375. if ($this->isForcedToNullIfZero($info)) {
  7376. if (empty($obj->{$field})) {
  7377. $this->{$field} = null;
  7378. } else {
  7379. $this->{$field} = (double) $obj->{$field};
  7380. }
  7381. } else {
  7382. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7383. $this->{$field} = (double) $obj->{$field};
  7384. } else {
  7385. $this->{$field} = null;
  7386. }
  7387. }
  7388. } else {
  7389. $this->{$field} = $obj->{$field};
  7390. }
  7391. }
  7392. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7393. if (!isset($this->fields['ref']) && isset($this->id)) {
  7394. $this->ref = $this->id;
  7395. }
  7396. }
  7397. /**
  7398. * Function to concat keys of fields
  7399. *
  7400. * @param string $alias String of alias of table for fields. For example 't'.
  7401. * @return string list of alias fields
  7402. */
  7403. public function getFieldList($alias = '')
  7404. {
  7405. $keys = array_keys($this->fields);
  7406. if (!empty($alias)) {
  7407. $keys_with_alias = array();
  7408. foreach ($keys as $fieldname) {
  7409. $keys_with_alias[] = $alias . '.' . $fieldname;
  7410. }
  7411. return implode(',', $keys_with_alias);
  7412. } else {
  7413. return implode(',', $keys);
  7414. }
  7415. }
  7416. /**
  7417. * Add quote to field value if necessary
  7418. *
  7419. * @param string|int $value Value to protect
  7420. * @param array $fieldsentry Properties of field
  7421. * @return string
  7422. */
  7423. protected function quote($value, $fieldsentry)
  7424. {
  7425. if (is_null($value)) {
  7426. return 'NULL';
  7427. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7428. return $this->db->escape("$value");
  7429. } elseif ($fieldsentry['type'] == 'boolean') {
  7430. if ($value) {
  7431. return 'true';
  7432. } else {
  7433. return 'false';
  7434. }
  7435. } else {
  7436. return "'".$this->db->escape($value)."'";
  7437. }
  7438. }
  7439. /**
  7440. * Create object into database
  7441. *
  7442. * @param User $user User that creates
  7443. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7444. * @return int <0 if KO, Id of created object if OK
  7445. */
  7446. public function createCommon(User $user, $notrigger = false)
  7447. {
  7448. global $langs;
  7449. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7450. $error = 0;
  7451. $now = dol_now();
  7452. $fieldvalues = $this->setSaveQuery();
  7453. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7454. $fieldvalues['date_creation'] = $this->db->idate($now);
  7455. }
  7456. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7457. $fieldvalues['fk_user_creat'] = $user->id;
  7458. }
  7459. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7460. if (array_key_exists('ref', $fieldvalues)) {
  7461. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7462. }
  7463. $keys = array();
  7464. $values = array(); // Array to store string forged for SQL syntax
  7465. foreach ($fieldvalues as $k => $v) {
  7466. $keys[$k] = $k;
  7467. $value = $this->fields[$k];
  7468. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7469. }
  7470. // Clean and check mandatory
  7471. foreach ($keys as $key) {
  7472. // If field is an implicit foreign key field
  7473. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7474. $values[$key] = '';
  7475. }
  7476. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7477. $values[$key] = '';
  7478. }
  7479. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7480. $error++;
  7481. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7482. }
  7483. // If value is null and there is a default value for field
  7484. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7485. $values[$key] = $this->fields[$key]['default'];
  7486. }
  7487. // If field is an implicit foreign key field
  7488. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7489. if (isset($this->fields[$key]['default'])) {
  7490. $values[$key] = $this->fields[$key]['default'];
  7491. } else {
  7492. $values[$key] = 'null';
  7493. }
  7494. }
  7495. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7496. $values[$key] = 'null';
  7497. }
  7498. }
  7499. if ($error) {
  7500. return -1;
  7501. }
  7502. $this->db->begin();
  7503. if (!$error) {
  7504. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
  7505. $sql .= ' ('.implode(", ", $keys).')';
  7506. $sql .= ' VALUES ('.implode(", ", $values).')';
  7507. $res = $this->db->query($sql);
  7508. if ($res === false) {
  7509. $error++;
  7510. $this->errors[] = $this->db->lasterror();
  7511. }
  7512. }
  7513. if (!$error) {
  7514. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  7515. }
  7516. // If we have a field ref with a default value of (PROV)
  7517. if (!$error) {
  7518. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && !is_null($this->fields['ref']['default']) && $this->fields['ref']['default'] == '(PROV)') {
  7519. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7520. $resqlupdate = $this->db->query($sql);
  7521. if ($resqlupdate === false) {
  7522. $error++;
  7523. $this->errors[] = $this->db->lasterror();
  7524. } else {
  7525. $this->ref = '(PROV'.$this->id.')';
  7526. }
  7527. }
  7528. }
  7529. // Create extrafields
  7530. if (!$error) {
  7531. $result = $this->insertExtraFields();
  7532. if ($result < 0) {
  7533. $error++;
  7534. }
  7535. }
  7536. // Create lines
  7537. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  7538. $num = (is_array($this->lines) ? count($this->lines) : 0);
  7539. for ($i = 0; $i < $num; $i++) {
  7540. $line = $this->lines[$i];
  7541. $keyforparent = $this->fk_element;
  7542. $line->$keyforparent = $this->id;
  7543. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  7544. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  7545. if (!is_object($line)) {
  7546. $line = (object) $line;
  7547. }
  7548. $result = $line->create($user, 1);
  7549. if ($result < 0) {
  7550. $this->error = $this->db->lasterror();
  7551. $this->db->rollback();
  7552. return -1;
  7553. }
  7554. }
  7555. }
  7556. // Triggers
  7557. if (!$error && !$notrigger) {
  7558. // Call triggers
  7559. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  7560. if ($result < 0) {
  7561. $error++;
  7562. }
  7563. // End call triggers
  7564. }
  7565. // Commit or rollback
  7566. if ($error) {
  7567. $this->db->rollback();
  7568. return -1;
  7569. } else {
  7570. $this->db->commit();
  7571. return $this->id;
  7572. }
  7573. }
  7574. /**
  7575. * Load object in memory from the database
  7576. *
  7577. * @param int $id Id object
  7578. * @param string $ref Ref
  7579. * @param string $morewhere More SQL filters (' AND ...')
  7580. * @return int <0 if KO, 0 if not found, >0 if OK
  7581. */
  7582. public function fetchCommon($id, $ref = null, $morewhere = '')
  7583. {
  7584. if (empty($id) && empty($ref) && empty($morewhere)) {
  7585. return -1;
  7586. }
  7587. $fieldlist = $this->getFieldList('t');
  7588. if (empty($fieldlist)) {
  7589. return 0;
  7590. }
  7591. $sql = 'SELECT '.$fieldlist;
  7592. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  7593. if (!empty($id)) {
  7594. $sql .= ' WHERE t.rowid = '.((int) $id);
  7595. } elseif (!empty($ref)) {
  7596. $sql .= " WHERE t.ref = ".$this->quote($ref, $this->fields['ref']);
  7597. } else {
  7598. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  7599. }
  7600. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  7601. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  7602. }
  7603. if ($morewhere) {
  7604. $sql .= $morewhere;
  7605. }
  7606. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  7607. $res = $this->db->query($sql);
  7608. if ($res) {
  7609. $obj = $this->db->fetch_object($res);
  7610. if ($obj) {
  7611. $this->setVarsFromFetchObj($obj);
  7612. // Retrieve all extrafield
  7613. // fetch optionals attributes and labels
  7614. $this->fetch_optionals();
  7615. return $this->id;
  7616. } else {
  7617. return 0;
  7618. }
  7619. } else {
  7620. $this->error = $this->db->lasterror();
  7621. $this->errors[] = $this->error;
  7622. return -1;
  7623. }
  7624. }
  7625. /**
  7626. * Load object in memory from the database
  7627. *
  7628. * @param string $morewhere More SQL filters (' AND ...')
  7629. * @return int <0 if KO, 0 if not found, >0 if OK
  7630. */
  7631. public function fetchLinesCommon($morewhere = '')
  7632. {
  7633. $objectlineclassname = get_class($this).'Line';
  7634. if (!class_exists($objectlineclassname)) {
  7635. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  7636. return -1;
  7637. }
  7638. $objectline = new $objectlineclassname($this->db);
  7639. $sql = 'SELECT '.$objectline->getFieldList('l');
  7640. $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element.' as l';
  7641. $sql .= ' WHERE l.fk_'.$this->element.' = '.$this->id;
  7642. if ($morewhere) {
  7643. $sql .= $morewhere;
  7644. }
  7645. if (isset($objectline->fields['position'])) {
  7646. $sql .= $this->db->order('position', 'ASC');
  7647. }
  7648. $resql = $this->db->query($sql);
  7649. if ($resql) {
  7650. $num_rows = $this->db->num_rows($resql);
  7651. $i = 0;
  7652. while ($i < $num_rows) {
  7653. $obj = $this->db->fetch_object($resql);
  7654. if ($obj) {
  7655. $newline = new $objectlineclassname($this->db);
  7656. $newline->setVarsFromFetchObj($obj);
  7657. $this->lines[] = $newline;
  7658. }
  7659. $i++;
  7660. }
  7661. return 1;
  7662. } else {
  7663. $this->error = $this->db->lasterror();
  7664. $this->errors[] = $this->error;
  7665. return -1;
  7666. }
  7667. }
  7668. /**
  7669. * Update object into database
  7670. *
  7671. * @param User $user User that modifies
  7672. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7673. * @return int <0 if KO, >0 if OK
  7674. */
  7675. public function updateCommon(User $user, $notrigger = false)
  7676. {
  7677. global $conf, $langs;
  7678. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  7679. $error = 0;
  7680. $now = dol_now();
  7681. $fieldvalues = $this->setSaveQuery();
  7682. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  7683. $fieldvalues['date_modification'] = $this->db->idate($now);
  7684. }
  7685. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  7686. $fieldvalues['fk_user_modif'] = $user->id;
  7687. }
  7688. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  7689. if (array_key_exists('ref', $fieldvalues)) {
  7690. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7691. }
  7692. // Add quotes and escape on fields with type string
  7693. $keys = array();
  7694. $values = array();
  7695. $tmp = array();
  7696. foreach ($fieldvalues as $k => $v) {
  7697. $keys[$k] = $k;
  7698. $value = $this->fields[$k];
  7699. $values[$k] = $this->quote($v, $value);
  7700. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  7701. }
  7702. // Clean and check mandatory fields
  7703. foreach ($keys as $key) {
  7704. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7705. $values[$key] = ''; // This is an implicit foreign key field
  7706. }
  7707. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7708. $values[$key] = ''; // This is an explicit foreign key field
  7709. }
  7710. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  7711. /*
  7712. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  7713. {
  7714. $error++;
  7715. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7716. }*/
  7717. }
  7718. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  7719. $this->db->begin();
  7720. if (!$error) {
  7721. $res = $this->db->query($sql);
  7722. if ($res === false) {
  7723. $error++;
  7724. $this->errors[] = $this->db->lasterror();
  7725. }
  7726. }
  7727. // Update extrafield
  7728. if (!$error) {
  7729. $result = $this->insertExtraFields();
  7730. if ($result < 0) {
  7731. $error++;
  7732. }
  7733. }
  7734. // Triggers
  7735. if (!$error && !$notrigger) {
  7736. // Call triggers
  7737. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  7738. if ($result < 0) {
  7739. $error++;
  7740. } //Do also here what you must do to rollback action if trigger fail
  7741. // End call triggers
  7742. }
  7743. // Commit or rollback
  7744. if ($error) {
  7745. $this->db->rollback();
  7746. return -1;
  7747. } else {
  7748. $this->db->commit();
  7749. return $this->id;
  7750. }
  7751. }
  7752. /**
  7753. * Delete object in database
  7754. *
  7755. * @param User $user User that deletes
  7756. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7757. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  7758. * @return int <=0 if KO, >0 if OK
  7759. */
  7760. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  7761. {
  7762. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  7763. $error = 0;
  7764. $this->db->begin();
  7765. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  7766. foreach ($this->childtables as $table) {
  7767. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7768. $resql = $this->db->query($sql);
  7769. if (!$resql) {
  7770. $this->error = $this->db->lasterror();
  7771. $this->errors[] = $this->error;
  7772. $this->db->rollback();
  7773. return -1;
  7774. }
  7775. }
  7776. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  7777. $objectisused = $this->isObjectUsed($this->id);
  7778. if (!empty($objectisused)) {
  7779. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  7780. $this->error = 'ErrorRecordHasChildren';
  7781. $this->errors[] = $this->error;
  7782. $this->db->rollback();
  7783. return 0;
  7784. }
  7785. }
  7786. // Delete cascade first
  7787. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  7788. foreach ($this->childtablesoncascade as $table) {
  7789. $deleteFromObject = explode(':', $table);
  7790. if (count($deleteFromObject) >= 2) {
  7791. $className = str_replace('@', '', $deleteFromObject[0]);
  7792. $filePath = $deleteFromObject[1];
  7793. $columnName = $deleteFromObject[2];
  7794. if (dol_include_once($filePath)) {
  7795. $childObject = new $className($this->db);
  7796. if (method_exists($childObject, 'deleteByParentField')) {
  7797. $result = $childObject->deleteByParentField($this->id, $columnName);
  7798. if ($result < 0) {
  7799. $error++;
  7800. $this->errors[] = $childObject->error;
  7801. break;
  7802. }
  7803. } else {
  7804. $error++;
  7805. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  7806. break;
  7807. }
  7808. } else {
  7809. $error++;
  7810. $this->errors[] = 'Cannot include child class file '.$filePath;
  7811. break;
  7812. }
  7813. } else {
  7814. // Delete record in child table
  7815. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7816. $resql = $this->db->query($sql);
  7817. if (!$resql) {
  7818. $error++;
  7819. $this->error = $this->db->lasterror();
  7820. $this->errors[] = $this->error;
  7821. break;
  7822. }
  7823. }
  7824. }
  7825. }
  7826. if (!$error) {
  7827. if (!$notrigger) {
  7828. // Call triggers
  7829. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  7830. if ($result < 0) {
  7831. $error++;
  7832. } // Do also here what you must do to rollback action if trigger fail
  7833. // End call triggers
  7834. }
  7835. }
  7836. // Delete llx_ecm_files
  7837. if (!$error) {
  7838. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  7839. if (!$res) {
  7840. $error++;
  7841. }
  7842. }
  7843. if (!$error && !empty($this->isextrafieldmanaged)) {
  7844. $result = $this->deleteExtraFields();
  7845. if ($result < 0) {
  7846. $error++;
  7847. }
  7848. }
  7849. if (!$error) {
  7850. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
  7851. $res = $this->db->query($sql);
  7852. if ($res === false) {
  7853. $error++;
  7854. $this->errors[] = $this->db->lasterror();
  7855. }
  7856. }
  7857. // Commit or rollback
  7858. if ($error) {
  7859. $this->db->rollback();
  7860. return -1;
  7861. } else {
  7862. $this->db->commit();
  7863. return 1;
  7864. }
  7865. }
  7866. /**
  7867. * Delete all child object from a parent ID
  7868. *
  7869. * @param int $parentId Parent Id
  7870. * @param string $parentField Name of Foreign key parent column
  7871. * @return int <0 if KO, >0 if OK
  7872. * @throws Exception
  7873. */
  7874. public function deleteByParentField($parentId = 0, $parentField = '')
  7875. {
  7876. global $user;
  7877. $error = 0;
  7878. $deleted = 0;
  7879. if (!empty($parentId) && !empty($parentField)) {
  7880. $this->db->begin();
  7881. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  7882. $sql .= ' WHERE '.$parentField.' = '.(int) $parentId;
  7883. $resql = $this->db->query($sql);
  7884. if (!$resql) {
  7885. $this->errors[] = $this->db->lasterror();
  7886. $error++;
  7887. } else {
  7888. while ($obj = $this->db->fetch_object($resql)) {
  7889. $result = $this->fetch($obj->rowid);
  7890. if ($result < 0) {
  7891. $error++;
  7892. $this->errors[] = $this->error;
  7893. } else {
  7894. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  7895. $result = $this->delete();
  7896. } else {
  7897. $result = $this->delete($user);
  7898. }
  7899. if ($result < 0) {
  7900. $error++;
  7901. $this->errors[] = $this->error;
  7902. } else {
  7903. $deleted++;
  7904. }
  7905. }
  7906. }
  7907. }
  7908. if (empty($error)) {
  7909. $this->db->commit();
  7910. return $deleted;
  7911. } else {
  7912. $this->error = implode(', ', $this->errors);
  7913. $this->db->rollback();
  7914. return $error * -1;
  7915. }
  7916. }
  7917. return $deleted;
  7918. }
  7919. /**
  7920. * Delete a line of object in database
  7921. *
  7922. * @param User $user User that delete
  7923. * @param int $idline Id of line to delete
  7924. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7925. * @return int >0 if OK, <0 if KO
  7926. */
  7927. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  7928. {
  7929. global $conf;
  7930. $error = 0;
  7931. $tmpforobjectclass = get_class($this);
  7932. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  7933. // Call trigger
  7934. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  7935. if ($result < 0) {
  7936. return -1;
  7937. }
  7938. // End call triggers
  7939. $this->db->begin();
  7940. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  7941. $sql .= " WHERE rowid = ".((int) $idline);
  7942. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  7943. $resql = $this->db->query($sql);
  7944. if (!$resql) {
  7945. $this->error = "Error ".$this->db->lasterror();
  7946. $error++;
  7947. }
  7948. if (empty($error)) {
  7949. // Remove extrafields
  7950. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  7951. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  7952. $tmpobjectline->id = $idline;
  7953. $result = $tmpobjectline->deleteExtraFields();
  7954. if ($result < 0) {
  7955. $error++;
  7956. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  7957. }
  7958. }
  7959. }
  7960. if (empty($error)) {
  7961. $this->db->commit();
  7962. return 1;
  7963. } else {
  7964. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  7965. $this->db->rollback();
  7966. return -1;
  7967. }
  7968. }
  7969. /**
  7970. * Set to a status
  7971. *
  7972. * @param User $user Object user that modify
  7973. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  7974. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  7975. * @param string $triggercode Trigger code to use
  7976. * @return int <0 if KO, >0 if OK
  7977. */
  7978. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  7979. {
  7980. $error = 0;
  7981. $this->db->begin();
  7982. $statusfield = 'status';
  7983. if ($this->element == 'don' || $this->element == 'donation') {
  7984. $statusfield = 'fk_statut';
  7985. }
  7986. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  7987. $sql .= " SET ".$statusfield." = ".((int) $status);
  7988. $sql .= " WHERE rowid = ".$this->id;
  7989. if ($this->db->query($sql)) {
  7990. if (!$error) {
  7991. $this->oldcopy = clone $this;
  7992. }
  7993. if (!$error && !$notrigger) {
  7994. // Call trigger
  7995. $result = $this->call_trigger($triggercode, $user);
  7996. if ($result < 0) {
  7997. $error++;
  7998. }
  7999. }
  8000. if (!$error) {
  8001. $this->status = $status;
  8002. $this->db->commit();
  8003. return 1;
  8004. } else {
  8005. $this->db->rollback();
  8006. return -1;
  8007. }
  8008. } else {
  8009. $this->error = $this->db->error();
  8010. $this->db->rollback();
  8011. return -1;
  8012. }
  8013. }
  8014. /**
  8015. * Initialise object with example values
  8016. * Id must be 0 if object instance is a specimen
  8017. *
  8018. * @return int
  8019. */
  8020. public function initAsSpecimenCommon()
  8021. {
  8022. global $user;
  8023. $this->id = 0;
  8024. $this->specimen = 1;
  8025. $fields = array(
  8026. 'label' => 'This is label',
  8027. 'ref' => 'ABCD1234',
  8028. 'description' => 'This is a description',
  8029. 'qty' => 123.12,
  8030. 'note_public' => 'Public note',
  8031. 'note_private' => 'Private note',
  8032. 'date_creation' => (dol_now() - 3600 * 48),
  8033. 'date_modification' => (dol_now() - 3600 * 24),
  8034. 'fk_user_creat' => $user->id,
  8035. 'fk_user_modif' => $user->id,
  8036. 'date' => dol_now(),
  8037. );
  8038. foreach ($fields as $key => $value) {
  8039. if (array_key_exists($key, $this->fields)) {
  8040. $this->{$key} = $value;
  8041. }
  8042. }
  8043. return 1;
  8044. }
  8045. /* Part for comments */
  8046. /**
  8047. * Load comments linked with current task
  8048. * @return boolean 1 if ok
  8049. */
  8050. public function fetchComments()
  8051. {
  8052. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8053. $comment = new Comment($this->db);
  8054. $result = $comment->fetchAllFor($this->element, $this->id);
  8055. if ($result < 0) {
  8056. $this->errors = array_merge($this->errors, $comment->errors);
  8057. return -1;
  8058. } else {
  8059. $this->comments = $comment->comments;
  8060. }
  8061. return count($this->comments);
  8062. }
  8063. /**
  8064. * Return nb comments already posted
  8065. *
  8066. * @return int
  8067. */
  8068. public function getNbComments()
  8069. {
  8070. return count($this->comments);
  8071. }
  8072. /**
  8073. * Trim object parameters
  8074. *
  8075. * @param string[] $parameters array of parameters to trim
  8076. * @return void
  8077. */
  8078. public function trimParameters($parameters)
  8079. {
  8080. if (!is_array($parameters)) {
  8081. return;
  8082. }
  8083. foreach ($parameters as $parameter) {
  8084. if (isset($this->$parameter)) {
  8085. $this->$parameter = trim($this->$parameter);
  8086. }
  8087. }
  8088. }
  8089. /* Part for categories/tags */
  8090. /**
  8091. * Sets object to given categories.
  8092. *
  8093. * Deletes object from existing categories not supplied.
  8094. * Adds it to non existing supplied categories.
  8095. * Existing categories are left untouch.
  8096. *
  8097. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8098. * @return int Array of category objects or < 0 if KO
  8099. */
  8100. public function getCategoriesCommon($type_categ)
  8101. {
  8102. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8103. // Get current categories
  8104. $c = new Categorie($this->db);
  8105. $existing = $c->containing($this->id, $type_categ, 'id');
  8106. return $existing;
  8107. }
  8108. /**
  8109. * Sets object to given categories.
  8110. *
  8111. * Adds it to non existing supplied categories.
  8112. * Deletes object from existing categories not supplied (if remove_existing==true).
  8113. * Existing categories are left untouch.
  8114. *
  8115. * @param int[]|int $categories Category ID or array of Categories IDs
  8116. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8117. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8118. * @return int <0 if KO, >0 if OK
  8119. */
  8120. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8121. {
  8122. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8123. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8124. if (empty($type_categ)) {
  8125. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8126. return -1;
  8127. }
  8128. // Handle single category
  8129. if (!is_array($categories)) {
  8130. $categories = array($categories);
  8131. }
  8132. // Get current categories
  8133. $c = new Categorie($this->db);
  8134. $existing = $c->containing($this->id, $type_categ, 'id');
  8135. if ($remove_existing) {
  8136. // Diff
  8137. if (is_array($existing)) {
  8138. $to_del = array_diff($existing, $categories);
  8139. $to_add = array_diff($categories, $existing);
  8140. } else {
  8141. $to_del = array(); // Nothing to delete
  8142. $to_add = $categories;
  8143. }
  8144. } else {
  8145. $to_del = array(); // Nothing to delete
  8146. $to_add = array_diff($categories, $existing);
  8147. }
  8148. $error = 0;
  8149. $ok=0;
  8150. // Process
  8151. foreach ($to_del as $del) {
  8152. if ($c->fetch($del) > 0) {
  8153. $result=$c->del_type($this, $type_categ);
  8154. if ($result < 0) {
  8155. $error++;
  8156. $this->error = $c->error;
  8157. $this->errors = $c->errors;
  8158. break;
  8159. } else {
  8160. $ok+=$result;
  8161. }
  8162. }
  8163. }
  8164. foreach ($to_add as $add) {
  8165. if ($c->fetch($add) > 0) {
  8166. $result = $c->add_type($this, $type_categ);
  8167. if ($result < 0) {
  8168. $error++;
  8169. $this->error = $c->error;
  8170. $this->errors = $c->errors;
  8171. break;
  8172. } else {
  8173. $ok+=$result;
  8174. }
  8175. }
  8176. }
  8177. return $error ? -1 * $error : $ok;
  8178. }
  8179. /**
  8180. * Copy related categories to another object
  8181. *
  8182. * @param int $fromId Id object source
  8183. * @param int $toId Id object cible
  8184. * @param string $type Type of category ('product', ...)
  8185. * @return int < 0 if error, > 0 if ok
  8186. */
  8187. public function cloneCategories($fromId, $toId, $type = '')
  8188. {
  8189. $this->db->begin();
  8190. if (empty($type)) {
  8191. $type = $this->table_element;
  8192. }
  8193. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8194. $categorystatic = new Categorie($this->db);
  8195. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8196. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8197. $sql .= " WHERE fk_product = ".((int) $fromId);
  8198. if (!$this->db->query($sql)) {
  8199. $this->error = $this->db->lasterror();
  8200. $this->db->rollback();
  8201. return -1;
  8202. }
  8203. $this->db->commit();
  8204. return 1;
  8205. }
  8206. /**
  8207. * Delete related files of object in database
  8208. *
  8209. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8210. * @return bool True if OK, False if KO
  8211. */
  8212. public function deleteEcmFiles($mode = 0)
  8213. {
  8214. global $conf;
  8215. $this->db->begin();
  8216. // Delete in database with mode 0
  8217. if ($mode == 0) {
  8218. switch ($this->element) {
  8219. case 'propal':
  8220. $element = 'propale';
  8221. break;
  8222. case 'product':
  8223. $element = 'produit';
  8224. break;
  8225. case 'order_supplier':
  8226. $element = 'fournisseur/commande';
  8227. break;
  8228. case 'invoice_supplier':
  8229. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8230. break;
  8231. case 'shipping':
  8232. $element = 'expedition/sending';
  8233. break;
  8234. default:
  8235. $element = $this->element;
  8236. }
  8237. // Delete ecm_files extrafields
  8238. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN (";
  8239. $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8240. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  8241. $sql .= ")";
  8242. if (!$this->db->query($sql)) {
  8243. $this->error = $this->db->lasterror();
  8244. $this->db->rollback();
  8245. return false;
  8246. }
  8247. // Delete ecm_files
  8248. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  8249. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8250. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  8251. if (!$this->db->query($sql)) {
  8252. $this->error = $this->db->lasterror();
  8253. $this->db->rollback();
  8254. return false;
  8255. }
  8256. }
  8257. // Delete in database with mode 1
  8258. if ($mode == 1) {
  8259. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields";
  8260. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id.")";
  8261. $resql = $this->db->query($sql);
  8262. if (!$resql) {
  8263. $this->error = $this->db->lasterror();
  8264. $this->db->rollback();
  8265. return false;
  8266. }
  8267. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files";
  8268. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".((int) $this->id);
  8269. $resql = $this->db->query($sql);
  8270. if (!$resql) {
  8271. $this->error = $this->db->lasterror();
  8272. $this->db->rollback();
  8273. return false;
  8274. }
  8275. }
  8276. $this->db->commit();
  8277. return true;
  8278. }
  8279. }