commonobject.class.php 350 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176
  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-2022 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-2022 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-2023 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
  19. * Copyright (C) 2023 Lenin Rivas <lenin.rivas777@gmail.com>
  20. *
  21. * This program is free software; you can redistribute it and/or modify
  22. * it under the terms of the GNU General Public License as published by
  23. * the Free Software Foundation; either version 3 of the License, or
  24. * (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU General Public License
  32. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  33. */
  34. /**
  35. * \file htdocs/core/class/commonobject.class.php
  36. * \ingroup core
  37. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  38. */
  39. /**
  40. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  41. */
  42. abstract class CommonObject
  43. {
  44. const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
  45. /**
  46. * @var DoliDb Database handler (result of a new DoliDB)
  47. */
  48. public $db;
  49. /**
  50. * @var int The object identifier
  51. */
  52. public $id;
  53. /**
  54. * @var int The environment ID when using a multicompany module
  55. */
  56. public $entity;
  57. /**
  58. * @var string Error string
  59. * @see $errors
  60. */
  61. public $error;
  62. /**
  63. * @var string Error string that is hidden but can be used to store complementatry technical code.
  64. */
  65. public $errorhidden;
  66. /**
  67. * @var string[] Array of error strings
  68. */
  69. public $errors = array();
  70. /**
  71. * @var array To store error results of ->validateField()
  72. */
  73. private $validateFieldsErrors = array();
  74. /**
  75. * @var string ID to identify managed object
  76. */
  77. public $element;
  78. /**
  79. * @var int The related element
  80. */
  81. public $fk_element;
  82. /**
  83. * @var string Name to use for 'features' parameter to check module permissions user->rights->feature with restrictedArea().
  84. * Undefined means same value than $element. Can be use to force a check on another element for example for class of line, we mention here the parent element.
  85. */
  86. public $element_for_permission;
  87. /**
  88. * @var string Name of table without prefix where object is stored
  89. */
  90. public $table_element;
  91. /**
  92. * @var string Name of subtable line
  93. */
  94. public $table_element_line = '';
  95. /**
  96. * @var int 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  97. */
  98. public $ismultientitymanaged;
  99. /**
  100. * @var string Key value used to track if data is coming from import wizard
  101. */
  102. public $import_key;
  103. /**
  104. * @var mixed Contains data to manage extrafields
  105. */
  106. public $array_options = array();
  107. /**
  108. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  109. */
  110. public $fields = array();
  111. /**
  112. * @var mixed Array to store alternative languages values of object
  113. */
  114. public $array_languages = null; // Value is array() when load already tried
  115. /**
  116. * @var array To store result of ->liste_contact()
  117. */
  118. public $contacts_ids;
  119. /**
  120. * @var mixed Array of linked objects, set and used when calling ->create() to be able to create links during the creation of object
  121. */
  122. public $linked_objects;
  123. /**
  124. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  125. */
  126. public $linkedObjectsIds;
  127. /**
  128. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  129. */
  130. public $linkedObjects;
  131. /**
  132. * @var boolean[] Array of boolean with object id as key and value as true if linkedObjects full loaded for object id. Loaded by ->fetchObjectLinked. Important for pdf generation time reduction.
  133. */
  134. private $linkedObjectsFullLoaded = array();
  135. /**
  136. * @var CommonObject To store a cloned copy of object before to edit it and keep track of old properties
  137. */
  138. public $oldcopy;
  139. /**
  140. * @var string Column name of the ref field.
  141. */
  142. protected $table_ref_field = '';
  143. /**
  144. * @var integer 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  145. */
  146. public $restrictiononfksoc = 0;
  147. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  148. /**
  149. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  150. */
  151. public $context = array();
  152. /**
  153. * @var string Contains canvas name if record is an alternative canvas record
  154. */
  155. public $canvas;
  156. /**
  157. * @var Project The related project object
  158. * @see fetch_projet()
  159. */
  160. public $project;
  161. /**
  162. * @var int The related project ID
  163. * @see setProject(), project
  164. */
  165. public $fk_project;
  166. /**
  167. * @var Project The related project object
  168. * @deprecated
  169. * @see project
  170. */
  171. public $projet;
  172. /**
  173. * @deprecated
  174. * @see $fk_project
  175. */
  176. public $fk_projet;
  177. /**
  178. * @var Contact A related contact object
  179. * @see fetch_contact()
  180. */
  181. public $contact;
  182. /**
  183. * @var int The related contact ID
  184. * @see fetch_contact()
  185. */
  186. public $contact_id;
  187. /**
  188. * @var Societe A related thirdparty object
  189. * @see fetch_thirdparty()
  190. */
  191. public $thirdparty;
  192. /**
  193. * @var User A related user
  194. * @see fetch_user()
  195. */
  196. public $user;
  197. /**
  198. * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type
  199. * @see fetch_origin()
  200. */
  201. public $origin;
  202. /**
  203. * @var int The id of originating object
  204. * @see fetch_origin()
  205. */
  206. public $origin_id;
  207. /**
  208. * @var string The object's reference
  209. */
  210. public $ref;
  211. /**
  212. * @var string An external reference for the object
  213. */
  214. public $ref_ext;
  215. /**
  216. * @var string The object's previous reference
  217. */
  218. public $ref_previous;
  219. /**
  220. * @var string The object's next reference
  221. */
  222. public $ref_next;
  223. /**
  224. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  225. */
  226. public $newref;
  227. /**
  228. * @var int The object's status. Prefer use of status.
  229. * @see setStatut()
  230. */
  231. public $statut;
  232. /**
  233. * @var int The object's status
  234. * @see setStatut()
  235. */
  236. public $status;
  237. /**
  238. * @var string
  239. * @see getFullAddress()
  240. */
  241. public $country;
  242. /**
  243. * @var int
  244. * @see getFullAddress(), country
  245. */
  246. public $country_id;
  247. /**
  248. * @var string The ISO country code on 2 chars.
  249. * @see getFullAddress(), isInEEC(), country
  250. */
  251. public $country_code;
  252. /**
  253. * @var string
  254. * @see getFullAddress()
  255. */
  256. public $state;
  257. /**
  258. * @var int
  259. * @see getFullAddress(), state
  260. */
  261. public $state_id;
  262. /**
  263. * @var string
  264. * @see getFullAddress(), $state
  265. */
  266. public $state_code;
  267. /**
  268. * @var int
  269. * @see getFullAddress(), $region_code, $region
  270. */
  271. public $region_id;
  272. /**
  273. * @var string
  274. * @see getFullAddress(), $region_id, $region
  275. */
  276. public $region_code;
  277. /**
  278. * @var string
  279. * @see getFullAddress(), $region_id, $region_code
  280. */
  281. public $region;
  282. /**
  283. * @var int
  284. * @see fetch_barcode()
  285. */
  286. public $barcode_type;
  287. /**
  288. * @var string
  289. * @see fetch_barcode(), barcode_type
  290. */
  291. public $barcode_type_code;
  292. /**
  293. * @var string
  294. * @see fetch_barcode(), barcode_type
  295. */
  296. public $barcode_type_label;
  297. /**
  298. * @var string
  299. * @see fetch_barcode(), barcode_type
  300. */
  301. public $barcode_type_coder;
  302. /**
  303. * @var int Payment method ID (cheque, cash, ...)
  304. * @see setPaymentMethods()
  305. */
  306. public $mode_reglement_id;
  307. /**
  308. * @var int Payment terms ID
  309. * @see setPaymentTerms()
  310. */
  311. public $cond_reglement_id;
  312. /**
  313. * @var int Demand reason ID
  314. */
  315. public $demand_reason_id;
  316. /**
  317. * @var int Transport mode ID (For module intracomm report)
  318. * @see setTransportMode()
  319. */
  320. public $transport_mode_id;
  321. /**
  322. * @var int Payment terms ID
  323. * @deprecated Kept for compatibility
  324. * @see cond_reglement_id;
  325. */
  326. public $cond_reglement;
  327. /**
  328. * @var int Delivery address ID
  329. * @see setDeliveryAddress()
  330. * @deprecated
  331. */
  332. public $fk_delivery_address;
  333. /**
  334. * @var int Shipping method ID
  335. * @see setShippingMethod()
  336. */
  337. public $shipping_method_id;
  338. /**
  339. * @var string Shipping method label
  340. * @see setShippingMethod()
  341. */
  342. public $shipping_method;
  343. /**
  344. * @var string multicurrency code
  345. */
  346. public $multicurrency_code;
  347. /**
  348. * @var string multicurrency tx
  349. */
  350. public $multicurrency_tx;
  351. /**
  352. * @var string
  353. * @see SetDocModel()
  354. */
  355. public $model_pdf;
  356. /**
  357. * @var string
  358. * @deprecated
  359. * @see $model_pdf
  360. */
  361. public $modelpdf;
  362. /**
  363. * @var string
  364. * Contains relative path of last generated main file
  365. */
  366. public $last_main_doc;
  367. /**
  368. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  369. * @deprecated
  370. * @see $fk_account
  371. */
  372. public $fk_bank;
  373. /**
  374. * @var int Bank account ID
  375. * @see SetBankAccount()
  376. */
  377. public $fk_account;
  378. /**
  379. * @var string Open ID
  380. */
  381. public $openid;
  382. /**
  383. * @var string Public note
  384. * @see update_note()
  385. */
  386. public $note_public;
  387. /**
  388. * @var string Private note
  389. * @see update_note()
  390. */
  391. public $note_private;
  392. /**
  393. * @deprecated
  394. * @see $note_private
  395. */
  396. public $note;
  397. /**
  398. * @var float Total amount before taxes
  399. * @see update_price()
  400. */
  401. public $total_ht;
  402. /**
  403. * @var float Total VAT amount
  404. * @see update_price()
  405. */
  406. public $total_tva;
  407. /**
  408. * @var float Total local tax 1 amount
  409. * @see update_price()
  410. */
  411. public $total_localtax1;
  412. /**
  413. * @var float Total local tax 2 amount
  414. * @see update_price()
  415. */
  416. public $total_localtax2;
  417. /**
  418. * @var float Total amount with taxes
  419. * @see update_price()
  420. */
  421. public $total_ttc;
  422. /**
  423. * @var CommonObjectLine[]
  424. */
  425. public $lines;
  426. /**
  427. * @var mixed Contains comments
  428. * @see fetchComments()
  429. */
  430. public $comments = array();
  431. /**
  432. * @var string The name
  433. */
  434. public $name;
  435. /**
  436. * @var string The lastname
  437. */
  438. public $lastname;
  439. /**
  440. * @var string The firstname
  441. */
  442. public $firstname;
  443. /**
  444. * @var string The civility code, not an integer
  445. */
  446. public $civility_id;
  447. // Dates
  448. /**
  449. * @var integer|string date_creation
  450. */
  451. public $date_creation;
  452. /**
  453. * @var integer|string $date_validation;
  454. */
  455. public $date_validation; // Date validation
  456. /**
  457. * @var integer|string $date_modification;
  458. */
  459. public $date_modification; // Date last change (tms field)
  460. /**
  461. * @var integer|string $date_cloture;
  462. */
  463. public $date_cloture; // Date closing (tms field)
  464. /**
  465. * @var User|int User author/creation
  466. * @TODO Merge with user_creation
  467. */
  468. public $user_author;
  469. /**
  470. * @var User|int User author/creation
  471. * @TODO Remove type id
  472. */
  473. public $user_creation;
  474. /**
  475. * @var int User id author/creation
  476. */
  477. public $user_creation_id;
  478. /**
  479. * @var User|int User of validation
  480. * @TODO Merge with user_validation
  481. */
  482. public $user_valid;
  483. /**
  484. * @var User|int User of validation
  485. * @TODO Remove type id
  486. */
  487. public $user_validation;
  488. /**
  489. * @var int User id of validation
  490. */
  491. public $user_validation_id;
  492. /**
  493. * @var int User id closing object
  494. */
  495. public $user_closing_id;
  496. /**
  497. * @var User|int User last modifier
  498. * @TODO Remove type id
  499. */
  500. public $user_modification;
  501. /**
  502. * @var int User id last modifier
  503. */
  504. public $user_modification_id;
  505. public $next_prev_filter;
  506. /**
  507. * @var int 1 if object is specimen
  508. */
  509. public $specimen = 0;
  510. /**
  511. * @var int Id of contact to send object (used by the trigger of module Agenda)
  512. */
  513. public $sendtoid;
  514. /**
  515. * @var float Amount already paid (used to show correct status)
  516. */
  517. public $alreadypaid;
  518. protected $labelStatus;
  519. protected $labelStatusShort;
  520. /**
  521. * @var int showphoto_on_popup
  522. */
  523. public $showphoto_on_popup;
  524. /**
  525. * @var array nb used in load_stateboard
  526. */
  527. public $nb = array();
  528. /**
  529. * @var string output
  530. */
  531. public $output;
  532. /**
  533. * @var array List of child tables. To test if we can delete object.
  534. */
  535. protected $childtables = array();
  536. /**
  537. * @var array List of child tables. To know object to delete on cascade.
  538. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  539. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  540. */
  541. protected $childtablesoncascade = array();
  542. // No constructor as it is an abstract class
  543. /**
  544. * Check an object id/ref exists
  545. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  546. *
  547. * @param string $element String of element ('product', 'facture', ...)
  548. * @param int $id Id of object
  549. * @param string $ref Ref of object to check
  550. * @param string $ref_ext Ref ext of object to check
  551. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  552. */
  553. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  554. {
  555. global $db, $conf;
  556. $sql = "SELECT rowid, ref, ref_ext";
  557. $sql .= " FROM ".$db->prefix().$element;
  558. $sql .= " WHERE entity IN (".getEntity($element).")";
  559. if ($id > 0) {
  560. $sql .= " AND rowid = ".((int) $id);
  561. } elseif ($ref) {
  562. $sql .= " AND ref = '".$db->escape($ref)."'";
  563. } elseif ($ref_ext) {
  564. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  565. } else {
  566. $error = 'ErrorWrongParameters';
  567. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  568. return -1;
  569. }
  570. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  571. $sql .= " AND entity = ".((int) $conf->entity);
  572. }
  573. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  574. $resql = $db->query($sql);
  575. if ($resql) {
  576. $num = $db->num_rows($resql);
  577. if ($num > 0) {
  578. return 1;
  579. } else {
  580. return 0;
  581. }
  582. }
  583. return -1;
  584. }
  585. /**
  586. * setErrorsFromObject
  587. *
  588. * @param CommonObject $object commonobject
  589. * @return void
  590. */
  591. public function setErrorsFromObject($object)
  592. {
  593. if (!empty($object->error)) {
  594. $this->error = $object->error;
  595. }
  596. if (!empty($object->errors)) {
  597. $this->errors = array_merge($this->errors, $object->errors);
  598. }
  599. }
  600. /**
  601. * Return array of datas to show into a tooltip. This method must be implemented in each object class.
  602. *
  603. * @since v18
  604. * @param array $params params to construct tooltip data
  605. * @return array
  606. */
  607. public function getTooltipContentArray($params)
  608. {
  609. return [];
  610. }
  611. /**
  612. * getTooltipContent
  613. *
  614. * @param array $params params
  615. * @since v18
  616. * @return string
  617. */
  618. public function getTooltipContent($params)
  619. {
  620. global $action, $extrafields, $langs, $hookmanager;
  621. // If there is too much extrafields, we do not include them into tooltip
  622. $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP = getDolGlobalInt('MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
  623. $datas = $this->getTooltipContentArray($params);
  624. $count = 0;
  625. // Add extrafields
  626. if (!empty($extrafields->attributes[$this->table_element]['label'])) {
  627. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  628. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  629. continue;
  630. }
  631. if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
  632. $datas['more_extrafields'] = '<br>...';
  633. break;
  634. }
  635. $enabled = 1;
  636. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  637. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
  638. }
  639. if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  640. $enabled = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
  641. }
  642. $perms = 1;
  643. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  644. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
  645. }
  646. if (empty($enabled)) {
  647. continue; // 0 = Never visible field
  648. }
  649. if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
  650. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation
  651. }
  652. if (empty($perms)) {
  653. continue; // 0 = Not visible
  654. }
  655. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  656. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  657. }
  658. $labelextra = $langs->trans((string) $extrafields->attributes[$this->table_element]['label'][$key]);
  659. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  660. $datas[$key]= '<br><b><u>'. $labelextra . '</u></b>';
  661. } else {
  662. $value = (empty($this->array_options['options_' . $key]) ? '' : $this->array_options['options_' . $key]);
  663. $datas[$key]= '<br><b>'. $labelextra . ':</b> ' . $extrafields->showOutputField($key, $value, '', $this->table_element);
  664. $count++;
  665. }
  666. }
  667. }
  668. $hookmanager->initHooks(array($this->element . 'dao'));
  669. $parameters = array(
  670. 'tooltipcontentarray' => &$datas
  671. );
  672. // Note that $action and $object may have been modified by some hooks
  673. $hookmanager->executeHooks('getTooltipContent', $parameters, $this, $action);
  674. //var_dump($datas);
  675. $label = implode($datas);
  676. return $label;
  677. }
  678. /**
  679. * Method to output saved errors
  680. *
  681. * @return string String with errors
  682. */
  683. public function errorsToString()
  684. {
  685. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  686. }
  687. /**
  688. * Return customer ref for screen output.
  689. *
  690. * @param string $objref Customer ref
  691. * @return string Customer ref formated
  692. */
  693. public function getFormatedCustomerRef($objref)
  694. {
  695. global $hookmanager;
  696. $parameters = array('objref'=>$objref);
  697. $action = '';
  698. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  699. if ($reshook > 0) {
  700. return $hookmanager->resArray['objref'];
  701. }
  702. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  703. }
  704. /**
  705. * Return supplier ref for screen output.
  706. *
  707. * @param string $objref Supplier ref
  708. * @return string Supplier ref formated
  709. */
  710. public function getFormatedSupplierRef($objref)
  711. {
  712. global $hookmanager;
  713. $parameters = array('objref'=>$objref);
  714. $action = '';
  715. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  716. if ($reshook > 0) {
  717. return $hookmanager->resArray['objref'];
  718. }
  719. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  720. }
  721. /**
  722. * Return full address of contact
  723. *
  724. * @param int $withcountry 1=Add country into address string
  725. * @param string $sep Separator to use to build string
  726. * @param int $withregion 1=Add region into address string
  727. * @param string $extralangcode User extralanguages as value
  728. * @return string Full address string
  729. */
  730. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  731. {
  732. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  733. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  734. $tmparray = getCountry($this->country_id, 'all');
  735. $this->country_code = $tmparray['code'];
  736. $this->country = $tmparray['label'];
  737. }
  738. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  739. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  740. $tmparray = getState($this->state_id, 'all', 0, 1);
  741. $this->state_code = $tmparray['code'];
  742. $this->state = $tmparray['label'];
  743. $this->region_code = $tmparray['region_code'];
  744. $this->region = $tmparray['region'];
  745. }
  746. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  747. }
  748. /**
  749. * Return the link of last main doc file for direct public download.
  750. *
  751. * @param string $modulepart Module related to document
  752. * @param int $initsharekey Init the share key if it was not yet defined
  753. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  754. * @return string Link or empty string if there is no download link
  755. */
  756. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  757. {
  758. global $user, $dolibarr_main_url_root;
  759. if (empty($this->last_main_doc)) {
  760. return ''; // No way to known which document name to use
  761. }
  762. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  763. $ecmfile = new EcmFiles($this->db);
  764. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  765. if ($result < 0) {
  766. $this->error = $ecmfile->error;
  767. $this->errors = $ecmfile->errors;
  768. return -1;
  769. }
  770. if (empty($ecmfile->id)) {
  771. // Add entry into index
  772. if ($initsharekey) {
  773. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  774. // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
  775. /*
  776. $ecmfile->filepath = $rel_dir;
  777. $ecmfile->filename = $filename;
  778. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  779. $ecmfile->fullpath_orig = '';
  780. $ecmfile->gen_or_uploaded = 'generated';
  781. $ecmfile->description = ''; // indexed content
  782. $ecmfile->keywords = ''; // keyword content
  783. $ecmfile->share = getRandomPassword(true);
  784. $result = $ecmfile->create($user);
  785. if ($result < 0)
  786. {
  787. $this->error = $ecmfile->error;
  788. $this->errors = $ecmfile->errors;
  789. }
  790. */
  791. } else {
  792. return '';
  793. }
  794. } elseif (empty($ecmfile->share)) {
  795. // Add entry into index
  796. if ($initsharekey) {
  797. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  798. $ecmfile->share = getRandomPassword(true);
  799. $ecmfile->update($user);
  800. } else {
  801. return '';
  802. }
  803. }
  804. // Define $urlwithroot
  805. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  806. // This is to use external domain name found into config file
  807. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  808. //else
  809. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  810. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  811. $forcedownload = 0;
  812. $paramlink = '';
  813. //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  814. //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  815. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  816. if (!empty($ecmfile->share)) {
  817. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  818. }
  819. if ($forcedownload) {
  820. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  821. }
  822. if ($relativelink) {
  823. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  824. } else {
  825. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  826. }
  827. // Here $ecmfile->share is defined
  828. return $linktoreturn;
  829. }
  830. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  831. /**
  832. * Add a link between element $this->element and a contact
  833. *
  834. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  835. * @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
  836. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  837. * @param int $notrigger Disable all triggers
  838. * @return int <0 if KO, 0 if already added, >0 if OK
  839. */
  840. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  841. {
  842. // phpcs:enable
  843. global $user, $langs;
  844. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  845. // Check parameters
  846. if ($fk_socpeople <= 0) {
  847. $langs->load("errors");
  848. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  849. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  850. return -1;
  851. }
  852. if (!$type_contact) {
  853. $langs->load("errors");
  854. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  855. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  856. return -2;
  857. }
  858. $id_type_contact = 0;
  859. if (is_numeric($type_contact)) {
  860. $id_type_contact = $type_contact;
  861. } else {
  862. // We look for id type_contact
  863. $sql = "SELECT tc.rowid";
  864. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  865. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  866. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  867. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  868. //print $sql;
  869. $resql = $this->db->query($sql);
  870. if ($resql) {
  871. $obj = $this->db->fetch_object($resql);
  872. if ($obj) {
  873. $id_type_contact = $obj->rowid;
  874. }
  875. }
  876. }
  877. if ($id_type_contact == 0) {
  878. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  879. 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");
  880. return -3;
  881. }
  882. $datecreate = dol_now();
  883. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  884. $TListeContacts = $this->liste_contact(-1, $source);
  885. $already_added = false;
  886. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  887. foreach ($TListeContacts as $array_contact) {
  888. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  889. $already_added = true;
  890. break;
  891. }
  892. }
  893. }
  894. if (!$already_added) {
  895. $this->db->begin();
  896. // Insert into database
  897. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  898. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  899. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  900. $sql .= "'".$this->db->idate($datecreate)."'";
  901. $sql .= ", 4, ".((int) $id_type_contact);
  902. $sql .= ")";
  903. $resql = $this->db->query($sql);
  904. if ($resql) {
  905. if (!$notrigger) {
  906. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  907. if ($result < 0) {
  908. $this->db->rollback();
  909. return -1;
  910. }
  911. }
  912. $this->db->commit();
  913. return 1;
  914. } else {
  915. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  916. $this->error = $this->db->errno();
  917. $this->db->rollback();
  918. return -2;
  919. } else {
  920. $this->error = $this->db->lasterror();
  921. $this->db->rollback();
  922. return -1;
  923. }
  924. }
  925. } else {
  926. return 0;
  927. }
  928. }
  929. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  930. /**
  931. * Copy contact from one element to current
  932. *
  933. * @param CommonObject $objFrom Source element
  934. * @param string $source Nature of contact ('internal' or 'external')
  935. * @return int >0 if OK, <0 if KO
  936. */
  937. public function copy_linked_contact($objFrom, $source = 'internal')
  938. {
  939. // phpcs:enable
  940. $contacts = $objFrom->liste_contact(-1, $source);
  941. foreach ($contacts as $contact) {
  942. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  943. return -1;
  944. }
  945. }
  946. return 1;
  947. }
  948. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  949. /**
  950. * Update a link to contact line
  951. *
  952. * @param int $rowid Id of line contact-element
  953. * @param int $statut New status of link
  954. * @param int $type_contact_id Id of contact type (not modified if 0)
  955. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  956. * @return int <0 if KO, >= 0 if OK
  957. */
  958. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  959. {
  960. // phpcs:enable
  961. // Insert into database
  962. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  963. $sql .= " statut = ".$statut;
  964. if ($type_contact_id) {
  965. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  966. }
  967. if ($fk_socpeople) {
  968. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  969. }
  970. $sql .= " where rowid = ".((int) $rowid);
  971. $resql = $this->db->query($sql);
  972. if ($resql) {
  973. return 0;
  974. } else {
  975. $this->error = $this->db->lasterror();
  976. return -1;
  977. }
  978. }
  979. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  980. /**
  981. * Delete a link to contact line
  982. *
  983. * @param int $rowid Id of contact link line to delete
  984. * @param int $notrigger Disable all triggers
  985. * @return int >0 if OK, <0 if KO
  986. */
  987. public function delete_contact($rowid, $notrigger = 0)
  988. {
  989. // phpcs:enable
  990. global $user;
  991. $this->db->begin();
  992. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  993. $sql .= " WHERE rowid = ".((int) $rowid);
  994. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  995. if ($this->db->query($sql)) {
  996. if (!$notrigger) {
  997. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  998. if ($result < 0) {
  999. $this->db->rollback();
  1000. return -1;
  1001. }
  1002. }
  1003. $this->db->commit();
  1004. return 1;
  1005. } else {
  1006. $this->error = $this->db->lasterror();
  1007. $this->db->rollback();
  1008. return -1;
  1009. }
  1010. }
  1011. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1012. /**
  1013. * Delete all links between an object $this and all its contacts in llx_element_contact
  1014. *
  1015. * @param string $source '' or 'internal' or 'external'
  1016. * @param string $code Type of contact (code or id)
  1017. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1018. */
  1019. public function delete_linked_contact($source = '', $code = '')
  1020. {
  1021. // phpcs:enable
  1022. $listId = '';
  1023. $temp = array();
  1024. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1025. if (!empty($typeContact)) {
  1026. foreach ($typeContact as $key => $value) {
  1027. array_push($temp, $key);
  1028. }
  1029. $listId = implode(",", $temp);
  1030. }
  1031. // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
  1032. // any type or record instead of only the ones of the current object. So we do nothing in such a case.
  1033. if (empty($listId)) {
  1034. return 0;
  1035. }
  1036. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1037. $sql .= " WHERE element_id = ".((int) $this->id);
  1038. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1039. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1040. if ($this->db->query($sql)) {
  1041. return 1;
  1042. } else {
  1043. $this->error = $this->db->lasterror();
  1044. return -1;
  1045. }
  1046. }
  1047. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1048. /**
  1049. * Get array of all contacts for an object
  1050. *
  1051. * @param int $statusoflink Status of links to get (-1=all). Not used.
  1052. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1053. * @param int $list 0:Returned array contains all properties, 1:Return array contains just id
  1054. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1055. * @param int $status Status of user or company
  1056. * @param array $arrayoftcids Array with ID of type of contacts. If we provide this, we can make a ec.fk_c_type_contact in ($arrayoftcids) to avoid link on tc table. TODO Not implemented.
  1057. * @return array|int Array of contacts, -1 if error
  1058. */
  1059. public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
  1060. {
  1061. // phpcs:enable
  1062. global $langs;
  1063. $tab = array();
  1064. $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
  1065. if ($source == 'internal') {
  1066. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1067. }
  1068. if ($source == 'external' || $source == 'thirdparty') {
  1069. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1070. }
  1071. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1072. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1073. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc,";
  1074. $sql .= " ".$this->db->prefix()."element_contact ec";
  1075. if ($source == 'internal') { // internal contact (user)
  1076. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1077. }
  1078. if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
  1079. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1080. }
  1081. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1082. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1083. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1084. if ($code) {
  1085. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1086. }
  1087. if ($source == 'internal') {
  1088. $sql .= " AND tc.source = 'internal'";
  1089. if ($status >= 0) {
  1090. $sql .= " AND t.statut = ".((int) $status);
  1091. }
  1092. }
  1093. if ($source == 'external' || $source == 'thirdparty') {
  1094. $sql .= " AND tc.source = 'external'";
  1095. if ($status >= 0) {
  1096. $sql .= " AND t.statut = ".((int) $status); // t is llx_socpeople
  1097. }
  1098. }
  1099. $sql .= " AND tc.active = 1";
  1100. if ($statusoflink >= 0) {
  1101. $sql .= " AND ec.statut = ".((int) $statusoflink);
  1102. }
  1103. $sql .= " ORDER BY t.lastname ASC";
  1104. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1105. $resql = $this->db->query($sql);
  1106. if ($resql) {
  1107. $num = $this->db->num_rows($resql);
  1108. $i = 0;
  1109. while ($i < $num) {
  1110. $obj = $this->db->fetch_object($resql);
  1111. if (!$list) {
  1112. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1113. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1114. $tab[$i] = array(
  1115. 'parentId' => $this->id,
  1116. 'source' => $obj->source,
  1117. 'socid' => $obj->socid,
  1118. 'id' => $obj->id,
  1119. 'nom' => $obj->lastname, // For backward compatibility
  1120. 'civility' => $obj->civility,
  1121. 'lastname' => $obj->lastname,
  1122. 'firstname' => $obj->firstname,
  1123. 'email'=>$obj->email,
  1124. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1125. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1126. 'statuscontact' => $obj->statuscontact,
  1127. 'rowid' => $obj->rowid,
  1128. 'code' => $obj->code,
  1129. 'libelle' => $libelle_type,
  1130. 'status' => $obj->statuslink,
  1131. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1132. );
  1133. } else {
  1134. $tab[$i] = $obj->id;
  1135. }
  1136. $i++;
  1137. }
  1138. return $tab;
  1139. } else {
  1140. $this->error = $this->db->lasterror();
  1141. dol_print_error($this->db);
  1142. return -1;
  1143. }
  1144. }
  1145. /**
  1146. * Update status of a contact linked to object
  1147. *
  1148. * @param int $rowid Id of link between object and contact
  1149. * @return int <0 if KO, >=0 if OK
  1150. */
  1151. public function swapContactStatus($rowid)
  1152. {
  1153. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1154. $sql .= " tc.code, tc.libelle";
  1155. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1156. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1157. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1158. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1159. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1160. $resql = $this->db->query($sql);
  1161. if ($resql) {
  1162. $obj = $this->db->fetch_object($resql);
  1163. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1164. $result = $this->update_contact($rowid, $newstatut);
  1165. $this->db->free($resql);
  1166. return $result;
  1167. } else {
  1168. $this->error = $this->db->error();
  1169. dol_print_error($this->db);
  1170. return -1;
  1171. }
  1172. }
  1173. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1174. /**
  1175. * Return array with list of possible values for type of contacts
  1176. *
  1177. * @param string $source 'internal', 'external' or 'all'
  1178. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1179. * @param int $option 0=Return array id->label, 1=Return array code->label
  1180. * @param int $activeonly 0=all status of contact, 1=only the active
  1181. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1182. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1183. */
  1184. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1185. {
  1186. // phpcs:enable
  1187. global $langs;
  1188. if (empty($order)) {
  1189. $order = 'position';
  1190. }
  1191. if ($order == 'position') {
  1192. $order .= ',code';
  1193. }
  1194. $tab = array();
  1195. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1196. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1197. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1198. if ($activeonly == 1) {
  1199. $sql .= " AND tc.active=1"; // only the active types
  1200. }
  1201. if (!empty($source) && $source != 'all') {
  1202. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1203. }
  1204. if (!empty($code)) {
  1205. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1206. }
  1207. $sql .= $this->db->order($order, 'ASC');
  1208. //print "sql=".$sql;
  1209. $resql = $this->db->query($sql);
  1210. if ($resql) {
  1211. $num = $this->db->num_rows($resql);
  1212. $i = 0;
  1213. while ($i < $num) {
  1214. $obj = $this->db->fetch_object($resql);
  1215. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1216. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1217. if (empty($option)) {
  1218. $tab[$obj->rowid] = $libelle_type;
  1219. } else {
  1220. $tab[$obj->code] = $libelle_type;
  1221. }
  1222. $i++;
  1223. }
  1224. return $tab;
  1225. } else {
  1226. $this->error = $this->db->lasterror();
  1227. //dol_print_error($this->db);
  1228. return null;
  1229. }
  1230. }
  1231. /**
  1232. * Return array with list of possible values for type of contacts
  1233. *
  1234. * @param string $source 'internal', 'external' or 'all'
  1235. * @param int $option 0=Return array id->label, 1=Return array code->label
  1236. * @param int $activeonly 0=all status of contact, 1=only the active
  1237. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1238. * @param string $element Filter on 1 element type
  1239. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1240. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1241. */
  1242. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1243. {
  1244. global $langs, $conf;
  1245. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1246. $tab = array();
  1247. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1248. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1249. $sqlWhere = array();
  1250. if (!empty($element)) {
  1251. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1252. }
  1253. if (!empty($excludeelement)) {
  1254. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1255. }
  1256. if ($activeonly == 1) {
  1257. $sqlWhere[] = " tc.active=1"; // only the active types
  1258. }
  1259. if (!empty($source) && $source != 'all') {
  1260. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1261. }
  1262. if (!empty($code)) {
  1263. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1264. }
  1265. if (count($sqlWhere) > 0) {
  1266. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1267. }
  1268. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1269. dol_syslog(__METHOD__, LOG_DEBUG);
  1270. $resql = $this->db->query($sql);
  1271. if ($resql) {
  1272. $num = $this->db->num_rows($resql);
  1273. if ($num > 0) {
  1274. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1275. while ($obj = $this->db->fetch_object($resql)) {
  1276. $modulename = $obj->element;
  1277. if (strpos($obj->element, 'project') !== false) {
  1278. $modulename = 'projet';
  1279. } elseif ($obj->element == 'contrat') {
  1280. $element = 'contract';
  1281. } elseif ($obj->element == 'action') {
  1282. $modulename = 'agenda';
  1283. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1284. $modulename = 'fournisseur';
  1285. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1286. $modulename = 'fournisseur';
  1287. }
  1288. if (!empty($conf->{$modulename}->enabled)) {
  1289. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1290. $tmpelement = $obj->element;
  1291. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1292. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1293. if (empty($option)) {
  1294. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1295. } else {
  1296. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1297. }
  1298. }
  1299. }
  1300. }
  1301. return $tab;
  1302. } else {
  1303. $this->error = $this->db->lasterror();
  1304. return null;
  1305. }
  1306. }
  1307. /**
  1308. * Return id of contacts for a source and a contact code.
  1309. * Example: contact client de facturation ('external', 'BILLING')
  1310. * Example: contact client de livraison ('external', 'SHIPPING')
  1311. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1312. *
  1313. * @param string $source 'external' or 'internal'
  1314. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1315. * @param int $status limited to a certain status
  1316. * @return array List of id for such contacts
  1317. */
  1318. public function getIdContact($source, $code, $status = 0)
  1319. {
  1320. global $conf;
  1321. $result = array();
  1322. $i = 0;
  1323. //cas particulier pour les expeditions
  1324. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1325. $id = $this->origin_id;
  1326. $element = 'commande';
  1327. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1328. $id = $this->origin_id;
  1329. $element = 'order_supplier';
  1330. } else {
  1331. $id = $this->id;
  1332. $element = $this->element;
  1333. }
  1334. $sql = "SELECT ec.fk_socpeople";
  1335. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1336. if ($source == 'internal') {
  1337. $sql .= " ".$this->db->prefix()."user as c,";
  1338. }
  1339. if ($source == 'external') {
  1340. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1341. }
  1342. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1343. $sql .= " WHERE ec.element_id = ".((int) $id);
  1344. $sql .= " AND ec.fk_socpeople = c.rowid";
  1345. if ($source == 'internal') {
  1346. $sql .= " AND c.entity IN (".getEntity('user').")";
  1347. }
  1348. if ($source == 'external') {
  1349. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1350. }
  1351. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1352. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1353. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1354. if ($code) {
  1355. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1356. }
  1357. $sql .= " AND tc.active = 1";
  1358. if ($status) {
  1359. $sql .= " AND ec.statut = ".((int) $status);
  1360. }
  1361. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1362. $resql = $this->db->query($sql);
  1363. if ($resql) {
  1364. while ($obj = $this->db->fetch_object($resql)) {
  1365. $result[$i] = $obj->fk_socpeople;
  1366. $i++;
  1367. }
  1368. } else {
  1369. $this->error = $this->db->error();
  1370. return null;
  1371. }
  1372. return $result;
  1373. }
  1374. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1375. /**
  1376. * Load object contact with id=$this->contact_id into $this->contact
  1377. *
  1378. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1379. * @return int <0 if KO, >0 if OK
  1380. */
  1381. public function fetch_contact($contactid = null)
  1382. {
  1383. // phpcs:enable
  1384. if (empty($contactid)) {
  1385. $contactid = $this->contact_id;
  1386. }
  1387. if (empty($contactid)) {
  1388. return 0;
  1389. }
  1390. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1391. $contact = new Contact($this->db);
  1392. $result = $contact->fetch($contactid);
  1393. $this->contact = $contact;
  1394. return $result;
  1395. }
  1396. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1397. /**
  1398. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1399. *
  1400. * @param int $force_thirdparty_id Force thirdparty id
  1401. * @return int <0 if KO, >0 if OK
  1402. */
  1403. public function fetch_thirdparty($force_thirdparty_id = 0)
  1404. {
  1405. // phpcs:enable
  1406. global $conf;
  1407. if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
  1408. return 0;
  1409. }
  1410. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1411. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
  1412. if ($force_thirdparty_id) {
  1413. $idtofetch = $force_thirdparty_id;
  1414. }
  1415. if ($idtofetch) {
  1416. $thirdparty = new Societe($this->db);
  1417. $result = $thirdparty->fetch($idtofetch);
  1418. if ($result<0) {
  1419. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1420. }
  1421. $this->thirdparty = $thirdparty;
  1422. // Use first price level if level not defined for third party
  1423. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1424. $this->thirdparty->price_level = 1;
  1425. }
  1426. return $result;
  1427. } else {
  1428. return -1;
  1429. }
  1430. }
  1431. /**
  1432. * Looks for an object with ref matching the wildcard provided
  1433. * It does only work when $this->table_ref_field is set
  1434. *
  1435. * @param string $ref Wildcard
  1436. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1437. */
  1438. public function fetchOneLike($ref)
  1439. {
  1440. if (!$this->table_ref_field) {
  1441. return 0;
  1442. }
  1443. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1444. $query = $this->db->query($sql);
  1445. if (!$this->db->num_rows($query)) {
  1446. return 0;
  1447. }
  1448. $result = $this->db->fetch_object($query);
  1449. return $this->fetch($result->rowid);
  1450. }
  1451. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1452. /**
  1453. * Load data for barcode into properties ->barcode_type*
  1454. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1455. * if it is not defined, ->element must be defined to know default barcode type.
  1456. *
  1457. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1458. */
  1459. public function fetch_barcode()
  1460. {
  1461. // phpcs:enable
  1462. global $conf;
  1463. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1464. $idtype = $this->barcode_type;
  1465. 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
  1466. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1467. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1468. } elseif ($this->element == 'societe') {
  1469. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1470. } else {
  1471. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1472. }
  1473. }
  1474. if ($idtype > 0) {
  1475. 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
  1476. $sql = "SELECT rowid, code, libelle as label, coder";
  1477. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1478. $sql .= " WHERE rowid = ".((int) $idtype);
  1479. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1480. $resql = $this->db->query($sql);
  1481. if ($resql) {
  1482. $obj = $this->db->fetch_object($resql);
  1483. $this->barcode_type = $obj->rowid;
  1484. $this->barcode_type_code = $obj->code;
  1485. $this->barcode_type_label = $obj->label;
  1486. $this->barcode_type_coder = $obj->coder;
  1487. return 1;
  1488. } else {
  1489. dol_print_error($this->db);
  1490. return -1;
  1491. }
  1492. }
  1493. }
  1494. return 0;
  1495. }
  1496. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1497. /**
  1498. * Load the project with id $this->fk_project into this->project
  1499. *
  1500. * @return int <0 if KO, >=0 if OK
  1501. */
  1502. public function fetch_project()
  1503. {
  1504. // phpcs:enable
  1505. return $this->fetch_projet();
  1506. }
  1507. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1508. /**
  1509. * Load the project with id $this->fk_project into this->project
  1510. *
  1511. * @return int <0 if KO, >=0 if OK
  1512. */
  1513. public function fetch_projet()
  1514. {
  1515. // phpcs:enable
  1516. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1517. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1518. $this->fk_project = $this->fk_projet; // For backward compatibility
  1519. }
  1520. if (empty($this->fk_project)) {
  1521. return 0;
  1522. }
  1523. $project = new Project($this->db);
  1524. $result = $project->fetch($this->fk_project);
  1525. $this->projet = $project; // deprecated
  1526. $this->project = $project;
  1527. return $result;
  1528. }
  1529. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1530. /**
  1531. * Load the product with id $this->fk_product into this->product
  1532. *
  1533. * @return int <0 if KO, >=0 if OK
  1534. */
  1535. public function fetch_product()
  1536. {
  1537. // phpcs:enable
  1538. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1539. if (empty($this->fk_product)) {
  1540. return 0;
  1541. }
  1542. $product = new Product($this->db);
  1543. $result = $product->fetch($this->fk_product);
  1544. $this->product = $product;
  1545. return $result;
  1546. }
  1547. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1548. /**
  1549. * Load the user with id $userid into this->user
  1550. *
  1551. * @param int $userid Id du contact
  1552. * @return int <0 if KO, >0 if OK
  1553. */
  1554. public function fetch_user($userid)
  1555. {
  1556. // phpcs:enable
  1557. $user = new User($this->db);
  1558. $result = $user->fetch($userid);
  1559. $this->user = $user;
  1560. return $result;
  1561. }
  1562. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1563. /**
  1564. * Read linked origin object
  1565. *
  1566. * @return void
  1567. */
  1568. public function fetch_origin()
  1569. {
  1570. // phpcs:enable
  1571. if ($this->origin == 'shipping') {
  1572. $this->origin = 'expedition';
  1573. }
  1574. if ($this->origin == 'delivery') {
  1575. $this->origin = 'livraison';
  1576. }
  1577. if ($this->origin == 'order_supplier') {
  1578. $this->origin = 'commandeFournisseur';
  1579. }
  1580. $origin = $this->origin;
  1581. $classname = ucfirst($origin);
  1582. $this->$origin = new $classname($this->db);
  1583. $this->$origin->fetch($this->origin_id);
  1584. }
  1585. /**
  1586. * Load object from specific field
  1587. *
  1588. * @param string $table Table element or element line
  1589. * @param string $field Field selected
  1590. * @param string $key Import key
  1591. * @param string $element Element name
  1592. * @return int <0 if KO, >0 if OK
  1593. */
  1594. public function fetchObjectFrom($table, $field, $key, $element = null)
  1595. {
  1596. global $conf;
  1597. $result = false;
  1598. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1599. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1600. if (!empty($element)) {
  1601. $sql .= " AND entity IN (".getEntity($element).")";
  1602. } else {
  1603. $sql .= " AND entity = ".((int) $conf->entity);
  1604. }
  1605. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1606. $resql = $this->db->query($sql);
  1607. if ($resql) {
  1608. $row = $this->db->fetch_row($resql);
  1609. // Test for avoid error -1
  1610. if ($row[0] > 0) {
  1611. $result = $this->fetch($row[0]);
  1612. }
  1613. }
  1614. return $result;
  1615. }
  1616. /**
  1617. * Getter generic. Load value from a specific field
  1618. *
  1619. * @param string $table Table of element or element line
  1620. * @param int $id Element id
  1621. * @param string $field Field selected
  1622. * @return int <0 if KO, >0 if OK
  1623. */
  1624. public function getValueFrom($table, $id, $field)
  1625. {
  1626. $result = false;
  1627. if (!empty($id) && !empty($field) && !empty($table)) {
  1628. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1629. $sql .= " WHERE rowid = ".((int) $id);
  1630. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1631. $resql = $this->db->query($sql);
  1632. if ($resql) {
  1633. $row = $this->db->fetch_row($resql);
  1634. $result = $row[0];
  1635. }
  1636. }
  1637. return $result;
  1638. }
  1639. /**
  1640. * Setter generic. Update a specific field into database.
  1641. * Warning: Trigger is run only if param trigkey is provided.
  1642. *
  1643. * @param string $field Field to update
  1644. * @param mixed $value New value
  1645. * @param string $table To force other table element or element line (should not be used)
  1646. * @param int $id To force other object id (should not be used)
  1647. * @param string $format Data format ('text', 'int', 'date'). 'text' is used if not defined
  1648. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1649. * @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'
  1650. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1651. * @param string $fk_user_field Name of field to save user id making change
  1652. * @return int <0 if KO, >0 if OK
  1653. * @see updateExtraField()
  1654. */
  1655. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1656. {
  1657. global $user, $langs, $conf;
  1658. if (empty($table)) {
  1659. $table = $this->table_element;
  1660. }
  1661. if (empty($id)) {
  1662. $id = $this->id;
  1663. }
  1664. if (empty($format)) {
  1665. $format = 'text';
  1666. }
  1667. if (empty($id_field)) {
  1668. $id_field = 'rowid';
  1669. }
  1670. // Special case
  1671. if ($table == 'product' && $field == 'note_private') {
  1672. $field = 'note';
  1673. }
  1674. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1675. $fk_user_field = 'fk_user_mod';
  1676. }
  1677. if ($trigkey) {
  1678. $oldvalue = null;
  1679. $sql = "SELECT " . $field;
  1680. $sql .= " FROM " . MAIN_DB_PREFIX . $table;
  1681. $sql .= " WHERE " . $id_field . " = " . ((int) $id);
  1682. $resql = $this->db->query($sql);
  1683. if ($resql) {
  1684. if ($obj = $this->db->fetch_object($resql)) {
  1685. if ($format == 'date') {
  1686. $oldvalue = $this->db->jdate($obj->$field);
  1687. } else {
  1688. $oldvalue = $obj->$field;
  1689. }
  1690. }
  1691. } else {
  1692. $this->error = $this->db->lasterror();
  1693. return -1;
  1694. }
  1695. }
  1696. $error = 0;
  1697. dol_syslog(__METHOD__, LOG_DEBUG);
  1698. $this->db->begin();
  1699. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1700. if ($format == 'text') {
  1701. $sql .= $field." = '".$this->db->escape($value)."'";
  1702. } elseif ($format == 'int') {
  1703. $sql .= $field." = ".((int) $value);
  1704. } elseif ($format == 'date') {
  1705. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1706. } elseif ($format == 'dategmt') {
  1707. $sql .= $field." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null");
  1708. }
  1709. if ($fk_user_field) {
  1710. if (!empty($fuser) && is_object($fuser)) {
  1711. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1712. } elseif (empty($fuser) || $fuser != 'none') {
  1713. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1714. }
  1715. }
  1716. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1717. $resql = $this->db->query($sql);
  1718. if ($resql) {
  1719. if ($trigkey) {
  1720. // call trigger with updated object values
  1721. if (method_exists($this, 'fetch')) {
  1722. $result = $this->fetch($id);
  1723. } else {
  1724. $result = $this->fetchCommon($id);
  1725. }
  1726. $this->oldcopy = clone $this;
  1727. if (property_exists($this->oldcopy, $field)) {
  1728. $this->oldcopy->$field = $oldvalue;
  1729. }
  1730. if ($result >= 0) {
  1731. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1732. }
  1733. if ($result < 0) {
  1734. $error++;
  1735. }
  1736. }
  1737. if (!$error) {
  1738. if (property_exists($this, $field)) {
  1739. $this->$field = $value;
  1740. }
  1741. $this->db->commit();
  1742. return 1;
  1743. } else {
  1744. $this->db->rollback();
  1745. return -2;
  1746. }
  1747. } else {
  1748. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1749. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1750. } else {
  1751. $this->error = $this->db->lasterror();
  1752. }
  1753. $this->db->rollback();
  1754. return -1;
  1755. }
  1756. }
  1757. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1758. /**
  1759. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1760. *
  1761. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1762. * @param string $fieldid Name of field to use for the select MAX and MIN
  1763. * @param int $nodbprefix Do not include DB prefix to forge table name
  1764. * @return int <0 if KO, >0 if OK
  1765. */
  1766. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1767. {
  1768. // phpcs:enable
  1769. global $conf, $user;
  1770. if (!$this->table_element) {
  1771. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1772. return -1;
  1773. }
  1774. if ($fieldid == 'none') {
  1775. return 1;
  1776. }
  1777. // For backward compatibility
  1778. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1779. $fieldid = 'titre';
  1780. }
  1781. // Security on socid
  1782. $socid = 0;
  1783. if ($user->socid > 0) {
  1784. $socid = $user->socid;
  1785. }
  1786. // this->ismultientitymanaged contains
  1787. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1788. $aliastablesociete = 's';
  1789. if ($this->element == 'societe') {
  1790. $aliastablesociete = 'te'; // te as table_element
  1791. }
  1792. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1793. $sql = "SELECT MAX(te.".$fieldid.")";
  1794. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1795. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1796. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1797. }
  1798. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1799. $tmparray = explode('@', $this->ismultientitymanaged);
  1800. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1801. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1802. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1803. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1804. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1805. }
  1806. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1807. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1808. }
  1809. $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)
  1810. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1811. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1812. }
  1813. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1814. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1815. }
  1816. if (!empty($filter)) {
  1817. if (!preg_match('/^\s*AND/i', $filter)) {
  1818. $sql .= " AND "; // For backward compatibility
  1819. }
  1820. $sql .= $filter;
  1821. }
  1822. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1823. $tmparray = explode('@', $this->ismultientitymanaged);
  1824. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1825. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1826. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1827. }
  1828. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1829. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1830. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1831. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1832. } else {
  1833. $sql .= " AND ug.fk_user = te.rowid";
  1834. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1835. }
  1836. } else {
  1837. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1838. }
  1839. }
  1840. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1841. $tmparray = explode('@', $this->ismultientitymanaged);
  1842. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1843. }
  1844. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1845. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1846. }
  1847. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1848. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1849. }
  1850. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1851. $sql .= ' AND te.rowid = '.((int) $socid);
  1852. }
  1853. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1854. $result = $this->db->query($sql);
  1855. if (!$result) {
  1856. $this->error = $this->db->lasterror();
  1857. return -1;
  1858. }
  1859. $row = $this->db->fetch_row($result);
  1860. $this->ref_previous = $row[0];
  1861. $sql = "SELECT MIN(te.".$fieldid.")";
  1862. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1863. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1864. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1865. }
  1866. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1867. $tmparray = explode('@', $this->ismultientitymanaged);
  1868. $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1869. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1870. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1871. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1872. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1873. }
  1874. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1875. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1876. }
  1877. $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)
  1878. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1879. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1880. }
  1881. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1882. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1883. }
  1884. if (!empty($filter)) {
  1885. if (!preg_match('/^\s*AND/i', $filter)) {
  1886. $sql .= " AND "; // For backward compatibility
  1887. }
  1888. $sql .= $filter;
  1889. }
  1890. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1891. $tmparray = explode('@', $this->ismultientitymanaged);
  1892. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1893. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1894. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1895. }
  1896. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1897. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1898. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1899. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1900. } else {
  1901. $sql .= " AND ug.fk_user = te.rowid";
  1902. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1903. }
  1904. } else {
  1905. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1906. }
  1907. }
  1908. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1909. $tmparray = explode('@', $this->ismultientitymanaged);
  1910. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1911. }
  1912. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1913. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1914. }
  1915. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1916. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1917. }
  1918. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1919. $sql .= ' AND te.rowid = '.((int) $socid);
  1920. }
  1921. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1922. // 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
  1923. $result = $this->db->query($sql);
  1924. if (!$result) {
  1925. $this->error = $this->db->lasterror();
  1926. return -2;
  1927. }
  1928. $row = $this->db->fetch_row($result);
  1929. $this->ref_next = $row[0];
  1930. return 1;
  1931. }
  1932. /**
  1933. * Return list of id of contacts of object
  1934. *
  1935. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1936. * @return array Array of id of contacts (if source=external or internal)
  1937. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1938. */
  1939. public function getListContactId($source = 'external')
  1940. {
  1941. $contactAlreadySelected = array();
  1942. $tab = $this->liste_contact(-1, $source);
  1943. $num = count($tab);
  1944. $i = 0;
  1945. while ($i < $num) {
  1946. if ($source == 'thirdparty') {
  1947. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1948. } else {
  1949. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1950. }
  1951. $i++;
  1952. }
  1953. return $contactAlreadySelected;
  1954. }
  1955. /**
  1956. * Link element with a project
  1957. *
  1958. * @param int $projectid Project id to link element to
  1959. * @param int $notrigger Disable the trigger
  1960. * @return int <0 if KO, >0 if OK
  1961. */
  1962. public function setProject($projectid, $notrigger = 0)
  1963. {
  1964. global $user;
  1965. $error = 0;
  1966. if (!$this->table_element) {
  1967. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1968. return -1;
  1969. }
  1970. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  1971. if (!empty($this->fields['fk_project'])) { // Common case
  1972. if ($projectid) {
  1973. $sql .= " SET fk_project = ".((int) $projectid);
  1974. } else {
  1975. $sql .= " SET fk_project = NULL";
  1976. }
  1977. $sql .= ' WHERE rowid = '.((int) $this->id);
  1978. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  1979. if ($projectid) {
  1980. $sql .= " SET fk_project = ".((int) $projectid);
  1981. } else {
  1982. $sql .= " SET fk_project = NULL";
  1983. }
  1984. $sql .= ' WHERE id = '.((int) $this->id);
  1985. } else // Special case for old architecture objects
  1986. {
  1987. if ($projectid) {
  1988. $sql .= ' SET fk_projet = '.((int) $projectid);
  1989. } else {
  1990. $sql .= ' SET fk_projet = NULL';
  1991. }
  1992. $sql .= " WHERE rowid = ".((int) $this->id);
  1993. }
  1994. $this->db->begin();
  1995. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1996. if ($this->db->query($sql)) {
  1997. $this->fk_project = ((int) $projectid);
  1998. } else {
  1999. dol_print_error($this->db);
  2000. $error++;
  2001. }
  2002. // Triggers
  2003. if (!$error && !$notrigger) {
  2004. // Call triggers
  2005. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2006. if ($result < 0) {
  2007. $error++;
  2008. } //Do also here what you must do to rollback action if trigger fail
  2009. // End call triggers
  2010. }
  2011. // Commit or rollback
  2012. if ($error) {
  2013. $this->db->rollback();
  2014. return -1;
  2015. } else {
  2016. $this->db->commit();
  2017. return 1;
  2018. }
  2019. }
  2020. /**
  2021. * Change the payments methods
  2022. *
  2023. * @param int $id Id of new payment method
  2024. * @return int >0 if OK, <0 if KO
  2025. */
  2026. public function setPaymentMethods($id)
  2027. {
  2028. global $user;
  2029. $error = 0; $notrigger = 0;
  2030. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2031. if ($this->statut >= 0 || $this->element == 'societe') {
  2032. // TODO uniformize field name
  2033. $fieldname = 'fk_mode_reglement';
  2034. if ($this->element == 'societe') {
  2035. $fieldname = 'mode_reglement';
  2036. }
  2037. if (get_class($this) == 'Fournisseur') {
  2038. $fieldname = 'mode_reglement_supplier';
  2039. }
  2040. if (get_class($this) == 'Tva') {
  2041. $fieldname = 'fk_typepayment';
  2042. }
  2043. if (get_class($this) == 'Salary') {
  2044. $fieldname = 'fk_typepayment';
  2045. }
  2046. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2047. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2048. $sql .= ' WHERE rowid='.((int) $this->id);
  2049. if ($this->db->query($sql)) {
  2050. $this->mode_reglement_id = $id;
  2051. // for supplier
  2052. if (get_class($this) == 'Fournisseur') {
  2053. $this->mode_reglement_supplier_id = $id;
  2054. }
  2055. // Triggers
  2056. if (!$error && !$notrigger) {
  2057. // Call triggers
  2058. if (get_class($this) == 'Commande') {
  2059. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2060. } else {
  2061. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2062. }
  2063. if ($result < 0) {
  2064. $error++;
  2065. }
  2066. // End call triggers
  2067. }
  2068. return 1;
  2069. } else {
  2070. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2071. $this->error = $this->db->error();
  2072. return -1;
  2073. }
  2074. } else {
  2075. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2076. $this->error = 'Status of the object is incompatible '.$this->statut;
  2077. return -2;
  2078. }
  2079. }
  2080. /**
  2081. * Change the multicurrency code
  2082. *
  2083. * @param string $code multicurrency code
  2084. * @return int >0 if OK, <0 if KO
  2085. */
  2086. public function setMulticurrencyCode($code)
  2087. {
  2088. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2089. if ($this->statut >= 0 || $this->element == 'societe') {
  2090. $fieldname = 'multicurrency_code';
  2091. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2092. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2093. $sql .= ' WHERE rowid='.((int) $this->id);
  2094. if ($this->db->query($sql)) {
  2095. $this->multicurrency_code = $code;
  2096. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2097. if ($rate) {
  2098. $this->setMulticurrencyRate($rate, 2);
  2099. }
  2100. return 1;
  2101. } else {
  2102. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2103. $this->error = $this->db->error();
  2104. return -1;
  2105. }
  2106. } else {
  2107. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2108. $this->error = 'Status of the object is incompatible '.$this->statut;
  2109. return -2;
  2110. }
  2111. }
  2112. /**
  2113. * Change the multicurrency rate
  2114. *
  2115. * @param double $rate multicurrency rate
  2116. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2117. * @return int >0 if OK, <0 if KO
  2118. */
  2119. public function setMulticurrencyRate($rate, $mode = 1)
  2120. {
  2121. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2122. if ($this->statut >= 0 || $this->element == 'societe') {
  2123. $fieldname = 'multicurrency_tx';
  2124. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2125. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2126. $sql .= ' WHERE rowid='.((int) $this->id);
  2127. if ($this->db->query($sql)) {
  2128. $this->multicurrency_tx = $rate;
  2129. // Update line price
  2130. if (!empty($this->lines)) {
  2131. foreach ($this->lines as &$line) {
  2132. // Amounts in company currency will be recalculated
  2133. if ($mode == 1) {
  2134. $line->subprice = 0;
  2135. }
  2136. // Amounts in foreign currency will be recalculated
  2137. if ($mode == 2) {
  2138. $line->multicurrency_subprice = 0;
  2139. }
  2140. switch ($this->element) {
  2141. case 'propal':
  2142. /** @var Propal $this */
  2143. /** @var PropaleLigne $line */
  2144. $this->updateline(
  2145. $line->id,
  2146. $line->subprice,
  2147. $line->qty,
  2148. $line->remise_percent,
  2149. $line->tva_tx,
  2150. $line->localtax1_tx,
  2151. $line->localtax2_tx,
  2152. ($line->description ? $line->description : $line->desc),
  2153. 'HT',
  2154. $line->info_bits,
  2155. $line->special_code,
  2156. $line->fk_parent_line,
  2157. $line->skip_update_total,
  2158. $line->fk_fournprice,
  2159. $line->pa_ht,
  2160. $line->label,
  2161. $line->product_type,
  2162. $line->date_start,
  2163. $line->date_end,
  2164. $line->array_options,
  2165. $line->fk_unit,
  2166. $line->multicurrency_subprice
  2167. );
  2168. break;
  2169. case 'commande':
  2170. /** @var Commande $this */
  2171. /** @var OrderLine $line */
  2172. $this->updateline(
  2173. $line->id,
  2174. ($line->description ? $line->description : $line->desc),
  2175. $line->subprice,
  2176. $line->qty,
  2177. $line->remise_percent,
  2178. $line->tva_tx,
  2179. $line->localtax1_tx,
  2180. $line->localtax2_tx,
  2181. 'HT',
  2182. $line->info_bits,
  2183. $line->date_start,
  2184. $line->date_end,
  2185. $line->product_type,
  2186. $line->fk_parent_line,
  2187. $line->skip_update_total,
  2188. $line->fk_fournprice,
  2189. $line->pa_ht,
  2190. $line->label,
  2191. $line->special_code,
  2192. $line->array_options,
  2193. $line->fk_unit,
  2194. $line->multicurrency_subprice
  2195. );
  2196. break;
  2197. case 'facture':
  2198. /** @var Facture $this */
  2199. /** @var FactureLigne $line */
  2200. $this->updateline(
  2201. $line->id,
  2202. ($line->description ? $line->description : $line->desc),
  2203. $line->subprice,
  2204. $line->qty,
  2205. $line->remise_percent,
  2206. $line->date_start,
  2207. $line->date_end,
  2208. $line->tva_tx,
  2209. $line->localtax1_tx,
  2210. $line->localtax2_tx,
  2211. 'HT',
  2212. $line->info_bits,
  2213. $line->product_type,
  2214. $line->fk_parent_line,
  2215. $line->skip_update_total,
  2216. $line->fk_fournprice,
  2217. $line->pa_ht,
  2218. $line->label,
  2219. $line->special_code,
  2220. $line->array_options,
  2221. $line->situation_percent,
  2222. $line->fk_unit,
  2223. $line->multicurrency_subprice
  2224. );
  2225. break;
  2226. case 'supplier_proposal':
  2227. /** @var SupplierProposal $this */
  2228. /** @var SupplierProposalLine $line */
  2229. $this->updateline(
  2230. $line->id,
  2231. $line->subprice,
  2232. $line->qty,
  2233. $line->remise_percent,
  2234. $line->tva_tx,
  2235. $line->localtax1_tx,
  2236. $line->localtax2_tx,
  2237. ($line->description ? $line->description : $line->desc),
  2238. 'HT',
  2239. $line->info_bits,
  2240. $line->special_code,
  2241. $line->fk_parent_line,
  2242. $line->skip_update_total,
  2243. $line->fk_fournprice,
  2244. $line->pa_ht,
  2245. $line->label,
  2246. $line->product_type,
  2247. $line->array_options,
  2248. $line->ref_fourn,
  2249. $line->multicurrency_subprice
  2250. );
  2251. break;
  2252. case 'order_supplier':
  2253. /** @var CommandeFournisseur $this */
  2254. /** @var CommandeFournisseurLigne $line */
  2255. $this->updateline(
  2256. $line->id,
  2257. ($line->description ? $line->description : $line->desc),
  2258. $line->subprice,
  2259. $line->qty,
  2260. $line->remise_percent,
  2261. $line->tva_tx,
  2262. $line->localtax1_tx,
  2263. $line->localtax2_tx,
  2264. 'HT',
  2265. $line->info_bits,
  2266. $line->product_type,
  2267. false,
  2268. $line->date_start,
  2269. $line->date_end,
  2270. $line->array_options,
  2271. $line->fk_unit,
  2272. $line->multicurrency_subprice,
  2273. $line->ref_supplier
  2274. );
  2275. break;
  2276. case 'invoice_supplier':
  2277. /** @var FactureFournisseur $this */
  2278. /** @var SupplierInvoiceLine $line */
  2279. $this->updateline(
  2280. $line->id,
  2281. ($line->description ? $line->description : $line->desc),
  2282. $line->subprice,
  2283. $line->tva_tx,
  2284. $line->localtax1_tx,
  2285. $line->localtax2_tx,
  2286. $line->qty,
  2287. 0,
  2288. 'HT',
  2289. $line->info_bits,
  2290. $line->product_type,
  2291. $line->remise_percent,
  2292. false,
  2293. $line->date_start,
  2294. $line->date_end,
  2295. $line->array_options,
  2296. $line->fk_unit,
  2297. $line->multicurrency_subprice,
  2298. $line->ref_supplier
  2299. );
  2300. break;
  2301. default:
  2302. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2303. break;
  2304. }
  2305. }
  2306. }
  2307. return 1;
  2308. } else {
  2309. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2310. $this->error = $this->db->error();
  2311. return -1;
  2312. }
  2313. } else {
  2314. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2315. $this->error = 'Status of the object is incompatible '.$this->statut;
  2316. return -2;
  2317. }
  2318. }
  2319. /**
  2320. * Change the payments terms
  2321. *
  2322. * @param int $id Id of new payment terms
  2323. * @param string $deposit_percent % of deposit if needed by payment terms
  2324. * @return int >0 if OK, <0 if KO
  2325. */
  2326. public function setPaymentTerms($id, $deposit_percent = null)
  2327. {
  2328. dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
  2329. if ($this->statut >= 0 || $this->element == 'societe') {
  2330. // TODO uniformize field name
  2331. $fieldname = 'fk_cond_reglement';
  2332. if ($this->element == 'societe') {
  2333. $fieldname = 'cond_reglement';
  2334. }
  2335. if (get_class($this) == 'Fournisseur') {
  2336. $fieldname = 'cond_reglement_supplier';
  2337. }
  2338. if (empty($deposit_percent) || $deposit_percent < 0) {
  2339. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2340. }
  2341. if ($deposit_percent > 100) {
  2342. $deposit_percent = 100;
  2343. }
  2344. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2345. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2346. if (in_array($this->table_element, array('propal', 'commande', 'societe'))) {
  2347. $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
  2348. }
  2349. $sql .= ' WHERE rowid='.((int) $this->id);
  2350. if ($this->db->query($sql)) {
  2351. $this->cond_reglement_id = $id;
  2352. // for supplier
  2353. if (get_class($this) == 'Fournisseur') {
  2354. $this->cond_reglement_supplier_id = $id;
  2355. }
  2356. $this->cond_reglement = $id; // for compatibility
  2357. $this->deposit_percent = $deposit_percent;
  2358. return 1;
  2359. } else {
  2360. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2361. $this->error = $this->db->error();
  2362. return -1;
  2363. }
  2364. } else {
  2365. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2366. $this->error = 'Status of the object is incompatible '.$this->statut;
  2367. return -2;
  2368. }
  2369. }
  2370. /**
  2371. * Change the transport mode methods
  2372. *
  2373. * @param int $id Id of transport mode
  2374. * @return int >0 if OK, <0 if KO
  2375. */
  2376. public function setTransportMode($id)
  2377. {
  2378. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2379. if ($this->statut >= 0 || $this->element == 'societe') {
  2380. $fieldname = 'fk_transport_mode';
  2381. if ($this->element == 'societe') {
  2382. $fieldname = 'transport_mode';
  2383. }
  2384. if (get_class($this) == 'Fournisseur') {
  2385. $fieldname = 'transport_mode_supplier';
  2386. }
  2387. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2388. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2389. $sql .= ' WHERE rowid='.((int) $this->id);
  2390. if ($this->db->query($sql)) {
  2391. $this->transport_mode_id = $id;
  2392. // for supplier
  2393. if (get_class($this) == 'Fournisseur') {
  2394. $this->transport_mode_supplier_id = $id;
  2395. }
  2396. return 1;
  2397. } else {
  2398. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2399. $this->error = $this->db->error();
  2400. return -1;
  2401. }
  2402. } else {
  2403. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2404. $this->error = 'Status of the object is incompatible '.$this->statut;
  2405. return -2;
  2406. }
  2407. }
  2408. /**
  2409. * Change the retained warranty payments terms
  2410. *
  2411. * @param int $id Id of new payment terms
  2412. * @return int >0 if OK, <0 if KO
  2413. */
  2414. public function setRetainedWarrantyPaymentTerms($id)
  2415. {
  2416. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2417. if ($this->statut >= 0 || $this->element == 'societe') {
  2418. $fieldname = 'retained_warranty_fk_cond_reglement';
  2419. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2420. $sql .= " SET ".$fieldname." = ".((int) $id);
  2421. $sql .= ' WHERE rowid='.((int) $this->id);
  2422. if ($this->db->query($sql)) {
  2423. $this->retained_warranty_fk_cond_reglement = $id;
  2424. return 1;
  2425. } else {
  2426. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2427. $this->error = $this->db->error();
  2428. return -1;
  2429. }
  2430. } else {
  2431. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2432. $this->error = 'Status of the object is incompatible '.$this->statut;
  2433. return -2;
  2434. }
  2435. }
  2436. /**
  2437. * Define delivery address
  2438. * @deprecated
  2439. *
  2440. * @param int $id Address id
  2441. * @return int <0 si ko, >0 si ok
  2442. */
  2443. public function setDeliveryAddress($id)
  2444. {
  2445. $fieldname = 'fk_delivery_address';
  2446. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2447. $fieldname = 'fk_address';
  2448. }
  2449. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2450. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2451. if ($this->db->query($sql)) {
  2452. $this->fk_delivery_address = $id;
  2453. return 1;
  2454. } else {
  2455. $this->error = $this->db->error();
  2456. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2457. return -1;
  2458. }
  2459. }
  2460. /**
  2461. * Change the shipping method
  2462. *
  2463. * @param int $shipping_method_id Id of shipping method
  2464. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2465. * @param User $userused Object user
  2466. *
  2467. * @return int 1 if OK, 0 if KO
  2468. */
  2469. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2470. {
  2471. global $user;
  2472. if (empty($userused)) {
  2473. $userused = $user;
  2474. }
  2475. $error = 0;
  2476. if (!$this->table_element) {
  2477. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2478. return -1;
  2479. }
  2480. $this->db->begin();
  2481. if ($shipping_method_id < 0) {
  2482. $shipping_method_id = 'NULL';
  2483. }
  2484. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2485. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2486. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2487. $sql .= " WHERE rowid=".((int) $this->id);
  2488. $resql = $this->db->query($sql);
  2489. if (!$resql) {
  2490. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2491. $this->error = $this->db->lasterror();
  2492. $error++;
  2493. } else {
  2494. if (!$notrigger) {
  2495. // Call trigger
  2496. $this->context = array('shippingmethodupdate'=>1);
  2497. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2498. if ($result < 0) {
  2499. $error++;
  2500. }
  2501. // End call trigger
  2502. }
  2503. }
  2504. if ($error) {
  2505. $this->db->rollback();
  2506. return -1;
  2507. } else {
  2508. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2509. $this->db->commit();
  2510. return 1;
  2511. }
  2512. }
  2513. /**
  2514. * Change the warehouse
  2515. *
  2516. * @param int $warehouse_id Id of warehouse
  2517. * @return int 1 if OK, 0 if KO
  2518. */
  2519. public function setWarehouse($warehouse_id)
  2520. {
  2521. if (!$this->table_element) {
  2522. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2523. return -1;
  2524. }
  2525. if ($warehouse_id < 0) {
  2526. $warehouse_id = 'NULL';
  2527. }
  2528. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2529. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2530. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2531. $sql .= " WHERE rowid=".((int) $this->id);
  2532. if ($this->db->query($sql)) {
  2533. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2534. return 1;
  2535. } else {
  2536. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2537. $this->error = $this->db->error();
  2538. return 0;
  2539. }
  2540. }
  2541. /**
  2542. * Set last model used by doc generator
  2543. *
  2544. * @param User $user User object that make change
  2545. * @param string $modelpdf Modele name
  2546. * @return int <0 if KO, >0 if OK
  2547. */
  2548. public function setDocModel($user, $modelpdf)
  2549. {
  2550. if (!$this->table_element) {
  2551. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2552. return -1;
  2553. }
  2554. $newmodelpdf = dol_trunc($modelpdf, 255);
  2555. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2556. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2557. $sql .= " WHERE rowid = ".((int) $this->id);
  2558. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2559. $resql = $this->db->query($sql);
  2560. if ($resql) {
  2561. $this->model_pdf = $modelpdf;
  2562. $this->modelpdf = $modelpdf; // For bakward compatibility
  2563. return 1;
  2564. } else {
  2565. dol_print_error($this->db);
  2566. return 0;
  2567. }
  2568. }
  2569. /**
  2570. * Change the bank account
  2571. *
  2572. * @param int $fk_account Id of bank account
  2573. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2574. * @param User $userused Object user
  2575. * @return int 1 if OK, 0 if KO
  2576. */
  2577. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2578. {
  2579. global $user;
  2580. if (empty($userused)) {
  2581. $userused = $user;
  2582. }
  2583. $error = 0;
  2584. if (!$this->table_element) {
  2585. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2586. return -1;
  2587. }
  2588. $this->db->begin();
  2589. if ($fk_account < 0) {
  2590. $fk_account = 'NULL';
  2591. }
  2592. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2593. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2594. $sql .= " SET fk_account = ".((int) $fk_account);
  2595. $sql .= " WHERE rowid=".((int) $this->id);
  2596. $resql = $this->db->query($sql);
  2597. if (!$resql) {
  2598. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2599. $this->error = $this->db->lasterror();
  2600. $error++;
  2601. } else {
  2602. if (!$notrigger) {
  2603. // Call trigger
  2604. $this->context = array('bankaccountupdate'=>1);
  2605. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2606. if ($result < 0) {
  2607. $error++;
  2608. }
  2609. // End call trigger
  2610. }
  2611. }
  2612. if ($error) {
  2613. $this->db->rollback();
  2614. return -1;
  2615. } else {
  2616. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2617. $this->db->commit();
  2618. return 1;
  2619. }
  2620. }
  2621. // TODO: Move line related operations to CommonObjectLine?
  2622. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2623. /**
  2624. * Save a new position (field rang) for details lines.
  2625. * You can choose to set position for lines with already a position or lines without any position defined.
  2626. *
  2627. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2628. * @param string $rowidorder ASC or DESC
  2629. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2630. * @return int <0 if KO, >0 if OK
  2631. */
  2632. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2633. {
  2634. // phpcs:enable
  2635. if (!$this->table_element_line) {
  2636. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2637. return -1;
  2638. }
  2639. if (!$this->fk_element) {
  2640. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2641. return -1;
  2642. }
  2643. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2644. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2645. $fieldposition = 'position';
  2646. }
  2647. // Count number of lines to reorder (according to choice $renum)
  2648. $nl = 0;
  2649. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2650. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2651. if (!$renum) {
  2652. $sql .= " AND " . $fieldposition . " = 0";
  2653. }
  2654. if ($renum) {
  2655. $sql .= " AND " . $fieldposition . " <> 0";
  2656. }
  2657. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2658. $resql = $this->db->query($sql);
  2659. if ($resql) {
  2660. $row = $this->db->fetch_row($resql);
  2661. $nl = $row[0];
  2662. } else {
  2663. dol_print_error($this->db);
  2664. }
  2665. if ($nl > 0) {
  2666. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2667. $rows = array();
  2668. // We first search all lines that are parent lines (for multilevel details lines)
  2669. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2670. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2671. if ($fk_parent_line) {
  2672. $sql .= ' AND fk_parent_line IS NULL';
  2673. }
  2674. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2675. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2676. $resql = $this->db->query($sql);
  2677. if ($resql) {
  2678. $i = 0;
  2679. $num = $this->db->num_rows($resql);
  2680. while ($i < $num) {
  2681. $row = $this->db->fetch_row($resql);
  2682. $rows[] = $row[0]; // Add parent line into array rows
  2683. $childrens = $this->getChildrenOfLine($row[0]);
  2684. if (!empty($childrens)) {
  2685. foreach ($childrens as $child) {
  2686. array_push($rows, $child);
  2687. }
  2688. }
  2689. $i++;
  2690. }
  2691. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2692. if (!empty($rows)) {
  2693. foreach ($rows as $key => $row) {
  2694. $this->updateRangOfLine($row, ($key + 1));
  2695. }
  2696. }
  2697. } else {
  2698. dol_print_error($this->db);
  2699. }
  2700. }
  2701. return 1;
  2702. }
  2703. /**
  2704. * Get children of line
  2705. *
  2706. * @param int $id Id of parent line
  2707. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2708. * @return array Array with list of children lines id
  2709. */
  2710. public function getChildrenOfLine($id, $includealltree = 0)
  2711. {
  2712. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2713. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2714. $fieldposition = 'position';
  2715. }
  2716. $rows = array();
  2717. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2718. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2719. $sql .= ' AND fk_parent_line = '.((int) $id);
  2720. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2721. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2722. $resql = $this->db->query($sql);
  2723. if ($resql) {
  2724. if ($this->db->num_rows($resql) > 0) {
  2725. while ($row = $this->db->fetch_row($resql)) {
  2726. $rows[] = $row[0];
  2727. if (!empty($includealltree)) {
  2728. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2729. }
  2730. }
  2731. }
  2732. }
  2733. return $rows;
  2734. }
  2735. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2736. /**
  2737. * Update a line to have a lower rank
  2738. *
  2739. * @param int $rowid Id of line
  2740. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2741. * @return void
  2742. */
  2743. public function line_up($rowid, $fk_parent_line = true)
  2744. {
  2745. // phpcs:enable
  2746. $this->line_order(false, 'ASC', $fk_parent_line);
  2747. // Get rang of line
  2748. $rang = $this->getRangOfLine($rowid);
  2749. // Update position of line
  2750. $this->updateLineUp($rowid, $rang);
  2751. }
  2752. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2753. /**
  2754. * Update a line to have a higher rank
  2755. *
  2756. * @param int $rowid Id of line
  2757. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2758. * @return void
  2759. */
  2760. public function line_down($rowid, $fk_parent_line = true)
  2761. {
  2762. // phpcs:enable
  2763. $this->line_order(false, 'ASC', $fk_parent_line);
  2764. // Get rang of line
  2765. $rang = $this->getRangOfLine($rowid);
  2766. // Get max value for rang
  2767. $max = $this->line_max();
  2768. // Update position of line
  2769. $this->updateLineDown($rowid, $rang, $max);
  2770. }
  2771. /**
  2772. * Update position of line (rang)
  2773. *
  2774. * @param int $rowid Id of line
  2775. * @param int $rang Position
  2776. * @return int <0 if KO, >0 if OK
  2777. */
  2778. public function updateRangOfLine($rowid, $rang)
  2779. {
  2780. global $hookmanager;
  2781. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2782. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2783. $fieldposition = 'position';
  2784. }
  2785. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2786. $sql .= ' WHERE rowid = '.((int) $rowid);
  2787. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2788. if (!$this->db->query($sql)) {
  2789. dol_print_error($this->db);
  2790. return -1;
  2791. } else {
  2792. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2793. $action='';
  2794. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2795. return 1;
  2796. }
  2797. }
  2798. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2799. /**
  2800. * Update position of line with ajax (rang)
  2801. *
  2802. * @param array $rows Array of rows
  2803. * @return void
  2804. */
  2805. public function line_ajaxorder($rows)
  2806. {
  2807. // phpcs:enable
  2808. $num = count($rows);
  2809. for ($i = 0; $i < $num; $i++) {
  2810. $this->updateRangOfLine($rows[$i], ($i + 1));
  2811. }
  2812. }
  2813. /**
  2814. * Update position of line up (rang)
  2815. *
  2816. * @param int $rowid Id of line
  2817. * @param int $rang Position
  2818. * @return void
  2819. */
  2820. public function updateLineUp($rowid, $rang)
  2821. {
  2822. if ($rang > 1) {
  2823. $fieldposition = 'rang';
  2824. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2825. $fieldposition = 'position';
  2826. }
  2827. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2828. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2829. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2830. if ($this->db->query($sql)) {
  2831. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2832. $sql .= ' WHERE rowid = '.((int) $rowid);
  2833. if (!$this->db->query($sql)) {
  2834. dol_print_error($this->db);
  2835. }
  2836. } else {
  2837. dol_print_error($this->db);
  2838. }
  2839. }
  2840. }
  2841. /**
  2842. * Update position of line down (rang)
  2843. *
  2844. * @param int $rowid Id of line
  2845. * @param int $rang Position
  2846. * @param int $max Max
  2847. * @return void
  2848. */
  2849. public function updateLineDown($rowid, $rang, $max)
  2850. {
  2851. if ($rang < $max) {
  2852. $fieldposition = 'rang';
  2853. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2854. $fieldposition = 'position';
  2855. }
  2856. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2857. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2858. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2859. if ($this->db->query($sql)) {
  2860. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2861. $sql .= ' WHERE rowid = '.((int) $rowid);
  2862. if (!$this->db->query($sql)) {
  2863. dol_print_error($this->db);
  2864. }
  2865. } else {
  2866. dol_print_error($this->db);
  2867. }
  2868. }
  2869. }
  2870. /**
  2871. * Get position of line (rang)
  2872. *
  2873. * @param int $rowid Id of line
  2874. * @return int Value of rang in table of lines
  2875. */
  2876. public function getRangOfLine($rowid)
  2877. {
  2878. $fieldposition = 'rang';
  2879. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2880. $fieldposition = 'position';
  2881. }
  2882. $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  2883. $sql .= " WHERE rowid = ".((int) $rowid);
  2884. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2885. $resql = $this->db->query($sql);
  2886. if ($resql) {
  2887. $row = $this->db->fetch_row($resql);
  2888. return $row[0];
  2889. }
  2890. return 0;
  2891. }
  2892. /**
  2893. * Get rowid of the line relative to its position
  2894. *
  2895. * @param int $rang Rang value
  2896. * @return int Rowid of the line
  2897. */
  2898. public function getIdOfLine($rang)
  2899. {
  2900. $fieldposition = 'rang';
  2901. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2902. $fieldposition = 'position';
  2903. }
  2904. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2905. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2906. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  2907. $resql = $this->db->query($sql);
  2908. if ($resql) {
  2909. $row = $this->db->fetch_row($resql);
  2910. return $row[0];
  2911. }
  2912. return 0;
  2913. }
  2914. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2915. /**
  2916. * Get max value used for position of line (rang)
  2917. *
  2918. * @param int $fk_parent_line Parent line id
  2919. * @return int Max value of rang in table of lines
  2920. */
  2921. public function line_max($fk_parent_line = 0)
  2922. {
  2923. // phpcs:enable
  2924. $positionfield = 'rang';
  2925. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  2926. $positionfield = 'position';
  2927. }
  2928. // Search the last rang with fk_parent_line
  2929. if ($fk_parent_line) {
  2930. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2931. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2932. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  2933. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2934. $resql = $this->db->query($sql);
  2935. if ($resql) {
  2936. $row = $this->db->fetch_row($resql);
  2937. if (!empty($row[0])) {
  2938. return $row[0];
  2939. } else {
  2940. return $this->getRangOfLine($fk_parent_line);
  2941. }
  2942. }
  2943. } else {
  2944. // If not, search the last rang of element
  2945. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2946. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2947. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2948. $resql = $this->db->query($sql);
  2949. if ($resql) {
  2950. $row = $this->db->fetch_row($resql);
  2951. return $row[0];
  2952. }
  2953. }
  2954. return 0;
  2955. }
  2956. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2957. /**
  2958. * Update external ref of element
  2959. *
  2960. * @param string $ref_ext Update field ref_ext
  2961. * @return int <0 if KO, >0 if OK
  2962. */
  2963. public function update_ref_ext($ref_ext)
  2964. {
  2965. // phpcs:enable
  2966. if (!$this->table_element) {
  2967. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2968. return -1;
  2969. }
  2970. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2971. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2972. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  2973. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2974. if ($this->db->query($sql)) {
  2975. $this->ref_ext = $ref_ext;
  2976. return 1;
  2977. } else {
  2978. $this->error = $this->db->error();
  2979. return -1;
  2980. }
  2981. }
  2982. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2983. /**
  2984. * Update note of element
  2985. *
  2986. * @param string $note New value for note
  2987. * @param string $suffix '', '_public' or '_private'
  2988. * @return int <0 if KO, >0 if OK
  2989. */
  2990. public function update_note($note, $suffix = '')
  2991. {
  2992. // phpcs:enable
  2993. global $user;
  2994. if (!$this->table_element) {
  2995. $this->error = 'update_note was called on objet with property table_element not defined';
  2996. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2997. return -1;
  2998. }
  2999. if (!in_array($suffix, array('', '_public', '_private'))) {
  3000. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3001. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3002. return -2;
  3003. }
  3004. $newsuffix = $suffix;
  3005. // Special cas
  3006. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3007. $newsuffix = '';
  3008. }
  3009. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3010. $fieldusermod = "fk_user_mod";
  3011. } elseif ($this->table_element == 'ecm_files') {
  3012. $fieldusermod = "fk_user_m";
  3013. } else {
  3014. $fieldusermod = "fk_user_modif";
  3015. }
  3016. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3017. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  3018. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  3019. $sql .= " WHERE rowid = ".((int) $this->id);
  3020. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  3021. if ($this->db->query($sql)) {
  3022. if ($suffix == '_public') {
  3023. $this->note_public = $note;
  3024. } elseif ($suffix == '_private') {
  3025. $this->note_private = $note;
  3026. } else {
  3027. $this->note = $note; // deprecated
  3028. $this->note_private = $note;
  3029. }
  3030. return 1;
  3031. } else {
  3032. $this->error = $this->db->lasterror();
  3033. return -1;
  3034. }
  3035. }
  3036. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3037. /**
  3038. * Update public note (kept for backward compatibility)
  3039. *
  3040. * @param string $note New value for note
  3041. * @return int <0 if KO, >0 if OK
  3042. * @deprecated
  3043. * @see update_note()
  3044. */
  3045. public function update_note_public($note)
  3046. {
  3047. // phpcs:enable
  3048. return $this->update_note($note, '_public');
  3049. }
  3050. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3051. /**
  3052. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3053. * Must be called at end of methods addline or updateline.
  3054. *
  3055. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3056. * @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
  3057. * @param int $nodatabaseupdate 1=Do not update database total fields of the main object. Update only properties in memory. Can be used to save SQL when this method is called several times, so we can do it only once at end.
  3058. * @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 (used to analyze lines to check corrupted data).
  3059. * @return int <0 if KO, >0 if OK
  3060. */
  3061. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3062. {
  3063. // phpcs:enable
  3064. global $conf, $hookmanager, $action;
  3065. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3066. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3067. if ($reshook > 0) {
  3068. return 1; // replacement code
  3069. } elseif ($reshook < 0) {
  3070. return -1; // failure
  3071. } // reshook = 0 => execute normal code
  3072. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3073. $MODULE = "";
  3074. if ($this->element == 'propal') {
  3075. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3076. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3077. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3078. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3079. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3080. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3081. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3082. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3083. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3084. } elseif ($this->element == 'supplier_proposal') {
  3085. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3086. }
  3087. if (!empty($MODULE)) {
  3088. if (!empty($conf->global->$MODULE)) {
  3089. $modsactivated = explode(',', $conf->global->$MODULE);
  3090. foreach ($modsactivated as $mod) {
  3091. if (isModEnabled($mod)) {
  3092. return 1; // update was disabled by specific setup
  3093. }
  3094. }
  3095. }
  3096. }
  3097. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3098. $forcedroundingmode = $roundingadjust;
  3099. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3100. $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
  3101. } elseif ($forcedroundingmode == 'auto') {
  3102. $forcedroundingmode = '0';
  3103. }
  3104. $error = 0;
  3105. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3106. // Define constants to find lines to sum (field name int the table_element_line not into table_element)
  3107. $fieldtva = 'total_tva';
  3108. $fieldlocaltax1 = 'total_localtax1';
  3109. $fieldlocaltax2 = 'total_localtax2';
  3110. $fieldup = 'subprice';
  3111. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3112. $fieldtva = 'tva';
  3113. $fieldup = 'pu_ht';
  3114. }
  3115. if ($this->element == 'invoice_supplier_rec') {
  3116. $fieldup = 'pu_ht';
  3117. }
  3118. if ($this->element == 'expensereport') {
  3119. $fieldup = 'value_unit';
  3120. }
  3121. $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,";
  3122. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3123. if ($this->table_element_line == 'facturedet') {
  3124. $sql .= ', situation_percent';
  3125. }
  3126. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3127. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3128. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3129. if ($exclspec) {
  3130. $product_field = 'product_type';
  3131. if ($this->table_element_line == 'contratdet') {
  3132. $product_field = ''; // contratdet table has no product_type field
  3133. }
  3134. if ($product_field) {
  3135. $sql .= " AND ".$product_field." <> 9";
  3136. }
  3137. }
  3138. $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
  3139. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3140. $resql = $this->db->query($sql);
  3141. if ($resql) {
  3142. $this->total_ht = 0;
  3143. $this->total_tva = 0;
  3144. $this->total_localtax1 = 0;
  3145. $this->total_localtax2 = 0;
  3146. $this->total_ttc = 0;
  3147. $total_ht_by_vats = array();
  3148. $total_tva_by_vats = array();
  3149. $total_ttc_by_vats = array();
  3150. $this->multicurrency_total_ht = 0;
  3151. $this->multicurrency_total_tva = 0;
  3152. $this->multicurrency_total_ttc = 0;
  3153. $num = $this->db->num_rows($resql);
  3154. $i = 0;
  3155. while ($i < $num) {
  3156. $obj = $this->db->fetch_object($resql);
  3157. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3158. $parameters = array('fk_element' => $obj->rowid);
  3159. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3160. 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'
  3161. // This part of code is to fix data. We should not call it too often.
  3162. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3163. $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);
  3164. $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price and unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
  3165. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3166. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
  3167. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3168. if ($diff_on_current_total) {
  3169. // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
  3170. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3171. dol_syslog('We found unconsistent data into detailed line (diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (ht=".$obj->total_ht." vat=".$obj->total_tva." tax1=".$obj->total_localtax1." tax2=".$obj->total_localtax2." ttc=".$obj->total_ttc."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
  3172. $resqlfix = $this->db->query($sqlfix);
  3173. if (!$resqlfix) {
  3174. dol_print_error($this->db, 'Failed to update line');
  3175. }
  3176. $obj->total_tva = $tmpcal[1];
  3177. $obj->total_ttc = $tmpcal[2];
  3178. } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
  3179. // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
  3180. // we ask to force the use of rounding on line (like done on calculation) so we force update of line
  3181. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
  3182. dol_syslog('We found a line with different rounding 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);
  3183. $resqlfix = $this->db->query($sqlfix);
  3184. if (!$resqlfix) {
  3185. dol_print_error($this->db, 'Failed to update line');
  3186. }
  3187. $obj->total_tva = $tmpcal[1];
  3188. $obj->total_ttc = $tmpcal[2];
  3189. }
  3190. }
  3191. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3192. $this->total_tva += $obj->total_tva;
  3193. $this->total_localtax1 += $obj->total_localtax1;
  3194. $this->total_localtax2 += $obj->total_localtax2;
  3195. $this->total_ttc += $obj->total_ttc;
  3196. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3197. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3198. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3199. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3200. $total_ht_by_vats[$obj->vatrate] = 0;
  3201. }
  3202. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3203. $total_tva_by_vats[$obj->vatrate] = 0;
  3204. }
  3205. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3206. $total_ttc_by_vats[$obj->vatrate] = 0;
  3207. }
  3208. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3209. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3210. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3211. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3212. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3213. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3214. //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";
  3215. if ($diff) {
  3216. if (abs($diff) > 0.1) {
  3217. $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.';
  3218. dol_syslog($errmsg, LOG_WARNING);
  3219. dol_print_error('', $errmsg);
  3220. exit;
  3221. }
  3222. $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - $diff).", total_ttc = ".price2num($obj->total_ttc - $diff)." WHERE rowid = ".((int) $obj->rowid);
  3223. 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);
  3224. $resqlfix = $this->db->query($sqlfix);
  3225. if (!$resqlfix) {
  3226. dol_print_error($this->db, 'Failed to update line');
  3227. }
  3228. $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
  3229. $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
  3230. $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
  3231. $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
  3232. }
  3233. }
  3234. $i++;
  3235. }
  3236. // Add revenue stamp to total
  3237. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3238. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3239. // Situations totals
  3240. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3241. $prev_sits = $this->get_prev_sits();
  3242. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3243. $this->total_ht -= $sit->total_ht;
  3244. $this->total_tva -= $sit->total_tva;
  3245. $this->total_localtax1 -= $sit->total_localtax1;
  3246. $this->total_localtax2 -= $sit->total_localtax2;
  3247. $this->total_ttc -= $sit->total_ttc;
  3248. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3249. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3250. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3251. }
  3252. }
  3253. // Clean total
  3254. $this->total_ht = (float) price2num($this->total_ht);
  3255. $this->total_tva = (float) price2num($this->total_tva);
  3256. $this->total_localtax1 = (float) price2num($this->total_localtax1);
  3257. $this->total_localtax2 = (float) price2num($this->total_localtax2);
  3258. $this->total_ttc = (float) price2num($this->total_ttc);
  3259. $this->db->free($resql);
  3260. // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
  3261. $fieldht = 'total_ht';
  3262. $fieldtva = 'tva';
  3263. $fieldlocaltax1 = 'localtax1';
  3264. $fieldlocaltax2 = 'localtax2';
  3265. $fieldttc = 'total_ttc';
  3266. // Specific code for backward compatibility with old field names
  3267. if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
  3268. $fieldtva = 'total_tva';
  3269. }
  3270. if (empty($nodatabaseupdate)) {
  3271. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3272. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
  3273. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
  3274. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
  3275. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
  3276. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
  3277. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3278. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3279. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3280. $sql .= " WHERE rowid = ".((int) $this->id);
  3281. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3282. $resql = $this->db->query($sql);
  3283. if (!$resql) {
  3284. $error++;
  3285. $this->error = $this->db->lasterror();
  3286. $this->errors[] = $this->db->lasterror();
  3287. }
  3288. }
  3289. if (!$error) {
  3290. return 1;
  3291. } else {
  3292. return -1;
  3293. }
  3294. } else {
  3295. dol_print_error($this->db, 'Bad request in update_price');
  3296. return -1;
  3297. }
  3298. }
  3299. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3300. /**
  3301. * Add an object link into llx_element_element.
  3302. *
  3303. * @param string $origin Linked element type
  3304. * @param int $origin_id Linked element id
  3305. * @param User $f_user User that create
  3306. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3307. * @return int <=0 if KO, >0 if OK
  3308. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3309. */
  3310. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3311. {
  3312. // phpcs:enable
  3313. global $user, $hookmanager, $action;
  3314. $origin = (!empty($origin) ? $origin : $this->origin);
  3315. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3316. $f_user = isset($f_user) ? $f_user : $user;
  3317. // Special case
  3318. if ($origin == 'order') {
  3319. $origin = 'commande';
  3320. }
  3321. if ($origin == 'invoice') {
  3322. $origin = 'facture';
  3323. }
  3324. if ($origin == 'invoice_template') {
  3325. $origin = 'facturerec';
  3326. }
  3327. if ($origin == 'supplierorder') {
  3328. $origin = 'order_supplier';
  3329. }
  3330. // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
  3331. // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
  3332. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3333. // Add module part to target type if object has $module property and isn't in core modules.
  3334. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3335. $parameters = array('targettype'=>$targettype);
  3336. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3337. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3338. if ($reshook > 0) {
  3339. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3340. }
  3341. $this->db->begin();
  3342. $error = 0;
  3343. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3344. $sql .= "fk_source";
  3345. $sql .= ", sourcetype";
  3346. $sql .= ", fk_target";
  3347. $sql .= ", targettype";
  3348. $sql .= ") VALUES (";
  3349. $sql .= ((int) $origin_id);
  3350. $sql .= ", '" . $this->db->escape($origin) . "'";
  3351. $sql .= ", " . ((int) $this->id);
  3352. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3353. $sql .= ")";
  3354. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3355. if ($this->db->query($sql)) {
  3356. if (!$notrigger) {
  3357. // Call trigger
  3358. $this->context['link_origin'] = $origin;
  3359. $this->context['link_origin_id'] = $origin_id;
  3360. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3361. if ($result < 0) {
  3362. $error++;
  3363. }
  3364. // End call triggers
  3365. }
  3366. } else {
  3367. $this->error = $this->db->lasterror();
  3368. $error++;
  3369. }
  3370. if (!$error) {
  3371. $this->db->commit();
  3372. return 1;
  3373. } else {
  3374. $this->db->rollback();
  3375. return 0;
  3376. }
  3377. }
  3378. /**
  3379. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3380. * this->linkedObjectsIds array +
  3381. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3382. * Possible usage for parameters:
  3383. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3384. * - source id+type -> will get list of targets linked to source
  3385. * - target id+type -> will get list of sources linked to target
  3386. * - source id+type + target type -> will get list of targets of the type linked to source
  3387. * - target id+type + source type -> will get list of sources of the type linked to target
  3388. *
  3389. * @param int $sourceid Object source id (if not defined, id of object)
  3390. * @param string $sourcetype Object source type (if not defined, element name of object)
  3391. * @param int $targetid Object target id (if not defined, id of object)
  3392. * @param string $targettype Object target type (if not defined, element name of object)
  3393. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3394. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3395. * @param string $orderby SQL 'ORDER BY' clause
  3396. * @param int|string $loadalsoobjects Load also array this->linkedObjects. Use 0 to increase performances, Use 1 to load all, Use value of type ('facture', 'facturerec', ...) to load only a type of object.
  3397. * @return int <0 if KO, >0 if OK
  3398. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3399. */
  3400. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3401. {
  3402. global $conf, $hookmanager, $action;
  3403. // Important for pdf generation time reduction
  3404. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3405. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3406. return 1;
  3407. }
  3408. $this->linkedObjectsIds = array();
  3409. $this->linkedObjects = array();
  3410. $justsource = false;
  3411. $justtarget = false;
  3412. $withtargettype = false;
  3413. $withsourcetype = false;
  3414. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3415. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3416. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3417. if ($reshook > 0) {
  3418. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3419. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3420. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3421. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3422. }
  3423. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3424. $justsource = true; // the source (id and type) is a search criteria
  3425. if (!empty($targettype)) {
  3426. $withtargettype = true;
  3427. }
  3428. }
  3429. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3430. $justtarget = true; // the target (id and type) is a search criteria
  3431. if (!empty($sourcetype)) {
  3432. $withsourcetype = true;
  3433. }
  3434. }
  3435. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3436. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3437. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3438. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3439. /*if (empty($sourceid) && empty($targetid))
  3440. {
  3441. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3442. return -1;
  3443. }*/
  3444. // Links between objects are stored in table element_element
  3445. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3446. $sql .= " FROM ".$this->db->prefix()."element_element";
  3447. $sql .= " WHERE ";
  3448. if ($justsource || $justtarget) {
  3449. if ($justsource) {
  3450. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3451. if ($withtargettype) {
  3452. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3453. }
  3454. } elseif ($justtarget) {
  3455. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3456. if ($withsourcetype) {
  3457. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3458. }
  3459. }
  3460. } else {
  3461. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3462. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3463. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3464. $this->linkedObjectsFullLoaded[$this->id] = true;
  3465. }
  3466. }
  3467. $sql .= " ORDER BY ".$orderby;
  3468. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3469. $resql = $this->db->query($sql);
  3470. if ($resql) {
  3471. $num = $this->db->num_rows($resql);
  3472. $i = 0;
  3473. while ($i < $num) {
  3474. $obj = $this->db->fetch_object($resql);
  3475. if ($justsource || $justtarget) {
  3476. if ($justsource) {
  3477. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3478. } elseif ($justtarget) {
  3479. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3480. }
  3481. } else {
  3482. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3483. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3484. }
  3485. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3486. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3487. }
  3488. }
  3489. $i++;
  3490. }
  3491. if (!empty($this->linkedObjectsIds)) {
  3492. $tmparray = $this->linkedObjectsIds;
  3493. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3494. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3495. $module = $element = $subelement = $objecttype;
  3496. $regs = array();
  3497. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3498. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3499. $module = $element = $regs[1];
  3500. $subelement = $regs[2];
  3501. }
  3502. $classpath = $element.'/class';
  3503. // To work with non standard classpath or module name
  3504. if ($objecttype == 'facture') {
  3505. $classpath = 'compta/facture/class';
  3506. } elseif ($objecttype == 'facturerec') {
  3507. $classpath = 'compta/facture/class';
  3508. $module = 'facture';
  3509. } elseif ($objecttype == 'propal') {
  3510. $classpath = 'comm/propal/class';
  3511. } elseif ($objecttype == 'supplier_proposal') {
  3512. $classpath = 'supplier_proposal/class';
  3513. } elseif ($objecttype == 'shipping') {
  3514. $classpath = 'expedition/class';
  3515. $subelement = 'expedition';
  3516. $module = 'expedition';
  3517. } elseif ($objecttype == 'delivery') {
  3518. $classpath = 'delivery/class';
  3519. $subelement = 'delivery';
  3520. $module = 'delivery_note';
  3521. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3522. $classpath = 'fourn/class';
  3523. $module = 'fournisseur';
  3524. } elseif ($objecttype == 'fichinter') {
  3525. $classpath = 'fichinter/class';
  3526. $subelement = 'fichinter';
  3527. $module = 'ficheinter';
  3528. } elseif ($objecttype == 'subscription') {
  3529. $classpath = 'adherents/class';
  3530. $module = 'adherent';
  3531. } elseif ($objecttype == 'contact') {
  3532. $module = 'societe';
  3533. }
  3534. // Set classfile
  3535. $classfile = strtolower($subelement);
  3536. $classname = ucfirst($subelement);
  3537. if ($objecttype == 'order') {
  3538. $classfile = 'commande';
  3539. $classname = 'Commande';
  3540. } elseif ($objecttype == 'invoice_supplier') {
  3541. $classfile = 'fournisseur.facture';
  3542. $classname = 'FactureFournisseur';
  3543. } elseif ($objecttype == 'order_supplier') {
  3544. $classfile = 'fournisseur.commande';
  3545. $classname = 'CommandeFournisseur';
  3546. } elseif ($objecttype == 'supplier_proposal') {
  3547. $classfile = 'supplier_proposal';
  3548. $classname = 'SupplierProposal';
  3549. } elseif ($objecttype == 'facturerec') {
  3550. $classfile = 'facture-rec';
  3551. $classname = 'FactureRec';
  3552. } elseif ($objecttype == 'subscription') {
  3553. $classfile = 'subscription';
  3554. $classname = 'Subscription';
  3555. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3556. $classpath = 'projet/class';
  3557. $classfile = 'project';
  3558. $classname = 'Project';
  3559. } elseif ($objecttype == 'conferenceorboothattendee') {
  3560. $classpath = 'eventorganization/class';
  3561. $classfile = 'conferenceorboothattendee';
  3562. $classname = 'ConferenceOrBoothAttendee';
  3563. $module = 'eventorganization';
  3564. } elseif ($objecttype == 'conferenceorbooth') {
  3565. $classpath = 'eventorganization/class';
  3566. $classfile = 'conferenceorbooth';
  3567. $classname = 'ConferenceOrBooth';
  3568. $module = 'eventorganization';
  3569. } elseif ($objecttype == 'mo') {
  3570. $classpath = 'mrp/class';
  3571. $classfile = 'mo';
  3572. $classname = 'Mo';
  3573. $module = 'mrp';
  3574. }
  3575. // Here $module, $classfile and $classname are set, we can use them.
  3576. if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
  3577. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3578. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3579. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3580. if (class_exists($classname)) {
  3581. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3582. $object = new $classname($this->db);
  3583. $ret = $object->fetch($objectid);
  3584. if ($ret >= 0) {
  3585. $this->linkedObjects[$objecttype][$i] = $object;
  3586. }
  3587. }
  3588. }
  3589. }
  3590. } else {
  3591. unset($this->linkedObjectsIds[$objecttype]);
  3592. }
  3593. }
  3594. }
  3595. return 1;
  3596. } else {
  3597. dol_print_error($this->db);
  3598. return -1;
  3599. }
  3600. }
  3601. /**
  3602. * Clear the cache saying that all linked object were already loaded. So next fetchObjectLinked will reload all links.
  3603. *
  3604. * @return int <0 if KO, >0 if OK
  3605. * @see fetchObjectLinked()
  3606. */
  3607. public function clearObjectLinkedCache()
  3608. {
  3609. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3610. unset($this->linkedObjectsFullLoaded[$this->id]);
  3611. }
  3612. return 1;
  3613. }
  3614. /**
  3615. * Update object linked of a current object
  3616. *
  3617. * @param int $sourceid Object source id
  3618. * @param string $sourcetype Object source type
  3619. * @param int $targetid Object target id
  3620. * @param string $targettype Object target type
  3621. * @param User $f_user User that create
  3622. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3623. * @return int >0 if OK, <0 if KO
  3624. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3625. */
  3626. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3627. {
  3628. global $user;
  3629. $updatesource = false;
  3630. $updatetarget = false;
  3631. $f_user = isset($f_user) ? $f_user : $user;
  3632. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3633. $updatesource = true;
  3634. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3635. $updatetarget = true;
  3636. }
  3637. $this->db->begin();
  3638. $error = 0;
  3639. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3640. if ($updatesource) {
  3641. $sql .= "fk_source = " . ((int) $sourceid);
  3642. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3643. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3644. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3645. } elseif ($updatetarget) {
  3646. $sql .= "fk_target = " . ((int) $targetid);
  3647. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3648. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3649. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3650. }
  3651. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3652. if ($this->db->query($sql)) {
  3653. if (!$notrigger) {
  3654. // Call trigger
  3655. $this->context['link_source_id'] = $sourceid;
  3656. $this->context['link_source_type'] = $sourcetype;
  3657. $this->context['link_target_id'] = $targetid;
  3658. $this->context['link_target_type'] = $targettype;
  3659. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3660. if ($result < 0) {
  3661. $error++;
  3662. }
  3663. // End call triggers
  3664. }
  3665. } else {
  3666. $this->error = $this->db->lasterror();
  3667. $error++;
  3668. }
  3669. if (!$error) {
  3670. $this->db->commit();
  3671. return 1;
  3672. } else {
  3673. $this->db->rollback();
  3674. return -1;
  3675. }
  3676. }
  3677. /**
  3678. * Delete all links between an object $this
  3679. *
  3680. * @param int $sourceid Object source id
  3681. * @param string $sourcetype Object source type
  3682. * @param int $targetid Object target id
  3683. * @param string $targettype Object target type
  3684. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3685. * @param User $f_user User that create
  3686. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3687. * @return int >0 if OK, <0 if KO
  3688. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3689. */
  3690. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3691. {
  3692. global $user;
  3693. $deletesource = false;
  3694. $deletetarget = false;
  3695. $f_user = isset($f_user) ? $f_user : $user;
  3696. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3697. $deletesource = true;
  3698. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3699. $deletetarget = true;
  3700. }
  3701. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3702. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3703. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3704. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3705. $this->db->begin();
  3706. $error = 0;
  3707. if (!$notrigger) {
  3708. // Call trigger
  3709. $this->context['link_id'] = $rowid;
  3710. $this->context['link_source_id'] = $sourceid;
  3711. $this->context['link_source_type'] = $sourcetype;
  3712. $this->context['link_target_id'] = $targetid;
  3713. $this->context['link_target_type'] = $targettype;
  3714. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3715. if ($result < 0) {
  3716. $error++;
  3717. }
  3718. // End call triggers
  3719. }
  3720. if (!$error) {
  3721. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3722. $sql .= " WHERE";
  3723. if ($rowid > 0) {
  3724. $sql .= " rowid = " . ((int) $rowid);
  3725. } else {
  3726. if ($deletesource) {
  3727. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3728. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3729. } elseif ($deletetarget) {
  3730. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3731. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3732. } else {
  3733. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3734. $sql .= " OR";
  3735. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3736. }
  3737. }
  3738. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3739. if (!$this->db->query($sql)) {
  3740. $this->error = $this->db->lasterror();
  3741. $this->errors[] = $this->error;
  3742. $error++;
  3743. }
  3744. }
  3745. if (!$error) {
  3746. $this->db->commit();
  3747. return 1;
  3748. } else {
  3749. $this->db->rollback();
  3750. return 0;
  3751. }
  3752. }
  3753. /**
  3754. * Function used to get an array with all items linked to an object id in association table
  3755. *
  3756. * @param int $fk_object_where id of object we need to get linked items
  3757. * @param string $field_select name of field we need to get a list
  3758. * @param string $field_where name of field of object we need to get linked items
  3759. * @param string $table_element name of association table
  3760. * @return array|int Array of record, -1 if empty
  3761. */
  3762. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3763. {
  3764. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3765. return -1;
  3766. }
  3767. global $db;
  3768. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3769. $resql = $db->query($sql);
  3770. $TRes = array();
  3771. if (!empty($resql)) {
  3772. while ($res = $db->fetch_object($resql)) {
  3773. $TRes[] = $res->{$field_select};
  3774. }
  3775. }
  3776. return $TRes;
  3777. }
  3778. /**
  3779. * Function used to remove all items linked to an object id in association table
  3780. *
  3781. * @param int $fk_object_where id of object we need to remove linked items
  3782. * @param string $field_where name of field of object we need to delete linked items
  3783. * @param string $table_element name of association table
  3784. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3785. */
  3786. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3787. {
  3788. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3789. return -1;
  3790. }
  3791. global $db;
  3792. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3793. $resql = $db->query($sql);
  3794. if (empty($resql)) {
  3795. return 0;
  3796. }
  3797. return 1;
  3798. }
  3799. /**
  3800. * Set status of an object.
  3801. *
  3802. * @param int $status Status to set
  3803. * @param int $elementId Id of element to force (use this->id by default if null)
  3804. * @param string $elementType Type of element to force (use this->table_element by default)
  3805. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated.
  3806. * @param string $fieldstatus Name of status field in this->table_element
  3807. * @return int <0 if KO, >0 if OK
  3808. */
  3809. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3810. {
  3811. global $user, $langs, $conf;
  3812. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3813. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3814. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3815. $this->db->begin();
  3816. if ($elementTable == 'facture_rec') {
  3817. $fieldstatus = "suspended";
  3818. }
  3819. if ($elementTable == 'mailing') {
  3820. $fieldstatus = "statut";
  3821. }
  3822. if ($elementTable == 'cronjob') {
  3823. $fieldstatus = "status";
  3824. }
  3825. if ($elementTable == 'user') {
  3826. $fieldstatus = "statut";
  3827. }
  3828. if ($elementTable == 'expensereport') {
  3829. $fieldstatus = "fk_statut";
  3830. }
  3831. if ($elementTable == 'commande_fournisseur_dispatch') {
  3832. $fieldstatus = "status";
  3833. }
  3834. if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3835. $fieldstatus = 'status';
  3836. }
  3837. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3838. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3839. // If status = 1 = validated, update also fk_user_valid
  3840. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3841. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3842. $sql .= ", fk_user_valid = ".((int) $user->id);
  3843. }
  3844. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3845. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3846. }
  3847. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3848. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3849. }
  3850. $sql .= " WHERE rowid = ".((int) $elementId);
  3851. $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
  3852. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3853. $resql = $this->db->query($sql);
  3854. if ($resql) {
  3855. $error = 0;
  3856. $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
  3857. if ($nb_rows_affected > 0) {
  3858. if (empty($trigkey)) {
  3859. // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
  3860. if ($this->element == 'supplier_proposal' && $status == 2) {
  3861. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3862. }
  3863. if ($this->element == 'supplier_proposal' && $status == 3) {
  3864. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3865. }
  3866. if ($this->element == 'supplier_proposal' && $status == 4) {
  3867. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3868. }
  3869. if ($this->element == 'fichinter' && $status == 3) {
  3870. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3871. }
  3872. if ($this->element == 'fichinter' && $status == 2) {
  3873. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3874. }
  3875. if ($this->element == 'fichinter' && $status == 1) {
  3876. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3877. }
  3878. }
  3879. if ($trigkey) {
  3880. // Call trigger
  3881. $result = $this->call_trigger($trigkey, $user);
  3882. if ($result < 0) {
  3883. $error++;
  3884. }
  3885. // End call triggers
  3886. }
  3887. } else {
  3888. // The status was probably already good. We do nothing more, no triggers.
  3889. }
  3890. if (!$error) {
  3891. $this->db->commit();
  3892. if (empty($savElementId)) {
  3893. // If the element we update is $this (so $elementId was provided as null)
  3894. if ($fieldstatus == 'tosell') {
  3895. $this->status = $status;
  3896. } elseif ($fieldstatus == 'tobuy') {
  3897. $this->status_buy = $status;
  3898. } else {
  3899. $this->statut = $status;
  3900. $this->status = $status;
  3901. }
  3902. }
  3903. return 1;
  3904. } else {
  3905. $this->db->rollback();
  3906. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3907. return -1;
  3908. }
  3909. } else {
  3910. $this->error = $this->db->lasterror();
  3911. $this->db->rollback();
  3912. return -1;
  3913. }
  3914. }
  3915. /**
  3916. * Load type of canvas of an object if it exists
  3917. *
  3918. * @param int $id Record id
  3919. * @param string $ref Record ref
  3920. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3921. */
  3922. public function getCanvas($id = 0, $ref = '')
  3923. {
  3924. global $conf;
  3925. if (empty($id) && empty($ref)) {
  3926. return 0;
  3927. }
  3928. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3929. return 0; // To increase speed. Not enabled by default.
  3930. }
  3931. // Clean parameters
  3932. $ref = trim($ref);
  3933. $sql = "SELECT rowid, canvas";
  3934. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  3935. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3936. if (!empty($id)) {
  3937. $sql .= " AND rowid = ".((int) $id);
  3938. }
  3939. if (!empty($ref)) {
  3940. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3941. }
  3942. $resql = $this->db->query($sql);
  3943. if ($resql) {
  3944. $obj = $this->db->fetch_object($resql);
  3945. if ($obj) {
  3946. $this->canvas = $obj->canvas;
  3947. return 1;
  3948. } else {
  3949. return 0;
  3950. }
  3951. } else {
  3952. dol_print_error($this->db);
  3953. return -1;
  3954. }
  3955. }
  3956. /**
  3957. * Get special code of a line
  3958. *
  3959. * @param int $lineid Id of line
  3960. * @return int Special code
  3961. */
  3962. public function getSpecialCode($lineid)
  3963. {
  3964. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  3965. $sql .= " WHERE rowid = ".((int) $lineid);
  3966. $resql = $this->db->query($sql);
  3967. if ($resql) {
  3968. $row = $this->db->fetch_row($resql);
  3969. return $row[0];
  3970. }
  3971. return 0;
  3972. }
  3973. /**
  3974. * Function to check if an object is used by others (by children).
  3975. * Check is done into this->childtables. There is no check into llx_element_element.
  3976. *
  3977. * @param int $id Force id of object
  3978. * @param int $entity Force entity to check
  3979. * @return int <0 if KO, 0 if not used, >0 if already used
  3980. */
  3981. public function isObjectUsed($id = 0, $entity = 0)
  3982. {
  3983. global $langs;
  3984. if (empty($id)) {
  3985. $id = $this->id;
  3986. }
  3987. // Check parameters
  3988. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3989. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3990. return -1;
  3991. }
  3992. $arraytoscan = $this->childtables; // array('tablename'=>array('fk_element'=>'parentfield'), ...) or array('tablename'=>array('parent'=>table_parent, 'parentkey'=>'nameoffieldforparentfkkey'), ...)
  3993. // For backward compatibility, we check if array is old format array('tablename1', 'tablename2', ...)
  3994. $tmparray = array_keys($this->childtables);
  3995. if (is_numeric($tmparray[0])) {
  3996. $arraytoscan = array_flip($this->childtables);
  3997. }
  3998. // Test if child exists
  3999. $haschild = 0;
  4000. foreach ($arraytoscan as $table => $element) {
  4001. //print $id.'-'.$table.'-'.$elementname.'<br>';
  4002. // Check if element can be deleted
  4003. $sql = "SELECT COUNT(*) as nb";
  4004. $sql.= " FROM ".$this->db->prefix().$table." as c";
  4005. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4006. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  4007. }
  4008. if (!empty($element['fk_element'])) {
  4009. $sql.= " WHERE c.".$element['fk_element']." = ".((int) $id);
  4010. } else {
  4011. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  4012. }
  4013. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4014. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  4015. }
  4016. if (!empty($element['parent']) && !empty($element['parenttypefield']) && !empty($element['parenttypevalue'])) {
  4017. $sql.= " AND c.".$element['parenttypefield']." = '".$this->db->escape($element['parenttypevalue'])."'";
  4018. }
  4019. if (!empty($entity)) {
  4020. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4021. $sql.= " AND p.entity = ".((int) $entity);
  4022. } else {
  4023. $sql.= " AND c.entity = ".((int) $entity);
  4024. }
  4025. }
  4026. $resql = $this->db->query($sql);
  4027. if ($resql) {
  4028. $obj = $this->db->fetch_object($resql);
  4029. if ($obj->nb > 0) {
  4030. $langs->load("errors");
  4031. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4032. $haschild += $obj->nb;
  4033. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4034. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4035. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4036. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4037. } else { // new usage: $element['name']=Translation key
  4038. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4039. }
  4040. break; // We found at least one, we stop here
  4041. }
  4042. } else {
  4043. $this->errors[] = $this->db->lasterror();
  4044. return -1;
  4045. }
  4046. }
  4047. if ($haschild > 0) {
  4048. $this->errors[] = "ErrorRecordHasChildren";
  4049. return $haschild;
  4050. } else {
  4051. return 0;
  4052. }
  4053. }
  4054. /**
  4055. * Function to say how many lines object contains
  4056. *
  4057. * @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
  4058. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4059. */
  4060. public function hasProductsOrServices($predefined = -1)
  4061. {
  4062. $nb = 0;
  4063. foreach ($this->lines as $key => $val) {
  4064. $qualified = 0;
  4065. if ($predefined == -1) {
  4066. $qualified = 1;
  4067. }
  4068. if ($predefined == 1 && $val->fk_product > 0) {
  4069. $qualified = 1;
  4070. }
  4071. if ($predefined == 0 && $val->fk_product <= 0) {
  4072. $qualified = 1;
  4073. }
  4074. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4075. $qualified = 1;
  4076. }
  4077. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4078. $qualified = 1;
  4079. }
  4080. if ($qualified) {
  4081. $nb++;
  4082. }
  4083. }
  4084. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4085. return $nb;
  4086. }
  4087. /**
  4088. * Function that returns the total amount HT of discounts applied for all lines.
  4089. *
  4090. * @return float|string Total amout of discount
  4091. */
  4092. public function getTotalDiscount()
  4093. {
  4094. if (!empty($this->table_element_line) ) {
  4095. $total_discount = 0.00;
  4096. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4097. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4098. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4099. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4100. $resql = $this->db->query($sql);
  4101. if ($resql) {
  4102. $num = $this->db->num_rows($resql);
  4103. $i = 0;
  4104. while ($i < $num) {
  4105. $obj = $this->db->fetch_object($resql);
  4106. $pu_ht = $obj->pu_ht;
  4107. $qty = $obj->qty;
  4108. $total_ht = $obj->total_ht;
  4109. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4110. $total_discount += $total_discount_line;
  4111. $i++;
  4112. }
  4113. }
  4114. //print $total_discount; exit;
  4115. return price2num($total_discount);
  4116. }
  4117. return null;
  4118. }
  4119. /**
  4120. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4121. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4122. *
  4123. * @return array array('weight'=>...,'volume'=>...)
  4124. */
  4125. public function getTotalWeightVolume()
  4126. {
  4127. $totalWeight = 0;
  4128. $totalVolume = 0;
  4129. // defined for shipment only
  4130. $totalOrdered = '';
  4131. // defined for shipment only
  4132. $totalToShip = '';
  4133. foreach ($this->lines as $line) {
  4134. if (isset($line->qty_asked)) {
  4135. if (empty($totalOrdered)) {
  4136. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4137. }
  4138. $totalOrdered += $line->qty_asked; // defined for shipment only
  4139. }
  4140. if (isset($line->qty_shipped)) {
  4141. if (empty($totalToShip)) {
  4142. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4143. }
  4144. $totalToShip += $line->qty_shipped; // defined for shipment only
  4145. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4146. if (empty($totalToShip)) {
  4147. $totalToShip = 0;
  4148. }
  4149. $totalToShip += $line->qty; // defined for reception only
  4150. }
  4151. // Define qty, weight, volume, weight_units, volume_units
  4152. if ($this->element == 'shipping') {
  4153. // for shipments
  4154. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4155. } else {
  4156. $qty = $line->qty ? $line->qty : 0;
  4157. }
  4158. $weight = !empty($line->weight) ? $line->weight : 0;
  4159. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4160. $volume = !empty($line->volume) ? $line->volume : 0;
  4161. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4162. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4163. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4164. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4165. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4166. $weightUnit = 0;
  4167. $volumeUnit = 0;
  4168. if (!empty($weight_units)) {
  4169. $weightUnit = $weight_units;
  4170. }
  4171. if (!empty($volume_units)) {
  4172. $volumeUnit = $volume_units;
  4173. }
  4174. if (empty($totalWeight)) {
  4175. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4176. }
  4177. if (empty($totalVolume)) {
  4178. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4179. }
  4180. //var_dump($line->volume_units);
  4181. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4182. $trueWeightUnit = pow(10, $weightUnit);
  4183. $totalWeight += $weight * $qty * $trueWeightUnit;
  4184. } else {
  4185. if ($weight_units == 99) {
  4186. // conversion 1 Pound = 0.45359237 KG
  4187. $trueWeightUnit = 0.45359237;
  4188. $totalWeight += $weight * $qty * $trueWeightUnit;
  4189. } elseif ($weight_units == 98) {
  4190. // conversion 1 Ounce = 0.0283495 KG
  4191. $trueWeightUnit = 0.0283495;
  4192. $totalWeight += $weight * $qty * $trueWeightUnit;
  4193. } else {
  4194. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4195. }
  4196. }
  4197. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4198. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4199. $trueVolumeUnit = pow(10, $volumeUnit);
  4200. //print $line->volume;
  4201. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4202. } else {
  4203. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4204. }
  4205. }
  4206. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4207. }
  4208. /**
  4209. * Set extra parameters
  4210. *
  4211. * @return int <0 if KO, >0 if OK
  4212. */
  4213. public function setExtraParameters()
  4214. {
  4215. $this->db->begin();
  4216. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4217. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4218. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4219. $sql .= " WHERE rowid = ".((int) $this->id);
  4220. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4221. $resql = $this->db->query($sql);
  4222. if (!$resql) {
  4223. $this->error = $this->db->lasterror();
  4224. $this->db->rollback();
  4225. return -1;
  4226. } else {
  4227. $this->db->commit();
  4228. return 1;
  4229. }
  4230. }
  4231. // --------------------
  4232. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4233. // --------------------
  4234. /* This is to show add lines */
  4235. /**
  4236. * Show add free and predefined products/services form
  4237. *
  4238. * @param int $dateSelector 1=Show also date range input fields
  4239. * @param Societe $seller Object thirdparty who sell
  4240. * @param Societe $buyer Object thirdparty who buy
  4241. * @param string $defaulttpldir Directory where to find the template
  4242. * @return void
  4243. */
  4244. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4245. {
  4246. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4247. global $form;
  4248. // Line extrafield
  4249. if (!is_object($extrafields)) {
  4250. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4251. $extrafields = new ExtraFields($this->db);
  4252. }
  4253. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4254. // Output template part (modules that overwrite templates must declare this into descriptor)
  4255. // Use global variables + $dateSelector + $seller and $buyer
  4256. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4257. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4258. foreach ($dirtpls as $module => $reldir) {
  4259. if (!empty($module)) {
  4260. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4261. } else {
  4262. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4263. }
  4264. if (empty($conf->file->strict_mode)) {
  4265. $res = @include $tpl;
  4266. } else {
  4267. $res = include $tpl; // for debug
  4268. }
  4269. if ($res) {
  4270. break;
  4271. }
  4272. }
  4273. }
  4274. /* This is to show array of line of details */
  4275. /**
  4276. * Return HTML table for object lines
  4277. * TODO Move this into an output class file (htmlline.class.php)
  4278. * If lines are into a template, title must also be into a template
  4279. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4280. *
  4281. * @param string $action Action code
  4282. * @param Societe $seller Object of seller third party
  4283. * @param Societe $buyer Object of buyer third party
  4284. * @param int $selected ID line selected
  4285. * @param int $dateSelector 1=Show also date range input fields
  4286. * @param string $defaulttpldir Directory where to find the template
  4287. * @return void
  4288. */
  4289. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4290. {
  4291. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4292. // TODO We should not use global var for this
  4293. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4294. // Define usemargins
  4295. $usemargins = 0;
  4296. if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4297. $usemargins = 1;
  4298. }
  4299. $num = count($this->lines);
  4300. // Line extrafield
  4301. if (!is_object($extrafields)) {
  4302. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4303. $extrafields = new ExtraFields($this->db);
  4304. }
  4305. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4306. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4307. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4308. if (empty($reshook)) {
  4309. // Output template part (modules that overwrite templates must declare this into descriptor)
  4310. // Use global variables + $dateSelector + $seller and $buyer
  4311. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4312. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4313. foreach ($dirtpls as $module => $reldir) {
  4314. $res = 0;
  4315. if (!empty($module)) {
  4316. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4317. } else {
  4318. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4319. }
  4320. if (file_exists($tpl)) {
  4321. if (empty($conf->file->strict_mode)) {
  4322. $res = @include $tpl;
  4323. } else {
  4324. $res = include $tpl; // for debug
  4325. }
  4326. }
  4327. if ($res) {
  4328. break;
  4329. }
  4330. }
  4331. }
  4332. $i = 0;
  4333. print "<!-- begin printObjectLines() --><tbody>\n";
  4334. foreach ($this->lines as $line) {
  4335. //Line extrafield
  4336. $line->fetch_optionals();
  4337. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
  4338. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4339. if (empty($line->fk_parent_line)) {
  4340. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4341. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4342. } else {
  4343. $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);
  4344. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4345. }
  4346. }
  4347. if (empty($reshook)) {
  4348. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4349. }
  4350. $i++;
  4351. }
  4352. print "</tbody><!-- end printObjectLines() -->\n";
  4353. }
  4354. /**
  4355. * Return HTML content of a detail line
  4356. * TODO Move this into an output class file (htmlline.class.php)
  4357. *
  4358. * @param string $action GET/POST action
  4359. * @param CommonObjectLine $line Selected object line to output
  4360. * @param string $var Not used
  4361. * @param int $num Number of line (0)
  4362. * @param int $i I
  4363. * @param int $dateSelector 1=Show also date range input fields
  4364. * @param Societe $seller Object of seller third party
  4365. * @param Societe $buyer Object of buyer third party
  4366. * @param int $selected ID line selected
  4367. * @param Extrafields $extrafields Object of extrafields
  4368. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4369. * @return void
  4370. */
  4371. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4372. {
  4373. global $conf, $langs, $user, $object, $hookmanager;
  4374. global $form;
  4375. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4376. $object_rights = $this->getRights();
  4377. $text = '';
  4378. $description = '';
  4379. // Line in view mode
  4380. if ($action != 'editline' || $selected != $line->id) {
  4381. // Product
  4382. if (!empty($line->fk_product) && $line->fk_product > 0) {
  4383. $product_static = new Product($this->db);
  4384. $product_static->fetch($line->fk_product);
  4385. $product_static->ref = $line->ref; //can change ref in hook
  4386. $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
  4387. $text = $product_static->getNomUrl(1);
  4388. // Define output language and label
  4389. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  4390. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4391. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4392. return;
  4393. }
  4394. $prod = new Product($this->db);
  4395. $prod->fetch($line->fk_product);
  4396. $outputlangs = $langs;
  4397. $newlang = '';
  4398. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4399. $newlang = GETPOST('lang_id', 'aZ09');
  4400. }
  4401. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4402. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4403. }
  4404. if (!empty($newlang)) {
  4405. $outputlangs = new Translate("", $conf);
  4406. $outputlangs->setDefaultLang($newlang);
  4407. }
  4408. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4409. } else {
  4410. $label = $line->product_label;
  4411. }
  4412. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4413. $description .= (getDolGlobalInt('PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
  4414. }
  4415. $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
  4416. // Output template part (modules that overwrite templates must declare this into descriptor)
  4417. // Use global variables + $dateSelector + $seller and $buyer
  4418. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4419. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4420. foreach ($dirtpls as $module => $reldir) {
  4421. $res = 0;
  4422. if (!empty($module)) {
  4423. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4424. } else {
  4425. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4426. }
  4427. if (file_exists($tpl)) {
  4428. if (empty($conf->file->strict_mode)) {
  4429. $res = @include $tpl;
  4430. } else {
  4431. $res = include $tpl; // for debug
  4432. }
  4433. }
  4434. if ($res) {
  4435. break;
  4436. }
  4437. }
  4438. }
  4439. // Line in update mode
  4440. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4441. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4442. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4443. // Output template part (modules that overwrite templates must declare this into descriptor)
  4444. // Use global variables + $dateSelector + $seller and $buyer
  4445. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4446. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4447. foreach ($dirtpls as $module => $reldir) {
  4448. if (!empty($module)) {
  4449. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4450. } else {
  4451. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4452. }
  4453. if (empty($conf->file->strict_mode)) {
  4454. $res = @include $tpl;
  4455. } else {
  4456. $res = include $tpl; // for debug
  4457. }
  4458. if ($res) {
  4459. break;
  4460. }
  4461. }
  4462. }
  4463. }
  4464. /* This is to show array of line of details of source object */
  4465. /**
  4466. * Return HTML table table of source object lines
  4467. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4468. * If lines are into a template, title must also be into a template
  4469. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4470. *
  4471. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4472. * @param array $selectedLines Array of lines id for selected lines
  4473. * @return void
  4474. */
  4475. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4476. {
  4477. global $langs, $hookmanager, $conf, $form, $action;
  4478. print '<tr class="liste_titre">';
  4479. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4480. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4481. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4482. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4483. if (isModEnabled("multicurrency")) {
  4484. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4485. }
  4486. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4487. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  4488. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4489. }
  4490. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4491. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4492. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4493. print '</tr>';
  4494. $i = 0;
  4495. if (!empty($this->lines)) {
  4496. foreach ($this->lines as $line) {
  4497. $reshook = 0;
  4498. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4499. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4500. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4501. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4502. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4503. }
  4504. if (empty($reshook)) {
  4505. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4506. }
  4507. $i++;
  4508. }
  4509. }
  4510. }
  4511. /**
  4512. * Return HTML with a line of table array of source object lines
  4513. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4514. * If lines are into a template, title must also be into a template
  4515. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4516. *
  4517. * @param CommonObjectLine $line Line
  4518. * @param string $var Var
  4519. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4520. * @param string $defaulttpldir Directory where to find the template
  4521. * @param array $selectedLines Array of lines id for selected lines
  4522. * @return void
  4523. */
  4524. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4525. {
  4526. global $langs, $conf;
  4527. //var_dump($line);
  4528. if (!empty($line->date_start)) {
  4529. $date_start = $line->date_start;
  4530. } else {
  4531. $date_start = $line->date_debut_prevue;
  4532. if ($line->date_debut_reel) {
  4533. $date_start = $line->date_debut_reel;
  4534. }
  4535. }
  4536. if (!empty($line->date_end)) {
  4537. $date_end = $line->date_end;
  4538. } else {
  4539. $date_end = $line->date_fin_prevue;
  4540. if ($line->date_fin_reel) {
  4541. $date_end = $line->date_fin_reel;
  4542. }
  4543. }
  4544. $this->tpl['id'] = $line->id;
  4545. $this->tpl['label'] = '';
  4546. if (!empty($line->fk_parent_line)) {
  4547. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4548. }
  4549. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4550. $discount = new DiscountAbsolute($this->db);
  4551. $discount->fk_soc = $this->socid;
  4552. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4553. } elseif (!empty($line->fk_product)) {
  4554. $productstatic = new Product($this->db);
  4555. $productstatic->id = $line->fk_product;
  4556. $productstatic->ref = $line->ref;
  4557. $productstatic->type = $line->fk_product_type;
  4558. if (empty($productstatic->ref)) {
  4559. $line->fetch_product();
  4560. $productstatic = $line->product;
  4561. }
  4562. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4563. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4564. // Dates
  4565. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4566. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4567. }
  4568. } else {
  4569. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4570. if (!empty($line->desc)) {
  4571. $this->tpl['label'] .= $line->desc;
  4572. } else {
  4573. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4574. }
  4575. // Dates
  4576. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4577. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4578. }
  4579. }
  4580. if (!empty($line->desc)) {
  4581. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4582. $discount = new DiscountAbsolute($this->db);
  4583. $discount->fetch($line->fk_remise_except);
  4584. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4585. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4586. $discount = new DiscountAbsolute($this->db);
  4587. $discount->fetch($line->fk_remise_except);
  4588. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4589. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4590. $discount = new DiscountAbsolute($this->db);
  4591. $discount->fetch($line->fk_remise_except);
  4592. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4593. } elseif ($line->desc == '(EXCESS PAID)') {
  4594. $discount = new DiscountAbsolute($this->db);
  4595. $discount->fetch($line->fk_remise_except);
  4596. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4597. } else {
  4598. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4599. }
  4600. } else {
  4601. $this->tpl['description'] = '&nbsp;';
  4602. }
  4603. // VAT Rate
  4604. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4605. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4606. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4607. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4608. }
  4609. $this->tpl['price'] = price($line->subprice);
  4610. $this->tpl['total_ht'] = price($line->total_ht);
  4611. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4612. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4613. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  4614. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4615. }
  4616. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4617. // Is the line strike or not
  4618. $this->tpl['strike'] = 0;
  4619. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4620. $this->tpl['strike'] = 1;
  4621. }
  4622. // Output template part (modules that overwrite templates must declare this into descriptor)
  4623. // Use global variables + $dateSelector + $seller and $buyer
  4624. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4625. foreach ($dirtpls as $module => $reldir) {
  4626. if (!empty($module)) {
  4627. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4628. } else {
  4629. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4630. }
  4631. if (empty($conf->file->strict_mode)) {
  4632. $res = @include $tpl;
  4633. } else {
  4634. $res = include $tpl; // for debug
  4635. }
  4636. if ($res) {
  4637. break;
  4638. }
  4639. }
  4640. }
  4641. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4642. /**
  4643. * Add resources to the current object : add entry into llx_element_resources
  4644. * Need $this->element & $this->id
  4645. *
  4646. * @param int $resource_id Resource id
  4647. * @param string $resource_type 'resource'
  4648. * @param int $busy Busy or not
  4649. * @param int $mandatory Mandatory or not
  4650. * @return int <=0 if KO, >0 if OK
  4651. */
  4652. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4653. {
  4654. // phpcs:enable
  4655. $this->db->begin();
  4656. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4657. $sql .= "resource_id";
  4658. $sql .= ", resource_type";
  4659. $sql .= ", element_id";
  4660. $sql .= ", element_type";
  4661. $sql .= ", busy";
  4662. $sql .= ", mandatory";
  4663. $sql .= ") VALUES (";
  4664. $sql .= ((int) $resource_id);
  4665. $sql .= ", '".$this->db->escape($resource_type)."'";
  4666. $sql .= ", '".$this->db->escape($this->id)."'";
  4667. $sql .= ", '".$this->db->escape($this->element)."'";
  4668. $sql .= ", '".$this->db->escape($busy)."'";
  4669. $sql .= ", '".$this->db->escape($mandatory)."'";
  4670. $sql .= ")";
  4671. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4672. if ($this->db->query($sql)) {
  4673. $this->db->commit();
  4674. return 1;
  4675. } else {
  4676. $this->error = $this->db->lasterror();
  4677. $this->db->rollback();
  4678. return 0;
  4679. }
  4680. }
  4681. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4682. /**
  4683. * Delete a link to resource line
  4684. *
  4685. * @param int $rowid Id of resource line to delete
  4686. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4687. * @param int $notrigger Disable all triggers
  4688. * @return int >0 if OK, <0 if KO
  4689. */
  4690. public function delete_resource($rowid, $element, $notrigger = 0)
  4691. {
  4692. // phpcs:enable
  4693. global $user;
  4694. $this->db->begin();
  4695. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4696. $sql .= " WHERE rowid = ".((int) $rowid);
  4697. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4698. $resql = $this->db->query($sql);
  4699. if (!$resql) {
  4700. $this->error = $this->db->lasterror();
  4701. $this->db->rollback();
  4702. return -1;
  4703. } else {
  4704. if (!$notrigger) {
  4705. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4706. if ($result < 0) {
  4707. $this->db->rollback();
  4708. return -1;
  4709. }
  4710. }
  4711. $this->db->commit();
  4712. return 1;
  4713. }
  4714. }
  4715. /**
  4716. * Overwrite magic function to solve problem of cloning object that are kept as references
  4717. *
  4718. * @return void
  4719. */
  4720. public function __clone()
  4721. {
  4722. // Force a copy of this->lines, otherwise it will point to same object.
  4723. if (isset($this->lines) && is_array($this->lines)) {
  4724. $nboflines = count($this->lines);
  4725. for ($i = 0; $i < $nboflines; $i++) {
  4726. $this->lines[$i] = clone $this->lines[$i];
  4727. }
  4728. }
  4729. }
  4730. /**
  4731. * Common function for all objects extending CommonObject for generating documents
  4732. *
  4733. * @param string $modelspath Relative folder where generators are placed
  4734. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4735. * @param Translate $outputlangs Output language to use
  4736. * @param int $hidedetails 1 to hide details. 0 by default
  4737. * @param int $hidedesc 1 to hide product description. 0 by default
  4738. * @param int $hideref 1 to hide product reference. 0 by default
  4739. * @param null|array $moreparams Array to provide more information
  4740. * @return int >0 if OK, <0 if KO
  4741. * @see addFileIntoDatabaseIndex()
  4742. */
  4743. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4744. {
  4745. global $conf, $langs, $user, $hookmanager, $action;
  4746. $srctemplatepath = '';
  4747. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4748. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4749. if (!empty($reshook)) {
  4750. return $reshook;
  4751. }
  4752. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4753. if (empty($modele)) {
  4754. $this->error = 'BadValueForParameterModele';
  4755. return -1;
  4756. }
  4757. // Increase limit for PDF build
  4758. $err = error_reporting();
  4759. error_reporting(0);
  4760. @set_time_limit(120);
  4761. error_reporting($err);
  4762. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4763. $tmp = explode(':', $modele, 2);
  4764. if (!empty($tmp[1])) {
  4765. $modele = $tmp[0];
  4766. $srctemplatepath = $tmp[1];
  4767. }
  4768. // Search template files
  4769. $file = '';
  4770. $classname = '';
  4771. $filefound = '';
  4772. $dirmodels = array('/');
  4773. if (is_array($conf->modules_parts['models'])) {
  4774. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4775. }
  4776. foreach ($dirmodels as $reldir) {
  4777. foreach (array('doc', 'pdf') as $prefix) {
  4778. if (in_array(get_class($this), array('Adherent'))) {
  4779. // Member module use prefix_modele.class.php
  4780. $file = $prefix."_".$modele.".class.php";
  4781. } else {
  4782. // Other module use prefix_modele.modules.php
  4783. $file = $prefix."_".$modele.".modules.php";
  4784. }
  4785. // On verifie l'emplacement du modele
  4786. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4787. if (file_exists($file)) {
  4788. $filefound = $file;
  4789. $classname = $prefix.'_'.$modele;
  4790. break;
  4791. }
  4792. }
  4793. if ($filefound) {
  4794. break;
  4795. }
  4796. }
  4797. if (!$filefound) {
  4798. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4799. $this->errors[] = $this->error;
  4800. dol_syslog($this->error, LOG_ERR);
  4801. return -1;
  4802. }
  4803. // If generator was found
  4804. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4805. require_once $file;
  4806. $obj = new $classname($this->db);
  4807. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4808. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4809. $varfortemplatedir = $obj->scandir;
  4810. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4811. $dirtoscan = $conf->global->$varfortemplatedir;
  4812. $listoffiles = array();
  4813. // Now we add first model found in directories scanned
  4814. $listofdir = explode(',', $dirtoscan);
  4815. foreach ($listofdir as $key => $tmpdir) {
  4816. $tmpdir = trim($tmpdir);
  4817. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4818. if (!$tmpdir) {
  4819. unset($listofdir[$key]);
  4820. continue;
  4821. }
  4822. if (is_dir($tmpdir)) {
  4823. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4824. if (count($tmpfiles)) {
  4825. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4826. }
  4827. }
  4828. }
  4829. if (count($listoffiles)) {
  4830. foreach ($listoffiles as $record) {
  4831. $srctemplatepath = $record['fullname'];
  4832. break;
  4833. }
  4834. }
  4835. }
  4836. if (empty($srctemplatepath)) {
  4837. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4838. return -1;
  4839. }
  4840. }
  4841. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4842. if (!dol_is_file($srctemplatepath)) {
  4843. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4844. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4845. return -1;
  4846. }
  4847. }
  4848. // We save charset_output to restore it because write_file can change it if needed for
  4849. // output format that does not support UTF8.
  4850. $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
  4851. if (in_array(get_class($this), array('Adherent'))) {
  4852. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4853. } else {
  4854. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4855. }
  4856. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4857. if ($resultwritefile > 0) {
  4858. $outputlangs->charset_output = $sav_charset_output;
  4859. // We delete old preview
  4860. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4861. dol_delete_preview($this);
  4862. // Index file in database
  4863. if (!empty($obj->result['fullpath'])) {
  4864. $destfull = $obj->result['fullpath'];
  4865. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4866. $update_main_doc_field = 0;
  4867. if (!empty($obj->update_main_doc_field)) {
  4868. $update_main_doc_field = 1;
  4869. }
  4870. // Check that the file exists, before indexing it.
  4871. // Hint: It does not exist, if we create a PDF and auto delete the ODT File
  4872. if (dol_is_file($destfull)) {
  4873. $this->indexFile($destfull, $update_main_doc_field);
  4874. }
  4875. } else {
  4876. 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);
  4877. }
  4878. // Success in building document. We build meta file.
  4879. dol_meta_create($this);
  4880. return 1;
  4881. } else {
  4882. $outputlangs->charset_output = $sav_charset_output;
  4883. $this->error = $obj->error;
  4884. $this->errors = $obj->errors;
  4885. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  4886. return -1;
  4887. }
  4888. }
  4889. /**
  4890. * Index a file into the ECM database
  4891. *
  4892. * @param string $destfull Full path of file to index
  4893. * @param int $update_main_doc_field Update field main_doc fied into the table of object.
  4894. * This param is set when called for a document generation if document generator hase
  4895. * ->update_main_doc_field set and returns ->result['fullpath'].
  4896. * @return int <0 if KO, >0 if OK
  4897. */
  4898. public function indexFile($destfull, $update_main_doc_field)
  4899. {
  4900. global $conf, $user;
  4901. $upload_dir = dirname($destfull);
  4902. $destfile = basename($destfull);
  4903. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4904. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4905. $filename = basename($destfile);
  4906. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4907. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4908. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4909. $ecmfile = new EcmFiles($this->db);
  4910. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4911. // Set the public "share" key
  4912. $setsharekey = false;
  4913. if ($this->element == 'propal' || $this->element == 'proposal') {
  4914. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4915. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4916. }
  4917. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4918. $setsharekey = true;
  4919. }
  4920. }
  4921. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4922. $setsharekey = true;
  4923. }
  4924. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4925. $setsharekey = true;
  4926. }
  4927. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4928. $setsharekey = true;
  4929. }
  4930. if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4931. $setsharekey = true;
  4932. }
  4933. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4934. $setsharekey = true;
  4935. }
  4936. if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4937. $setsharekey = true;
  4938. }
  4939. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4940. $setsharekey = true;
  4941. }
  4942. if ($setsharekey) {
  4943. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4944. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4945. $ecmfile->share = getRandomPassword(true);
  4946. }
  4947. }
  4948. if ($result > 0) {
  4949. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4950. $ecmfile->fullpath_orig = '';
  4951. $ecmfile->gen_or_uploaded = 'generated';
  4952. $ecmfile->description = ''; // indexed content
  4953. $ecmfile->keywords = ''; // keyword content
  4954. $result = $ecmfile->update($user);
  4955. if ($result < 0) {
  4956. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4957. return -1;
  4958. }
  4959. } else {
  4960. $ecmfile->entity = $conf->entity;
  4961. $ecmfile->filepath = $rel_dir;
  4962. $ecmfile->filename = $filename;
  4963. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4964. $ecmfile->fullpath_orig = '';
  4965. $ecmfile->gen_or_uploaded = 'generated';
  4966. $ecmfile->description = ''; // indexed content
  4967. $ecmfile->keywords = ''; // keyword content
  4968. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  4969. $ecmfile->src_object_id = $this->id;
  4970. $result = $ecmfile->create($user);
  4971. if ($result < 0) {
  4972. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4973. return -1;
  4974. }
  4975. }
  4976. /*$this->result['fullname']=$destfull;
  4977. $this->result['filepath']=$ecmfile->filepath;
  4978. $this->result['filename']=$ecmfile->filename;*/
  4979. //var_dump($obj->update_main_doc_field);exit;
  4980. if ($update_main_doc_field && !empty($this->table_element)) {
  4981. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  4982. $sql .= " WHERE rowid = ".((int) $this->id);
  4983. $resql = $this->db->query($sql);
  4984. if (!$resql) {
  4985. dol_print_error($this->db);
  4986. return -1;
  4987. } else {
  4988. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4989. }
  4990. }
  4991. }
  4992. return 1;
  4993. }
  4994. /**
  4995. * Build thumb
  4996. * @todo Move this into files.lib.php
  4997. *
  4998. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4999. * @return void
  5000. */
  5001. public function addThumbs($file)
  5002. {
  5003. $file_osencoded = dol_osencode($file);
  5004. if (file_exists($file_osencoded)) {
  5005. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  5006. $tmparraysize = getDefaultImageSizes();
  5007. $maxwidthsmall = $tmparraysize['maxwidthsmall'];
  5008. $maxheightsmall = $tmparraysize['maxheightsmall'];
  5009. $maxwidthmini = $tmparraysize['maxwidthmini'];
  5010. $maxheightmini = $tmparraysize['maxheightmini'];
  5011. //$quality = $tmparraysize['quality'];
  5012. $quality = 50; // For thumbs, we force quality to 50
  5013. // Create small thumbs for company (Ratio is near 16/9)
  5014. // Used on logon for example
  5015. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  5016. // Create mini thumbs for company (Ratio is near 16/9)
  5017. // Used on menu or for setup page for example
  5018. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  5019. }
  5020. }
  5021. /**
  5022. * Delete thumbs
  5023. * @todo Move this into files.lib.php
  5024. *
  5025. * @param string $file Path file in UTF8 to original file to delete thumbs.
  5026. * @return void
  5027. */
  5028. public function delThumbs($file)
  5029. {
  5030. $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file
  5031. dol_delete_file($imgThumbName);
  5032. $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file
  5033. dol_delete_file($imgThumbName);
  5034. }
  5035. /* Functions common to commonobject and commonobjectline */
  5036. /* For default values */
  5037. /**
  5038. * Return the default value to use for a field when showing the create form of object.
  5039. * Return values in this order:
  5040. * 1) If parameter is available into POST, we return it first.
  5041. * 2) If not but an alternate value was provided as parameter of function, we return it.
  5042. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  5043. * 4) Return value found into database (TODO No yet implemented)
  5044. *
  5045. * @param string $fieldname Name of field
  5046. * @param string $alternatevalue Alternate value to use
  5047. * @param string $type Type of data
  5048. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  5049. **/
  5050. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml')
  5051. {
  5052. global $conf, $_POST;
  5053. // If param here has been posted, we use this value first.
  5054. if (GETPOSTISSET($fieldname)) {
  5055. return GETPOST($fieldname, $type, 3);
  5056. }
  5057. if (isset($alternatevalue)) {
  5058. return $alternatevalue;
  5059. }
  5060. $newelement = $this->element;
  5061. if ($newelement == 'facture') {
  5062. $newelement = 'invoice';
  5063. }
  5064. if ($newelement == 'commande') {
  5065. $newelement = 'order';
  5066. }
  5067. if (empty($newelement)) {
  5068. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5069. return '';
  5070. }
  5071. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  5072. //var_dump($keyforfieldname);
  5073. if (isset($conf->global->$keyforfieldname)) {
  5074. return $conf->global->$keyforfieldname;
  5075. }
  5076. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5077. // store content into $conf->cache['overwrite_default']
  5078. return '';
  5079. }
  5080. /* For triggers */
  5081. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5082. /**
  5083. * Call trigger based on this instance.
  5084. * Some context information may also be provided into array property this->context.
  5085. * NB: Error from trigger are stacked in interface->errors
  5086. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5087. *
  5088. * @param string $triggerName trigger's name to execute
  5089. * @param User $user Object user
  5090. * @return int Result of run_triggers
  5091. */
  5092. public function call_trigger($triggerName, $user)
  5093. {
  5094. // phpcs:enable
  5095. global $langs, $conf;
  5096. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5097. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5098. exit;
  5099. }
  5100. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5101. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5102. $langs = new Translate('', $conf);
  5103. }
  5104. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5105. $interface = new Interfaces($this->db);
  5106. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5107. if ($result < 0) {
  5108. if (!empty($this->errors)) {
  5109. $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.
  5110. } else {
  5111. $this->errors = $interface->errors;
  5112. }
  5113. }
  5114. return $result;
  5115. }
  5116. /* Functions for data in other language */
  5117. /**
  5118. * Function to get alternative languages of a data into $this->array_languages
  5119. * This method is NOT called by method fetch of objects but must be called separately.
  5120. *
  5121. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5122. * @see fetch_optionnals()
  5123. */
  5124. public function fetchValuesForExtraLanguages()
  5125. {
  5126. // To avoid SQL errors. Probably not the better solution though
  5127. if (!$this->element) {
  5128. return 0;
  5129. }
  5130. if (!($this->id > 0)) {
  5131. return 0;
  5132. }
  5133. if (is_array($this->array_languages)) {
  5134. return 1;
  5135. }
  5136. $this->array_languages = array();
  5137. $element = $this->element;
  5138. if ($element == 'categorie') {
  5139. $element = 'categories'; // For compatibility
  5140. }
  5141. // Request to get translation values for object
  5142. $sql = "SELECT rowid, property, lang , value";
  5143. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5144. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5145. $sql .= " AND fk_object = ".((int) $this->id);
  5146. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5147. $resql = $this->db->query($sql);
  5148. if ($resql) {
  5149. $numrows = $this->db->num_rows($resql);
  5150. if ($numrows) {
  5151. $i = 0;
  5152. while ($i < $numrows) {
  5153. $obj = $this->db->fetch_object($resql);
  5154. $key = $obj->property;
  5155. $value = $obj->value;
  5156. $codelang = $obj->lang;
  5157. $type = $this->fields[$key]['type'];
  5158. // we can add this attribute to object
  5159. if (preg_match('/date/', $type)) {
  5160. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5161. } else {
  5162. $this->array_languages[$key][$codelang] = $value;
  5163. }
  5164. $i++;
  5165. }
  5166. }
  5167. $this->db->free($resql);
  5168. if ($numrows) {
  5169. return $numrows;
  5170. } else {
  5171. return 0;
  5172. }
  5173. } else {
  5174. dol_print_error($this->db);
  5175. return -1;
  5176. }
  5177. }
  5178. /**
  5179. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5180. *
  5181. * @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.
  5182. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5183. */
  5184. public function setValuesForExtraLanguages($onlykey = '')
  5185. {
  5186. global $_POST, $langs;
  5187. // Get extra fields
  5188. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5189. $tmparray = explode('-', $postfieldkey);
  5190. if ($tmparray[0] != 'field') {
  5191. continue;
  5192. }
  5193. $element = $tmparray[1];
  5194. $key = $tmparray[2];
  5195. $codelang = $tmparray[3];
  5196. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5197. if (!empty($onlykey) && $key != $onlykey) {
  5198. continue;
  5199. }
  5200. if ($element != $this->element) {
  5201. continue;
  5202. }
  5203. $key_type = $this->fields[$key]['type'];
  5204. $enabled = 1;
  5205. if (isset($this->fields[$key]['enabled'])) {
  5206. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5207. }
  5208. /*$perms = 1;
  5209. if (isset($this->fields[$key]['perms']))
  5210. {
  5211. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5212. }*/
  5213. if (empty($enabled)) {
  5214. continue;
  5215. }
  5216. //if (empty($perms)) continue;
  5217. if (in_array($key_type, array('date'))) {
  5218. // Clean parameters
  5219. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5220. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5221. } elseif (in_array($key_type, array('datetime'))) {
  5222. // Clean parameters
  5223. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5224. $value_key = dol_mktime(GETPOST($postfieldkey."hour", 'int'), GETPOST($postfieldkey."min", 'int'), 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5225. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5226. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5227. if (!empty($value_arr)) {
  5228. $value_key = implode(',', $value_arr);
  5229. } else {
  5230. $value_key = '';
  5231. }
  5232. } elseif (in_array($key_type, array('price', 'double'))) {
  5233. $value_arr = GETPOST($postfieldkey, 'alpha');
  5234. $value_key = price2num($value_arr);
  5235. } else {
  5236. $value_key = GETPOST($postfieldkey);
  5237. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5238. $value_key = '';
  5239. }
  5240. }
  5241. $this->array_languages[$key][$codelang] = $value_key;
  5242. /*if ($nofillrequired) {
  5243. $langs->load('errors');
  5244. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5245. return -1;
  5246. }*/
  5247. }
  5248. return 1;
  5249. }
  5250. /* Functions for extrafields */
  5251. /**
  5252. * Function to make a fetch but set environment to avoid to load computed values before.
  5253. *
  5254. * @param int $id ID of object
  5255. * @return int >0 if OK, 0 if not found, <0 if KO
  5256. */
  5257. public function fetchNoCompute($id)
  5258. {
  5259. global $conf;
  5260. $savDisableCompute = $conf->disable_compute;
  5261. $conf->disable_compute = 1;
  5262. $ret = $this->fetch($id);
  5263. $conf->disable_compute = $savDisableCompute;
  5264. return $ret;
  5265. }
  5266. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5267. /**
  5268. * Function to get extra fields of an object into $this->array_options
  5269. * This method is in most cases called by method fetch of objects but you can call it separately.
  5270. *
  5271. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5272. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5273. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5274. * @see fetchValuesForExtraLanguages()
  5275. */
  5276. public function fetch_optionals($rowid = null, $optionsArray = null)
  5277. {
  5278. // phpcs:enable
  5279. global $conf, $extrafields;
  5280. if (empty($rowid)) {
  5281. $rowid = $this->id;
  5282. }
  5283. if (empty($rowid) && isset($this->rowid)) {
  5284. $rowid = $this->rowid; // deprecated
  5285. }
  5286. // To avoid SQL errors. Probably not the better solution though
  5287. if (!$this->table_element) {
  5288. return 0;
  5289. }
  5290. $this->array_options = array();
  5291. if (!is_array($optionsArray)) {
  5292. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5293. if (!isset($extrafields) || !is_object($extrafields)) {
  5294. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5295. $extrafields = new ExtraFields($this->db);
  5296. }
  5297. // Load array of extrafields for elementype = $this->table_element
  5298. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5299. $extrafields->fetch_name_optionals_label($this->table_element);
  5300. }
  5301. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5302. } else {
  5303. global $extrafields;
  5304. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5305. }
  5306. $table_element = $this->table_element;
  5307. if ($table_element == 'categorie') {
  5308. $table_element = 'categories'; // For compatibility
  5309. }
  5310. // Request to get complementary values
  5311. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5312. $sql = "SELECT rowid";
  5313. foreach ($optionsArray as $name => $label) {
  5314. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5315. $sql .= ", ".$name;
  5316. }
  5317. }
  5318. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5319. $sql .= " WHERE fk_object = ".((int) $rowid);
  5320. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5321. $resql = $this->db->query($sql);
  5322. if ($resql) {
  5323. $numrows = $this->db->num_rows($resql);
  5324. if ($numrows) {
  5325. $tab = $this->db->fetch_array($resql);
  5326. foreach ($tab as $key => $value) {
  5327. // 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)
  5328. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5329. // we can add this attribute to object
  5330. if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5331. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5332. $this->array_options["options_".$key] = $this->db->jdate($value);
  5333. } else {
  5334. $this->array_options["options_".$key] = $value;
  5335. }
  5336. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5337. }
  5338. }
  5339. }
  5340. // If field is a computed field, value must become result of compute (regardless of whether a row exists
  5341. // in the element's extrafields table)
  5342. if (is_array($extrafields->attributes[$this->table_element]['label'])) {
  5343. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  5344. if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5345. //var_dump($conf->disable_compute);
  5346. if (empty($conf->disable_compute)) {
  5347. global $objectoffield; // We set a global variable to $objectoffield so
  5348. $objectoffield = $this; // we can use it inside computed formula
  5349. $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5350. }
  5351. }
  5352. }
  5353. }
  5354. $this->db->free($resql);
  5355. if ($numrows) {
  5356. return $numrows;
  5357. } else {
  5358. return 0;
  5359. }
  5360. } else {
  5361. $this->errors[]=$this->db->lasterror;
  5362. return -1;
  5363. }
  5364. }
  5365. return 0;
  5366. }
  5367. /**
  5368. * Delete all extra fields values for the current object.
  5369. *
  5370. * @return int <0 if KO, >0 if OK
  5371. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5372. */
  5373. public function deleteExtraFields()
  5374. {
  5375. global $conf;
  5376. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5377. return 0;
  5378. }
  5379. $this->db->begin();
  5380. $table_element = $this->table_element;
  5381. if ($table_element == 'categorie') {
  5382. $table_element = 'categories'; // For compatibility
  5383. }
  5384. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5385. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5386. $resql = $this->db->query($sql_del);
  5387. if (!$resql) {
  5388. $this->error = $this->db->lasterror();
  5389. $this->db->rollback();
  5390. return -1;
  5391. } else {
  5392. $this->db->commit();
  5393. return 1;
  5394. }
  5395. }
  5396. /**
  5397. * Add/Update all extra fields values for the current object.
  5398. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5399. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5400. *
  5401. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5402. * @param User $userused Object user
  5403. * @return int -1=error, O=did nothing, 1=OK
  5404. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5405. */
  5406. public function insertExtraFields($trigger = '', $userused = null)
  5407. {
  5408. global $conf, $langs, $user;
  5409. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5410. return 0;
  5411. }
  5412. if (empty($userused)) {
  5413. $userused = $user;
  5414. }
  5415. $error = 0;
  5416. if (!empty($this->array_options)) {
  5417. // Check parameters
  5418. $langs->load('admin');
  5419. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5420. $extrafields = new ExtraFields($this->db);
  5421. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5422. // Eliminate copied source object extra fields that do not exist in target object
  5423. $new_array_options = array();
  5424. foreach ($this->array_options as $key => $value) {
  5425. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5426. $new_array_options[$key] = $value;
  5427. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contain the 'options_' prefix
  5428. $new_array_options['options_'.$key] = $value;
  5429. }
  5430. }
  5431. foreach ($new_array_options as $key => $value) {
  5432. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5433. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5434. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5435. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5436. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5437. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5438. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5439. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5440. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5441. if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
  5442. $new_array_options[$key] = null;
  5443. }
  5444. // Similar code than into insertExtraFields
  5445. if ($attributeRequired) {
  5446. $mandatorypb = false;
  5447. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5448. $mandatorypb = true;
  5449. }
  5450. if ($this->array_options[$key] === '') {
  5451. $mandatorypb = true;
  5452. }
  5453. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5454. $mandatorypb = true;
  5455. }
  5456. if ($mandatorypb) {
  5457. $langs->load("errors");
  5458. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5459. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5460. return -1;
  5461. }
  5462. }
  5463. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5464. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5465. if (!empty($attrfieldcomputed)) {
  5466. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5467. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5468. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5469. $new_array_options[$key] = $value;
  5470. } else {
  5471. $new_array_options[$key] = null;
  5472. }
  5473. }
  5474. switch ($attributeType) {
  5475. case 'int':
  5476. if (!is_numeric($value) && $value != '') {
  5477. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5478. return -1;
  5479. } elseif ($value == '') {
  5480. $new_array_options[$key] = null;
  5481. }
  5482. break;
  5483. case 'price':
  5484. case 'double':
  5485. $value = price2num($value);
  5486. if (!is_numeric($value) && $value != '') {
  5487. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5488. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5489. return -1;
  5490. } elseif ($value == '') {
  5491. $value = null;
  5492. }
  5493. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5494. $new_array_options[$key] = $value;
  5495. break;
  5496. /*case 'select': // Not required, we chosed value='0' for undefined values
  5497. if ($value=='-1')
  5498. {
  5499. $this->array_options[$key] = null;
  5500. }
  5501. break;*/
  5502. case 'password':
  5503. $algo = '';
  5504. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5505. // If there is an encryption choice, we use it to crypt data before insert
  5506. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5507. $algo = reset($tmparrays);
  5508. if ($algo != '') {
  5509. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5510. //var_dump($action);
  5511. //var_dump($this->oldcopy);exit;
  5512. 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
  5513. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5514. if (isset($this->oldcopy->array_options[$key]) && $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.
  5515. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5516. } else {
  5517. // var_dump($algo);
  5518. $newvalue = dol_hash($this->array_options[$key], $algo);
  5519. $new_array_options[$key] = $newvalue;
  5520. }
  5521. } else {
  5522. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5523. }
  5524. }
  5525. } else // Common usage
  5526. {
  5527. $new_array_options[$key] = $this->array_options[$key];
  5528. }
  5529. break;
  5530. case 'date':
  5531. case 'datetime':
  5532. // If data is a string instead of a timestamp, we convert it
  5533. if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
  5534. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5535. }
  5536. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5537. break;
  5538. case 'datetimegmt':
  5539. // If data is a string instead of a timestamp, we convert it
  5540. if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
  5541. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5542. }
  5543. $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt');
  5544. break;
  5545. case 'link':
  5546. $param_list = array_keys($attributeParam['options']);
  5547. // 0 : ObjectName
  5548. // 1 : classPath
  5549. $InfoFieldList = explode(":", $param_list[0]);
  5550. dol_include_once($InfoFieldList[1]);
  5551. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5552. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5553. $new_array_options[$key] = '';
  5554. } elseif ($value) {
  5555. $object = new $InfoFieldList[0]($this->db);
  5556. if (is_numeric($value)) {
  5557. $res = $object->fetch($value); // Common case
  5558. } else {
  5559. $res = $object->fetch('', $value); // For compatibility
  5560. }
  5561. if ($res > 0) {
  5562. $new_array_options[$key] = $object->id;
  5563. } else {
  5564. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5565. return -1;
  5566. }
  5567. }
  5568. } else {
  5569. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5570. }
  5571. break;
  5572. case 'checkbox':
  5573. case 'chkbxlst':
  5574. if (is_array($this->array_options[$key])) {
  5575. $new_array_options[$key] = implode(',', $this->array_options[$key]);
  5576. } else {
  5577. $new_array_options[$key] = $this->array_options[$key];
  5578. }
  5579. break;
  5580. }
  5581. }
  5582. $this->db->begin();
  5583. $table_element = $this->table_element;
  5584. if ($table_element == 'categorie') {
  5585. $table_element = 'categories'; // For compatibility
  5586. }
  5587. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5588. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5589. $this->db->query($sql_del);
  5590. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5591. foreach ($new_array_options as $key => $value) {
  5592. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5593. // Add field of attribut
  5594. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5595. $sql .= ",".$attributeKey;
  5596. }
  5597. }
  5598. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5599. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5600. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5601. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5602. $sql .= ",".$tmpkey;
  5603. }
  5604. }
  5605. }
  5606. $sql .= ") VALUES (".$this->id;
  5607. foreach ($new_array_options as $key => $value) {
  5608. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5609. // Add field of attribute
  5610. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5611. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5612. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5613. } else {
  5614. $sql .= ",null";
  5615. }
  5616. }
  5617. }
  5618. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5619. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5620. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5621. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5622. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5623. $sql .= ", 0";
  5624. } else {
  5625. $sql .= ", ''";
  5626. }
  5627. }
  5628. }
  5629. }
  5630. $sql .= ")";
  5631. $resql = $this->db->query($sql);
  5632. if (!$resql) {
  5633. $this->error = $this->db->lasterror();
  5634. $error++;
  5635. }
  5636. if (!$error && $trigger) {
  5637. // Call trigger
  5638. $this->context = array('extrafieldaddupdate'=>1);
  5639. $result = $this->call_trigger($trigger, $userused);
  5640. if ($result < 0) {
  5641. $error++;
  5642. }
  5643. // End call trigger
  5644. }
  5645. if ($error) {
  5646. $this->db->rollback();
  5647. return -1;
  5648. } else {
  5649. $this->db->commit();
  5650. return 1;
  5651. }
  5652. } else {
  5653. return 0;
  5654. }
  5655. }
  5656. /**
  5657. * Add/Update all extra fields values for the current object.
  5658. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5659. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5660. *
  5661. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5662. * @param User $userused Object user
  5663. * @return int -1=error, O=did nothing, 1=OK
  5664. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5665. */
  5666. public function insertExtraLanguages($trigger = '', $userused = null)
  5667. {
  5668. global $conf, $langs, $user;
  5669. if (empty($userused)) {
  5670. $userused = $user;
  5671. }
  5672. $error = 0;
  5673. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5674. return 0; // For avoid conflicts if trigger used
  5675. }
  5676. if (is_array($this->array_languages)) {
  5677. $new_array_languages = $this->array_languages;
  5678. foreach ($new_array_languages as $key => $value) {
  5679. $attributeKey = $key;
  5680. $attributeType = $this->fields[$attributeKey]['type'];
  5681. $attributeLabel = $this->fields[$attributeKey]['label'];
  5682. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5683. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5684. switch ($attributeType) {
  5685. case 'int':
  5686. if (!is_numeric($value) && $value != '') {
  5687. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5688. return -1;
  5689. } elseif ($value == '') {
  5690. $new_array_languages[$key] = null;
  5691. }
  5692. break;
  5693. case 'double':
  5694. $value = price2num($value);
  5695. if (!is_numeric($value) && $value != '') {
  5696. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5697. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5698. return -1;
  5699. } elseif ($value == '') {
  5700. $new_array_languages[$key] = null;
  5701. } else {
  5702. $new_array_languages[$key] = $value;
  5703. }
  5704. break;
  5705. /*case 'select': // Not required, we chosed value='0' for undefined values
  5706. if ($value=='-1')
  5707. {
  5708. $this->array_options[$key] = null;
  5709. }
  5710. break;*/
  5711. }
  5712. }
  5713. $this->db->begin();
  5714. $table_element = $this->table_element;
  5715. if ($table_element == 'categorie') {
  5716. $table_element = 'categories'; // For compatibility
  5717. }
  5718. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5719. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5720. foreach ($langcodearray as $langcode => $value) {
  5721. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5722. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5723. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5724. $this->db->query($sql_del);
  5725. if ($value !== '') {
  5726. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5727. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5728. $sql .= ")";
  5729. $resql = $this->db->query($sql);
  5730. if (!$resql) {
  5731. $this->error = $this->db->lasterror();
  5732. $error++;
  5733. break;
  5734. }
  5735. }
  5736. }
  5737. }
  5738. if (!$error && $trigger) {
  5739. // Call trigger
  5740. $this->context = array('extralanguagesaddupdate'=>1);
  5741. $result = $this->call_trigger($trigger, $userused);
  5742. if ($result < 0) {
  5743. $error++;
  5744. }
  5745. // End call trigger
  5746. }
  5747. if ($error) {
  5748. $this->db->rollback();
  5749. return -1;
  5750. } else {
  5751. $this->db->commit();
  5752. return 1;
  5753. }
  5754. } else {
  5755. return 0;
  5756. }
  5757. }
  5758. /**
  5759. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5760. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5761. *
  5762. * @param string $key Key of the extrafield to update (without starting 'options_')
  5763. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5764. * @param User $userused Object user
  5765. * @return int -1=error, O=did nothing, 1=OK
  5766. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5767. */
  5768. public function updateExtraField($key, $trigger = null, $userused = null)
  5769. {
  5770. global $conf, $langs, $user;
  5771. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5772. return 0;
  5773. }
  5774. if (empty($userused)) {
  5775. $userused = $user;
  5776. }
  5777. $error = 0;
  5778. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5779. // Check parameters
  5780. $langs->load('admin');
  5781. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5782. $extrafields = new ExtraFields($this->db);
  5783. $extrafields->fetch_name_optionals_label($this->table_element);
  5784. $value = $this->array_options["options_".$key];
  5785. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5786. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5787. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5788. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5789. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5790. // Similar code than into insertExtraFields
  5791. if ($attributeRequired) {
  5792. $mandatorypb = false;
  5793. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5794. $mandatorypb = true;
  5795. }
  5796. if ($this->array_options["options_".$key] === '') {
  5797. $mandatorypb = true;
  5798. }
  5799. if ($mandatorypb) {
  5800. $langs->load("errors");
  5801. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5802. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5803. return -1;
  5804. }
  5805. }
  5806. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5807. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5808. if (!empty($attrfieldcomputed)) {
  5809. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5810. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5811. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5812. $this->array_options["options_".$key] = $value;
  5813. } else {
  5814. $this->array_options["options_".$key] = null;
  5815. }
  5816. }
  5817. switch ($attributeType) {
  5818. case 'int':
  5819. if (!is_numeric($value) && $value != '') {
  5820. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5821. return -1;
  5822. } elseif ($value === '') {
  5823. $this->array_options["options_".$key] = null;
  5824. }
  5825. break;
  5826. case 'double':
  5827. $value = price2num($value);
  5828. if (!is_numeric($value) && $value != '') {
  5829. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5830. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5831. return -1;
  5832. } elseif ($value === '') {
  5833. $value = null;
  5834. }
  5835. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5836. $this->array_options["options_".$key] = $value;
  5837. break;
  5838. /*case 'select': // Not required, we chosed value='0' for undefined values
  5839. if ($value=='-1')
  5840. {
  5841. $this->array_options[$key] = null;
  5842. }
  5843. break;*/
  5844. case 'price':
  5845. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5846. break;
  5847. case 'date':
  5848. case 'datetime':
  5849. if (empty($this->array_options["options_".$key])) {
  5850. $this->array_options["options_".$key] = null;
  5851. } else {
  5852. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5853. }
  5854. break;
  5855. case 'datetimegmt':
  5856. if (empty($this->array_options["options_".$key])) {
  5857. $this->array_options["options_".$key] = null;
  5858. } else {
  5859. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt');
  5860. }
  5861. break;
  5862. case 'boolean':
  5863. if (empty($this->array_options["options_".$key])) {
  5864. $this->array_options["options_".$key] = null;
  5865. }
  5866. break;
  5867. /*
  5868. case 'link':
  5869. $param_list = array_keys($attributeParam['options']);
  5870. // 0 : ObjectName
  5871. // 1 : classPath
  5872. $InfoFieldList = explode(":", $param_list[0]);
  5873. dol_include_once($InfoFieldList[1]);
  5874. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5875. {
  5876. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5877. {
  5878. $new_array_options[$key] = '';
  5879. } elseif ($value) {
  5880. $object = new $InfoFieldList[0]($this->db);
  5881. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5882. else $res = $object->fetch('', $value); // For compatibility
  5883. if ($res > 0) $new_array_options[$key] = $object->id;
  5884. else {
  5885. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5886. $this->db->rollback();
  5887. return -1;
  5888. }
  5889. }
  5890. } else {
  5891. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5892. }
  5893. break;
  5894. */
  5895. case 'checkbox':
  5896. case 'chkbxlst':
  5897. if (is_array($this->array_options[$key])) {
  5898. $new_array_options[$key] = implode(',', $this->array_options[$key]);
  5899. } else {
  5900. $new_array_options[$key] = $this->array_options[$key];
  5901. }
  5902. break;
  5903. }
  5904. $this->db->begin();
  5905. $linealreadyfound = 0;
  5906. // 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)
  5907. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5908. $resql = $this->db->query($sql);
  5909. if ($resql) {
  5910. $tmpobj = $this->db->fetch_object($resql);
  5911. if ($tmpobj) {
  5912. $linealreadyfound = $tmpobj->nb;
  5913. }
  5914. }
  5915. if ($linealreadyfound) {
  5916. if ($this->array_options["options_".$key] === null) {
  5917. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5918. } else {
  5919. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5920. }
  5921. $sql .= " WHERE fk_object = ".((int) $this->id);
  5922. } else {
  5923. $result = $this->insertExtraFields('', $user);
  5924. if ($result < 0) {
  5925. $error++;
  5926. }
  5927. }
  5928. $resql = $this->db->query($sql);
  5929. if (!$resql) {
  5930. $error++;
  5931. $this->error = $this->db->lasterror();
  5932. }
  5933. if (!$error && $trigger) {
  5934. // Call trigger
  5935. $this->context = array('extrafieldupdate'=>1);
  5936. $result = $this->call_trigger($trigger, $userused);
  5937. if ($result < 0) {
  5938. $error++;
  5939. }
  5940. // End call trigger
  5941. }
  5942. if ($error) {
  5943. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5944. $this->db->rollback();
  5945. return -1;
  5946. } else {
  5947. $this->db->commit();
  5948. return 1;
  5949. }
  5950. } else {
  5951. return 0;
  5952. }
  5953. }
  5954. /**
  5955. * Update an extra language value for the current object.
  5956. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5957. *
  5958. * @param string $key Key of the extrafield (without starting 'options_')
  5959. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5960. * @param User $userused Object user
  5961. * @return int -1=error, O=did nothing, 1=OK
  5962. * @see updateExtraFields(), insertExtraLanguages()
  5963. */
  5964. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5965. {
  5966. global $conf, $langs, $user;
  5967. if (empty($userused)) {
  5968. $userused = $user;
  5969. }
  5970. $error = 0;
  5971. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5972. return 0; // For avoid conflicts if trigger used
  5973. }
  5974. return 0;
  5975. }
  5976. /**
  5977. * Return HTML string to put an input field into a page
  5978. * Code very similar with showInputField of extra fields
  5979. *
  5980. * @param array|null $val Array of properties for field to show (used only if ->fields not defined)
  5981. * @param string $key Key of attribute
  5982. * @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)
  5983. * @param string $moreparam To add more parameters on html input tag
  5984. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5985. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5986. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5987. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5988. * @return string
  5989. */
  5990. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5991. {
  5992. global $conf, $langs, $form;
  5993. if (!is_object($form)) {
  5994. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5995. $form = new Form($this->db);
  5996. }
  5997. if (!empty($this->fields)) {
  5998. $val = $this->fields[$key];
  5999. }
  6000. // Validation tests and output
  6001. $fieldValidationErrorMsg = '';
  6002. $validationClass = '';
  6003. $fieldValidationErrorMsg = $this->getFieldError($key);
  6004. if (!empty($fieldValidationErrorMsg)) {
  6005. $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
  6006. } else {
  6007. $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
  6008. }
  6009. $out = '';
  6010. $type = '';
  6011. $isDependList = 0;
  6012. $param = array();
  6013. $param['options'] = array();
  6014. $reg = array();
  6015. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  6016. // Because we work on extrafields
  6017. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6018. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6019. $type = 'link';
  6020. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6021. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6022. $type = 'link';
  6023. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  6024. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6025. $type = 'link';
  6026. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6027. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6028. $type = 'sellist';
  6029. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6030. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6031. $type = 'sellist';
  6032. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  6033. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6034. $type = 'sellist';
  6035. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6036. $param['options'] = array($reg[1] => 'N');
  6037. $type = 'chkbxlst';
  6038. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  6039. $param['options'] = array();
  6040. $type = 'varchar';
  6041. $size = $reg[1];
  6042. } elseif (preg_match('/varchar/', $val['type'])) {
  6043. $param['options'] = array();
  6044. $type = 'varchar';
  6045. } else {
  6046. $param['options'] = array();
  6047. $type = $this->fields[$key]['type'];
  6048. }
  6049. // Special case that force options and type ($type can be integer, varchar, ...)
  6050. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  6051. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  6052. $type = 'select';
  6053. }
  6054. $label = $this->fields[$key]['label'];
  6055. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  6056. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  6057. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  6058. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  6059. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  6060. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  6061. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  6062. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  6063. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  6064. $objectid = $this->id;
  6065. if ($computed) {
  6066. if (!preg_match('/^search_/', $keyprefix)) {
  6067. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  6068. } else {
  6069. return '';
  6070. }
  6071. }
  6072. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  6073. if (empty($morecss) && !empty($val['css'])) {
  6074. $morecss = $val['css'];
  6075. } elseif (empty($morecss)) {
  6076. if ($type == 'date') {
  6077. $morecss = 'minwidth100imp';
  6078. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  6079. $morecss = 'minwidth200imp';
  6080. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6081. $morecss = 'maxwidth75';
  6082. } elseif ($type == 'url') {
  6083. $morecss = 'minwidth400';
  6084. } elseif ($type == 'boolean') {
  6085. $morecss = '';
  6086. } else {
  6087. if (round($size) < 12) {
  6088. $morecss = 'minwidth100';
  6089. } elseif (round($size) <= 48) {
  6090. $morecss = 'minwidth200';
  6091. } else {
  6092. $morecss = 'minwidth400';
  6093. }
  6094. }
  6095. }
  6096. // Add validation state class
  6097. if (!empty($validationClass)) {
  6098. $morecss.= $validationClass;
  6099. }
  6100. if (in_array($type, array('date'))) {
  6101. $tmp = explode(',', $size);
  6102. $newsize = $tmp[0];
  6103. $showtime = 0;
  6104. // Do not show current date when field not required (see selectDate() method)
  6105. if (!$required && $value == '') {
  6106. $value = '-1';
  6107. }
  6108. // TODO Must also support $moreparam
  6109. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6110. } elseif (in_array($type, array('datetime'))) {
  6111. $tmp = explode(',', $size);
  6112. $newsize = $tmp[0];
  6113. $showtime = 1;
  6114. // Do not show current date when field not required (see selectDate() method)
  6115. if (!$required && $value == '') $value = '-1';
  6116. // TODO Must also support $moreparam
  6117. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6118. } elseif (in_array($type, array('duration'))) {
  6119. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6120. } elseif (in_array($type, array('int', 'integer'))) {
  6121. $tmp = explode(',', $size);
  6122. $newsize = $tmp[0];
  6123. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($newsize > 0 ? ' maxlength="'.$newsize.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6124. } elseif (in_array($type, array('real'))) {
  6125. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6126. } elseif (preg_match('/varchar/', $type)) {
  6127. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($size > 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6128. } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
  6129. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6130. } elseif (preg_match('/^text/', $type)) {
  6131. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6132. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6133. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6134. $out = $doleditor->Create(1);
  6135. } else {
  6136. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6137. }
  6138. } elseif (preg_match('/^html/', $type)) {
  6139. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6140. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6141. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
  6142. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6143. } else {
  6144. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6145. }
  6146. } elseif ($type == 'boolean') {
  6147. $checked = '';
  6148. if (!empty($value)) {
  6149. $checked = ' checked value="1" ';
  6150. } else {
  6151. $checked = ' value="1" ';
  6152. }
  6153. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6154. } elseif ($type == 'price') {
  6155. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6156. $value = price($value);
  6157. }
  6158. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6159. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6160. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6161. $value = price($value);
  6162. }
  6163. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6164. } elseif ($type == 'select') {
  6165. $out = '';
  6166. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6167. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6168. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6169. }
  6170. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6171. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6172. $out .= '<option value="0">&nbsp;</option>';
  6173. }
  6174. foreach ($param['options'] as $keyb => $valb) {
  6175. if ((string) $keyb == '') {
  6176. continue;
  6177. }
  6178. if (strpos($valb, "|") !== false) {
  6179. list($valb, $parent) = explode('|', $valb);
  6180. }
  6181. $out .= '<option value="'.$keyb.'"';
  6182. $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
  6183. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6184. $out .= '>'.$valb.'</option>';
  6185. }
  6186. $out .= '</select>';
  6187. } elseif ($type == 'sellist') {
  6188. $out = '';
  6189. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6190. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6191. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6192. }
  6193. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6194. if (is_array($param['options'])) {
  6195. $param_list = array_keys($param['options']);
  6196. $InfoFieldList = explode(":", $param_list[0]);
  6197. $parentName = '';
  6198. $parentField = '';
  6199. // 0 : tableName
  6200. // 1 : label field name
  6201. // 2 : key fields name (if differ of rowid)
  6202. // 3 : key field parent (for dependent lists)
  6203. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6204. // 5 : id category type
  6205. // 6 : ids categories list separated by comma for category root
  6206. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6207. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6208. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6209. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6210. } else {
  6211. $keyList = $InfoFieldList[2].' as rowid';
  6212. }
  6213. }
  6214. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6215. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6216. $keyList .= ', '.$parentField;
  6217. }
  6218. $filter_categorie = false;
  6219. if (count($InfoFieldList) > 5) {
  6220. if ($InfoFieldList[0] == 'categorie') {
  6221. $filter_categorie = true;
  6222. }
  6223. }
  6224. if ($filter_categorie === false) {
  6225. $fields_label = explode('|', $InfoFieldList[1]);
  6226. if (is_array($fields_label)) {
  6227. $keyList .= ', ';
  6228. $keyList .= implode(', ', $fields_label);
  6229. }
  6230. $sqlwhere = '';
  6231. $sql = "SELECT " . $keyList;
  6232. $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
  6233. if (!empty($InfoFieldList[4])) {
  6234. // can use SELECT request
  6235. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6236. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6237. }
  6238. // current object id can be use into filter
  6239. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6240. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6241. } else {
  6242. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6243. }
  6244. //We have to join on extrafield table
  6245. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6246. $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra";
  6247. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6248. } else {
  6249. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6250. }
  6251. } else {
  6252. $sqlwhere .= ' WHERE 1=1';
  6253. }
  6254. // Some tables may have field, some other not. For the moment we disable it.
  6255. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6256. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6257. }
  6258. $sql .= $sqlwhere;
  6259. //print $sql;
  6260. $sql .= ' ORDER BY ' . implode(', ', $fields_label);
  6261. dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
  6262. $resql = $this->db->query($sql);
  6263. if ($resql) {
  6264. $out .= '<option value="0">&nbsp;</option>';
  6265. $num = $this->db->num_rows($resql);
  6266. $i = 0;
  6267. while ($i < $num) {
  6268. $labeltoshow = '';
  6269. $obj = $this->db->fetch_object($resql);
  6270. // Several field into label (eq table:code|libelle:rowid)
  6271. $notrans = false;
  6272. $fields_label = explode('|', $InfoFieldList[1]);
  6273. if (count($fields_label) > 1) {
  6274. $notrans = true;
  6275. foreach ($fields_label as $field_toshow) {
  6276. $labeltoshow .= $obj->$field_toshow . ' ';
  6277. }
  6278. } else {
  6279. $labeltoshow = $obj->{$InfoFieldList[1]};
  6280. }
  6281. $labeltoshow = dol_trunc($labeltoshow, 45);
  6282. if ($value == $obj->rowid) {
  6283. foreach ($fields_label as $field_toshow) {
  6284. $translabel = $langs->trans($obj->$field_toshow);
  6285. if ($translabel != $obj->$field_toshow) {
  6286. $labeltoshow = dol_trunc($translabel) . ' ';
  6287. } else {
  6288. $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
  6289. }
  6290. }
  6291. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6292. } else {
  6293. if (!$notrans) {
  6294. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6295. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6296. $labeltoshow = dol_trunc($translabel, 18);
  6297. } else {
  6298. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6299. }
  6300. }
  6301. if (empty($labeltoshow)) {
  6302. $labeltoshow = '(not defined)';
  6303. }
  6304. if ($value == $obj->rowid) {
  6305. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6306. }
  6307. if (!empty($InfoFieldList[3]) && $parentField) {
  6308. $parent = $parentName . ':' . $obj->{$parentField};
  6309. $isDependList = 1;
  6310. }
  6311. $out .= '<option value="' . $obj->rowid . '"';
  6312. $out .= ($value == $obj->rowid ? ' selected' : '');
  6313. $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
  6314. $out .= '>' . $labeltoshow . '</option>';
  6315. }
  6316. $i++;
  6317. }
  6318. $this->db->free($resql);
  6319. } else {
  6320. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6321. }
  6322. } else {
  6323. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6324. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6325. $out .= '<option value="0">&nbsp;</option>';
  6326. foreach ($data as $data_key => $data_value) {
  6327. $out .= '<option value="' . $data_key . '"';
  6328. $out .= ($value == $data_key ? ' selected' : '');
  6329. $out .= '>' . $data_value . '</option>';
  6330. }
  6331. }
  6332. }
  6333. $out .= '</select>';
  6334. } elseif ($type == 'checkbox') {
  6335. $value_arr = explode(',', $value);
  6336. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
  6337. } elseif ($type == 'radio') {
  6338. $out = '';
  6339. foreach ($param['options'] as $keyopt => $valopt) {
  6340. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6341. $out .= ' value="'.$keyopt.'"';
  6342. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6343. $out .= ($value == $keyopt ? 'checked' : '');
  6344. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
  6345. }
  6346. } elseif ($type == 'chkbxlst') {
  6347. if (is_array($value)) {
  6348. $value_arr = $value;
  6349. } else {
  6350. $value_arr = explode(',', $value);
  6351. }
  6352. if (is_array($param['options'])) {
  6353. $param_list = array_keys($param['options']);
  6354. $InfoFieldList = explode(":", $param_list[0]);
  6355. $parentName = '';
  6356. $parentField = '';
  6357. // 0 : tableName
  6358. // 1 : label field name
  6359. // 2 : key fields name (if differ of rowid)
  6360. // 3 : key field parent (for dependent lists)
  6361. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6362. // 5 : id category type
  6363. // 6 : ids categories list separated by comma for category root
  6364. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6365. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6366. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6367. $keyList .= ', '.$parentField;
  6368. }
  6369. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6370. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6371. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6372. } else {
  6373. $keyList = $InfoFieldList[2].' as rowid';
  6374. }
  6375. }
  6376. $filter_categorie = false;
  6377. if (count($InfoFieldList) > 5) {
  6378. if ($InfoFieldList[0] == 'categorie') {
  6379. $filter_categorie = true;
  6380. }
  6381. }
  6382. if ($filter_categorie === false) {
  6383. $fields_label = explode('|', $InfoFieldList[1]);
  6384. if (is_array($fields_label)) {
  6385. $keyList .= ', ';
  6386. $keyList .= implode(', ', $fields_label);
  6387. }
  6388. $sqlwhere = '';
  6389. $sql = "SELECT " . $keyList;
  6390. $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
  6391. if (!empty($InfoFieldList[4])) {
  6392. // can use SELECT request
  6393. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6394. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6395. }
  6396. // current object id can be use into filter
  6397. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6398. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6399. } else {
  6400. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6401. }
  6402. // We have to join on extrafield table
  6403. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6404. $sql .= ' as main, ' . $this->db->prefix() . $InfoFieldList[0] . '_extrafields as extra';
  6405. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6406. } else {
  6407. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6408. }
  6409. } else {
  6410. $sqlwhere .= ' WHERE 1=1';
  6411. }
  6412. // Some tables may have field, some other not. For the moment we disable it.
  6413. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6414. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6415. }
  6416. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6417. // print $sql;
  6418. $sql .= $sqlwhere;
  6419. dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
  6420. $resql = $this->db->query($sql);
  6421. if ($resql) {
  6422. $num = $this->db->num_rows($resql);
  6423. $i = 0;
  6424. $data = array();
  6425. while ($i < $num) {
  6426. $labeltoshow = '';
  6427. $obj = $this->db->fetch_object($resql);
  6428. $notrans = false;
  6429. // Several field into label (eq table:code|libelle:rowid)
  6430. $fields_label = explode('|', $InfoFieldList[1]);
  6431. if (count($fields_label) > 1) {
  6432. $notrans = true;
  6433. foreach ($fields_label as $field_toshow) {
  6434. $labeltoshow .= $obj->$field_toshow . ' ';
  6435. }
  6436. } else {
  6437. $labeltoshow = $obj->{$InfoFieldList[1]};
  6438. }
  6439. $labeltoshow = dol_trunc($labeltoshow, 45);
  6440. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6441. foreach ($fields_label as $field_toshow) {
  6442. $translabel = $langs->trans($obj->$field_toshow);
  6443. if ($translabel != $obj->$field_toshow) {
  6444. $labeltoshow = dol_trunc($translabel, 18) . ' ';
  6445. } else {
  6446. $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
  6447. }
  6448. }
  6449. $data[$obj->rowid] = $labeltoshow;
  6450. } else {
  6451. if (!$notrans) {
  6452. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6453. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6454. $labeltoshow = dol_trunc($translabel, 18);
  6455. } else {
  6456. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6457. }
  6458. }
  6459. if (empty($labeltoshow)) {
  6460. $labeltoshow = '(not defined)';
  6461. }
  6462. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6463. $data[$obj->rowid] = $labeltoshow;
  6464. }
  6465. if (!empty($InfoFieldList[3]) && $parentField) {
  6466. $parent = $parentName . ':' . $obj->{$parentField};
  6467. $isDependList = 1;
  6468. }
  6469. $data[$obj->rowid] = $labeltoshow;
  6470. }
  6471. $i++;
  6472. }
  6473. $this->db->free($resql);
  6474. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6475. } else {
  6476. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6477. }
  6478. } else {
  6479. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6480. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6481. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6482. }
  6483. }
  6484. } elseif ($type == 'link') {
  6485. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6486. $param_list_array = explode(':', $param_list[0]);
  6487. $showempty = (($required && $default != '') ? 0 : 1);
  6488. if (!preg_match('/search_/', $keyprefix)) {
  6489. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6490. if (!empty($this->fields[$key]['picto'])) {
  6491. $morecss .= ' widthcentpercentminusxx';
  6492. } else {
  6493. $morecss .= ' widthcentpercentminusx';
  6494. }
  6495. } else {
  6496. if (!empty($this->fields[$key]['picto'])) {
  6497. $morecss .= ' widthcentpercentminusx';
  6498. }
  6499. }
  6500. }
  6501. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6502. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6503. 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".
  6504. list($class, $classfile) = explode(':', $param_list[0]);
  6505. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6506. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6507. } else {
  6508. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6509. }
  6510. $paramforthenewlink = '';
  6511. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6512. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6513. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6514. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6515. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6516. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6517. $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>';
  6518. }
  6519. }
  6520. } elseif ($type == 'password') {
  6521. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6522. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6523. } elseif ($type == 'array') {
  6524. $newval = $val;
  6525. $newval['type'] = 'varchar(256)';
  6526. $out = '';
  6527. if (!empty($value)) {
  6528. foreach ($value as $option) {
  6529. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6530. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6531. }
  6532. }
  6533. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6534. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6535. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6536. if (!empty($conf->use_javascript_ajax)) {
  6537. $out .= '
  6538. <script nonce="'.getNonce().'">
  6539. $(document).ready(function() {
  6540. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6541. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6542. });
  6543. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6544. $(this).parent().remove();
  6545. });
  6546. });
  6547. </script>';
  6548. }
  6549. }
  6550. if (!empty($hidden)) {
  6551. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6552. }
  6553. if ($isDependList==1) {
  6554. $out .= $this->getJSListDependancies('_common');
  6555. }
  6556. /* Add comments
  6557. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6558. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6559. */
  6560. // Display error message for field
  6561. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6562. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6563. }
  6564. return $out;
  6565. }
  6566. /**
  6567. * Return HTML string to show a field into a page
  6568. * Code very similar with showOutputField of extra fields
  6569. *
  6570. * @param array $val Array of properties of field to show
  6571. * @param string $key Key of attribute
  6572. * @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)
  6573. * @param string $moreparam To add more parametes on html input tag
  6574. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6575. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6576. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6577. * @return string
  6578. */
  6579. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6580. {
  6581. global $conf, $langs, $form;
  6582. if (!is_object($form)) {
  6583. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6584. $form = new Form($this->db);
  6585. }
  6586. $label = empty($val['label']) ? '' : $val['label'];
  6587. $type = empty($val['type']) ? '' : $val['type'];
  6588. $size = empty($val['css']) ? '' : $val['css'];
  6589. $reg = array();
  6590. // Convert var to be able to share same code than showOutputField of extrafields
  6591. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6592. $type = 'varchar'; // convert varchar(xx) int varchar
  6593. $size = $reg[1];
  6594. } elseif (preg_match('/varchar/', $type)) {
  6595. $type = 'varchar'; // convert varchar(xx) int varchar
  6596. }
  6597. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6598. $type = 'select';
  6599. }
  6600. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6601. $type = 'link';
  6602. }
  6603. $default = empty($val['default']) ? '' : $val['default'];
  6604. $computed = empty($val['computed']) ? '' : $val['computed'];
  6605. $unique = empty($val['unique']) ? '' : $val['unique'];
  6606. $required = empty($val['required']) ? '' : $val['required'];
  6607. $param = array();
  6608. $param['options'] = array();
  6609. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6610. $param['options'] = $val['arrayofkeyval'];
  6611. }
  6612. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6613. $type = 'link';
  6614. $stringforoptions = $reg[1].':'.$reg[2];
  6615. if ($reg[1] == 'User') {
  6616. $stringforoptions .= ':-1';
  6617. }
  6618. $param['options'] = array($stringforoptions => $stringforoptions);
  6619. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6620. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6621. $type = 'sellist';
  6622. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6623. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6624. $type = 'sellist';
  6625. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6626. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6627. $type = 'sellist';
  6628. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6629. $param['options'] = array($reg[1] => 'N');
  6630. $type = 'chkbxlst';
  6631. }
  6632. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6633. $list = (empty($val['list']) ? '' : $val['list']);
  6634. $help = (empty($val['help']) ? '' : $val['help']);
  6635. $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)
  6636. if ($hidden) {
  6637. return '';
  6638. }
  6639. // If field is a computed field, value must become result of compute
  6640. if ($computed) {
  6641. // Make the eval of compute string
  6642. //var_dump($computed);
  6643. $value = dol_eval($computed, 1, 0, '');
  6644. }
  6645. if (empty($morecss)) {
  6646. if ($type == 'date') {
  6647. $morecss = 'minwidth100imp';
  6648. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6649. $morecss = 'minwidth200imp';
  6650. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6651. $morecss = 'maxwidth75';
  6652. } elseif ($type == 'url') {
  6653. $morecss = 'minwidth400';
  6654. } elseif ($type == 'boolean') {
  6655. $morecss = '';
  6656. } else {
  6657. if (is_numeric($size) && round($size) < 12) {
  6658. $morecss = 'minwidth100';
  6659. } elseif (is_numeric($size) && round($size) <= 48) {
  6660. $morecss = 'minwidth200';
  6661. } else {
  6662. $morecss = 'minwidth400';
  6663. }
  6664. }
  6665. }
  6666. // Format output value differently according to properties of field
  6667. if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
  6668. if ($key != 'rowid' || empty($this->fields['ref'])) { // If we want ref field or if we want ID and there is no ref field, we show the link.
  6669. $value = $this->getNomUrl(1, '', 0, '', 1);
  6670. }
  6671. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6672. $value = $this->getLibStatut(3);
  6673. } elseif ($type == 'date') {
  6674. if (!empty($value)) {
  6675. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6676. } else {
  6677. $value = '';
  6678. }
  6679. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6680. if (!empty($value)) {
  6681. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6682. } else {
  6683. $value = '';
  6684. }
  6685. } elseif ($type == 'duration') {
  6686. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6687. if (!is_null($value) && $value !== '') {
  6688. $value = convertSecondToTime($value, 'allhourmin');
  6689. }
  6690. } elseif ($type == 'double' || $type == 'real') {
  6691. if (!is_null($value) && $value !== '') {
  6692. $value = price($value);
  6693. }
  6694. } elseif ($type == 'boolean') {
  6695. $checked = '';
  6696. if (!empty($value)) {
  6697. $checked = ' checked ';
  6698. }
  6699. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6700. } elseif ($type == 'mail' || $type == 'email') {
  6701. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6702. } elseif ($type == 'url') {
  6703. $value = dol_print_url($value, '_blank', 32, 1);
  6704. } elseif ($type == 'phone') {
  6705. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
  6706. } elseif ($type == 'ip') {
  6707. $value = dol_print_ip($value, 0);
  6708. } elseif ($type == 'price') {
  6709. if (!is_null($value) && $value !== '') {
  6710. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6711. }
  6712. } elseif ($type == 'select') {
  6713. $value = isset($param['options'][$value])?$param['options'][$value]:'';
  6714. } elseif ($type == 'sellist') {
  6715. $param_list = array_keys($param['options']);
  6716. $InfoFieldList = explode(":", $param_list[0]);
  6717. $selectkey = "rowid";
  6718. $keyList = 'rowid';
  6719. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6720. $selectkey = $InfoFieldList[2];
  6721. $keyList = $InfoFieldList[2].' as rowid';
  6722. }
  6723. $fields_label = explode('|', $InfoFieldList[1]);
  6724. if (is_array($fields_label)) {
  6725. $keyList .= ', ';
  6726. $keyList .= implode(', ', $fields_label);
  6727. }
  6728. $filter_categorie = false;
  6729. if (count($InfoFieldList) > 5) {
  6730. if ($InfoFieldList[0] == 'categorie') {
  6731. $filter_categorie = true;
  6732. }
  6733. }
  6734. $sql = "SELECT ".$keyList;
  6735. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6736. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6737. $sql .= ' as main';
  6738. }
  6739. if ($selectkey == 'rowid' && empty($value)) {
  6740. $sql .= " WHERE ".$selectkey." = 0";
  6741. } elseif ($selectkey == 'rowid') {
  6742. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6743. } else {
  6744. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6745. }
  6746. //$sql.= ' AND entity = '.$conf->entity;
  6747. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6748. $resql = $this->db->query($sql);
  6749. if ($resql) {
  6750. if ($filter_categorie === false) {
  6751. $value = ''; // value was used, so now we reste it to use it to build final output
  6752. $numrows = $this->db->num_rows($resql);
  6753. if ($numrows) {
  6754. $obj = $this->db->fetch_object($resql);
  6755. // Several field into label (eq table:code|libelle:rowid)
  6756. $fields_label = explode('|', $InfoFieldList[1]);
  6757. if (is_array($fields_label) && count($fields_label) > 1) {
  6758. foreach ($fields_label as $field_toshow) {
  6759. $translabel = '';
  6760. if (!empty($obj->$field_toshow)) {
  6761. $translabel = $langs->trans($obj->$field_toshow);
  6762. }
  6763. if ($translabel != $field_toshow) {
  6764. $value .= dol_trunc($translabel, 18) . ' ';
  6765. } else {
  6766. $value .= $obj->$field_toshow . ' ';
  6767. }
  6768. }
  6769. } else {
  6770. $translabel = '';
  6771. if (!empty($obj->{$InfoFieldList[1]})) {
  6772. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6773. }
  6774. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6775. $value = dol_trunc($translabel, 18);
  6776. } else {
  6777. $value = $obj->{$InfoFieldList[1]};
  6778. }
  6779. }
  6780. }
  6781. } else {
  6782. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6783. $toprint = array();
  6784. $obj = $this->db->fetch_object($resql);
  6785. $c = new Categorie($this->db);
  6786. $c->fetch($obj->rowid);
  6787. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  6788. foreach ($ways as $way) {
  6789. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  6790. }
  6791. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6792. }
  6793. } else {
  6794. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6795. }
  6796. } elseif ($type == 'radio') {
  6797. $value = $param['options'][$value];
  6798. } elseif ($type == 'checkbox') {
  6799. $value_arr = explode(',', $value);
  6800. $value = '';
  6801. if (is_array($value_arr) && count($value_arr) > 0) {
  6802. $toprint = array();
  6803. foreach ($value_arr as $keyval => $valueval) {
  6804. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6805. }
  6806. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6807. }
  6808. } elseif ($type == 'chkbxlst') {
  6809. $value_arr = explode(',', $value);
  6810. $param_list = array_keys($param['options']);
  6811. $InfoFieldList = explode(":", $param_list[0]);
  6812. $selectkey = "rowid";
  6813. $keyList = 'rowid';
  6814. if (count($InfoFieldList) >= 3) {
  6815. $selectkey = $InfoFieldList[2];
  6816. $keyList = $InfoFieldList[2].' as rowid';
  6817. }
  6818. $fields_label = explode('|', $InfoFieldList[1]);
  6819. if (is_array($fields_label)) {
  6820. $keyList .= ', ';
  6821. $keyList .= implode(', ', $fields_label);
  6822. }
  6823. $filter_categorie = false;
  6824. if (count($InfoFieldList) > 5) {
  6825. if ($InfoFieldList[0] == 'categorie') {
  6826. $filter_categorie = true;
  6827. }
  6828. }
  6829. $sql = "SELECT ".$keyList;
  6830. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6831. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6832. $sql .= ' as main';
  6833. }
  6834. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6835. // $sql.= ' AND entity = '.$conf->entity;
  6836. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6837. $resql = $this->db->query($sql);
  6838. if ($resql) {
  6839. if ($filter_categorie === false) {
  6840. $value = ''; // value was used, so now we reste it to use it to build final output
  6841. $toprint = array();
  6842. while ($obj = $this->db->fetch_object($resql)) {
  6843. // Several field into label (eq table:code|libelle:rowid)
  6844. $fields_label = explode('|', $InfoFieldList[1]);
  6845. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6846. if (is_array($fields_label) && count($fields_label) > 1) {
  6847. foreach ($fields_label as $field_toshow) {
  6848. $translabel = '';
  6849. if (!empty($obj->$field_toshow)) {
  6850. $translabel = $langs->trans($obj->$field_toshow);
  6851. }
  6852. if ($translabel != $field_toshow) {
  6853. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  6854. } else {
  6855. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
  6856. }
  6857. }
  6858. } else {
  6859. $translabel = '';
  6860. if (!empty($obj->{$InfoFieldList[1]})) {
  6861. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6862. }
  6863. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6864. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  6865. } else {
  6866. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
  6867. }
  6868. }
  6869. }
  6870. }
  6871. } else {
  6872. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6873. $toprint = array();
  6874. while ($obj = $this->db->fetch_object($resql)) {
  6875. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6876. $c = new Categorie($this->db);
  6877. $c->fetch($obj->rowid);
  6878. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  6879. foreach ($ways as $way) {
  6880. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  6881. }
  6882. }
  6883. }
  6884. }
  6885. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6886. } else {
  6887. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6888. }
  6889. } elseif ($type == 'link') {
  6890. $out = '';
  6891. // only if something to display (perf)
  6892. if ($value) {
  6893. $param_list = array_keys($param['options']); // Example: $param_list='ObjectName:classPath:-1::customer'
  6894. $InfoFieldList = explode(":", $param_list[0]);
  6895. $classname = $InfoFieldList[0];
  6896. $classpath = $InfoFieldList[1];
  6897. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6898. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6899. if (!empty($classpath)) {
  6900. dol_include_once($InfoFieldList[1]);
  6901. if ($classname && class_exists($classname)) {
  6902. $object = new $classname($this->db);
  6903. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6904. $result = $object->fetch($value, '', '', '', 0, 1, 1);
  6905. } else {
  6906. $result = $object->fetch($value);
  6907. }
  6908. if ($result > 0) {
  6909. if ($object->element === 'product') {
  6910. $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
  6911. if (isset($val['get_name_url_params'])) {
  6912. $get_name_url_params = explode(':', $val['get_name_url_params']);
  6913. if (!empty($get_name_url_params)) {
  6914. $param_num_max = count($get_name_url_param_arr) - 1;
  6915. foreach ($get_name_url_params as $param_num => $param_value) {
  6916. if ($param_num > $param_num_max) {
  6917. break;
  6918. }
  6919. $get_name_url_param_arr[$param_num] = $param_value;
  6920. }
  6921. }
  6922. }
  6923. /**
  6924. * @var Product $object
  6925. */
  6926. $value = $object->getNomUrl($get_name_url_param_arr[0], $get_name_url_param_arr[1], $get_name_url_param_arr[2], $get_name_url_param_arr[3], $get_name_url_param_arr[4], $get_name_url_param_arr[5], $get_name_url_param_arr[6]);
  6927. } else {
  6928. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6929. }
  6930. } else {
  6931. $value = '';
  6932. }
  6933. }
  6934. } else {
  6935. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6936. return 'Error bad setup of extrafield';
  6937. }
  6938. } else {
  6939. $value = '';
  6940. }
  6941. } elseif ($type == 'password') {
  6942. $value = preg_replace('/./i', '*', $value);
  6943. } elseif ($type == 'array') {
  6944. $value = implode('<br>', $value);
  6945. } else { // text|html|varchar
  6946. $value = dol_htmlentitiesbr($value);
  6947. }
  6948. //print $type.'-'.$size.'-'.$value;
  6949. $out = $value;
  6950. return $out;
  6951. }
  6952. /**
  6953. * clear validation message result for a field
  6954. *
  6955. * @param string $fieldKey Key of attribute to clear
  6956. * @return void
  6957. */
  6958. public function clearFieldError($fieldKey)
  6959. {
  6960. $this->error = '';
  6961. unset($this->validateFieldsErrors[$fieldKey]);
  6962. }
  6963. /**
  6964. * set validation error message a field
  6965. *
  6966. * @param string $fieldKey Key of attribute
  6967. * @param string $msg the field error message
  6968. * @return void
  6969. */
  6970. public function setFieldError($fieldKey, $msg = '')
  6971. {
  6972. global $langs;
  6973. if (empty($msg)) {
  6974. $msg = $langs->trans("UnknowError");
  6975. }
  6976. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6977. }
  6978. /**
  6979. * get field error message
  6980. *
  6981. * @param string $fieldKey Key of attribute
  6982. * @return string Error message of validation ('' if no error)
  6983. */
  6984. public function getFieldError($fieldKey)
  6985. {
  6986. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6987. return $this->validateFieldsErrors[$fieldKey];
  6988. }
  6989. return '';
  6990. }
  6991. /**
  6992. * Return validation test result for a field
  6993. *
  6994. * @param array $fields Array of properties of field to show
  6995. * @param string $fieldKey Key of attribute
  6996. * @param string $fieldValue value of attribute
  6997. * @return bool return false if fail true on success, see $this->error for error message
  6998. */
  6999. public function validateField($fields, $fieldKey, $fieldValue)
  7000. {
  7001. global $langs;
  7002. if (!class_exists('Validate')) {
  7003. require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php';
  7004. }
  7005. $this->clearFieldError($fieldKey);
  7006. if (!isset($fields[$fieldKey])) {
  7007. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  7008. return false;
  7009. }
  7010. $val = $fields[$fieldKey];
  7011. $param = array();
  7012. $param['options'] = array();
  7013. $type = $val['type'];
  7014. $required = false;
  7015. if (isset($val['notnull']) && $val['notnull'] === 1) {
  7016. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  7017. $required = true;
  7018. }
  7019. $maxSize = 0;
  7020. $minSize = 0;
  7021. //
  7022. // PREPARE Elements
  7023. //
  7024. $reg = array();
  7025. // Convert var to be able to share same code than showOutputField of extrafields
  7026. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  7027. $type = 'varchar'; // convert varchar(xx) int varchar
  7028. $maxSize = $reg[1];
  7029. } elseif (preg_match('/varchar/', $type)) {
  7030. $type = 'varchar'; // convert varchar(xx) int varchar
  7031. }
  7032. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7033. $type = 'select';
  7034. }
  7035. if (!empty($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7036. $type = 'link';
  7037. }
  7038. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7039. $param['options'] = $val['arrayofkeyval'];
  7040. }
  7041. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7042. $type = 'link';
  7043. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  7044. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7045. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  7046. $type = 'sellist';
  7047. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7048. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  7049. $type = 'sellist';
  7050. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  7051. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  7052. $type = 'sellist';
  7053. }
  7054. //
  7055. // TEST Value
  7056. //
  7057. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  7058. $validate = new Validate($this->db, $langs);
  7059. // little trick : to perform tests with good performances sort tests by quick to low
  7060. //
  7061. // COMMON TESTS
  7062. //
  7063. // Required test and empty value
  7064. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  7065. $this->setFieldError($fieldKey, $validate->error);
  7066. return false;
  7067. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  7068. // if no value sent and the field is not mandatory, no need to perform tests
  7069. return true;
  7070. }
  7071. // MAX Size test
  7072. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  7073. $this->setFieldError($fieldKey, $validate->error);
  7074. return false;
  7075. }
  7076. // MIN Size test
  7077. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  7078. $this->setFieldError($fieldKey, $validate->error);
  7079. return false;
  7080. }
  7081. //
  7082. // TESTS for TYPE
  7083. //
  7084. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  7085. if (!$validate->isTimestamp($fieldValue)) {
  7086. $this->setFieldError($fieldKey, $validate->error);
  7087. return false;
  7088. } else { return true; }
  7089. } elseif ($type == 'duration') {
  7090. if (!$validate->isDuration($fieldValue)) {
  7091. $this->setFieldError($fieldKey, $validate->error);
  7092. return false;
  7093. } else { return true; }
  7094. } elseif (in_array($type, array('double', 'real', 'price'))) {
  7095. // is numeric
  7096. if (!$validate->isNumeric($fieldValue)) {
  7097. $this->setFieldError($fieldKey, $validate->error);
  7098. return false;
  7099. } else { return true; }
  7100. } elseif ($type == 'boolean') {
  7101. if (!$validate->isBool($fieldValue)) {
  7102. $this->setFieldError($fieldKey, $validate->error);
  7103. return false;
  7104. } else { return true; }
  7105. } elseif ($type == 'mail') {
  7106. if (!$validate->isEmail($fieldValue)) {
  7107. $this->setFieldError($fieldKey, $validate->error);
  7108. return false;
  7109. }
  7110. } elseif ($type == 'url') {
  7111. if (!$validate->isUrl($fieldValue)) {
  7112. $this->setFieldError($fieldKey, $validate->error);
  7113. return false;
  7114. } else { return true; }
  7115. } elseif ($type == 'phone') {
  7116. if (!$validate->isPhone($fieldValue)) {
  7117. $this->setFieldError($fieldKey, $validate->error);
  7118. return false;
  7119. } else { return true; }
  7120. } elseif ($type == 'select' || $type == 'radio') {
  7121. if (!isset($param['options'][$fieldValue])) {
  7122. $this->error = $langs->trans('RequireValidValue');
  7123. return false;
  7124. } else { return true; }
  7125. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  7126. $param_list = array_keys($param['options']);
  7127. $InfoFieldList = explode(":", $param_list[0]);
  7128. $value_arr = explode(',', $fieldValue);
  7129. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  7130. $selectkey = "rowid";
  7131. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  7132. $selectkey = $InfoFieldList[2];
  7133. }
  7134. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  7135. $this->setFieldError($fieldKey, $validate->error);
  7136. return false;
  7137. } else { return true; }
  7138. } elseif ($type == 'link') {
  7139. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  7140. $InfoFieldList = explode(":", $param_list[0]);
  7141. $classname = $InfoFieldList[0];
  7142. $classpath = $InfoFieldList[1];
  7143. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  7144. $this->setFieldError($fieldKey, $validate->error);
  7145. return false;
  7146. } else { return true; }
  7147. }
  7148. // if no test failled all is ok
  7149. return true;
  7150. }
  7151. /**
  7152. * Function to show lines of extrafields with output datas.
  7153. * 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
  7154. *
  7155. * @param Extrafields $extrafields Extrafield Object
  7156. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  7157. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  7158. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  7159. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  7160. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  7161. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  7162. * @return string String with html content to show
  7163. */
  7164. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  7165. {
  7166. global $db, $conf, $langs, $action, $form, $hookmanager;
  7167. if (!is_object($form)) {
  7168. $form = new Form($db);
  7169. }
  7170. if (!is_object($extrafields)) {
  7171. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  7172. return 'Bad parameter extrafields for showOptionals';
  7173. }
  7174. if (!is_array($extrafields->attributes[$this->table_element])) {
  7175. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  7176. }
  7177. $out = '';
  7178. $parameters = array('mode'=>$mode, 'params'=>$params, 'keysuffix'=>$keysuffix, 'keyprefix'=>$keyprefix, 'display_type'=>$display_type);
  7179. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  7180. if (empty($reshook)) {
  7181. if (is_array($extrafields->attributes[$this->table_element]) && key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  7182. $out .= "\n";
  7183. $out .= '<!-- commonobject:showOptionals --> ';
  7184. $out .= "\n";
  7185. $nbofextrafieldsshown = 0;
  7186. $e = 0; // var to manage the modulo (odd/even)
  7187. $lastseparatorkeyfound = '';
  7188. $extrafields_collapse_num = '';
  7189. $extrafields_collapse_num_old = '';
  7190. $i = 0;
  7191. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  7192. $i++;
  7193. // Show only the key field in params
  7194. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  7195. continue;
  7196. }
  7197. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  7198. $enabled = 1;
  7199. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  7200. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
  7201. }
  7202. if (empty($enabled)) {
  7203. continue;
  7204. }
  7205. $visibility = 1;
  7206. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  7207. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
  7208. }
  7209. $perms = 1;
  7210. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  7211. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
  7212. }
  7213. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7214. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7215. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7216. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7217. } elseif ($mode == 'view' && empty($visibility)) {
  7218. continue;
  7219. }
  7220. if (empty($perms)) {
  7221. continue;
  7222. }
  7223. // Load language if required
  7224. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7225. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7226. }
  7227. $colspan = 0;
  7228. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  7229. if (array_key_exists('cols', $params)) {
  7230. $colspan = $params['cols'];
  7231. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7232. $reg = array();
  7233. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7234. $colspan = $reg[1];
  7235. } else {
  7236. $colspan = $params['colspan'];
  7237. }
  7238. }
  7239. }
  7240. $colspan = intval($colspan);
  7241. switch ($mode) {
  7242. case "view":
  7243. $value = ((!empty($this->array_options) && array_key_exists("options_".$key.$keysuffix, $this->array_options)) ? $this->array_options["options_".$key.$keysuffix] : null); // Value may be cleaned or formated later
  7244. break;
  7245. case "create":
  7246. case "edit":
  7247. // We get the value of property found with GETPOST so it takes into account:
  7248. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7249. $check = 'alphanohtml';
  7250. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7251. $check = 'restricthtml';
  7252. }
  7253. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7254. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7255. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7256. if (is_array($getposttemp)) {
  7257. // $getposttemp is an array but following code expects a comma separated string
  7258. $value = implode(",", $getposttemp);
  7259. } else {
  7260. $value = $getposttemp;
  7261. }
  7262. } else {
  7263. $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.
  7264. }
  7265. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7266. break;
  7267. }
  7268. $nbofextrafieldsshown++;
  7269. // Output value of the current field
  7270. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7271. $extrafields_collapse_num = $key;
  7272. /*
  7273. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7274. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7275. $extrafield_param_list = array_keys($extrafield_param['options']);
  7276. if (count($extrafield_param_list) > 0) {
  7277. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7278. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7279. //$extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7280. $extrafields_collapse_num = $key;
  7281. }
  7282. }
  7283. }
  7284. */
  7285. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7286. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7287. $lastseparatorkeyfound = $key;
  7288. } else {
  7289. $collapse_group = $extrafields_collapse_num.(!empty($this->id) ? '_'.$this->id : '');
  7290. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7291. $csstyle = '';
  7292. if (is_array($params) && count($params) > 0) {
  7293. if (array_key_exists('class', $params)) {
  7294. $class .= $params['class'].' ';
  7295. }
  7296. if (array_key_exists('style', $params)) {
  7297. $csstyle = $params['style'];
  7298. }
  7299. }
  7300. // add html5 elements
  7301. $domData = ' data-element="extrafield"';
  7302. $domData .= ' data-targetelement="'.$this->element.'"';
  7303. $domData .= ' data-targetid="'.$this->id.'"';
  7304. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7305. if ($display_type=='card') {
  7306. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7307. $colspan = 0;
  7308. }
  7309. if ($action == 'selectlines') {
  7310. $colspan++;
  7311. }
  7312. }
  7313. // Convert date into timestamp format (value in memory must be a timestamp)
  7314. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7315. $datenotinstring = null;
  7316. if (array_key_exists('options_'.$key, $this->array_options)) {
  7317. $datenotinstring = $this->array_options['options_'.$key];
  7318. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7319. $datenotinstring = $this->db->jdate($datenotinstring);
  7320. }
  7321. }
  7322. $datekey = $keyprefix.'options_'.$key.$keysuffix;
  7323. $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
  7324. }
  7325. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7326. $datenotinstring = null;
  7327. if (array_key_exists('options_'.$key, $this->array_options)) {
  7328. $datenotinstring = $this->array_options['options_'.$key];
  7329. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7330. $datenotinstring = $this->db->jdate($datenotinstring);
  7331. }
  7332. }
  7333. $timekey = $keyprefix.'options_'.$key.$keysuffix;
  7334. $value = (GETPOSTISSET($timekey)) ? dol_mktime(GETPOST($timekey.'hour', 'int', 3), GETPOST($timekey.'min', 'int', 3), GETPOST($timekey.'sec', 'int', 3), GETPOST($timekey.'month', 'int', 3), GETPOST($timekey.'day', 'int', 3), GETPOST($timekey.'year', 'int', 3), 'tzuserrel') : $datenotinstring;
  7335. }
  7336. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7337. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7338. if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
  7339. $value = price2num($value);
  7340. } elseif (isset($this->array_options['options_'.$key])) {
  7341. $value = $this->array_options['options_'.$key];
  7342. }
  7343. }
  7344. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7345. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
  7346. if ($action == 'create') {
  7347. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7348. }
  7349. }
  7350. $labeltoshow = $langs->trans($label);
  7351. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7352. if ($display_type == 'card') {
  7353. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
  7354. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
  7355. $out .= '<td></td>';
  7356. }
  7357. $out .= '<td class="'.(empty($params['tdclass']) ? 'titlefieldcreate' : $params['tdclass']).' wordbreak';
  7358. } elseif ($display_type == 'line') {
  7359. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
  7360. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  7361. }
  7362. //$out .= "titlefield";
  7363. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7364. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7365. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7366. if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
  7367. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7368. $out .= ' fieldrequired';
  7369. }
  7370. }
  7371. $out .= '">';
  7372. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7373. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7374. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7375. } else {
  7376. $out .= $labeltoshow;
  7377. }
  7378. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7379. $out .= '&nbsp;<span style="color: red">*</span>';
  7380. }
  7381. } else {
  7382. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7383. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7384. } else {
  7385. $out .= $labeltoshow;
  7386. }
  7387. }
  7388. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7389. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7390. if ($display_type == 'card') {
  7391. // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one
  7392. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7393. } elseif ($display_type == 'line') {
  7394. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="valuefieldcreate '.$this->element.'_extras_'.$key.' extra_inline_'.$extrafields->attributes[$this->table_element]['type'][$key].'">';
  7395. }
  7396. switch ($mode) {
  7397. case "view":
  7398. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7399. break;
  7400. case "create":
  7401. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7402. break;
  7403. case "edit":
  7404. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7405. break;
  7406. }
  7407. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7408. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7409. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7410. } else {
  7411. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7412. }
  7413. $e++;
  7414. }
  7415. }
  7416. $out .= "\n";
  7417. // Add code to manage list depending on others
  7418. if (!empty($conf->use_javascript_ajax)) {
  7419. $out .= $this->getJSListDependancies();
  7420. }
  7421. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7422. if (empty($nbofextrafieldsshown)) {
  7423. $out = '';
  7424. }
  7425. }
  7426. }
  7427. $out .= $hookmanager->resPrint;
  7428. return $out;
  7429. }
  7430. /**
  7431. * @param string $type Type for prefix
  7432. * @return string Javacript code to manage dependency
  7433. */
  7434. public function getJSListDependancies($type = '_extra')
  7435. {
  7436. $out = '
  7437. <script nonce="'.getNonce().'">
  7438. jQuery(document).ready(function() {
  7439. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7440. {
  7441. var val = $("select[name=\""+parent_list+"\"]").val();
  7442. var parentVal = parent_list + ":" + val;
  7443. if(typeof val == "string"){
  7444. if(val != "") {
  7445. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7446. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7447. $("select[name=\""+child_list+"\"]").append(options);
  7448. } else {
  7449. var options = orig_select.find("option[parent]").clone();
  7450. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7451. $("select[name=\""+child_list+"\"]").append(options);
  7452. }
  7453. } else if(val > 0) {
  7454. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7455. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7456. $("select[name=\""+child_list+"\"]").append(options);
  7457. } else {
  7458. var options = orig_select.find("option[parent]").clone();
  7459. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7460. $("select[name=\""+child_list+"\"]").append(options);
  7461. }
  7462. }
  7463. function setListDependencies'.$type.'() {
  7464. jQuery("select option[parent]").parent().each(function() {
  7465. var orig_select = {};
  7466. var child_list = $(this).attr("name");
  7467. orig_select[child_list] = $(this).clone();
  7468. var parent = $(this).find("option[parent]:first").attr("parent");
  7469. var infos = parent.split(":");
  7470. var parent_list = infos[0];
  7471. //Hide daughters lists
  7472. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7473. $("#"+child_list).hide();
  7474. //Show mother lists
  7475. } else if ($("#"+parent_list).val() != 0){
  7476. $("#"+parent_list).show();
  7477. }
  7478. //Show the child list if the parent list value is selected
  7479. $("select[name=\""+parent_list+"\"]").click(function() {
  7480. if ($(this).val() != 0){
  7481. $("#"+child_list).show()
  7482. }
  7483. });
  7484. //When we change parent list
  7485. $("select[name=\""+parent_list+"\"]").change(function() {
  7486. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7487. //Select the value 0 on child list after a change on the parent list
  7488. $("#"+child_list).val(0).trigger("change");
  7489. //Hide child lists if the parent value is set to 0
  7490. if ($(this).val() == 0){
  7491. $("#"+child_list).hide();
  7492. }
  7493. });
  7494. });
  7495. }
  7496. setListDependencies'.$type.'();
  7497. });
  7498. </script>'."\n";
  7499. return $out;
  7500. }
  7501. /**
  7502. * Returns the rights used for this class
  7503. * @return stdClass
  7504. */
  7505. public function getRights()
  7506. {
  7507. global $user;
  7508. $element = $this->element;
  7509. if ($element == 'facturerec') {
  7510. $element = 'facture';
  7511. } elseif ($element == 'invoice_supplier_rec') {
  7512. return $user->rights->fournisseur->facture;
  7513. } elseif ($element == 'evaluation') {
  7514. return $user->rights->hrm->evaluation;
  7515. }
  7516. return $user->rights->{$element};
  7517. }
  7518. /**
  7519. * Function used to replace a thirdparty id with another one.
  7520. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7521. * Column name fk_soc MUST be used to identify thirdparties
  7522. *
  7523. * @param DoliDB $dbs Database handler
  7524. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7525. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7526. * @param string[] $tables Tables that need to be changed
  7527. * @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)
  7528. * @return bool True if success, False if error
  7529. */
  7530. public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7531. {
  7532. foreach ($tables as $table) {
  7533. $sql = 'UPDATE '.$dbs->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7534. if (!$dbs->query($sql)) {
  7535. if ($ignoreerrors) {
  7536. return true; // TODO Not enough. If there is A-B on kept thirdparty and B-C on old one, we must get A-B-C after merge. Not A-B.
  7537. }
  7538. //$this->errors = $db->lasterror();
  7539. return false;
  7540. }
  7541. }
  7542. return true;
  7543. }
  7544. /**
  7545. * Function used to replace a product id with another one.
  7546. * This function is meant to be called from replaceProduct with the appropriate tables
  7547. * Column name fk_product MUST be used to identify products
  7548. *
  7549. * @param DoliDB $dbs Database handler
  7550. * @param int $origin_id Old product id (the product to delete)
  7551. * @param int $dest_id New product id (the product that will received element of the other)
  7552. * @param string[] $tables Tables that need to be changed
  7553. * @param int $ignoreerrors Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old product may already exists on new one)
  7554. * @return bool True if success, False if error
  7555. */
  7556. public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7557. {
  7558. foreach ($tables as $table) {
  7559. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7560. if (!$dbs->query($sql)) {
  7561. if ($ignoreerrors) {
  7562. return true; // TODO Not enough. If there is A-B on kept product and B-C on old one, we must get A-B-C after merge. Not A-B.
  7563. }
  7564. //$this->errors = $db->lasterror();
  7565. return false;
  7566. }
  7567. }
  7568. return true;
  7569. }
  7570. /**
  7571. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7572. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7573. * elseif calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7574. * elseif calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7575. * else set min buy price as buy price
  7576. *
  7577. * @param float $unitPrice Product unit price
  7578. * @param float $discountPercent Line discount percent
  7579. * @param int $fk_product Product id
  7580. * @return float <0 if KO, buyprice if OK
  7581. */
  7582. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7583. {
  7584. global $conf;
  7585. $buyPrice = 0;
  7586. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7587. // When ForceBuyingPriceIfNull is set
  7588. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7589. } else {
  7590. // Get cost price for margin calculation
  7591. if (!empty($fk_product) && $fk_product > 0) {
  7592. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7593. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7594. $product = new Product($this->db);
  7595. $result = $product->fetch($fk_product);
  7596. if ($result <= 0) {
  7597. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7598. return -1;
  7599. }
  7600. if ($product->cost_price > 0) {
  7601. $buyPrice = $product->cost_price;
  7602. } elseif ($product->pmp > 0) {
  7603. $buyPrice = $product->pmp;
  7604. }
  7605. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7606. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7607. $product = new Product($this->db);
  7608. $result = $product->fetch($fk_product);
  7609. if ($result <= 0) {
  7610. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7611. return -1;
  7612. }
  7613. if ($product->pmp > 0) {
  7614. $buyPrice = $product->pmp;
  7615. }
  7616. }
  7617. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7618. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7619. $productFournisseur = new ProductFournisseur($this->db);
  7620. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7621. $buyPrice = $productFournisseur->fourn_unitprice;
  7622. } elseif ($result < 0) {
  7623. $this->errors[] = $productFournisseur->error;
  7624. return -2;
  7625. }
  7626. }
  7627. }
  7628. }
  7629. return $buyPrice;
  7630. }
  7631. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7632. /**
  7633. * Show photos of an object (nbmax maximum), into several columns
  7634. *
  7635. * @param string $modulepart 'product', 'ticket', ...
  7636. * @param string $sdir Directory to scan (full absolute path)
  7637. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7638. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7639. * @param int $nbbyrow Number of image per line or -1 to use div separator or 0 to use no separator. Used only if size=1 or 'small'.
  7640. * @param int $showfilename 1=Show filename
  7641. * @param int $showaction 1=Show icon with action links (resize, delete)
  7642. * @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.
  7643. * @param int $maxWidth Max width of original image when size='small'
  7644. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7645. * @param int|string $overwritetitle Do not add title tag on image
  7646. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7647. * @param string $cache A string if we want to use a cached version of image
  7648. * @param string $addphotorefcss Add CSS to img of photos
  7649. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7650. */
  7651. public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $overwritetitle = 0, $usesharelink = 0, $cache = '', $addphotorefcss = 'photoref')
  7652. {
  7653. // phpcs:enable
  7654. global $conf, $user, $langs;
  7655. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7656. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7657. $sortfield = 'position_name';
  7658. $sortorder = 'asc';
  7659. $dir = $sdir.'/';
  7660. $pdir = '/';
  7661. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7662. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7663. // For backward compatibility
  7664. if ($modulepart == 'product') {
  7665. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  7666. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7667. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7668. }
  7669. }
  7670. // Defined relative dir to DOL_DATA_ROOT
  7671. $relativedir = '';
  7672. if ($dir) {
  7673. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7674. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7675. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7676. }
  7677. $dirthumb = $dir.'thumbs/';
  7678. $pdirthumb = $pdir.'thumbs/';
  7679. $return = '<!-- Photo -->'."\n";
  7680. $nbphoto = 0;
  7681. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7682. /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatiblity, we scan also old dirs
  7683. {
  7684. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7685. $filearray=array_merge($filearray, $filearrayold);
  7686. }*/
  7687. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7688. if (count($filearray)) {
  7689. if ($sortfield && $sortorder) {
  7690. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7691. }
  7692. foreach ($filearray as $key => $val) {
  7693. $photo = '';
  7694. $file = $val['name'];
  7695. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7696. if (image_format_supported($file) >= 0) {
  7697. $nbphoto++;
  7698. $photo = $file;
  7699. $viewfilename = $file;
  7700. if ($size == 1 || $size == 'small') { // Format vignette
  7701. // Find name of thumb file
  7702. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7703. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7704. // The thumb does not exists, so we will use the original file
  7705. $dirthumb = $dir;
  7706. $pdirthumb = $pdir;
  7707. $photo_vignette = basename($file);
  7708. }
  7709. // Get filesize of original file
  7710. $imgarray = dol_getImageSize($dir.$photo);
  7711. if ($nbbyrow > 0) {
  7712. if ($nbphoto == 1) {
  7713. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7714. }
  7715. if ($nbphoto % $nbbyrow == 1) {
  7716. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7717. }
  7718. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">'."\n";
  7719. } elseif ($nbbyrow < 0) {
  7720. $return .= '<div class="inline-block">'."\n";
  7721. }
  7722. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7723. if (empty($nolink)) {
  7724. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7725. if ($urladvanced) {
  7726. $return .= '<a href="'.$urladvanced.'">';
  7727. } else {
  7728. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7729. }
  7730. }
  7731. // Show image (width height=$maxHeight)
  7732. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7733. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7734. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7735. if ($overwritetitle) {
  7736. if (is_numeric($overwritetitle)) {
  7737. $alt = '';
  7738. } else {
  7739. $alt = $overwritetitle;
  7740. }
  7741. }
  7742. if ($usesharelink) {
  7743. if ($val['share']) {
  7744. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7745. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7746. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'"'.($maxHeight ?' height="'.$maxHeight.'"': '').' src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).($cache ? '&cache='.urlencode($cache) : '').'" title="'.dol_escape_htmltag($alt).'">';
  7747. } else {
  7748. $return .= '<!-- Show original file -->';
  7749. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).($cache ? '&cache='.urlencode($cache) : '').'" title="'.dol_escape_htmltag($alt).'">';
  7750. }
  7751. } else {
  7752. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7753. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7754. }
  7755. } else {
  7756. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7757. $return .= '<!-- Show thumb -->';
  7758. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').' maxwidth150onsmartphone maxwidth200"'.($maxHeight ?' height="'.$maxHeight.'"': '').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.($cache ? '&cache='.urlencode($cache) : '').'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7759. } else {
  7760. $return .= '<!-- Show original file -->';
  7761. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.($cache ? '&cache='.urlencode($cache) : '').'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7762. }
  7763. }
  7764. if (empty($nolink)) {
  7765. $return .= '</a>';
  7766. }
  7767. if ($showfilename) {
  7768. $return .= '<br>'.$viewfilename;
  7769. }
  7770. if ($showaction) {
  7771. $return .= '<br>';
  7772. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7773. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7774. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=addthumb&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7775. }
  7776. // Special cas for product
  7777. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7778. // Link to resize
  7779. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7780. // Link to delete
  7781. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7782. $return .= img_delete().'</a>';
  7783. }
  7784. }
  7785. $return .= "\n";
  7786. if ($nbbyrow > 0) {
  7787. $return .= '</td>';
  7788. if (($nbphoto % $nbbyrow) == 0) {
  7789. $return .= '</tr>';
  7790. }
  7791. } elseif ($nbbyrow < 0) {
  7792. $return .= '</div>'."\n";
  7793. }
  7794. }
  7795. if (empty($size)) { // Format origine
  7796. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7797. if ($showfilename) {
  7798. $return .= '<br>'.$viewfilename;
  7799. }
  7800. if ($showaction) {
  7801. // Special case for product
  7802. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7803. // Link to resize
  7804. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7805. // Link to delete
  7806. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7807. $return .= img_delete().'</a>';
  7808. }
  7809. }
  7810. }
  7811. // On continue ou on arrete de boucler ?
  7812. if ($nbmax && $nbphoto >= $nbmax) {
  7813. break;
  7814. }
  7815. }
  7816. }
  7817. if ($size == 1 || $size == 'small') {
  7818. if ($nbbyrow > 0) {
  7819. // Ferme tableau
  7820. while ($nbphoto % $nbbyrow) {
  7821. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7822. $nbphoto++;
  7823. }
  7824. if ($nbphoto) {
  7825. $return .= '</table>';
  7826. }
  7827. }
  7828. }
  7829. }
  7830. $this->nbphoto = $nbphoto;
  7831. return $return;
  7832. }
  7833. /**
  7834. * Function test if type is array
  7835. *
  7836. * @param array $info content informations of field
  7837. * @return bool true if array
  7838. */
  7839. protected function isArray($info)
  7840. {
  7841. if (is_array($info)) {
  7842. if (isset($info['type']) && $info['type'] == 'array') {
  7843. return true;
  7844. } else {
  7845. return false;
  7846. }
  7847. }
  7848. return false;
  7849. }
  7850. /**
  7851. * Function test if type is date
  7852. *
  7853. * @param array $info content informations of field
  7854. * @return bool true if date
  7855. */
  7856. public function isDate($info)
  7857. {
  7858. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7859. return true;
  7860. }
  7861. return false;
  7862. }
  7863. /**
  7864. * Function test if type is duration
  7865. *
  7866. * @param array $info content informations of field
  7867. * @return bool true if field of type duration
  7868. */
  7869. public function isDuration($info)
  7870. {
  7871. if (is_array($info)) {
  7872. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7873. return true;
  7874. } else {
  7875. return false;
  7876. }
  7877. } else {
  7878. return false;
  7879. }
  7880. }
  7881. /**
  7882. * Function test if type is integer
  7883. *
  7884. * @param array $info content informations of field
  7885. * @return bool true if integer
  7886. */
  7887. public function isInt($info)
  7888. {
  7889. if (is_array($info)) {
  7890. if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
  7891. return true;
  7892. } else {
  7893. return false;
  7894. }
  7895. } else {
  7896. return false;
  7897. }
  7898. }
  7899. /**
  7900. * Function test if type is float
  7901. *
  7902. * @param array $info content informations of field
  7903. * @return bool true if float
  7904. */
  7905. public function isFloat($info)
  7906. {
  7907. if (is_array($info)) {
  7908. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7909. return true;
  7910. } else {
  7911. return false;
  7912. }
  7913. }
  7914. return false;
  7915. }
  7916. /**
  7917. * Function test if type is text
  7918. *
  7919. * @param array $info content informations of field
  7920. * @return bool true if type text
  7921. */
  7922. public function isText($info)
  7923. {
  7924. if (is_array($info)) {
  7925. if (isset($info['type']) && $info['type'] == 'text') {
  7926. return true;
  7927. } else {
  7928. return false;
  7929. }
  7930. }
  7931. return false;
  7932. }
  7933. /**
  7934. * Function test if field can be null
  7935. *
  7936. * @param array $info content informations of field
  7937. * @return bool true if it can be null
  7938. */
  7939. protected function canBeNull($info)
  7940. {
  7941. if (is_array($info)) {
  7942. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7943. return true;
  7944. } else {
  7945. return false;
  7946. }
  7947. }
  7948. return true;
  7949. }
  7950. /**
  7951. * Function test if field is forced to null if zero or empty
  7952. *
  7953. * @param array $info content informations of field
  7954. * @return bool true if forced to null
  7955. */
  7956. protected function isForcedToNullIfZero($info)
  7957. {
  7958. if (is_array($info)) {
  7959. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7960. return true;
  7961. } else {
  7962. return false;
  7963. }
  7964. }
  7965. return false;
  7966. }
  7967. /**
  7968. * Function test if is indexed
  7969. *
  7970. * @param array $info content informations of field
  7971. * @return bool
  7972. */
  7973. protected function isIndex($info)
  7974. {
  7975. if (is_array($info)) {
  7976. if (isset($info['index']) && $info['index'] == true) {
  7977. return true;
  7978. } else {
  7979. return false;
  7980. }
  7981. }
  7982. return false;
  7983. }
  7984. /**
  7985. * Function to prepare a part of the query for insert by returning an array with all properties of object.
  7986. *
  7987. * Note $this->${field} are set by the page that make the createCommon() or the updateCommon().
  7988. * $this->${field} should be a clean and string value (so date are formated for SQL insert).
  7989. *
  7990. * @return array Array with all values of each properties to update
  7991. */
  7992. protected function setSaveQuery()
  7993. {
  7994. global $conf;
  7995. $queryarray = array();
  7996. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7997. // Depending on field type ('datetime', ...)
  7998. if ($this->isDate($info)) {
  7999. if (empty($this->{$field})) {
  8000. $queryarray[$field] = null;
  8001. } else {
  8002. $queryarray[$field] = $this->db->idate($this->{$field});
  8003. }
  8004. } elseif ($this->isDuration($info)) {
  8005. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8006. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8007. if (!isset($this->{$field})) {
  8008. if (!empty($info['default'])) {
  8009. $queryarray[$field] = $info['default'];
  8010. } else {
  8011. $queryarray[$field] = 0;
  8012. }
  8013. } else {
  8014. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8015. }
  8016. } else {
  8017. $queryarray[$field] = null;
  8018. }
  8019. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  8020. if ($field == 'entity' && is_null($this->{$field})) {
  8021. $queryarray[$field] = ((int) $conf->entity);
  8022. } else {
  8023. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8024. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8025. if (!isset($this->{$field})) {
  8026. $queryarray[$field] = 0;
  8027. } elseif ($this->isInt($info)) {
  8028. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8029. } elseif ($this->isFloat($info)) {
  8030. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8031. }
  8032. } else {
  8033. $queryarray[$field] = null;
  8034. }
  8035. }
  8036. } else {
  8037. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  8038. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  8039. $queryarray[$field] = $this->{$field};
  8040. }
  8041. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  8042. unset($queryarray[$field]);
  8043. }
  8044. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  8045. $queryarray[$field] = null; // May force 0 to null
  8046. }
  8047. }
  8048. return $queryarray;
  8049. }
  8050. /**
  8051. * Function to load data from a SQL pointer into properties of current object $this
  8052. *
  8053. * @param stdClass $obj Contain data of object from database
  8054. * @return void
  8055. */
  8056. public function setVarsFromFetchObj(&$obj)
  8057. {
  8058. global $db;
  8059. foreach ($this->fields as $field => $info) {
  8060. if ($this->isDate($info)) {
  8061. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  8062. $this->{$field} = '';
  8063. } else {
  8064. $this->{$field} = $db->jdate($obj->{$field});
  8065. }
  8066. } elseif ($this->isInt($info)) {
  8067. if ($field == 'rowid') {
  8068. $this->id = (int) $obj->{$field};
  8069. } else {
  8070. if ($this->isForcedToNullIfZero($info)) {
  8071. if (empty($obj->{$field})) {
  8072. $this->{$field} = null;
  8073. } else {
  8074. $this->{$field} = (double) $obj->{$field};
  8075. }
  8076. } else {
  8077. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8078. $this->{$field} = (int) $obj->{$field};
  8079. } else {
  8080. $this->{$field} = null;
  8081. }
  8082. }
  8083. }
  8084. } elseif ($this->isFloat($info)) {
  8085. if ($this->isForcedToNullIfZero($info)) {
  8086. if (empty($obj->{$field})) {
  8087. $this->{$field} = null;
  8088. } else {
  8089. $this->{$field} = (double) $obj->{$field};
  8090. }
  8091. } else {
  8092. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8093. $this->{$field} = (double) $obj->{$field};
  8094. } else {
  8095. $this->{$field} = null;
  8096. }
  8097. }
  8098. } else {
  8099. $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
  8100. }
  8101. }
  8102. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  8103. if (!isset($this->fields['ref']) && isset($this->id)) {
  8104. $this->ref = $this->id;
  8105. }
  8106. }
  8107. /**
  8108. * Function to concat keys of fields
  8109. *
  8110. * @param string $alias String of alias of table for fields. For example 't'. It is recommended to use '' and set alias into fields defintion.
  8111. * @return string list of alias fields
  8112. */
  8113. public function getFieldList($alias = '')
  8114. {
  8115. $keys = array_keys($this->fields);
  8116. if (!empty($alias)) {
  8117. $keys_with_alias = array();
  8118. foreach ($keys as $fieldname) {
  8119. $keys_with_alias[] = $alias . '.' . $fieldname;
  8120. }
  8121. return implode(',', $keys_with_alias);
  8122. } else {
  8123. return implode(',', $keys);
  8124. }
  8125. }
  8126. /**
  8127. * Add quote to field value if necessary
  8128. *
  8129. * @param string|int $value Value to protect
  8130. * @param array $fieldsentry Properties of field
  8131. * @return string
  8132. */
  8133. protected function quote($value, $fieldsentry)
  8134. {
  8135. if (is_null($value)) {
  8136. return 'NULL';
  8137. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  8138. return price2num("$value");
  8139. } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
  8140. return (int) $value;
  8141. } elseif ($fieldsentry['type'] == 'boolean') {
  8142. if ($value) {
  8143. return 'true';
  8144. } else {
  8145. return 'false';
  8146. }
  8147. } else {
  8148. return "'".$this->db->escape($value)."'";
  8149. }
  8150. }
  8151. /**
  8152. * Create object into database
  8153. *
  8154. * @param User $user User that creates
  8155. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8156. * @return int <0 if KO, Id of created object if OK
  8157. */
  8158. public function createCommon(User $user, $notrigger = false)
  8159. {
  8160. global $langs;
  8161. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  8162. $error = 0;
  8163. $now = dol_now();
  8164. $fieldvalues = $this->setSaveQuery();
  8165. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  8166. $fieldvalues['date_creation'] = $this->db->idate($now);
  8167. }
  8168. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  8169. $fieldvalues['fk_user_creat'] = $user->id;
  8170. }
  8171. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  8172. if (array_key_exists('ref', $fieldvalues)) {
  8173. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8174. }
  8175. $keys = array();
  8176. $values = array(); // Array to store string forged for SQL syntax
  8177. foreach ($fieldvalues as $k => $v) {
  8178. $keys[$k] = $k;
  8179. $value = $this->fields[$k];
  8180. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  8181. }
  8182. // Clean and check mandatory
  8183. foreach ($keys as $key) {
  8184. // If field is an implicit foreign key field (so type = 'integer:...')
  8185. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8186. $values[$key] = '';
  8187. }
  8188. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8189. $values[$key] = '';
  8190. }
  8191. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  8192. $error++;
  8193. $langs->load("errors");
  8194. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  8195. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8196. }
  8197. // If value is null and there is a default value for field
  8198. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  8199. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  8200. }
  8201. // If field is an implicit foreign key field (so type = 'integer:...')
  8202. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  8203. if (isset($this->fields[$key]['default'])) {
  8204. $values[$key] = ((int) $this->fields[$key]['default']);
  8205. } else {
  8206. $values[$key] = 'null';
  8207. }
  8208. }
  8209. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  8210. $values[$key] = 'null';
  8211. }
  8212. }
  8213. if ($error) {
  8214. return -1;
  8215. }
  8216. $this->db->begin();
  8217. if (!$error) {
  8218. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  8219. $sql .= " (".implode(", ", $keys).')';
  8220. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  8221. $res = $this->db->query($sql);
  8222. if (!$res) {
  8223. $error++;
  8224. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  8225. $this->errors[] = "ErrorRefAlreadyExists";
  8226. } else {
  8227. $this->errors[] = $this->db->lasterror();
  8228. }
  8229. }
  8230. }
  8231. if (!$error) {
  8232. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  8233. }
  8234. // If we have a field ref with a default value of (PROV)
  8235. if (!$error) {
  8236. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  8237. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  8238. $resqlupdate = $this->db->query($sql);
  8239. if ($resqlupdate === false) {
  8240. $error++;
  8241. $this->errors[] = $this->db->lasterror();
  8242. } else {
  8243. $this->ref = '(PROV'.$this->id.')';
  8244. }
  8245. }
  8246. }
  8247. // Create extrafields
  8248. if (!$error) {
  8249. $result = $this->insertExtraFields();
  8250. if ($result < 0) {
  8251. $error++;
  8252. }
  8253. }
  8254. // Create lines
  8255. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8256. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8257. for ($i = 0; $i < $num; $i++) {
  8258. $line = $this->lines[$i];
  8259. $keyforparent = $this->fk_element;
  8260. $line->$keyforparent = $this->id;
  8261. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8262. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8263. if (!is_object($line)) {
  8264. $line = (object) $line;
  8265. }
  8266. $result = $line->create($user, 1);
  8267. if ($result < 0) {
  8268. $this->error = $line->error;
  8269. $this->db->rollback();
  8270. return -1;
  8271. }
  8272. }
  8273. }
  8274. // Triggers
  8275. if (!$error && !$notrigger) {
  8276. // Call triggers
  8277. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  8278. if ($result < 0) {
  8279. $error++;
  8280. }
  8281. // End call triggers
  8282. }
  8283. // Commit or rollback
  8284. if ($error) {
  8285. $this->db->rollback();
  8286. return -1;
  8287. } else {
  8288. $this->db->commit();
  8289. return $this->id;
  8290. }
  8291. }
  8292. /**
  8293. * Load object in memory from the database
  8294. *
  8295. * @param int $id Id object
  8296. * @param string $ref Ref
  8297. * @param string $morewhere More SQL filters (' AND ...')
  8298. * @return int <0 if KO, 0 if not found, >0 if OK
  8299. */
  8300. public function fetchCommon($id, $ref = null, $morewhere = '')
  8301. {
  8302. if (empty($id) && empty($ref) && empty($morewhere)) {
  8303. return -1;
  8304. }
  8305. $fieldlist = $this->getFieldList('t');
  8306. if (empty($fieldlist)) {
  8307. return 0;
  8308. }
  8309. $sql = "SELECT ".$fieldlist;
  8310. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8311. if (!empty($id)) {
  8312. $sql .= ' WHERE t.rowid = '.((int) $id);
  8313. } elseif (!empty($ref)) {
  8314. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8315. } else {
  8316. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8317. }
  8318. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8319. $sql .= ' AND t.entity IN ('.getEntity($this->element).')';
  8320. }
  8321. if ($morewhere) {
  8322. $sql .= $morewhere;
  8323. }
  8324. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8325. $res = $this->db->query($sql);
  8326. if ($res) {
  8327. $obj = $this->db->fetch_object($res);
  8328. if ($obj) {
  8329. $this->setVarsFromFetchObj($obj);
  8330. // Retrieve all extrafield
  8331. // fetch optionals attributes and labels
  8332. $this->fetch_optionals();
  8333. return $this->id;
  8334. } else {
  8335. return 0;
  8336. }
  8337. } else {
  8338. $this->error = $this->db->lasterror();
  8339. $this->errors[] = $this->error;
  8340. return -1;
  8341. }
  8342. }
  8343. /**
  8344. * Load object in memory from the database
  8345. *
  8346. * @param string $morewhere More SQL filters (' AND ...')
  8347. * @return int <0 if KO, 0 if not found, >0 if OK
  8348. */
  8349. public function fetchLinesCommon($morewhere = '')
  8350. {
  8351. $objectlineclassname = get_class($this).'Line';
  8352. if (!class_exists($objectlineclassname)) {
  8353. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8354. return -1;
  8355. }
  8356. $objectline = new $objectlineclassname($this->db);
  8357. $sql = "SELECT ".$objectline->getFieldList('l');
  8358. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8359. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8360. if ($morewhere) {
  8361. $sql .= $morewhere;
  8362. }
  8363. if (isset($objectline->fields['position'])) {
  8364. $sql .= $this->db->order('position', 'ASC');
  8365. }
  8366. $resql = $this->db->query($sql);
  8367. if ($resql) {
  8368. $num_rows = $this->db->num_rows($resql);
  8369. $i = 0;
  8370. while ($i < $num_rows) {
  8371. $obj = $this->db->fetch_object($resql);
  8372. if ($obj) {
  8373. $newline = new $objectlineclassname($this->db);
  8374. $newline->setVarsFromFetchObj($obj);
  8375. $this->lines[] = $newline;
  8376. }
  8377. $i++;
  8378. }
  8379. return 1;
  8380. } else {
  8381. $this->error = $this->db->lasterror();
  8382. $this->errors[] = $this->error;
  8383. return -1;
  8384. }
  8385. }
  8386. /**
  8387. * Update object into database
  8388. *
  8389. * @param User $user User that modifies
  8390. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8391. * @return int <0 if KO, >0 if OK
  8392. */
  8393. public function updateCommon(User $user, $notrigger = false)
  8394. {
  8395. global $conf, $langs;
  8396. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8397. $error = 0;
  8398. $now = dol_now();
  8399. // $this->oldcopy should have been set by the caller of update
  8400. //if (empty($this->oldcopy)) {
  8401. // $this->oldcopy = dol_clone($this);
  8402. //}
  8403. $fieldvalues = $this->setSaveQuery();
  8404. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8405. $fieldvalues['date_modification'] = $this->db->idate($now);
  8406. }
  8407. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8408. $fieldvalues['fk_user_modif'] = $user->id;
  8409. }
  8410. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8411. if (array_key_exists('ref', $fieldvalues)) {
  8412. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8413. }
  8414. // Add quotes and escape on fields with type string
  8415. $keys = array();
  8416. $values = array();
  8417. $tmp = array();
  8418. foreach ($fieldvalues as $k => $v) {
  8419. $keys[$k] = $k;
  8420. $value = $this->fields[$k];
  8421. $values[$k] = $this->quote($v, $value);
  8422. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8423. }
  8424. // Clean and check mandatory fields
  8425. foreach ($keys as $key) {
  8426. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8427. $values[$key] = ''; // This is an implicit foreign key field
  8428. }
  8429. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8430. $values[$key] = ''; // This is an explicit foreign key field
  8431. }
  8432. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8433. /*
  8434. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8435. {
  8436. $error++;
  8437. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8438. }*/
  8439. }
  8440. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8441. $this->db->begin();
  8442. if (!$error) {
  8443. $res = $this->db->query($sql);
  8444. if (!$res) {
  8445. $error++;
  8446. $this->errors[] = $this->db->lasterror();
  8447. }
  8448. }
  8449. // Update extrafield
  8450. if (!$error) {
  8451. $result = $this->insertExtraFields();
  8452. if ($result < 0) {
  8453. $error++;
  8454. }
  8455. }
  8456. // Triggers
  8457. if (!$error && !$notrigger) {
  8458. // Call triggers
  8459. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8460. if ($result < 0) {
  8461. $error++;
  8462. } //Do also here what you must do to rollback action if trigger fail
  8463. // End call triggers
  8464. }
  8465. // Commit or rollback
  8466. if ($error) {
  8467. $this->db->rollback();
  8468. return -1;
  8469. } else {
  8470. $this->db->commit();
  8471. return $this->id;
  8472. }
  8473. }
  8474. /**
  8475. * Delete object in database
  8476. *
  8477. * @param User $user User that deletes
  8478. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8479. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8480. * @return int <0 if KO, 0=Nothing done because object has child, >0 if OK
  8481. */
  8482. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8483. {
  8484. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8485. $error = 0;
  8486. $this->db->begin();
  8487. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8488. foreach ($this->childtables as $table) {
  8489. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8490. $resql = $this->db->query($sql);
  8491. if (!$resql) {
  8492. $this->error = $this->db->lasterror();
  8493. $this->errors[] = $this->error;
  8494. $this->db->rollback();
  8495. return -1;
  8496. }
  8497. }
  8498. } elseif (!empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8499. $objectisused = $this->isObjectUsed($this->id);
  8500. if (!empty($objectisused)) {
  8501. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8502. $this->error = 'ErrorRecordHasChildren';
  8503. $this->errors[] = $this->error;
  8504. $this->db->rollback();
  8505. return 0;
  8506. }
  8507. }
  8508. // Delete cascade first
  8509. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8510. foreach ($this->childtablesoncascade as $table) {
  8511. $deleteFromObject = explode(':', $table);
  8512. if (count($deleteFromObject) >= 2) {
  8513. $className = str_replace('@', '', $deleteFromObject[0]);
  8514. $filePath = $deleteFromObject[1];
  8515. $columnName = $deleteFromObject[2];
  8516. $TMoreSQL = array();
  8517. $more_sql = $deleteFromObject[3];
  8518. if (!empty($more_sql)) {
  8519. $TMoreSQL['customsql'] = $more_sql;
  8520. }
  8521. if (dol_include_once($filePath)) {
  8522. $childObject = new $className($this->db);
  8523. if (method_exists($childObject, 'deleteByParentField')) {
  8524. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8525. if ($result < 0) {
  8526. $error++;
  8527. $this->errors[] = $childObject->error;
  8528. break;
  8529. }
  8530. } else {
  8531. $error++;
  8532. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8533. break;
  8534. }
  8535. } else {
  8536. $error++;
  8537. $this->errors[] = 'Cannot include child class file '.$filePath;
  8538. break;
  8539. }
  8540. } else {
  8541. // Delete record in child table
  8542. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8543. $resql = $this->db->query($sql);
  8544. if (!$resql) {
  8545. $error++;
  8546. $this->error = $this->db->lasterror();
  8547. $this->errors[] = $this->error;
  8548. break;
  8549. }
  8550. }
  8551. }
  8552. }
  8553. if (!$error) {
  8554. if (!$notrigger) {
  8555. // Call triggers
  8556. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8557. if ($result < 0) {
  8558. $error++;
  8559. } // Do also here what you must do to rollback action if trigger fail
  8560. // End call triggers
  8561. }
  8562. }
  8563. // Delete llx_ecm_files
  8564. if (!$error) {
  8565. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8566. if (!$res) {
  8567. $error++;
  8568. }
  8569. }
  8570. // Delete linked object
  8571. $res = $this->deleteObjectLinked();
  8572. if ($res < 0) {
  8573. $error++;
  8574. }
  8575. if (!$error && !empty($this->isextrafieldmanaged)) {
  8576. $result = $this->deleteExtraFields();
  8577. if ($result < 0) {
  8578. $error++;
  8579. }
  8580. }
  8581. if (!$error) {
  8582. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8583. $resql = $this->db->query($sql);
  8584. if (!$resql) {
  8585. $error++;
  8586. $this->errors[] = $this->db->lasterror();
  8587. }
  8588. }
  8589. // Commit or rollback
  8590. if ($error) {
  8591. $this->db->rollback();
  8592. return -1;
  8593. } else {
  8594. $this->db->commit();
  8595. return 1;
  8596. }
  8597. }
  8598. /**
  8599. * Delete all child object from a parent ID
  8600. *
  8601. * @param int $parentId Parent Id
  8602. * @param string $parentField Name of Foreign key parent column
  8603. * @param array $filter an array filter
  8604. * @param string $filtermode AND or OR
  8605. * @return int <0 if KO, >0 if OK
  8606. * @throws Exception
  8607. */
  8608. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8609. {
  8610. global $user;
  8611. $error = 0;
  8612. $deleted = 0;
  8613. if (!empty($parentId) && !empty($parentField)) {
  8614. $this->db->begin();
  8615. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8616. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8617. // Manage filters
  8618. $sqlwhere = array();
  8619. if (count($filter) > 0) {
  8620. foreach ($filter as $key => $value) {
  8621. if ($key == 'customsql') {
  8622. $sqlwhere[] = $value;
  8623. } elseif (strpos($value, '%') === false) {
  8624. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8625. } else {
  8626. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8627. }
  8628. }
  8629. }
  8630. if (count($sqlwhere) > 0) {
  8631. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8632. }
  8633. $resql = $this->db->query($sql);
  8634. if (!$resql) {
  8635. $this->errors[] = $this->db->lasterror();
  8636. $error++;
  8637. } else {
  8638. while ($obj = $this->db->fetch_object($resql)) {
  8639. $result = $this->fetch($obj->rowid);
  8640. if ($result < 0) {
  8641. $error++;
  8642. $this->errors[] = $this->error;
  8643. } else {
  8644. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8645. $result = $this->delete();
  8646. } else {
  8647. $result = $this->delete($user);
  8648. }
  8649. if ($result < 0) {
  8650. $error++;
  8651. $this->errors[] = $this->error;
  8652. } else {
  8653. $deleted++;
  8654. }
  8655. }
  8656. }
  8657. }
  8658. if (empty($error)) {
  8659. $this->db->commit();
  8660. return $deleted;
  8661. } else {
  8662. $this->error = implode(', ', $this->errors);
  8663. $this->db->rollback();
  8664. return $error * -1;
  8665. }
  8666. }
  8667. return $deleted;
  8668. }
  8669. /**
  8670. * Delete a line of object in database
  8671. *
  8672. * @param User $user User that delete
  8673. * @param int $idline Id of line to delete
  8674. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8675. * @return int >0 if OK, <0 if KO
  8676. */
  8677. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8678. {
  8679. global $conf;
  8680. $error = 0;
  8681. $tmpforobjectclass = get_class($this);
  8682. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8683. $this->db->begin();
  8684. // Call trigger
  8685. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8686. if ($result < 0) {
  8687. $error++;
  8688. }
  8689. // End call triggers
  8690. if (empty($error)) {
  8691. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8692. $sql .= " WHERE rowid = ".((int) $idline);
  8693. $resql = $this->db->query($sql);
  8694. if (!$resql) {
  8695. $this->error = "Error ".$this->db->lasterror();
  8696. $error++;
  8697. }
  8698. }
  8699. if (empty($error)) {
  8700. // Remove extrafields
  8701. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8702. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8703. $tmpobjectline->id = $idline;
  8704. $result = $tmpobjectline->deleteExtraFields();
  8705. if ($result < 0) {
  8706. $error++;
  8707. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8708. }
  8709. }
  8710. }
  8711. if (empty($error)) {
  8712. $this->db->commit();
  8713. return 1;
  8714. } else {
  8715. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8716. $this->db->rollback();
  8717. return -1;
  8718. }
  8719. }
  8720. /**
  8721. * Set to a status
  8722. *
  8723. * @param User $user Object user that modify
  8724. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8725. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8726. * @param string $triggercode Trigger code to use
  8727. * @return int <0 if KO, >0 if OK
  8728. */
  8729. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8730. {
  8731. $error = 0;
  8732. $this->db->begin();
  8733. $statusfield = 'status';
  8734. if (in_array($this->element, array('don', 'donation', 'shipping'))) {
  8735. $statusfield = 'fk_statut';
  8736. }
  8737. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8738. $sql .= " SET ".$statusfield." = ".((int) $status);
  8739. $sql .= " WHERE rowid = ".((int) $this->id);
  8740. if ($this->db->query($sql)) {
  8741. if (!$error) {
  8742. $this->oldcopy = clone $this;
  8743. }
  8744. if (!$error && !$notrigger) {
  8745. // Call trigger
  8746. $result = $this->call_trigger($triggercode, $user);
  8747. if ($result < 0) {
  8748. $error++;
  8749. }
  8750. }
  8751. if (!$error) {
  8752. $this->status = $status;
  8753. $this->db->commit();
  8754. return 1;
  8755. } else {
  8756. $this->db->rollback();
  8757. return -1;
  8758. }
  8759. } else {
  8760. $this->error = $this->db->error();
  8761. $this->db->rollback();
  8762. return -1;
  8763. }
  8764. }
  8765. /**
  8766. * Initialise object with example values
  8767. * Id must be 0 if object instance is a specimen
  8768. *
  8769. * @return int
  8770. */
  8771. public function initAsSpecimenCommon()
  8772. {
  8773. global $user;
  8774. $this->id = 0;
  8775. $this->specimen = 1;
  8776. $fields = array(
  8777. 'label' => 'This is label',
  8778. 'ref' => 'ABCD1234',
  8779. 'description' => 'This is a description',
  8780. 'qty' => 123.12,
  8781. 'note_public' => 'Public note',
  8782. 'note_private' => 'Private note',
  8783. 'date_creation' => (dol_now() - 3600 * 48),
  8784. 'date_modification' => (dol_now() - 3600 * 24),
  8785. 'fk_user_creat' => $user->id,
  8786. 'fk_user_modif' => $user->id,
  8787. 'date' => dol_now(),
  8788. );
  8789. foreach ($fields as $key => $value) {
  8790. if (array_key_exists($key, $this->fields)) {
  8791. $this->{$key} = $value;
  8792. }
  8793. }
  8794. // Force values to default values when known
  8795. if (property_exists($this, 'fields')) {
  8796. foreach ($this->fields as $key => $value) {
  8797. // If fields are already set, do nothing
  8798. if (array_key_exists($key, $fields)) {
  8799. continue;
  8800. }
  8801. if (!empty($value['default'])) {
  8802. $this->$key = $value['default'];
  8803. }
  8804. }
  8805. }
  8806. return 1;
  8807. }
  8808. /* Part for comments */
  8809. /**
  8810. * Load comments linked with current task
  8811. * @return boolean 1 if ok
  8812. */
  8813. public function fetchComments()
  8814. {
  8815. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8816. $comment = new Comment($this->db);
  8817. $result = $comment->fetchAllFor($this->element, $this->id);
  8818. if ($result < 0) {
  8819. $this->errors = array_merge($this->errors, $comment->errors);
  8820. return -1;
  8821. } else {
  8822. $this->comments = $comment->comments;
  8823. }
  8824. return count($this->comments);
  8825. }
  8826. /**
  8827. * Return nb comments already posted
  8828. *
  8829. * @return int
  8830. */
  8831. public function getNbComments()
  8832. {
  8833. return count($this->comments);
  8834. }
  8835. /**
  8836. * Trim object parameters
  8837. *
  8838. * @param string[] $parameters array of parameters to trim
  8839. * @return void
  8840. */
  8841. public function trimParameters($parameters)
  8842. {
  8843. if (!is_array($parameters)) {
  8844. return;
  8845. }
  8846. foreach ($parameters as $parameter) {
  8847. if (isset($this->$parameter)) {
  8848. $this->$parameter = trim($this->$parameter);
  8849. }
  8850. }
  8851. }
  8852. /* Part for categories/tags */
  8853. /**
  8854. * Sets object to given categories.
  8855. *
  8856. * Deletes object from existing categories not supplied.
  8857. * Adds it to non existing supplied categories.
  8858. * Existing categories are left untouch.
  8859. *
  8860. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8861. * @return int Array of category objects or < 0 if KO
  8862. */
  8863. public function getCategoriesCommon($type_categ)
  8864. {
  8865. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8866. // Get current categories
  8867. $c = new Categorie($this->db);
  8868. $existing = $c->containing($this->id, $type_categ, 'id');
  8869. return $existing;
  8870. }
  8871. /**
  8872. * Sets object to given categories.
  8873. *
  8874. * Adds it to non existing supplied categories.
  8875. * Deletes object from existing categories not supplied (if remove_existing==true).
  8876. * Existing categories are left untouch.
  8877. *
  8878. * @param int[]|int $categories Category ID or array of Categories IDs
  8879. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8880. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8881. * @return int <0 if KO, >0 if OK
  8882. */
  8883. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8884. {
  8885. // Handle single category
  8886. if (!is_array($categories)) {
  8887. $categories = array($categories);
  8888. }
  8889. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8890. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8891. if (empty($type_categ)) {
  8892. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8893. return -1;
  8894. }
  8895. // Get current categories
  8896. $c = new Categorie($this->db);
  8897. $existing = $c->containing($this->id, $type_categ, 'id');
  8898. if ($remove_existing) {
  8899. // Diff
  8900. if (is_array($existing)) {
  8901. $to_del = array_diff($existing, $categories);
  8902. $to_add = array_diff($categories, $existing);
  8903. } else {
  8904. $to_del = array(); // Nothing to delete
  8905. $to_add = $categories;
  8906. }
  8907. } else {
  8908. $to_del = array(); // Nothing to delete
  8909. $to_add = array_diff($categories, $existing);
  8910. }
  8911. $error = 0;
  8912. $ok = 0;
  8913. // Process
  8914. foreach ($to_del as $del) {
  8915. if ($c->fetch($del) > 0) {
  8916. $result=$c->del_type($this, $type_categ);
  8917. if ($result < 0) {
  8918. $error++;
  8919. $this->error = $c->error;
  8920. $this->errors = $c->errors;
  8921. break;
  8922. } else {
  8923. $ok += $result;
  8924. }
  8925. }
  8926. }
  8927. foreach ($to_add as $add) {
  8928. if ($c->fetch($add) > 0) {
  8929. $result = $c->add_type($this, $type_categ);
  8930. if ($result < 0) {
  8931. $error++;
  8932. $this->error = $c->error;
  8933. $this->errors = $c->errors;
  8934. break;
  8935. } else {
  8936. $ok += $result;
  8937. }
  8938. }
  8939. }
  8940. return $error ? (-1 * $error) : $ok;
  8941. }
  8942. /**
  8943. * Copy related categories to another object
  8944. *
  8945. * @param int $fromId Id object source
  8946. * @param int $toId Id object cible
  8947. * @param string $type Type of category ('product', ...)
  8948. * @return int < 0 if error, > 0 if ok
  8949. */
  8950. public function cloneCategories($fromId, $toId, $type = '')
  8951. {
  8952. $this->db->begin();
  8953. if (empty($type)) {
  8954. $type = $this->table_element;
  8955. }
  8956. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8957. $categorystatic = new Categorie($this->db);
  8958. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8959. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8960. $sql .= " WHERE fk_product = ".((int) $fromId);
  8961. if (!$this->db->query($sql)) {
  8962. $this->error = $this->db->lasterror();
  8963. $this->db->rollback();
  8964. return -1;
  8965. }
  8966. $this->db->commit();
  8967. return 1;
  8968. }
  8969. /**
  8970. * Delete related files of object in database
  8971. *
  8972. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8973. * @return bool True if OK, False if KO
  8974. */
  8975. public function deleteEcmFiles($mode = 0)
  8976. {
  8977. global $conf;
  8978. $this->db->begin();
  8979. // Delete in database with mode 0
  8980. if ($mode == 0) {
  8981. switch ($this->element) {
  8982. case 'propal':
  8983. $element = 'propale';
  8984. break;
  8985. case 'product':
  8986. $element = 'produit';
  8987. break;
  8988. case 'order_supplier':
  8989. $element = 'fournisseur/commande';
  8990. break;
  8991. case 'invoice_supplier':
  8992. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8993. break;
  8994. case 'shipping':
  8995. $element = 'expedition/sending';
  8996. break;
  8997. default:
  8998. $element = $this->element;
  8999. }
  9000. // Delete ecm_files extrafields
  9001. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  9002. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  9003. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  9004. $sql .= ")";
  9005. if (!$this->db->query($sql)) {
  9006. $this->error = $this->db->lasterror();
  9007. $this->db->rollback();
  9008. return false;
  9009. }
  9010. // Delete ecm_files
  9011. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  9012. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  9013. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  9014. if (!$this->db->query($sql)) {
  9015. $this->error = $this->db->lasterror();
  9016. $this->db->rollback();
  9017. return false;
  9018. }
  9019. }
  9020. // Delete in database with mode 1
  9021. if ($mode == 1) {
  9022. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  9023. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id).")";
  9024. $resql = $this->db->query($sql);
  9025. if (!$resql) {
  9026. $this->error = $this->db->lasterror();
  9027. $this->db->rollback();
  9028. return false;
  9029. }
  9030. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  9031. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  9032. $resql = $this->db->query($sql);
  9033. if (!$resql) {
  9034. $this->error = $this->db->lasterror();
  9035. $this->db->rollback();
  9036. return false;
  9037. }
  9038. }
  9039. $this->db->commit();
  9040. return true;
  9041. }
  9042. }