commonobject.class.php 352 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242
  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 string ID of module.
  47. */
  48. public $module;
  49. /**
  50. * @var DoliDb Database handler (result of a new DoliDB)
  51. */
  52. public $db;
  53. /**
  54. * @var int The object identifier
  55. */
  56. public $id;
  57. /**
  58. * @var int The environment ID when using a multicompany module
  59. */
  60. public $entity;
  61. /**
  62. * @var string Error string
  63. * @see $errors
  64. */
  65. public $error;
  66. /**
  67. * @var string Error string that is hidden but can be used to store complementatry technical code.
  68. */
  69. public $errorhidden;
  70. /**
  71. * @var string[] Array of error strings
  72. */
  73. public $errors = array();
  74. /**
  75. * @var array To store error results of ->validateField()
  76. */
  77. private $validateFieldsErrors = array();
  78. /**
  79. * @var string ID to identify managed object
  80. */
  81. public $element;
  82. /**
  83. * @var int The related element
  84. */
  85. public $fk_element;
  86. /**
  87. * @var string Name to use for 'features' parameter to check module permissions user->rights->feature with restrictedArea().
  88. * 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.
  89. */
  90. public $element_for_permission;
  91. /**
  92. * @var string Name of table without prefix where object is stored
  93. */
  94. public $table_element;
  95. /**
  96. * @var string Name of subtable line
  97. */
  98. public $table_element_line = '';
  99. /**
  100. * @var int 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  101. */
  102. public $ismultientitymanaged;
  103. /**
  104. * @var string Key value used to track if data is coming from import wizard
  105. */
  106. public $import_key;
  107. /**
  108. * @var mixed Contains data to manage extrafields
  109. */
  110. public $array_options = array();
  111. /**
  112. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  113. */
  114. public $fields = array();
  115. /**
  116. * @var mixed Array to store alternative languages values of object
  117. */
  118. public $array_languages = null; // Value is array() when load already tried
  119. /**
  120. * @var array To store result of ->liste_contact()
  121. */
  122. public $contacts_ids;
  123. /**
  124. * @var mixed Array of linked objects, set and used when calling ->create() to be able to create links during the creation of object
  125. */
  126. public $linked_objects;
  127. /**
  128. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  129. */
  130. public $linkedObjectsIds;
  131. /**
  132. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  133. */
  134. public $linkedObjects;
  135. /**
  136. * @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.
  137. */
  138. private $linkedObjectsFullLoaded = array();
  139. /**
  140. * @var CommonObject To store a cloned copy of object before to edit it and keep track of old properties
  141. */
  142. public $oldcopy;
  143. /**
  144. * @var CommonObject To store old value of a modified ref
  145. */
  146. public $oldref;
  147. /**
  148. * @var string Column name of the ref field.
  149. */
  150. protected $table_ref_field = '';
  151. /**
  152. * @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
  153. */
  154. public $restrictiononfksoc = 0;
  155. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  156. /**
  157. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  158. */
  159. public $context = array();
  160. // Properties set and used by Agenda trigger
  161. public $actionmsg;
  162. public $actionmsg2;
  163. /**
  164. * @var string Contains canvas name if record is an alternative canvas record
  165. */
  166. public $canvas;
  167. /**
  168. * @var Project The related project object
  169. * @see fetch_projet()
  170. */
  171. public $project;
  172. /**
  173. * @var int The related project ID
  174. * @see setProject(), project
  175. */
  176. public $fk_project;
  177. /**
  178. * @var Project The related project object
  179. * @deprecated
  180. * @see project
  181. */
  182. public $projet;
  183. /**
  184. * @deprecated
  185. * @see $fk_project
  186. */
  187. public $fk_projet;
  188. /**
  189. * @var Contact A related contact object
  190. * @see fetch_contact()
  191. */
  192. public $contact;
  193. /**
  194. * @var int The related contact ID
  195. * @see fetch_contact()
  196. */
  197. public $contact_id;
  198. /**
  199. * @var Societe A related thirdparty object
  200. * @see fetch_thirdparty()
  201. */
  202. public $thirdparty;
  203. /**
  204. * @var User A related user
  205. * @see fetch_user()
  206. */
  207. public $user;
  208. /**
  209. * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type
  210. * @see fetch_origin()
  211. */
  212. public $origin;
  213. /**
  214. * @var int The id of originating object
  215. * @see fetch_origin()
  216. */
  217. public $origin_id;
  218. /**
  219. * @var string The object's reference
  220. */
  221. public $ref;
  222. /**
  223. * @var string An external reference for the object
  224. */
  225. public $ref_ext;
  226. /**
  227. * @var string The object's previous reference
  228. */
  229. public $ref_previous;
  230. /**
  231. * @var string The object's next reference
  232. */
  233. public $ref_next;
  234. /**
  235. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  236. */
  237. public $newref;
  238. /**
  239. * @var int The object's status. Prefer use of status.
  240. * @deprecated
  241. * @see setStatut()
  242. */
  243. public $statut;
  244. /**
  245. * @var int The object's status
  246. * @see setStatut()
  247. */
  248. public $status;
  249. /**
  250. * @var string
  251. * @see getFullAddress()
  252. */
  253. public $country;
  254. /**
  255. * @var int
  256. * @see getFullAddress(), country
  257. */
  258. public $country_id;
  259. /**
  260. * @var string The ISO country code on 2 chars.
  261. * @see getFullAddress(), isInEEC(), country
  262. */
  263. public $country_code;
  264. /**
  265. * @var string
  266. * @see getFullAddress()
  267. */
  268. public $state;
  269. /**
  270. * @var int
  271. * @see getFullAddress(), state
  272. */
  273. public $state_id;
  274. /**
  275. * @var string
  276. * @see getFullAddress(), $state
  277. */
  278. public $state_code;
  279. /**
  280. * @var int
  281. * @see getFullAddress(), $region_code, $region
  282. */
  283. public $region_id;
  284. /**
  285. * @var string
  286. * @see getFullAddress(), $region_id, $region
  287. */
  288. public $region_code;
  289. /**
  290. * @var string
  291. * @see getFullAddress(), $region_id, $region_code
  292. */
  293. public $region;
  294. /**
  295. * @var int
  296. * @see fetch_barcode()
  297. */
  298. public $barcode_type;
  299. /**
  300. * @var string
  301. * @see fetch_barcode(), barcode_type
  302. */
  303. public $barcode_type_code;
  304. /**
  305. * @var string
  306. * @see fetch_barcode(), barcode_type
  307. */
  308. public $barcode_type_label;
  309. /**
  310. * @var string
  311. * @see fetch_barcode(), barcode_type
  312. */
  313. public $barcode_type_coder;
  314. /**
  315. * @var int Payment method ID (cheque, cash, ...)
  316. * @see setPaymentMethods()
  317. */
  318. public $mode_reglement_id;
  319. /**
  320. * @var int Payment terms ID
  321. * @see setPaymentTerms()
  322. */
  323. public $cond_reglement_id;
  324. /**
  325. * @var int Demand reason ID
  326. */
  327. public $demand_reason_id;
  328. /**
  329. * @var int Transport mode ID (For module intracomm report)
  330. * @see setTransportMode()
  331. */
  332. public $transport_mode_id;
  333. /**
  334. * @var int Payment terms ID
  335. * @deprecated Kept for compatibility
  336. * @see cond_reglement_id;
  337. */
  338. public $cond_reglement;
  339. /**
  340. * @var int Delivery address ID
  341. * @see setDeliveryAddress()
  342. * @deprecated
  343. */
  344. public $fk_delivery_address;
  345. /**
  346. * @var int Shipping method ID
  347. * @see setShippingMethod()
  348. */
  349. public $shipping_method_id;
  350. /**
  351. * @var string Shipping method label
  352. * @see setShippingMethod()
  353. */
  354. public $shipping_method;
  355. /**
  356. * @var string multicurrency code
  357. */
  358. public $multicurrency_code;
  359. /**
  360. * @var string multicurrency tx
  361. */
  362. public $multicurrency_tx;
  363. /**
  364. * @var string
  365. * @see SetDocModel()
  366. */
  367. public $model_pdf;
  368. /**
  369. * @var string
  370. * @deprecated
  371. * @see $model_pdf
  372. */
  373. public $modelpdf;
  374. /**
  375. * @var string
  376. * Contains relative path of last generated main file
  377. */
  378. public $last_main_doc;
  379. /**
  380. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  381. * @deprecated
  382. * @see $fk_account
  383. */
  384. public $fk_bank;
  385. /**
  386. * @var int Bank account ID
  387. * @see SetBankAccount()
  388. */
  389. public $fk_account;
  390. /**
  391. * @var string Open ID
  392. */
  393. public $openid;
  394. /**
  395. * @var string Public note
  396. * @see update_note()
  397. */
  398. public $note_public;
  399. /**
  400. * @var string Private note
  401. * @see update_note()
  402. */
  403. public $note_private;
  404. /**
  405. * @deprecated
  406. * @see $note_private
  407. */
  408. public $note;
  409. /**
  410. * @var float Total amount before taxes
  411. * @see update_price()
  412. */
  413. public $total_ht;
  414. /**
  415. * @var float Total VAT amount
  416. * @see update_price()
  417. */
  418. public $total_tva;
  419. /**
  420. * @var float Total local tax 1 amount
  421. * @see update_price()
  422. */
  423. public $total_localtax1;
  424. /**
  425. * @var float Total local tax 2 amount
  426. * @see update_price()
  427. */
  428. public $total_localtax2;
  429. /**
  430. * @var float Total amount with taxes
  431. * @see update_price()
  432. */
  433. public $total_ttc;
  434. /**
  435. * @var CommonObjectLine[]
  436. */
  437. public $lines;
  438. /**
  439. * @var mixed Contains comments
  440. * @see fetchComments()
  441. */
  442. public $comments = array();
  443. /**
  444. * @var string The name
  445. */
  446. public $name;
  447. /**
  448. * @var string The lastname
  449. */
  450. public $lastname;
  451. /**
  452. * @var string The firstname
  453. */
  454. public $firstname;
  455. /**
  456. * @var string The civility code, not an integer
  457. */
  458. public $civility_id;
  459. // Dates
  460. /**
  461. * @var integer|string date_creation
  462. */
  463. public $date_creation;
  464. /**
  465. * @var integer|string $date_validation;
  466. */
  467. public $date_validation; // Date validation
  468. /**
  469. * @var integer|string $date_modification;
  470. */
  471. public $date_modification; // Date last change (tms field)
  472. /**
  473. * @var integer|string $date_modification;
  474. * @deprecated Use date_modification
  475. */
  476. public $date_update;
  477. /**
  478. * @var integer|string $date_cloture;
  479. */
  480. public $date_cloture; // Date closing (tms field)
  481. /**
  482. * @var User|int User author/creation
  483. * @TODO Merge with user_creation
  484. */
  485. public $user_author;
  486. /**
  487. * @var User|int User author/creation
  488. * @TODO Remove type id
  489. */
  490. public $user_creation;
  491. /**
  492. * @var int User id author/creation
  493. */
  494. public $user_creation_id;
  495. /**
  496. * @var User|int User of validation
  497. * @TODO Merge with user_validation
  498. */
  499. public $user_valid;
  500. /**
  501. * @var User|int User of validation
  502. * @TODO Remove type id
  503. */
  504. public $user_validation;
  505. /**
  506. * @var int User id of validation
  507. */
  508. public $user_validation_id;
  509. /**
  510. * @var int User id closing object
  511. */
  512. public $user_closing_id;
  513. /**
  514. * @var User|int User last modifier
  515. * @TODO Remove type id
  516. */
  517. public $user_modification;
  518. /**
  519. * @var int User id last modifier
  520. */
  521. public $user_modification_id;
  522. public $next_prev_filter;
  523. /**
  524. * @var int 1 if object is specimen
  525. */
  526. public $specimen = 0;
  527. /**
  528. * @var int Id of contact to send object (used by the trigger of module Agenda)
  529. */
  530. public $sendtoid;
  531. /**
  532. * @var float Amount already paid (used to show correct status)
  533. */
  534. public $alreadypaid;
  535. public $labelStatus;
  536. protected $labelStatusShort;
  537. /**
  538. * @var int show photo on popup
  539. */
  540. public $showphoto_on_popup;
  541. /**
  542. * @var array nb used in load_stateboard
  543. */
  544. public $nb = array();
  545. /**
  546. * @var string output
  547. */
  548. public $output;
  549. /**
  550. * @var array extra parameters
  551. */
  552. public $extraparams = array();
  553. /**
  554. * @var array List of child tables. To test if we can delete object.
  555. */
  556. protected $childtables = array();
  557. /**
  558. * @var array List of child tables. To know object to delete on cascade.
  559. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  560. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  561. */
  562. protected $childtablesoncascade = array();
  563. // No constructor as it is an abstract class
  564. /**
  565. * Check an object id/ref exists
  566. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  567. *
  568. * @param string $element String of element ('product', 'facture', ...)
  569. * @param int $id Id of object
  570. * @param string $ref Ref of object to check
  571. * @param string $ref_ext Ref ext of object to check
  572. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  573. */
  574. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  575. {
  576. global $db, $conf;
  577. $sql = "SELECT rowid, ref, ref_ext";
  578. $sql .= " FROM ".$db->prefix().$element;
  579. $sql .= " WHERE entity IN (".getEntity($element).")";
  580. if ($id > 0) {
  581. $sql .= " AND rowid = ".((int) $id);
  582. } elseif ($ref) {
  583. $sql .= " AND ref = '".$db->escape($ref)."'";
  584. } elseif ($ref_ext) {
  585. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  586. } else {
  587. $error = 'ErrorWrongParameters';
  588. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  589. return -1;
  590. }
  591. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  592. $sql .= " AND entity = ".((int) $conf->entity);
  593. }
  594. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  595. $resql = $db->query($sql);
  596. if ($resql) {
  597. $num = $db->num_rows($resql);
  598. if ($num > 0) {
  599. return 1;
  600. } else {
  601. return 0;
  602. }
  603. }
  604. return -1;
  605. }
  606. /**
  607. * setErrorsFromObject
  608. *
  609. * @param CommonObject $object commonobject
  610. * @return void
  611. */
  612. public function setErrorsFromObject($object)
  613. {
  614. if (!empty($object->error)) {
  615. $this->error = $object->error;
  616. }
  617. if (!empty($object->errors)) {
  618. $this->errors = array_merge($this->errors, $object->errors);
  619. }
  620. }
  621. /**
  622. * Return array of datas to show into a tooltip. This method must be implemented in each object class.
  623. *
  624. * @since v18
  625. * @param array $params params to construct tooltip data
  626. * @return array
  627. */
  628. public function getTooltipContentArray($params)
  629. {
  630. return [];
  631. }
  632. /**
  633. * getTooltipContent
  634. *
  635. * @param array $params params
  636. * @since v18
  637. * @return string
  638. */
  639. public function getTooltipContent($params)
  640. {
  641. global $action, $extrafields, $langs, $hookmanager;
  642. // If there is too much extrafields, we do not include them into tooltip
  643. $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP = getDolGlobalInt('MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
  644. $datas = $this->getTooltipContentArray($params);
  645. $count = 0;
  646. // Add extrafields
  647. if (!empty($extrafields->attributes[$this->table_element]['label'])) {
  648. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  649. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  650. continue;
  651. }
  652. if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
  653. $datas['more_extrafields'] = '<br>...';
  654. break;
  655. }
  656. $enabled = 1;
  657. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  658. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
  659. }
  660. if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  661. $enabled = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
  662. }
  663. $perms = 1;
  664. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  665. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
  666. }
  667. if (empty($enabled)) {
  668. continue; // 0 = Never visible field
  669. }
  670. if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
  671. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation
  672. }
  673. if (empty($perms)) {
  674. continue; // 0 = Not visible
  675. }
  676. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  677. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  678. }
  679. $labelextra = $langs->trans((string) $extrafields->attributes[$this->table_element]['label'][$key]);
  680. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  681. $datas[$key]= '<br><b><u>'. $labelextra . '</u></b>';
  682. } else {
  683. $value = (empty($this->array_options['options_' . $key]) ? '' : $this->array_options['options_' . $key]);
  684. $datas[$key]= '<br><b>'. $labelextra . ':</b> ' . $extrafields->showOutputField($key, $value, '', $this->table_element);
  685. $count++;
  686. }
  687. }
  688. }
  689. $hookmanager->initHooks(array($this->element . 'dao'));
  690. $parameters = array(
  691. 'tooltipcontentarray' => &$datas,
  692. 'params' => $params,
  693. );
  694. // Note that $action and $object may have been modified by some hooks
  695. $hookmanager->executeHooks('getTooltipContent', $parameters, $this, $action);
  696. //var_dump($datas);
  697. $label = implode($datas);
  698. return $label;
  699. }
  700. /**
  701. * Method to output saved errors
  702. *
  703. * @return string String with errors
  704. */
  705. public function errorsToString()
  706. {
  707. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  708. }
  709. /**
  710. * Return customer ref for screen output.
  711. *
  712. * @param string $objref Customer ref
  713. * @return string Customer ref formated
  714. */
  715. public function getFormatedCustomerRef($objref)
  716. {
  717. global $hookmanager;
  718. $parameters = array('objref'=>$objref);
  719. $action = '';
  720. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  721. if ($reshook > 0) {
  722. return $hookmanager->resArray['objref'];
  723. }
  724. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  725. }
  726. /**
  727. * Return supplier ref for screen output.
  728. *
  729. * @param string $objref Supplier ref
  730. * @return string Supplier ref formated
  731. */
  732. public function getFormatedSupplierRef($objref)
  733. {
  734. global $hookmanager;
  735. $parameters = array('objref'=>$objref);
  736. $action = '';
  737. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  738. if ($reshook > 0) {
  739. return $hookmanager->resArray['objref'];
  740. }
  741. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  742. }
  743. /**
  744. * Return full address of contact
  745. *
  746. * @param int $withcountry 1=Add country into address string
  747. * @param string $sep Separator to use to build string
  748. * @param int $withregion 1=Add region into address string
  749. * @param string $extralangcode User extralanguages as value
  750. * @return string Full address string
  751. */
  752. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  753. {
  754. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  755. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  756. $tmparray = getCountry($this->country_id, 'all');
  757. $this->country_code = $tmparray['code'];
  758. $this->country = $tmparray['label'];
  759. }
  760. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  761. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  762. $tmparray = getState($this->state_id, 'all', 0, 1);
  763. $this->state_code = $tmparray['code'];
  764. $this->state = $tmparray['label'];
  765. $this->region_code = $tmparray['region_code'];
  766. $this->region = $tmparray['region'];
  767. }
  768. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  769. }
  770. /**
  771. * Return the link of last main doc file for direct public download.
  772. *
  773. * @param string $modulepart Module related to document
  774. * @param int $initsharekey Init the share key if it was not yet defined
  775. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  776. * @return string Link or empty string if there is no download link
  777. */
  778. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  779. {
  780. global $user, $dolibarr_main_url_root;
  781. if (empty($this->last_main_doc)) {
  782. return ''; // No way to known which document name to use
  783. }
  784. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  785. $ecmfile = new EcmFiles($this->db);
  786. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  787. if ($result < 0) {
  788. $this->error = $ecmfile->error;
  789. $this->errors = $ecmfile->errors;
  790. return -1;
  791. }
  792. if (empty($ecmfile->id)) {
  793. // Add entry into index
  794. if ($initsharekey) {
  795. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  796. // 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
  797. /*
  798. $ecmfile->filepath = $rel_dir;
  799. $ecmfile->filename = $filename;
  800. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  801. $ecmfile->fullpath_orig = '';
  802. $ecmfile->gen_or_uploaded = 'generated';
  803. $ecmfile->description = ''; // indexed content
  804. $ecmfile->keywords = ''; // keyword content
  805. $ecmfile->share = getRandomPassword(true);
  806. $result = $ecmfile->create($user);
  807. if ($result < 0)
  808. {
  809. $this->error = $ecmfile->error;
  810. $this->errors = $ecmfile->errors;
  811. }
  812. */
  813. } else {
  814. return '';
  815. }
  816. } elseif (empty($ecmfile->share)) {
  817. // Add entry into index
  818. if ($initsharekey) {
  819. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  820. $ecmfile->share = getRandomPassword(true);
  821. $ecmfile->update($user);
  822. } else {
  823. return '';
  824. }
  825. }
  826. // Define $urlwithroot
  827. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  828. // This is to use external domain name found into config file
  829. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  830. //else
  831. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  832. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  833. $forcedownload = 0;
  834. $paramlink = '';
  835. //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  836. //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  837. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  838. if (!empty($ecmfile->share)) {
  839. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  840. }
  841. if ($forcedownload) {
  842. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  843. }
  844. if ($relativelink) {
  845. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  846. } else {
  847. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  848. }
  849. // Here $ecmfile->share is defined
  850. return $linktoreturn;
  851. }
  852. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  853. /**
  854. * Add a link between element $this->element and a contact
  855. *
  856. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  857. * @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
  858. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  859. * @param int $notrigger Disable all triggers
  860. * @return int <0 if KO, 0 if already added, >0 if OK
  861. */
  862. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  863. {
  864. // phpcs:enable
  865. global $user, $langs;
  866. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  867. // Check parameters
  868. if ($fk_socpeople <= 0) {
  869. $langs->load("errors");
  870. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  871. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  872. return -1;
  873. }
  874. if (!$type_contact) {
  875. $langs->load("errors");
  876. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  877. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  878. return -2;
  879. }
  880. $id_type_contact = 0;
  881. if (is_numeric($type_contact)) {
  882. $id_type_contact = $type_contact;
  883. } else {
  884. // We look for id type_contact
  885. $sql = "SELECT tc.rowid";
  886. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  887. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  888. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  889. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  890. //print $sql;
  891. $resql = $this->db->query($sql);
  892. if ($resql) {
  893. $obj = $this->db->fetch_object($resql);
  894. if ($obj) {
  895. $id_type_contact = $obj->rowid;
  896. }
  897. }
  898. }
  899. if ($id_type_contact == 0) {
  900. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  901. 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");
  902. return -3;
  903. }
  904. $datecreate = dol_now();
  905. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  906. $TListeContacts = $this->liste_contact(-1, $source);
  907. $already_added = false;
  908. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  909. foreach ($TListeContacts as $array_contact) {
  910. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  911. $already_added = true;
  912. break;
  913. }
  914. }
  915. }
  916. if (!$already_added) {
  917. $this->db->begin();
  918. // Insert into database
  919. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  920. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  921. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  922. $sql .= "'".$this->db->idate($datecreate)."'";
  923. $sql .= ", 4, ".((int) $id_type_contact);
  924. $sql .= ")";
  925. $resql = $this->db->query($sql);
  926. if ($resql) {
  927. if (!$notrigger) {
  928. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  929. if ($result < 0) {
  930. $this->db->rollback();
  931. return -1;
  932. }
  933. }
  934. $this->db->commit();
  935. return 1;
  936. } else {
  937. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  938. $this->error = $this->db->errno();
  939. $this->db->rollback();
  940. return -2;
  941. } else {
  942. $this->error = $this->db->lasterror();
  943. $this->db->rollback();
  944. return -1;
  945. }
  946. }
  947. } else {
  948. return 0;
  949. }
  950. }
  951. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  952. /**
  953. * Copy contact from one element to current
  954. *
  955. * @param CommonObject $objFrom Source element
  956. * @param string $source Nature of contact ('internal' or 'external')
  957. * @return int >0 if OK, <0 if KO
  958. */
  959. public function copy_linked_contact($objFrom, $source = 'internal')
  960. {
  961. // phpcs:enable
  962. $contacts = $objFrom->liste_contact(-1, $source);
  963. foreach ($contacts as $contact) {
  964. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  965. return -1;
  966. }
  967. }
  968. return 1;
  969. }
  970. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  971. /**
  972. * Update a link to contact line
  973. *
  974. * @param int $rowid Id of line contact-element
  975. * @param int $statut New status of link
  976. * @param int $type_contact_id Id of contact type (not modified if 0)
  977. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  978. * @return int <0 if KO, >= 0 if OK
  979. */
  980. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  981. {
  982. // phpcs:enable
  983. // Insert into database
  984. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  985. $sql .= " statut = ".$statut;
  986. if ($type_contact_id) {
  987. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  988. }
  989. if ($fk_socpeople) {
  990. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  991. }
  992. $sql .= " where rowid = ".((int) $rowid);
  993. $resql = $this->db->query($sql);
  994. if ($resql) {
  995. return 0;
  996. } else {
  997. $this->error = $this->db->lasterror();
  998. return -1;
  999. }
  1000. }
  1001. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1002. /**
  1003. * Delete a link to contact line
  1004. *
  1005. * @param int $rowid Id of contact link line to delete
  1006. * @param int $notrigger Disable all triggers
  1007. * @return int >0 if OK, <0 if KO
  1008. */
  1009. public function delete_contact($rowid, $notrigger = 0)
  1010. {
  1011. // phpcs:enable
  1012. global $user;
  1013. $this->db->begin();
  1014. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1015. $sql .= " WHERE rowid = ".((int) $rowid);
  1016. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1017. if ($this->db->query($sql)) {
  1018. if (!$notrigger) {
  1019. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1020. if ($result < 0) {
  1021. $this->db->rollback();
  1022. return -1;
  1023. }
  1024. }
  1025. $this->db->commit();
  1026. return 1;
  1027. } else {
  1028. $this->error = $this->db->lasterror();
  1029. $this->db->rollback();
  1030. return -1;
  1031. }
  1032. }
  1033. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1034. /**
  1035. * Delete all links between an object $this and all its contacts in llx_element_contact
  1036. *
  1037. * @param string $source '' or 'internal' or 'external'
  1038. * @param string $code Type of contact (code or id)
  1039. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1040. */
  1041. public function delete_linked_contact($source = '', $code = '')
  1042. {
  1043. // phpcs:enable
  1044. $listId = '';
  1045. $temp = array();
  1046. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1047. if (!empty($typeContact)) {
  1048. foreach ($typeContact as $key => $value) {
  1049. array_push($temp, $key);
  1050. }
  1051. $listId = implode(",", $temp);
  1052. }
  1053. // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
  1054. // any type or record instead of only the ones of the current object. So we do nothing in such a case.
  1055. if (empty($listId)) {
  1056. return 0;
  1057. }
  1058. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1059. $sql .= " WHERE element_id = ".((int) $this->id);
  1060. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1061. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1062. if ($this->db->query($sql)) {
  1063. return 1;
  1064. } else {
  1065. $this->error = $this->db->lasterror();
  1066. return -1;
  1067. }
  1068. }
  1069. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1070. /**
  1071. * Get array of all contacts for an object
  1072. *
  1073. * @param int $statusoflink Status of links to get (-1=all). Not used.
  1074. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1075. * @param int $list 0:Returned array contains all properties, 1:Return array contains just id
  1076. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1077. * @param int $status Status of user or company
  1078. * @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.
  1079. * @return array|int Array of contacts, -1 if error
  1080. */
  1081. public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
  1082. {
  1083. // phpcs:enable
  1084. global $langs;
  1085. $tab = array();
  1086. $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
  1087. if ($source == 'internal') {
  1088. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1089. }
  1090. if ($source == 'external' || $source == 'thirdparty') {
  1091. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1092. }
  1093. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1094. $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
  1095. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc,";
  1096. $sql .= " ".$this->db->prefix()."element_contact ec";
  1097. if ($source == 'internal') { // internal contact (user)
  1098. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1099. }
  1100. if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
  1101. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1102. }
  1103. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1104. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1105. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1106. if ($code) {
  1107. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1108. }
  1109. if ($source == 'internal') {
  1110. $sql .= " AND tc.source = 'internal'";
  1111. if ($status >= 0) {
  1112. $sql .= " AND t.statut = ".((int) $status);
  1113. }
  1114. }
  1115. if ($source == 'external' || $source == 'thirdparty') {
  1116. $sql .= " AND tc.source = 'external'";
  1117. if ($status >= 0) {
  1118. $sql .= " AND t.statut = ".((int) $status); // t is llx_socpeople
  1119. }
  1120. }
  1121. $sql .= " AND tc.active = 1";
  1122. if ($statusoflink >= 0) {
  1123. $sql .= " AND ec.statut = ".((int) $statusoflink);
  1124. }
  1125. $sql .= " ORDER BY t.lastname ASC";
  1126. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1127. $resql = $this->db->query($sql);
  1128. if ($resql) {
  1129. $num = $this->db->num_rows($resql);
  1130. $i = 0;
  1131. while ($i < $num) {
  1132. $obj = $this->db->fetch_object($resql);
  1133. if (!$list) {
  1134. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1135. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
  1136. $tab[$i] = array(
  1137. 'parentId' => $this->id,
  1138. 'source' => $obj->source,
  1139. 'socid' => $obj->socid,
  1140. 'id' => $obj->id,
  1141. 'nom' => $obj->lastname, // For backward compatibility
  1142. 'civility' => $obj->civility,
  1143. 'lastname' => $obj->lastname,
  1144. 'firstname' => $obj->firstname,
  1145. 'email'=>$obj->email,
  1146. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1147. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1148. 'statuscontact' => $obj->statuscontact,
  1149. 'rowid' => $obj->rowid,
  1150. 'code' => $obj->code,
  1151. 'libelle' => $libelle_type,
  1152. 'status' => $obj->statuslink,
  1153. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1154. );
  1155. } else {
  1156. $tab[$i] = $obj->id;
  1157. }
  1158. $i++;
  1159. }
  1160. return $tab;
  1161. } else {
  1162. $this->error = $this->db->lasterror();
  1163. dol_print_error($this->db);
  1164. return -1;
  1165. }
  1166. }
  1167. /**
  1168. * Update status of a contact linked to object
  1169. *
  1170. * @param int $rowid Id of link between object and contact
  1171. * @return int <0 if KO, >=0 if OK
  1172. */
  1173. public function swapContactStatus($rowid)
  1174. {
  1175. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1176. $sql .= " tc.code, tc.libelle as type_label";
  1177. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1178. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1179. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1180. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1181. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1182. $resql = $this->db->query($sql);
  1183. if ($resql) {
  1184. $obj = $this->db->fetch_object($resql);
  1185. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1186. $result = $this->update_contact($rowid, $newstatut);
  1187. $this->db->free($resql);
  1188. return $result;
  1189. } else {
  1190. $this->error = $this->db->error();
  1191. dol_print_error($this->db);
  1192. return -1;
  1193. }
  1194. }
  1195. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1196. /**
  1197. * Return array with list of possible values for type of contacts
  1198. *
  1199. * @param string $source 'internal', 'external' or 'all'
  1200. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1201. * @param int $option 0=Return array id->label, 1=Return array code->label
  1202. * @param int $activeonly 0=all status of contact, 1=only the active
  1203. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1204. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1205. */
  1206. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1207. {
  1208. // phpcs:enable
  1209. global $langs;
  1210. if (empty($order)) {
  1211. $order = 'position';
  1212. }
  1213. if ($order == 'position') {
  1214. $order .= ',code';
  1215. }
  1216. $tab = array();
  1217. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
  1218. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1219. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1220. if ($activeonly == 1) {
  1221. $sql .= " AND tc.active=1"; // only the active types
  1222. }
  1223. if (!empty($source) && $source != 'all') {
  1224. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1225. }
  1226. if (!empty($code)) {
  1227. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1228. }
  1229. $sql .= $this->db->order($order, 'ASC');
  1230. //print "sql=".$sql;
  1231. $resql = $this->db->query($sql);
  1232. if ($resql) {
  1233. $num = $this->db->num_rows($resql);
  1234. $i = 0;
  1235. while ($i < $num) {
  1236. $obj = $this->db->fetch_object($resql);
  1237. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1238. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
  1239. if (empty($option)) {
  1240. $tab[$obj->rowid] = $libelle_type;
  1241. } else {
  1242. $tab[$obj->code] = $libelle_type;
  1243. }
  1244. $i++;
  1245. }
  1246. return $tab;
  1247. } else {
  1248. $this->error = $this->db->lasterror();
  1249. //dol_print_error($this->db);
  1250. return null;
  1251. }
  1252. }
  1253. /**
  1254. * Return array with list of possible values for type of contacts
  1255. *
  1256. * @param string $source 'internal', 'external' or 'all'
  1257. * @param int $option 0=Return array id->label, 1=Return array code->label
  1258. * @param int $activeonly 0=all status of contact, 1=only the active
  1259. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1260. * @param string $element Filter on 1 element type
  1261. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1262. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1263. */
  1264. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1265. {
  1266. global $langs, $conf;
  1267. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1268. $tab = array();
  1269. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element";
  1270. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1271. $sqlWhere = array();
  1272. if (!empty($element)) {
  1273. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1274. }
  1275. if (!empty($excludeelement)) {
  1276. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1277. }
  1278. if ($activeonly == 1) {
  1279. $sqlWhere[] = " tc.active=1"; // only the active types
  1280. }
  1281. if (!empty($source) && $source != 'all') {
  1282. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1283. }
  1284. if (!empty($code)) {
  1285. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1286. }
  1287. if (count($sqlWhere) > 0) {
  1288. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1289. }
  1290. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1291. dol_syslog(__METHOD__, LOG_DEBUG);
  1292. $resql = $this->db->query($sql);
  1293. if ($resql) {
  1294. $num = $this->db->num_rows($resql);
  1295. if ($num > 0) {
  1296. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1297. while ($obj = $this->db->fetch_object($resql)) {
  1298. $modulename = $obj->element;
  1299. if (strpos($obj->element, 'project') !== false) {
  1300. $modulename = 'projet';
  1301. } elseif ($obj->element == 'contrat') {
  1302. $element = 'contract';
  1303. } elseif ($obj->element == 'action') {
  1304. $modulename = 'agenda';
  1305. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1306. $modulename = 'fournisseur';
  1307. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1308. $modulename = 'fournisseur';
  1309. }
  1310. if (!empty($conf->{$modulename}->enabled)) {
  1311. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1312. $tmpelement = $obj->element;
  1313. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1314. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
  1315. if (empty($option)) {
  1316. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1317. } else {
  1318. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1319. }
  1320. }
  1321. }
  1322. }
  1323. return $tab;
  1324. } else {
  1325. $this->error = $this->db->lasterror();
  1326. return null;
  1327. }
  1328. }
  1329. /**
  1330. * Return id of contacts for a source and a contact code.
  1331. * Example: contact client de facturation ('external', 'BILLING')
  1332. * Example: contact client de livraison ('external', 'SHIPPING')
  1333. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1334. *
  1335. * @param string $source 'external' or 'internal'
  1336. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1337. * @param int $status limited to a certain status
  1338. * @return array List of id for such contacts
  1339. */
  1340. public function getIdContact($source, $code, $status = 0)
  1341. {
  1342. global $conf;
  1343. $result = array();
  1344. $i = 0;
  1345. //cas particulier pour les expeditions
  1346. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1347. $id = $this->origin_id;
  1348. $element = 'commande';
  1349. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1350. $id = $this->origin_id;
  1351. $element = 'order_supplier';
  1352. } else {
  1353. $id = $this->id;
  1354. $element = $this->element;
  1355. }
  1356. $sql = "SELECT ec.fk_socpeople";
  1357. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1358. if ($source == 'internal') {
  1359. $sql .= " ".$this->db->prefix()."user as c,";
  1360. }
  1361. if ($source == 'external') {
  1362. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1363. }
  1364. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1365. $sql .= " WHERE ec.element_id = ".((int) $id);
  1366. $sql .= " AND ec.fk_socpeople = c.rowid";
  1367. if ($source == 'internal') {
  1368. $sql .= " AND c.entity IN (".getEntity('user').")";
  1369. }
  1370. if ($source == 'external') {
  1371. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1372. }
  1373. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1374. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1375. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1376. if ($code) {
  1377. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1378. }
  1379. $sql .= " AND tc.active = 1";
  1380. if ($status) {
  1381. $sql .= " AND ec.statut = ".((int) $status);
  1382. }
  1383. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1384. $resql = $this->db->query($sql);
  1385. if ($resql) {
  1386. while ($obj = $this->db->fetch_object($resql)) {
  1387. $result[$i] = $obj->fk_socpeople;
  1388. $i++;
  1389. }
  1390. } else {
  1391. $this->error = $this->db->error();
  1392. return null;
  1393. }
  1394. return $result;
  1395. }
  1396. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1397. /**
  1398. * Load object contact with id=$this->contact_id into $this->contact
  1399. *
  1400. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1401. * @return int <0 if KO, >0 if OK
  1402. */
  1403. public function fetch_contact($contactid = null)
  1404. {
  1405. // phpcs:enable
  1406. if (empty($contactid)) {
  1407. $contactid = $this->contact_id;
  1408. }
  1409. if (empty($contactid)) {
  1410. return 0;
  1411. }
  1412. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1413. $contact = new Contact($this->db);
  1414. $result = $contact->fetch($contactid);
  1415. $this->contact = $contact;
  1416. return $result;
  1417. }
  1418. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1419. /**
  1420. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1421. *
  1422. * @param int $force_thirdparty_id Force thirdparty id
  1423. * @return int <0 if KO, >0 if OK
  1424. */
  1425. public function fetch_thirdparty($force_thirdparty_id = 0)
  1426. {
  1427. // phpcs:enable
  1428. global $conf;
  1429. if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
  1430. return 0;
  1431. }
  1432. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1433. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
  1434. if ($force_thirdparty_id) {
  1435. $idtofetch = $force_thirdparty_id;
  1436. }
  1437. if ($idtofetch) {
  1438. $thirdparty = new Societe($this->db);
  1439. $result = $thirdparty->fetch($idtofetch);
  1440. if ($result<0) {
  1441. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1442. }
  1443. $this->thirdparty = $thirdparty;
  1444. // Use first price level if level not defined for third party
  1445. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1446. $this->thirdparty->price_level = 1;
  1447. }
  1448. return $result;
  1449. } else {
  1450. return -1;
  1451. }
  1452. }
  1453. /**
  1454. * Looks for an object with ref matching the wildcard provided
  1455. * It does only work when $this->table_ref_field is set
  1456. *
  1457. * @param string $ref Wildcard
  1458. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1459. */
  1460. public function fetchOneLike($ref)
  1461. {
  1462. if (!$this->table_ref_field) {
  1463. return 0;
  1464. }
  1465. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1466. $query = $this->db->query($sql);
  1467. if (!$this->db->num_rows($query)) {
  1468. return 0;
  1469. }
  1470. $result = $this->db->fetch_object($query);
  1471. return $this->fetch($result->rowid);
  1472. }
  1473. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1474. /**
  1475. * Load data for barcode into properties ->barcode_type*
  1476. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1477. * if it is not defined, ->element must be defined to know default barcode type.
  1478. *
  1479. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1480. */
  1481. public function fetch_barcode()
  1482. {
  1483. // phpcs:enable
  1484. global $conf;
  1485. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1486. $idtype = $this->barcode_type;
  1487. 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
  1488. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1489. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1490. } elseif ($this->element == 'societe') {
  1491. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1492. } else {
  1493. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1494. }
  1495. }
  1496. if ($idtype > 0) {
  1497. 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
  1498. $sql = "SELECT rowid, code, libelle as label, coder";
  1499. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1500. $sql .= " WHERE rowid = ".((int) $idtype);
  1501. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1502. $resql = $this->db->query($sql);
  1503. if ($resql) {
  1504. $obj = $this->db->fetch_object($resql);
  1505. $this->barcode_type = $obj->rowid;
  1506. $this->barcode_type_code = $obj->code;
  1507. $this->barcode_type_label = $obj->label;
  1508. $this->barcode_type_coder = $obj->coder;
  1509. return 1;
  1510. } else {
  1511. dol_print_error($this->db);
  1512. return -1;
  1513. }
  1514. }
  1515. }
  1516. return 0;
  1517. }
  1518. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1519. /**
  1520. * Load the project with id $this->fk_project into this->project
  1521. *
  1522. * @return int <0 if KO, >=0 if OK
  1523. */
  1524. public function fetch_project()
  1525. {
  1526. // phpcs:enable
  1527. return $this->fetch_projet();
  1528. }
  1529. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1530. /**
  1531. * Load the project with id $this->fk_project into this->project
  1532. *
  1533. * @return int <0 if KO, >=0 if OK
  1534. */
  1535. public function fetch_projet()
  1536. {
  1537. // phpcs:enable
  1538. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1539. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1540. $this->fk_project = $this->fk_projet; // For backward compatibility
  1541. }
  1542. if (empty($this->fk_project)) {
  1543. return 0;
  1544. }
  1545. $project = new Project($this->db);
  1546. $result = $project->fetch($this->fk_project);
  1547. $this->projet = $project; // deprecated
  1548. $this->project = $project;
  1549. return $result;
  1550. }
  1551. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1552. /**
  1553. * Load the product with id $this->fk_product into this->product
  1554. *
  1555. * @return int <0 if KO, >=0 if OK
  1556. */
  1557. public function fetch_product()
  1558. {
  1559. // phpcs:enable
  1560. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1561. if (empty($this->fk_product)) {
  1562. return 0;
  1563. }
  1564. $product = new Product($this->db);
  1565. $result = $product->fetch($this->fk_product);
  1566. $this->product = $product;
  1567. return $result;
  1568. }
  1569. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1570. /**
  1571. * Load the user with id $userid into this->user
  1572. *
  1573. * @param int $userid Id du contact
  1574. * @return int <0 if KO, >0 if OK
  1575. */
  1576. public function fetch_user($userid)
  1577. {
  1578. // phpcs:enable
  1579. $user = new User($this->db);
  1580. $result = $user->fetch($userid);
  1581. $this->user = $user;
  1582. return $result;
  1583. }
  1584. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1585. /**
  1586. * Read linked origin object
  1587. *
  1588. * @return void
  1589. */
  1590. public function fetch_origin()
  1591. {
  1592. // phpcs:enable
  1593. if ($this->origin == 'shipping') {
  1594. $this->origin = 'expedition';
  1595. }
  1596. if ($this->origin == 'delivery') {
  1597. $this->origin = 'livraison';
  1598. }
  1599. if ($this->origin == 'order_supplier') {
  1600. $this->origin = 'commandeFournisseur';
  1601. }
  1602. $origin = $this->origin;
  1603. $classname = ucfirst($origin);
  1604. $this->$origin = new $classname($this->db);
  1605. $this->$origin->fetch($this->origin_id);
  1606. }
  1607. /**
  1608. * Load object from specific field
  1609. *
  1610. * @param string $table Table element or element line
  1611. * @param string $field Field selected
  1612. * @param string $key Import key
  1613. * @param string $element Element name
  1614. * @return int <0 if KO, >0 if OK
  1615. */
  1616. public function fetchObjectFrom($table, $field, $key, $element = null)
  1617. {
  1618. global $conf;
  1619. $result = false;
  1620. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1621. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1622. if (!empty($element)) {
  1623. $sql .= " AND entity IN (".getEntity($element).")";
  1624. } else {
  1625. $sql .= " AND entity = ".((int) $conf->entity);
  1626. }
  1627. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1628. $resql = $this->db->query($sql);
  1629. if ($resql) {
  1630. $row = $this->db->fetch_row($resql);
  1631. // Test for avoid error -1
  1632. if ($row[0] > 0) {
  1633. $result = $this->fetch($row[0]);
  1634. }
  1635. }
  1636. return $result;
  1637. }
  1638. /**
  1639. * Getter generic. Load value from a specific field
  1640. *
  1641. * @param string $table Table of element or element line
  1642. * @param int $id Element id
  1643. * @param string $field Field selected
  1644. * @return int <0 if KO, >0 if OK
  1645. */
  1646. public function getValueFrom($table, $id, $field)
  1647. {
  1648. $result = false;
  1649. if (!empty($id) && !empty($field) && !empty($table)) {
  1650. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1651. $sql .= " WHERE rowid = ".((int) $id);
  1652. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1653. $resql = $this->db->query($sql);
  1654. if ($resql) {
  1655. $row = $this->db->fetch_row($resql);
  1656. $result = $row[0];
  1657. }
  1658. }
  1659. return $result;
  1660. }
  1661. /**
  1662. * Setter generic. Update a specific field into database.
  1663. * Warning: Trigger is run only if param trigkey is provided.
  1664. *
  1665. * @param string $field Field to update
  1666. * @param mixed $value New value
  1667. * @param string $table To force other table element or element line (should not be used)
  1668. * @param int $id To force other object id (should not be used)
  1669. * @param string $format Data format ('text', 'int', 'date'). 'text' is used if not defined
  1670. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1671. * @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'
  1672. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1673. * @param string $fk_user_field Name of field to save user id making change
  1674. * @return int <0 if KO, >0 if OK
  1675. * @see updateExtraField()
  1676. */
  1677. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1678. {
  1679. global $user, $langs, $conf;
  1680. if (empty($table)) {
  1681. $table = $this->table_element;
  1682. }
  1683. if (empty($id)) {
  1684. $id = $this->id;
  1685. }
  1686. if (empty($format)) {
  1687. $format = 'text';
  1688. }
  1689. if (empty($id_field)) {
  1690. $id_field = 'rowid';
  1691. }
  1692. // Special case
  1693. if ($table == 'product' && $field == 'note_private') {
  1694. $field = 'note';
  1695. }
  1696. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1697. $fk_user_field = 'fk_user_mod';
  1698. }
  1699. if ($trigkey) {
  1700. $oldvalue = null;
  1701. $sql = "SELECT " . $field;
  1702. $sql .= " FROM " . MAIN_DB_PREFIX . $table;
  1703. $sql .= " WHERE " . $id_field . " = " . ((int) $id);
  1704. $resql = $this->db->query($sql);
  1705. if ($resql) {
  1706. if ($obj = $this->db->fetch_object($resql)) {
  1707. if ($format == 'date') {
  1708. $oldvalue = $this->db->jdate($obj->$field);
  1709. } else {
  1710. $oldvalue = $obj->$field;
  1711. }
  1712. }
  1713. } else {
  1714. $this->error = $this->db->lasterror();
  1715. return -1;
  1716. }
  1717. }
  1718. $error = 0;
  1719. dol_syslog(__METHOD__, LOG_DEBUG);
  1720. $this->db->begin();
  1721. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1722. if ($format == 'text') {
  1723. $sql .= $field." = '".$this->db->escape($value)."'";
  1724. } elseif ($format == 'int') {
  1725. $sql .= $field." = ".((int) $value);
  1726. } elseif ($format == 'date') {
  1727. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1728. } elseif ($format == 'dategmt') {
  1729. $sql .= $field." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null");
  1730. }
  1731. if ($fk_user_field) {
  1732. if (!empty($fuser) && is_object($fuser)) {
  1733. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1734. } elseif (empty($fuser) || $fuser != 'none') {
  1735. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1736. }
  1737. }
  1738. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1739. $resql = $this->db->query($sql);
  1740. if ($resql) {
  1741. if ($trigkey) {
  1742. // call trigger with updated object values
  1743. if (method_exists($this, 'fetch')) {
  1744. $result = $this->fetch($id);
  1745. } else {
  1746. $result = $this->fetchCommon($id);
  1747. }
  1748. $this->oldcopy = clone $this;
  1749. if (property_exists($this->oldcopy, $field)) {
  1750. $this->oldcopy->$field = $oldvalue;
  1751. }
  1752. if ($result >= 0) {
  1753. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1754. }
  1755. if ($result < 0) {
  1756. $error++;
  1757. }
  1758. }
  1759. if (!$error) {
  1760. if (property_exists($this, $field)) {
  1761. $this->$field = $value;
  1762. }
  1763. $this->db->commit();
  1764. return 1;
  1765. } else {
  1766. $this->db->rollback();
  1767. return -2;
  1768. }
  1769. } else {
  1770. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1771. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1772. } else {
  1773. $this->error = $this->db->lasterror();
  1774. }
  1775. $this->db->rollback();
  1776. return -1;
  1777. }
  1778. }
  1779. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1780. /**
  1781. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1782. *
  1783. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1784. * @param string $fieldid Name of field to use for the select MAX and MIN
  1785. * @param int $nodbprefix Do not include DB prefix to forge table name
  1786. * @return int <0 if KO, >0 if OK
  1787. */
  1788. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1789. {
  1790. // phpcs:enable
  1791. global $conf, $user;
  1792. if (!$this->table_element) {
  1793. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1794. return -1;
  1795. }
  1796. if ($fieldid == 'none') {
  1797. return 1;
  1798. }
  1799. // For backward compatibility
  1800. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1801. $fieldid = 'titre';
  1802. }
  1803. // Security on socid
  1804. $socid = 0;
  1805. if ($user->socid > 0) {
  1806. $socid = $user->socid;
  1807. }
  1808. // this->ismultientitymanaged contains
  1809. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1810. $aliastablesociete = 's';
  1811. if ($this->element == 'societe') {
  1812. $aliastablesociete = 'te'; // te as table_element
  1813. }
  1814. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1815. $sql = "SELECT MAX(te.".$fieldid.")";
  1816. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1817. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1818. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1819. }
  1820. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1821. $tmparray = explode('@', $this->ismultientitymanaged);
  1822. $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
  1823. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1824. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1825. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1826. $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
  1827. }
  1828. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1829. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1830. }
  1831. if ($fieldid == 'rowid') {
  1832. $sql .= " WHERE te.".$fieldid." < ".((int) $this->id);
  1833. } else {
  1834. $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1835. }
  1836. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1837. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1838. }
  1839. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1840. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1841. }
  1842. if (!empty($filter)) {
  1843. if (!preg_match('/^\s*AND/i', $filter)) {
  1844. $sql .= " AND "; // For backward compatibility
  1845. }
  1846. $sql .= $filter;
  1847. }
  1848. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1849. $tmparray = explode('@', $this->ismultientitymanaged);
  1850. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1851. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1852. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1853. }
  1854. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1855. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1856. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1857. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1858. } else {
  1859. $sql .= " AND ug.fk_user = te.rowid";
  1860. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1861. }
  1862. } else {
  1863. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1864. }
  1865. }
  1866. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1867. $tmparray = explode('@', $this->ismultientitymanaged);
  1868. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1869. }
  1870. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1871. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1872. }
  1873. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1874. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1875. }
  1876. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1877. $sql .= ' AND te.rowid = '.((int) $socid);
  1878. }
  1879. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1880. $result = $this->db->query($sql);
  1881. if (!$result) {
  1882. $this->error = $this->db->lasterror();
  1883. return -1;
  1884. }
  1885. $row = $this->db->fetch_row($result);
  1886. $this->ref_previous = $row[0];
  1887. $sql = "SELECT MIN(te.".$fieldid.")";
  1888. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1889. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1890. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1891. }
  1892. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1893. $tmparray = explode('@', $this->ismultientitymanaged);
  1894. $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
  1895. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1896. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1897. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1898. $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
  1899. }
  1900. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1901. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1902. }
  1903. if ($fieldid == 'rowid') {
  1904. $sql .= " WHERE te.".$fieldid." > ".((int) $this->id);
  1905. } else {
  1906. $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1907. }
  1908. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1909. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1910. }
  1911. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1912. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1913. }
  1914. if (!empty($filter)) {
  1915. if (!preg_match('/^\s*AND/i', $filter)) {
  1916. $sql .= " AND "; // For backward compatibility
  1917. }
  1918. $sql .= $filter;
  1919. }
  1920. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1921. $tmparray = explode('@', $this->ismultientitymanaged);
  1922. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1923. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1924. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1925. }
  1926. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1927. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1928. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1929. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1930. } else {
  1931. $sql .= " AND ug.fk_user = te.rowid";
  1932. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1933. }
  1934. } else {
  1935. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1936. }
  1937. }
  1938. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1939. $tmparray = explode('@', $this->ismultientitymanaged);
  1940. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1941. }
  1942. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1943. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1944. }
  1945. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1946. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1947. }
  1948. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1949. $sql .= ' AND te.rowid = '.((int) $socid);
  1950. }
  1951. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1952. // 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
  1953. $result = $this->db->query($sql);
  1954. if (!$result) {
  1955. $this->error = $this->db->lasterror();
  1956. return -2;
  1957. }
  1958. $row = $this->db->fetch_row($result);
  1959. $this->ref_next = $row[0];
  1960. return 1;
  1961. }
  1962. /**
  1963. * Return list of id of contacts of object
  1964. *
  1965. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1966. * @return array Array of id of contacts (if source=external or internal)
  1967. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1968. */
  1969. public function getListContactId($source = 'external')
  1970. {
  1971. $contactAlreadySelected = array();
  1972. $tab = $this->liste_contact(-1, $source);
  1973. $num = count($tab);
  1974. $i = 0;
  1975. while ($i < $num) {
  1976. if ($source == 'thirdparty') {
  1977. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1978. } else {
  1979. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1980. }
  1981. $i++;
  1982. }
  1983. return $contactAlreadySelected;
  1984. }
  1985. /**
  1986. * Link element with a project
  1987. *
  1988. * @param int $projectid Project id to link element to
  1989. * @param int $notrigger Disable the trigger
  1990. * @return int <0 if KO, >0 if OK
  1991. */
  1992. public function setProject($projectid, $notrigger = 0)
  1993. {
  1994. global $user;
  1995. $error = 0;
  1996. if (!$this->table_element) {
  1997. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1998. return -1;
  1999. }
  2000. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2001. if (!empty($this->fields['fk_project'])) { // Common case
  2002. if ($projectid) {
  2003. $sql .= " SET fk_project = ".((int) $projectid);
  2004. } else {
  2005. $sql .= " SET fk_project = NULL";
  2006. }
  2007. $sql .= ' WHERE rowid = '.((int) $this->id);
  2008. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  2009. if ($projectid) {
  2010. $sql .= " SET fk_project = ".((int) $projectid);
  2011. } else {
  2012. $sql .= " SET fk_project = NULL";
  2013. }
  2014. $sql .= ' WHERE id = '.((int) $this->id);
  2015. } else // Special case for old architecture objects
  2016. {
  2017. if ($projectid) {
  2018. $sql .= ' SET fk_projet = '.((int) $projectid);
  2019. } else {
  2020. $sql .= ' SET fk_projet = NULL';
  2021. }
  2022. $sql .= " WHERE rowid = ".((int) $this->id);
  2023. }
  2024. $this->db->begin();
  2025. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2026. if ($this->db->query($sql)) {
  2027. $this->fk_project = ((int) $projectid);
  2028. } else {
  2029. dol_print_error($this->db);
  2030. $error++;
  2031. }
  2032. // Triggers
  2033. if (!$error && !$notrigger) {
  2034. // Call triggers
  2035. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2036. if ($result < 0) {
  2037. $error++;
  2038. } //Do also here what you must do to rollback action if trigger fail
  2039. // End call triggers
  2040. }
  2041. // Commit or rollback
  2042. if ($error) {
  2043. $this->db->rollback();
  2044. return -1;
  2045. } else {
  2046. $this->db->commit();
  2047. return 1;
  2048. }
  2049. }
  2050. /**
  2051. * Change the payments methods
  2052. *
  2053. * @param int $id Id of new payment method
  2054. * @return int >0 if OK, <0 if KO
  2055. */
  2056. public function setPaymentMethods($id)
  2057. {
  2058. global $user;
  2059. $error = 0; $notrigger = 0;
  2060. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2061. if ($this->statut >= 0 || $this->element == 'societe') {
  2062. // TODO uniformize field name
  2063. $fieldname = 'fk_mode_reglement';
  2064. if ($this->element == 'societe') {
  2065. $fieldname = 'mode_reglement';
  2066. }
  2067. if (get_class($this) == 'Fournisseur') {
  2068. $fieldname = 'mode_reglement_supplier';
  2069. }
  2070. if (get_class($this) == 'Tva') {
  2071. $fieldname = 'fk_typepayment';
  2072. }
  2073. if (get_class($this) == 'Salary') {
  2074. $fieldname = 'fk_typepayment';
  2075. }
  2076. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2077. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2078. $sql .= ' WHERE rowid='.((int) $this->id);
  2079. if ($this->db->query($sql)) {
  2080. $this->mode_reglement_id = $id;
  2081. // for supplier
  2082. if (get_class($this) == 'Fournisseur') {
  2083. $this->mode_reglement_supplier_id = $id;
  2084. }
  2085. // Triggers
  2086. if (!$error && !$notrigger) {
  2087. // Call triggers
  2088. if (get_class($this) == 'Commande') {
  2089. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2090. } else {
  2091. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2092. }
  2093. if ($result < 0) {
  2094. $error++;
  2095. }
  2096. // End call triggers
  2097. }
  2098. return 1;
  2099. } else {
  2100. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2101. $this->error = $this->db->error();
  2102. return -1;
  2103. }
  2104. } else {
  2105. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2106. $this->error = 'Status of the object is incompatible '.$this->statut;
  2107. return -2;
  2108. }
  2109. }
  2110. /**
  2111. * Change the multicurrency code
  2112. *
  2113. * @param string $code multicurrency code
  2114. * @return int >0 if OK, <0 if KO
  2115. */
  2116. public function setMulticurrencyCode($code)
  2117. {
  2118. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2119. if ($this->statut >= 0 || $this->element == 'societe') {
  2120. $fieldname = 'multicurrency_code';
  2121. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2122. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2123. $sql .= ' WHERE rowid='.((int) $this->id);
  2124. if ($this->db->query($sql)) {
  2125. $this->multicurrency_code = $code;
  2126. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2127. if ($rate) {
  2128. $this->setMulticurrencyRate($rate, 2);
  2129. }
  2130. return 1;
  2131. } else {
  2132. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2133. $this->error = $this->db->error();
  2134. return -1;
  2135. }
  2136. } else {
  2137. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2138. $this->error = 'Status of the object is incompatible '.$this->statut;
  2139. return -2;
  2140. }
  2141. }
  2142. /**
  2143. * Change the multicurrency rate
  2144. *
  2145. * @param double $rate multicurrency rate
  2146. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2147. * @return int >0 if OK, <0 if KO
  2148. */
  2149. public function setMulticurrencyRate($rate, $mode = 1)
  2150. {
  2151. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2152. if ($this->statut >= 0 || $this->element == 'societe') {
  2153. $fieldname = 'multicurrency_tx';
  2154. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2155. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2156. $sql .= ' WHERE rowid='.((int) $this->id);
  2157. if ($this->db->query($sql)) {
  2158. $this->multicurrency_tx = $rate;
  2159. // Update line price
  2160. if (!empty($this->lines)) {
  2161. foreach ($this->lines as &$line) {
  2162. // Amounts in company currency will be recalculated
  2163. if ($mode == 1) {
  2164. $line->subprice = 0;
  2165. }
  2166. // Amounts in foreign currency will be recalculated
  2167. if ($mode == 2) {
  2168. $line->multicurrency_subprice = 0;
  2169. }
  2170. switch ($this->element) {
  2171. case 'propal':
  2172. /** @var Propal $this */
  2173. /** @var PropaleLigne $line */
  2174. $this->updateline(
  2175. $line->id,
  2176. $line->subprice,
  2177. $line->qty,
  2178. $line->remise_percent,
  2179. $line->tva_tx,
  2180. $line->localtax1_tx,
  2181. $line->localtax2_tx,
  2182. ($line->description ? $line->description : $line->desc),
  2183. 'HT',
  2184. $line->info_bits,
  2185. $line->special_code,
  2186. $line->fk_parent_line,
  2187. $line->skip_update_total,
  2188. $line->fk_fournprice,
  2189. $line->pa_ht,
  2190. $line->label,
  2191. $line->product_type,
  2192. $line->date_start,
  2193. $line->date_end,
  2194. $line->array_options,
  2195. $line->fk_unit,
  2196. $line->multicurrency_subprice
  2197. );
  2198. break;
  2199. case 'commande':
  2200. /** @var Commande $this */
  2201. /** @var OrderLine $line */
  2202. $this->updateline(
  2203. $line->id,
  2204. ($line->description ? $line->description : $line->desc),
  2205. $line->subprice,
  2206. $line->qty,
  2207. $line->remise_percent,
  2208. $line->tva_tx,
  2209. $line->localtax1_tx,
  2210. $line->localtax2_tx,
  2211. 'HT',
  2212. $line->info_bits,
  2213. $line->date_start,
  2214. $line->date_end,
  2215. $line->product_type,
  2216. $line->fk_parent_line,
  2217. $line->skip_update_total,
  2218. $line->fk_fournprice,
  2219. $line->pa_ht,
  2220. $line->label,
  2221. $line->special_code,
  2222. $line->array_options,
  2223. $line->fk_unit,
  2224. $line->multicurrency_subprice
  2225. );
  2226. break;
  2227. case 'facture':
  2228. /** @var Facture $this */
  2229. /** @var FactureLigne $line */
  2230. $this->updateline(
  2231. $line->id,
  2232. ($line->description ? $line->description : $line->desc),
  2233. $line->subprice,
  2234. $line->qty,
  2235. $line->remise_percent,
  2236. $line->date_start,
  2237. $line->date_end,
  2238. $line->tva_tx,
  2239. $line->localtax1_tx,
  2240. $line->localtax2_tx,
  2241. 'HT',
  2242. $line->info_bits,
  2243. $line->product_type,
  2244. $line->fk_parent_line,
  2245. $line->skip_update_total,
  2246. $line->fk_fournprice,
  2247. $line->pa_ht,
  2248. $line->label,
  2249. $line->special_code,
  2250. $line->array_options,
  2251. $line->situation_percent,
  2252. $line->fk_unit,
  2253. $line->multicurrency_subprice
  2254. );
  2255. break;
  2256. case 'supplier_proposal':
  2257. /** @var SupplierProposal $this */
  2258. /** @var SupplierProposalLine $line */
  2259. $this->updateline(
  2260. $line->id,
  2261. $line->subprice,
  2262. $line->qty,
  2263. $line->remise_percent,
  2264. $line->tva_tx,
  2265. $line->localtax1_tx,
  2266. $line->localtax2_tx,
  2267. ($line->description ? $line->description : $line->desc),
  2268. 'HT',
  2269. $line->info_bits,
  2270. $line->special_code,
  2271. $line->fk_parent_line,
  2272. $line->skip_update_total,
  2273. $line->fk_fournprice,
  2274. $line->pa_ht,
  2275. $line->label,
  2276. $line->product_type,
  2277. $line->array_options,
  2278. $line->ref_fourn,
  2279. $line->multicurrency_subprice
  2280. );
  2281. break;
  2282. case 'order_supplier':
  2283. /** @var CommandeFournisseur $this */
  2284. /** @var CommandeFournisseurLigne $line */
  2285. $this->updateline(
  2286. $line->id,
  2287. ($line->description ? $line->description : $line->desc),
  2288. $line->subprice,
  2289. $line->qty,
  2290. $line->remise_percent,
  2291. $line->tva_tx,
  2292. $line->localtax1_tx,
  2293. $line->localtax2_tx,
  2294. 'HT',
  2295. $line->info_bits,
  2296. $line->product_type,
  2297. false,
  2298. $line->date_start,
  2299. $line->date_end,
  2300. $line->array_options,
  2301. $line->fk_unit,
  2302. $line->multicurrency_subprice,
  2303. $line->ref_supplier
  2304. );
  2305. break;
  2306. case 'invoice_supplier':
  2307. /** @var FactureFournisseur $this */
  2308. /** @var SupplierInvoiceLine $line */
  2309. $this->updateline(
  2310. $line->id,
  2311. ($line->description ? $line->description : $line->desc),
  2312. $line->subprice,
  2313. $line->tva_tx,
  2314. $line->localtax1_tx,
  2315. $line->localtax2_tx,
  2316. $line->qty,
  2317. 0,
  2318. 'HT',
  2319. $line->info_bits,
  2320. $line->product_type,
  2321. $line->remise_percent,
  2322. false,
  2323. $line->date_start,
  2324. $line->date_end,
  2325. $line->array_options,
  2326. $line->fk_unit,
  2327. $line->multicurrency_subprice,
  2328. $line->ref_supplier
  2329. );
  2330. break;
  2331. default:
  2332. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2333. break;
  2334. }
  2335. }
  2336. }
  2337. return 1;
  2338. } else {
  2339. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2340. $this->error = $this->db->error();
  2341. return -1;
  2342. }
  2343. } else {
  2344. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2345. $this->error = 'Status of the object is incompatible '.$this->statut;
  2346. return -2;
  2347. }
  2348. }
  2349. /**
  2350. * Change the payments terms
  2351. *
  2352. * @param int $id Id of new payment terms
  2353. * @param string $deposit_percent % of deposit if needed by payment terms
  2354. * @return int >0 if OK, <0 if KO
  2355. */
  2356. public function setPaymentTerms($id, $deposit_percent = null)
  2357. {
  2358. dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
  2359. if ($this->statut >= 0 || $this->element == 'societe') {
  2360. // TODO uniformize field name
  2361. $fieldname = 'fk_cond_reglement';
  2362. if ($this->element == 'societe') {
  2363. $fieldname = 'cond_reglement';
  2364. }
  2365. if (get_class($this) == 'Fournisseur') {
  2366. $fieldname = 'cond_reglement_supplier';
  2367. }
  2368. if (empty($deposit_percent) || $deposit_percent < 0) {
  2369. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2370. }
  2371. if ($deposit_percent > 100) {
  2372. $deposit_percent = 100;
  2373. }
  2374. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2375. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2376. if (in_array($this->table_element, array('propal', 'commande', 'societe'))) {
  2377. $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
  2378. }
  2379. $sql .= ' WHERE rowid='.((int) $this->id);
  2380. if ($this->db->query($sql)) {
  2381. $this->cond_reglement_id = $id;
  2382. // for supplier
  2383. if (get_class($this) == 'Fournisseur') {
  2384. $this->cond_reglement_supplier_id = $id;
  2385. }
  2386. $this->cond_reglement = $id; // for compatibility
  2387. $this->deposit_percent = $deposit_percent;
  2388. return 1;
  2389. } else {
  2390. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2391. $this->error = $this->db->error();
  2392. return -1;
  2393. }
  2394. } else {
  2395. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2396. $this->error = 'Status of the object is incompatible '.$this->statut;
  2397. return -2;
  2398. }
  2399. }
  2400. /**
  2401. * Change the transport mode methods
  2402. *
  2403. * @param int $id Id of transport mode
  2404. * @return int >0 if OK, <0 if KO
  2405. */
  2406. public function setTransportMode($id)
  2407. {
  2408. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2409. if ($this->statut >= 0 || $this->element == 'societe') {
  2410. $fieldname = 'fk_transport_mode';
  2411. if ($this->element == 'societe') {
  2412. $fieldname = 'transport_mode';
  2413. }
  2414. if (get_class($this) == 'Fournisseur') {
  2415. $fieldname = 'transport_mode_supplier';
  2416. }
  2417. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2418. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2419. $sql .= ' WHERE rowid='.((int) $this->id);
  2420. if ($this->db->query($sql)) {
  2421. $this->transport_mode_id = $id;
  2422. // for supplier
  2423. if (get_class($this) == 'Fournisseur') {
  2424. $this->transport_mode_supplier_id = $id;
  2425. }
  2426. return 1;
  2427. } else {
  2428. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2429. $this->error = $this->db->error();
  2430. return -1;
  2431. }
  2432. } else {
  2433. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2434. $this->error = 'Status of the object is incompatible '.$this->statut;
  2435. return -2;
  2436. }
  2437. }
  2438. /**
  2439. * Change the retained warranty payments terms
  2440. *
  2441. * @param int $id Id of new payment terms
  2442. * @return int >0 if OK, <0 if KO
  2443. */
  2444. public function setRetainedWarrantyPaymentTerms($id)
  2445. {
  2446. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2447. if ($this->statut >= 0 || $this->element == 'societe') {
  2448. $fieldname = 'retained_warranty_fk_cond_reglement';
  2449. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2450. $sql .= " SET ".$fieldname." = ".((int) $id);
  2451. $sql .= ' WHERE rowid='.((int) $this->id);
  2452. if ($this->db->query($sql)) {
  2453. $this->retained_warranty_fk_cond_reglement = $id;
  2454. return 1;
  2455. } else {
  2456. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2457. $this->error = $this->db->error();
  2458. return -1;
  2459. }
  2460. } else {
  2461. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2462. $this->error = 'Status of the object is incompatible '.$this->statut;
  2463. return -2;
  2464. }
  2465. }
  2466. /**
  2467. * Define delivery address
  2468. * @deprecated
  2469. *
  2470. * @param int $id Address id
  2471. * @return int <0 si ko, >0 si ok
  2472. */
  2473. public function setDeliveryAddress($id)
  2474. {
  2475. $fieldname = 'fk_delivery_address';
  2476. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2477. $fieldname = 'fk_address';
  2478. }
  2479. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2480. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2481. if ($this->db->query($sql)) {
  2482. $this->fk_delivery_address = $id;
  2483. return 1;
  2484. } else {
  2485. $this->error = $this->db->error();
  2486. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2487. return -1;
  2488. }
  2489. }
  2490. /**
  2491. * Change the shipping method
  2492. *
  2493. * @param int $shipping_method_id Id of shipping method
  2494. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2495. * @param User $userused Object user
  2496. *
  2497. * @return int 1 if OK, 0 if KO
  2498. */
  2499. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2500. {
  2501. global $user;
  2502. if (empty($userused)) {
  2503. $userused = $user;
  2504. }
  2505. $error = 0;
  2506. if (!$this->table_element) {
  2507. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2508. return -1;
  2509. }
  2510. $this->db->begin();
  2511. if ($shipping_method_id < 0) {
  2512. $shipping_method_id = 'NULL';
  2513. }
  2514. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2515. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2516. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2517. $sql .= " WHERE rowid=".((int) $this->id);
  2518. $resql = $this->db->query($sql);
  2519. if (!$resql) {
  2520. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2521. $this->error = $this->db->lasterror();
  2522. $error++;
  2523. } else {
  2524. if (!$notrigger) {
  2525. // Call trigger
  2526. $this->context = array('shippingmethodupdate'=>1);
  2527. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2528. if ($result < 0) {
  2529. $error++;
  2530. }
  2531. // End call trigger
  2532. }
  2533. }
  2534. if ($error) {
  2535. $this->db->rollback();
  2536. return -1;
  2537. } else {
  2538. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2539. $this->db->commit();
  2540. return 1;
  2541. }
  2542. }
  2543. /**
  2544. * Change the warehouse
  2545. *
  2546. * @param int $warehouse_id Id of warehouse
  2547. * @return int 1 if OK, 0 if KO
  2548. */
  2549. public function setWarehouse($warehouse_id)
  2550. {
  2551. if (!$this->table_element) {
  2552. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2553. return -1;
  2554. }
  2555. if ($warehouse_id < 0) {
  2556. $warehouse_id = 'NULL';
  2557. }
  2558. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2559. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2560. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2561. $sql .= " WHERE rowid=".((int) $this->id);
  2562. if ($this->db->query($sql)) {
  2563. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2564. return 1;
  2565. } else {
  2566. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2567. $this->error = $this->db->error();
  2568. return 0;
  2569. }
  2570. }
  2571. /**
  2572. * Set last model used by doc generator
  2573. *
  2574. * @param User $user User object that make change
  2575. * @param string $modelpdf Modele name
  2576. * @return int <0 if KO, >0 if OK
  2577. */
  2578. public function setDocModel($user, $modelpdf)
  2579. {
  2580. if (!$this->table_element) {
  2581. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2582. return -1;
  2583. }
  2584. $newmodelpdf = dol_trunc($modelpdf, 255);
  2585. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2586. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2587. $sql .= " WHERE rowid = ".((int) $this->id);
  2588. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2589. $resql = $this->db->query($sql);
  2590. if ($resql) {
  2591. $this->model_pdf = $modelpdf;
  2592. $this->modelpdf = $modelpdf; // For bakward compatibility
  2593. return 1;
  2594. } else {
  2595. dol_print_error($this->db);
  2596. return 0;
  2597. }
  2598. }
  2599. /**
  2600. * Change the bank account
  2601. *
  2602. * @param int $fk_account Id of bank account
  2603. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2604. * @param User $userused Object user
  2605. * @return int 1 if OK, 0 if KO
  2606. */
  2607. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2608. {
  2609. global $user;
  2610. if (empty($userused)) {
  2611. $userused = $user;
  2612. }
  2613. $error = 0;
  2614. if (!$this->table_element) {
  2615. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2616. return -1;
  2617. }
  2618. $this->db->begin();
  2619. if ($fk_account < 0) {
  2620. $fk_account = 'NULL';
  2621. }
  2622. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2623. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2624. $sql .= " SET fk_account = ".((int) $fk_account);
  2625. $sql .= " WHERE rowid=".((int) $this->id);
  2626. $resql = $this->db->query($sql);
  2627. if (!$resql) {
  2628. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2629. $this->error = $this->db->lasterror();
  2630. $error++;
  2631. } else {
  2632. if (!$notrigger) {
  2633. // Call trigger
  2634. $this->context = array('bankaccountupdate'=>1);
  2635. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2636. if ($result < 0) {
  2637. $error++;
  2638. }
  2639. // End call trigger
  2640. }
  2641. }
  2642. if ($error) {
  2643. $this->db->rollback();
  2644. return -1;
  2645. } else {
  2646. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2647. $this->db->commit();
  2648. return 1;
  2649. }
  2650. }
  2651. // TODO: Move line related operations to CommonObjectLine?
  2652. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2653. /**
  2654. * Save a new position (field rang) for details lines.
  2655. * You can choose to set position for lines with already a position or lines without any position defined.
  2656. *
  2657. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2658. * @param string $rowidorder ASC or DESC
  2659. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2660. * @return int <0 if KO, >0 if OK
  2661. */
  2662. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2663. {
  2664. // phpcs:enable
  2665. if (!$this->table_element_line) {
  2666. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2667. return -1;
  2668. }
  2669. if (!$this->fk_element) {
  2670. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2671. return -1;
  2672. }
  2673. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2674. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2675. $fieldposition = 'position';
  2676. }
  2677. // Count number of lines to reorder (according to choice $renum)
  2678. $nl = 0;
  2679. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2680. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2681. if (!$renum) {
  2682. $sql .= " AND " . $fieldposition . " = 0";
  2683. }
  2684. if ($renum) {
  2685. $sql .= " AND " . $fieldposition . " <> 0";
  2686. }
  2687. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2688. $resql = $this->db->query($sql);
  2689. if ($resql) {
  2690. $row = $this->db->fetch_row($resql);
  2691. $nl = $row[0];
  2692. } else {
  2693. dol_print_error($this->db);
  2694. }
  2695. if ($nl > 0) {
  2696. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2697. $rows = array();
  2698. // We first search all lines that are parent lines (for multilevel details lines)
  2699. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2700. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2701. if ($fk_parent_line) {
  2702. $sql .= ' AND fk_parent_line IS NULL';
  2703. }
  2704. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2705. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2706. $resql = $this->db->query($sql);
  2707. if ($resql) {
  2708. $i = 0;
  2709. $num = $this->db->num_rows($resql);
  2710. while ($i < $num) {
  2711. $row = $this->db->fetch_row($resql);
  2712. $rows[] = $row[0]; // Add parent line into array rows
  2713. $childrens = $this->getChildrenOfLine($row[0]);
  2714. if (!empty($childrens)) {
  2715. foreach ($childrens as $child) {
  2716. array_push($rows, $child);
  2717. }
  2718. }
  2719. $i++;
  2720. }
  2721. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2722. if (!empty($rows)) {
  2723. foreach ($rows as $key => $row) {
  2724. $this->updateRangOfLine($row, ($key + 1));
  2725. }
  2726. }
  2727. } else {
  2728. dol_print_error($this->db);
  2729. }
  2730. }
  2731. return 1;
  2732. }
  2733. /**
  2734. * Get children of line
  2735. *
  2736. * @param int $id Id of parent line
  2737. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2738. * @return array Array with list of children lines id
  2739. */
  2740. public function getChildrenOfLine($id, $includealltree = 0)
  2741. {
  2742. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2743. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2744. $fieldposition = 'position';
  2745. }
  2746. $rows = array();
  2747. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2748. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2749. $sql .= ' AND fk_parent_line = '.((int) $id);
  2750. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2751. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2752. $resql = $this->db->query($sql);
  2753. if ($resql) {
  2754. if ($this->db->num_rows($resql) > 0) {
  2755. while ($row = $this->db->fetch_row($resql)) {
  2756. $rows[] = $row[0];
  2757. if (!empty($includealltree)) {
  2758. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2759. }
  2760. }
  2761. }
  2762. }
  2763. return $rows;
  2764. }
  2765. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2766. /**
  2767. * Update a line to have a lower rank
  2768. *
  2769. * @param int $rowid Id of line
  2770. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2771. * @return void
  2772. */
  2773. public function line_up($rowid, $fk_parent_line = true)
  2774. {
  2775. // phpcs:enable
  2776. $this->line_order(false, 'ASC', $fk_parent_line);
  2777. // Get rang of line
  2778. $rang = $this->getRangOfLine($rowid);
  2779. // Update position of line
  2780. $this->updateLineUp($rowid, $rang);
  2781. }
  2782. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2783. /**
  2784. * Update a line to have a higher rank
  2785. *
  2786. * @param int $rowid Id of line
  2787. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2788. * @return void
  2789. */
  2790. public function line_down($rowid, $fk_parent_line = true)
  2791. {
  2792. // phpcs:enable
  2793. $this->line_order(false, 'ASC', $fk_parent_line);
  2794. // Get rang of line
  2795. $rang = $this->getRangOfLine($rowid);
  2796. // Get max value for rang
  2797. $max = $this->line_max();
  2798. // Update position of line
  2799. $this->updateLineDown($rowid, $rang, $max);
  2800. }
  2801. /**
  2802. * Update position of line (rang)
  2803. *
  2804. * @param int $rowid Id of line
  2805. * @param int $rang Position
  2806. * @return int <0 if KO, >0 if OK
  2807. */
  2808. public function updateRangOfLine($rowid, $rang)
  2809. {
  2810. global $hookmanager;
  2811. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2812. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2813. $fieldposition = 'position';
  2814. }
  2815. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2816. $sql .= ' WHERE rowid = '.((int) $rowid);
  2817. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2818. if (!$this->db->query($sql)) {
  2819. dol_print_error($this->db);
  2820. return -1;
  2821. } else {
  2822. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2823. $action='';
  2824. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2825. return 1;
  2826. }
  2827. }
  2828. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2829. /**
  2830. * Update position of line with ajax (rang)
  2831. *
  2832. * @param array $rows Array of rows
  2833. * @return void
  2834. */
  2835. public function line_ajaxorder($rows)
  2836. {
  2837. // phpcs:enable
  2838. $num = count($rows);
  2839. for ($i = 0; $i < $num; $i++) {
  2840. $this->updateRangOfLine($rows[$i], ($i + 1));
  2841. }
  2842. }
  2843. /**
  2844. * Update position of line up (rang)
  2845. *
  2846. * @param int $rowid Id of line
  2847. * @param int $rang Position
  2848. * @return void
  2849. */
  2850. public function updateLineUp($rowid, $rang)
  2851. {
  2852. if ($rang > 1) {
  2853. $fieldposition = 'rang';
  2854. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2855. $fieldposition = 'position';
  2856. }
  2857. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2858. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2859. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2860. if ($this->db->query($sql)) {
  2861. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2862. $sql .= ' WHERE rowid = '.((int) $rowid);
  2863. if (!$this->db->query($sql)) {
  2864. dol_print_error($this->db);
  2865. }
  2866. } else {
  2867. dol_print_error($this->db);
  2868. }
  2869. }
  2870. }
  2871. /**
  2872. * Update position of line down (rang)
  2873. *
  2874. * @param int $rowid Id of line
  2875. * @param int $rang Position
  2876. * @param int $max Max
  2877. * @return void
  2878. */
  2879. public function updateLineDown($rowid, $rang, $max)
  2880. {
  2881. if ($rang < $max) {
  2882. $fieldposition = 'rang';
  2883. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2884. $fieldposition = 'position';
  2885. }
  2886. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2887. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2888. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2889. if ($this->db->query($sql)) {
  2890. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2891. $sql .= ' WHERE rowid = '.((int) $rowid);
  2892. if (!$this->db->query($sql)) {
  2893. dol_print_error($this->db);
  2894. }
  2895. } else {
  2896. dol_print_error($this->db);
  2897. }
  2898. }
  2899. }
  2900. /**
  2901. * Get position of line (rang)
  2902. *
  2903. * @param int $rowid Id of line
  2904. * @return int Value of rang in table of lines
  2905. */
  2906. public function getRangOfLine($rowid)
  2907. {
  2908. $fieldposition = 'rang';
  2909. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2910. $fieldposition = 'position';
  2911. }
  2912. $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  2913. $sql .= " WHERE rowid = ".((int) $rowid);
  2914. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2915. $resql = $this->db->query($sql);
  2916. if ($resql) {
  2917. $row = $this->db->fetch_row($resql);
  2918. return $row[0];
  2919. }
  2920. return 0;
  2921. }
  2922. /**
  2923. * Get rowid of the line relative to its position
  2924. *
  2925. * @param int $rang Rang value
  2926. * @return int Rowid of the line
  2927. */
  2928. public function getIdOfLine($rang)
  2929. {
  2930. $fieldposition = 'rang';
  2931. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2932. $fieldposition = 'position';
  2933. }
  2934. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2935. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2936. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  2937. $resql = $this->db->query($sql);
  2938. if ($resql) {
  2939. $row = $this->db->fetch_row($resql);
  2940. return $row[0];
  2941. }
  2942. return 0;
  2943. }
  2944. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2945. /**
  2946. * Get max value used for position of line (rang)
  2947. *
  2948. * @param int $fk_parent_line Parent line id
  2949. * @return int Max value of rang in table of lines
  2950. */
  2951. public function line_max($fk_parent_line = 0)
  2952. {
  2953. // phpcs:enable
  2954. $positionfield = 'rang';
  2955. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  2956. $positionfield = 'position';
  2957. }
  2958. // Search the last rang with fk_parent_line
  2959. if ($fk_parent_line) {
  2960. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2961. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2962. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  2963. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2964. $resql = $this->db->query($sql);
  2965. if ($resql) {
  2966. $row = $this->db->fetch_row($resql);
  2967. if (!empty($row[0])) {
  2968. return $row[0];
  2969. } else {
  2970. return $this->getRangOfLine($fk_parent_line);
  2971. }
  2972. }
  2973. } else {
  2974. // If not, search the last rang of element
  2975. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2976. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2977. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2978. $resql = $this->db->query($sql);
  2979. if ($resql) {
  2980. $row = $this->db->fetch_row($resql);
  2981. return $row[0];
  2982. }
  2983. }
  2984. return 0;
  2985. }
  2986. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2987. /**
  2988. * Update external ref of element
  2989. *
  2990. * @param string $ref_ext Update field ref_ext
  2991. * @return int <0 if KO, >0 if OK
  2992. */
  2993. public function update_ref_ext($ref_ext)
  2994. {
  2995. // phpcs:enable
  2996. if (!$this->table_element) {
  2997. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2998. return -1;
  2999. }
  3000. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3001. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  3002. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  3003. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  3004. if ($this->db->query($sql)) {
  3005. $this->ref_ext = $ref_ext;
  3006. return 1;
  3007. } else {
  3008. $this->error = $this->db->error();
  3009. return -1;
  3010. }
  3011. }
  3012. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3013. /**
  3014. * Update note of element
  3015. *
  3016. * @param string $note New value for note
  3017. * @param string $suffix '', '_public' or '_private'
  3018. * @return int <0 if KO, >0 if OK
  3019. */
  3020. public function update_note($note, $suffix = '')
  3021. {
  3022. // phpcs:enable
  3023. global $user;
  3024. if (!$this->table_element) {
  3025. $this->error = 'update_note was called on objet with property table_element not defined';
  3026. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  3027. return -1;
  3028. }
  3029. if (!in_array($suffix, array('', '_public', '_private'))) {
  3030. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3031. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3032. return -2;
  3033. }
  3034. $newsuffix = $suffix;
  3035. // Special cas
  3036. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3037. $newsuffix = '';
  3038. }
  3039. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3040. $fieldusermod = "fk_user_mod";
  3041. } elseif ($this->table_element == 'ecm_files') {
  3042. $fieldusermod = "fk_user_m";
  3043. } else {
  3044. $fieldusermod = "fk_user_modif";
  3045. }
  3046. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3047. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  3048. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  3049. $sql .= " WHERE rowid = ".((int) $this->id);
  3050. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  3051. if ($this->db->query($sql)) {
  3052. if ($suffix == '_public') {
  3053. $this->note_public = $note;
  3054. } elseif ($suffix == '_private') {
  3055. $this->note_private = $note;
  3056. } else {
  3057. $this->note = $note; // deprecated
  3058. $this->note_private = $note;
  3059. }
  3060. return 1;
  3061. } else {
  3062. $this->error = $this->db->lasterror();
  3063. return -1;
  3064. }
  3065. }
  3066. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3067. /**
  3068. * Update public note (kept for backward compatibility)
  3069. *
  3070. * @param string $note New value for note
  3071. * @return int <0 if KO, >0 if OK
  3072. * @deprecated
  3073. * @see update_note()
  3074. */
  3075. public function update_note_public($note)
  3076. {
  3077. // phpcs:enable
  3078. return $this->update_note($note, '_public');
  3079. }
  3080. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3081. /**
  3082. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3083. * Must be called at end of methods addline or updateline.
  3084. *
  3085. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3086. * @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
  3087. * @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.
  3088. * @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).
  3089. * @return int <0 if KO, >0 if OK
  3090. */
  3091. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3092. {
  3093. // phpcs:enable
  3094. global $conf, $hookmanager, $action;
  3095. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3096. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3097. if ($reshook > 0) {
  3098. return 1; // replacement code
  3099. } elseif ($reshook < 0) {
  3100. return -1; // failure
  3101. } // reshook = 0 => execute normal code
  3102. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3103. $MODULE = "";
  3104. if ($this->element == 'propal') {
  3105. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3106. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3107. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3108. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3109. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3110. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3111. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3112. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3113. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3114. } elseif ($this->element == 'supplier_proposal') {
  3115. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3116. }
  3117. if (!empty($MODULE)) {
  3118. if (!empty($conf->global->$MODULE)) {
  3119. $modsactivated = explode(',', $conf->global->$MODULE);
  3120. foreach ($modsactivated as $mod) {
  3121. if (isModEnabled($mod)) {
  3122. return 1; // update was disabled by specific setup
  3123. }
  3124. }
  3125. }
  3126. }
  3127. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3128. $forcedroundingmode = $roundingadjust;
  3129. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3130. $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
  3131. } elseif ($forcedroundingmode == 'auto') {
  3132. $forcedroundingmode = '0';
  3133. }
  3134. $error = 0;
  3135. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3136. // Define constants to find lines to sum (field name int the table_element_line not into table_element)
  3137. $fieldtva = 'total_tva';
  3138. $fieldlocaltax1 = 'total_localtax1';
  3139. $fieldlocaltax2 = 'total_localtax2';
  3140. $fieldup = 'subprice';
  3141. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3142. $fieldtva = 'tva';
  3143. $fieldup = 'pu_ht';
  3144. }
  3145. if ($this->element == 'invoice_supplier_rec') {
  3146. $fieldup = 'pu_ht';
  3147. }
  3148. if ($this->element == 'expensereport') {
  3149. $fieldup = 'value_unit';
  3150. }
  3151. $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,";
  3152. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3153. if ($this->table_element_line == 'facturedet') {
  3154. $sql .= ', situation_percent';
  3155. }
  3156. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3157. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3158. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3159. if ($exclspec) {
  3160. $product_field = 'product_type';
  3161. if ($this->table_element_line == 'contratdet') {
  3162. $product_field = ''; // contratdet table has no product_type field
  3163. }
  3164. if ($product_field) {
  3165. $sql .= " AND ".$product_field." <> 9";
  3166. }
  3167. }
  3168. $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
  3169. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3170. $resql = $this->db->query($sql);
  3171. if ($resql) {
  3172. $this->total_ht = 0;
  3173. $this->total_tva = 0;
  3174. $this->total_localtax1 = 0;
  3175. $this->total_localtax2 = 0;
  3176. $this->total_ttc = 0;
  3177. $total_ht_by_vats = array();
  3178. $total_tva_by_vats = array();
  3179. $total_ttc_by_vats = array();
  3180. $this->multicurrency_total_ht = 0;
  3181. $this->multicurrency_total_tva = 0;
  3182. $this->multicurrency_total_ttc = 0;
  3183. $this->db->begin();
  3184. $num = $this->db->num_rows($resql);
  3185. $i = 0;
  3186. while ($i < $num) {
  3187. $obj = $this->db->fetch_object($resql);
  3188. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3189. $parameters = array('fk_element' => $obj->rowid);
  3190. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3191. 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'
  3192. // This part of code is to fix data. We should not call it too often.
  3193. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3194. $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);
  3195. $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.
  3196. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3197. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
  3198. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3199. if ($diff_on_current_total) {
  3200. // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
  3201. $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);
  3202. 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);
  3203. $resqlfix = $this->db->query($sqlfix);
  3204. if (!$resqlfix) {
  3205. dol_print_error($this->db, 'Failed to update line');
  3206. }
  3207. $obj->total_tva = $tmpcal[1];
  3208. $obj->total_ttc = $tmpcal[2];
  3209. } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
  3210. // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
  3211. // we ask to force the use of rounding on line (like done on calculation) so we force update of line
  3212. $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);
  3213. 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);
  3214. $resqlfix = $this->db->query($sqlfix);
  3215. if (!$resqlfix) {
  3216. dol_print_error($this->db, 'Failed to update line');
  3217. }
  3218. $obj->total_tva = $tmpcal[1];
  3219. $obj->total_ttc = $tmpcal[2];
  3220. }
  3221. }
  3222. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3223. $this->total_tva += $obj->total_tva;
  3224. $this->total_localtax1 += $obj->total_localtax1;
  3225. $this->total_localtax2 += $obj->total_localtax2;
  3226. $this->total_ttc += $obj->total_ttc;
  3227. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3228. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3229. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3230. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3231. $total_ht_by_vats[$obj->vatrate] = 0;
  3232. }
  3233. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3234. $total_tva_by_vats[$obj->vatrate] = 0;
  3235. }
  3236. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3237. $total_ttc_by_vats[$obj->vatrate] = 0;
  3238. }
  3239. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3240. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3241. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3242. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on foreign currency
  3243. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3244. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3245. //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";
  3246. if ($diff) {
  3247. if (abs($diff) > (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)))) {
  3248. // If error is more than 10 times the accurancy of rounding. This should not happen.
  3249. $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your lines may be corrupted. Try to edit each line manually to fix this before restarting.';
  3250. dol_syslog($errmsg, LOG_WARNING);
  3251. $this->error = $errmsg;
  3252. $error++;
  3253. break;
  3254. }
  3255. $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);
  3256. 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);
  3257. $resqlfix = $this->db->query($sqlfix);
  3258. if (!$resqlfix) {
  3259. dol_print_error($this->db, 'Failed to update line');
  3260. }
  3261. $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
  3262. $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
  3263. $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
  3264. $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
  3265. }
  3266. }
  3267. $i++;
  3268. }
  3269. // Add revenue stamp to total
  3270. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3271. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3272. // Situations totals
  3273. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3274. $prev_sits = $this->get_prev_sits();
  3275. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3276. $this->total_ht -= $sit->total_ht;
  3277. $this->total_tva -= $sit->total_tva;
  3278. $this->total_localtax1 -= $sit->total_localtax1;
  3279. $this->total_localtax2 -= $sit->total_localtax2;
  3280. $this->total_ttc -= $sit->total_ttc;
  3281. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3282. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3283. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3284. }
  3285. }
  3286. // Clean total
  3287. $this->total_ht = (float) price2num($this->total_ht);
  3288. $this->total_tva = (float) price2num($this->total_tva);
  3289. $this->total_localtax1 = (float) price2num($this->total_localtax1);
  3290. $this->total_localtax2 = (float) price2num($this->total_localtax2);
  3291. $this->total_ttc = (float) price2num($this->total_ttc);
  3292. $this->db->free($resql);
  3293. // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
  3294. $fieldht = 'total_ht';
  3295. $fieldtva = 'tva';
  3296. $fieldlocaltax1 = 'localtax1';
  3297. $fieldlocaltax2 = 'localtax2';
  3298. $fieldttc = 'total_ttc';
  3299. // Specific code for backward compatibility with old field names
  3300. if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
  3301. $fieldtva = 'total_tva';
  3302. }
  3303. if (!$error && empty($nodatabaseupdate)) {
  3304. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3305. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
  3306. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
  3307. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
  3308. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
  3309. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
  3310. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3311. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3312. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3313. $sql .= " WHERE rowid = ".((int) $this->id);
  3314. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3315. $resql = $this->db->query($sql);
  3316. if (!$resql) {
  3317. $error++;
  3318. $this->error = $this->db->lasterror();
  3319. $this->errors[] = $this->db->lasterror();
  3320. }
  3321. }
  3322. if (!$error) {
  3323. $this->db->commit();
  3324. return 1;
  3325. } else {
  3326. $this->db->rollback();
  3327. return -1;
  3328. }
  3329. } else {
  3330. dol_print_error($this->db, 'Bad request in update_price');
  3331. return -1;
  3332. }
  3333. }
  3334. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3335. /**
  3336. * Add an object link into llx_element_element.
  3337. *
  3338. * @param string $origin Linked element type
  3339. * @param int $origin_id Linked element id
  3340. * @param User $f_user User that create
  3341. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3342. * @return int <=0 if KO, >0 if OK
  3343. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3344. */
  3345. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3346. {
  3347. // phpcs:enable
  3348. global $user, $hookmanager, $action;
  3349. $origin = (!empty($origin) ? $origin : $this->origin);
  3350. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3351. $f_user = isset($f_user) ? $f_user : $user;
  3352. // Special case
  3353. if ($origin == 'order') {
  3354. $origin = 'commande';
  3355. }
  3356. if ($origin == 'invoice') {
  3357. $origin = 'facture';
  3358. }
  3359. if ($origin == 'invoice_template') {
  3360. $origin = 'facturerec';
  3361. }
  3362. if ($origin == 'supplierorder') {
  3363. $origin = 'order_supplier';
  3364. }
  3365. // 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.
  3366. // 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.
  3367. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3368. // Add module part to target type if object has $module property and isn't in core modules.
  3369. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3370. $parameters = array('targettype'=>$targettype);
  3371. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3372. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3373. if ($reshook > 0) {
  3374. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3375. }
  3376. $this->db->begin();
  3377. $error = 0;
  3378. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3379. $sql .= "fk_source";
  3380. $sql .= ", sourcetype";
  3381. $sql .= ", fk_target";
  3382. $sql .= ", targettype";
  3383. $sql .= ") VALUES (";
  3384. $sql .= ((int) $origin_id);
  3385. $sql .= ", '" . $this->db->escape($origin) . "'";
  3386. $sql .= ", " . ((int) $this->id);
  3387. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3388. $sql .= ")";
  3389. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3390. if ($this->db->query($sql)) {
  3391. if (!$notrigger) {
  3392. // Call trigger
  3393. $this->context['link_origin'] = $origin;
  3394. $this->context['link_origin_id'] = $origin_id;
  3395. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3396. if ($result < 0) {
  3397. $error++;
  3398. }
  3399. // End call triggers
  3400. }
  3401. } else {
  3402. $this->error = $this->db->lasterror();
  3403. $error++;
  3404. }
  3405. if (!$error) {
  3406. $this->db->commit();
  3407. return 1;
  3408. } else {
  3409. $this->db->rollback();
  3410. return 0;
  3411. }
  3412. }
  3413. /**
  3414. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3415. * this->linkedObjectsIds array +
  3416. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3417. * Possible usage for parameters:
  3418. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3419. * - source id+type -> will get list of targets linked to source
  3420. * - target id+type -> will get list of sources linked to target
  3421. * - source id+type + target type -> will get list of targets of the type linked to source
  3422. * - target id+type + source type -> will get list of sources of the type linked to target
  3423. *
  3424. * @param int $sourceid Object source id (if not defined, $this->id)
  3425. * @param string $sourcetype Object source type (if not defined, $this->element)
  3426. * @param int $targetid Object target id (if not defined, $this->id)
  3427. * @param string $targettype Object target type (if not defined, $this->element)
  3428. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3429. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3430. * @param string $orderby SQL 'ORDER BY' clause
  3431. * @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.
  3432. * @return int <0 if KO, >0 if OK
  3433. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3434. */
  3435. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3436. {
  3437. global $conf, $hookmanager, $action;
  3438. // Important for pdf generation time reduction
  3439. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3440. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3441. return 1;
  3442. }
  3443. $this->linkedObjectsIds = array();
  3444. $this->linkedObjects = array();
  3445. $justsource = false;
  3446. $justtarget = false;
  3447. $withtargettype = false;
  3448. $withsourcetype = false;
  3449. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3450. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3451. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3452. if ($reshook > 0) {
  3453. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3454. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3455. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3456. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3457. }
  3458. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3459. $justsource = true; // the source (id and type) is a search criteria
  3460. if (!empty($targettype)) {
  3461. $withtargettype = true;
  3462. }
  3463. }
  3464. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3465. $justtarget = true; // the target (id and type) is a search criteria
  3466. if (!empty($sourcetype)) {
  3467. $withsourcetype = true;
  3468. }
  3469. }
  3470. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3471. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3472. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3473. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3474. /*if (empty($sourceid) && empty($targetid))
  3475. {
  3476. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3477. return -1;
  3478. }*/
  3479. // Links between objects are stored in table element_element
  3480. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3481. $sql .= " FROM ".$this->db->prefix()."element_element";
  3482. $sql .= " WHERE ";
  3483. if ($justsource || $justtarget) {
  3484. if ($justsource) {
  3485. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3486. if ($withtargettype) {
  3487. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3488. }
  3489. } elseif ($justtarget) {
  3490. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3491. if ($withsourcetype) {
  3492. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3493. }
  3494. }
  3495. } else {
  3496. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3497. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3498. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3499. $this->linkedObjectsFullLoaded[$this->id] = true;
  3500. }
  3501. }
  3502. $sql .= " ORDER BY ".$orderby;
  3503. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3504. $resql = $this->db->query($sql);
  3505. if ($resql) {
  3506. $num = $this->db->num_rows($resql);
  3507. $i = 0;
  3508. while ($i < $num) {
  3509. $obj = $this->db->fetch_object($resql);
  3510. if ($justsource || $justtarget) {
  3511. if ($justsource) {
  3512. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3513. } elseif ($justtarget) {
  3514. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3515. }
  3516. } else {
  3517. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3518. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3519. }
  3520. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3521. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3522. }
  3523. }
  3524. $i++;
  3525. }
  3526. if (!empty($this->linkedObjectsIds)) {
  3527. $tmparray = $this->linkedObjectsIds;
  3528. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3529. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3530. $module = $element = $subelement = $objecttype;
  3531. $regs = array();
  3532. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3533. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3534. $module = $element = $regs[1];
  3535. $subelement = $regs[2];
  3536. }
  3537. $classpath = $element.'/class';
  3538. // To work with non standard classpath or module name
  3539. if ($objecttype == 'facture') {
  3540. $classpath = 'compta/facture/class';
  3541. } elseif ($objecttype == 'facturerec') {
  3542. $classpath = 'compta/facture/class';
  3543. $module = 'facture';
  3544. } elseif ($objecttype == 'propal') {
  3545. $classpath = 'comm/propal/class';
  3546. } elseif ($objecttype == 'supplier_proposal') {
  3547. $classpath = 'supplier_proposal/class';
  3548. } elseif ($objecttype == 'shipping') {
  3549. $classpath = 'expedition/class';
  3550. $subelement = 'expedition';
  3551. $module = 'expedition';
  3552. } elseif ($objecttype == 'delivery') {
  3553. $classpath = 'delivery/class';
  3554. $subelement = 'delivery';
  3555. $module = 'delivery_note';
  3556. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3557. $classpath = 'fourn/class';
  3558. $module = 'fournisseur';
  3559. } elseif ($objecttype == 'fichinter') {
  3560. $classpath = 'fichinter/class';
  3561. $subelement = 'fichinter';
  3562. $module = 'ficheinter';
  3563. } elseif ($objecttype == 'subscription') {
  3564. $classpath = 'adherents/class';
  3565. $module = 'adherent';
  3566. } elseif ($objecttype == 'contact') {
  3567. $module = 'societe';
  3568. }
  3569. // Set classfile
  3570. $classfile = strtolower($subelement);
  3571. $classname = ucfirst($subelement);
  3572. if ($objecttype == 'order') {
  3573. $classfile = 'commande';
  3574. $classname = 'Commande';
  3575. } elseif ($objecttype == 'invoice_supplier') {
  3576. $classfile = 'fournisseur.facture';
  3577. $classname = 'FactureFournisseur';
  3578. } elseif ($objecttype == 'order_supplier') {
  3579. $classfile = 'fournisseur.commande';
  3580. $classname = 'CommandeFournisseur';
  3581. } elseif ($objecttype == 'supplier_proposal') {
  3582. $classfile = 'supplier_proposal';
  3583. $classname = 'SupplierProposal';
  3584. } elseif ($objecttype == 'facturerec') {
  3585. $classfile = 'facture-rec';
  3586. $classname = 'FactureRec';
  3587. } elseif ($objecttype == 'subscription') {
  3588. $classfile = 'subscription';
  3589. $classname = 'Subscription';
  3590. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3591. $classpath = 'projet/class';
  3592. $classfile = 'project';
  3593. $classname = 'Project';
  3594. } elseif ($objecttype == 'conferenceorboothattendee') {
  3595. $classpath = 'eventorganization/class';
  3596. $classfile = 'conferenceorboothattendee';
  3597. $classname = 'ConferenceOrBoothAttendee';
  3598. $module = 'eventorganization';
  3599. } elseif ($objecttype == 'conferenceorbooth') {
  3600. $classpath = 'eventorganization/class';
  3601. $classfile = 'conferenceorbooth';
  3602. $classname = 'ConferenceOrBooth';
  3603. $module = 'eventorganization';
  3604. } elseif ($objecttype == 'mo') {
  3605. $classpath = 'mrp/class';
  3606. $classfile = 'mo';
  3607. $classname = 'Mo';
  3608. $module = 'mrp';
  3609. }
  3610. // Here $module, $classfile and $classname are set, we can use them.
  3611. if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
  3612. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3613. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3614. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3615. if (class_exists($classname)) {
  3616. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3617. $object = new $classname($this->db);
  3618. $ret = $object->fetch($objectid);
  3619. if ($ret >= 0) {
  3620. $this->linkedObjects[$objecttype][$i] = $object;
  3621. }
  3622. }
  3623. }
  3624. }
  3625. } else {
  3626. unset($this->linkedObjectsIds[$objecttype]);
  3627. }
  3628. }
  3629. }
  3630. return 1;
  3631. } else {
  3632. dol_print_error($this->db);
  3633. return -1;
  3634. }
  3635. }
  3636. /**
  3637. * Clear the cache saying that all linked object were already loaded. So next fetchObjectLinked will reload all links.
  3638. *
  3639. * @return int <0 if KO, >0 if OK
  3640. * @see fetchObjectLinked()
  3641. */
  3642. public function clearObjectLinkedCache()
  3643. {
  3644. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3645. unset($this->linkedObjectsFullLoaded[$this->id]);
  3646. }
  3647. return 1;
  3648. }
  3649. /**
  3650. * Update object linked of a current object
  3651. *
  3652. * @param int $sourceid Object source id
  3653. * @param string $sourcetype Object source type
  3654. * @param int $targetid Object target id
  3655. * @param string $targettype Object target type
  3656. * @param User $f_user User that create
  3657. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3658. * @return int >0 if OK, <0 if KO
  3659. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3660. */
  3661. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3662. {
  3663. global $user;
  3664. $updatesource = false;
  3665. $updatetarget = false;
  3666. $f_user = isset($f_user) ? $f_user : $user;
  3667. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3668. $updatesource = true;
  3669. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3670. $updatetarget = true;
  3671. }
  3672. $this->db->begin();
  3673. $error = 0;
  3674. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3675. if ($updatesource) {
  3676. $sql .= "fk_source = " . ((int) $sourceid);
  3677. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3678. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3679. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3680. } elseif ($updatetarget) {
  3681. $sql .= "fk_target = " . ((int) $targetid);
  3682. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3683. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3684. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3685. }
  3686. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3687. if ($this->db->query($sql)) {
  3688. if (!$notrigger) {
  3689. // Call trigger
  3690. $this->context['link_source_id'] = $sourceid;
  3691. $this->context['link_source_type'] = $sourcetype;
  3692. $this->context['link_target_id'] = $targetid;
  3693. $this->context['link_target_type'] = $targettype;
  3694. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3695. if ($result < 0) {
  3696. $error++;
  3697. }
  3698. // End call triggers
  3699. }
  3700. } else {
  3701. $this->error = $this->db->lasterror();
  3702. $error++;
  3703. }
  3704. if (!$error) {
  3705. $this->db->commit();
  3706. return 1;
  3707. } else {
  3708. $this->db->rollback();
  3709. return -1;
  3710. }
  3711. }
  3712. /**
  3713. * Delete all links between an object $this
  3714. *
  3715. * @param int $sourceid Object source id
  3716. * @param string $sourcetype Object source type
  3717. * @param int $targetid Object target id
  3718. * @param string $targettype Object target type
  3719. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3720. * @param User $f_user User that create
  3721. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3722. * @return int >0 if OK, <0 if KO
  3723. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3724. */
  3725. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3726. {
  3727. global $user;
  3728. $deletesource = false;
  3729. $deletetarget = false;
  3730. $f_user = isset($f_user) ? $f_user : $user;
  3731. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3732. $deletesource = true;
  3733. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3734. $deletetarget = true;
  3735. }
  3736. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3737. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3738. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3739. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3740. $this->db->begin();
  3741. $error = 0;
  3742. if (!$notrigger) {
  3743. // Call trigger
  3744. $this->context['link_id'] = $rowid;
  3745. $this->context['link_source_id'] = $sourceid;
  3746. $this->context['link_source_type'] = $sourcetype;
  3747. $this->context['link_target_id'] = $targetid;
  3748. $this->context['link_target_type'] = $targettype;
  3749. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3750. if ($result < 0) {
  3751. $error++;
  3752. }
  3753. // End call triggers
  3754. }
  3755. if (!$error) {
  3756. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3757. $sql .= " WHERE";
  3758. if ($rowid > 0) {
  3759. $sql .= " rowid = " . ((int) $rowid);
  3760. } else {
  3761. if ($deletesource) {
  3762. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3763. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3764. } elseif ($deletetarget) {
  3765. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3766. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3767. } else {
  3768. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3769. $sql .= " OR";
  3770. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3771. }
  3772. }
  3773. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3774. if (!$this->db->query($sql)) {
  3775. $this->error = $this->db->lasterror();
  3776. $this->errors[] = $this->error;
  3777. $error++;
  3778. }
  3779. }
  3780. if (!$error) {
  3781. $this->db->commit();
  3782. return 1;
  3783. } else {
  3784. $this->db->rollback();
  3785. return 0;
  3786. }
  3787. }
  3788. /**
  3789. * Function used to get an array with all items linked to an object id in association table
  3790. *
  3791. * @param int $fk_object_where id of object we need to get linked items
  3792. * @param string $field_select name of field we need to get a list
  3793. * @param string $field_where name of field of object we need to get linked items
  3794. * @param string $table_element name of association table
  3795. * @return array|int Array of record, -1 if empty
  3796. */
  3797. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3798. {
  3799. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3800. return -1;
  3801. }
  3802. global $db;
  3803. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3804. $resql = $db->query($sql);
  3805. $TRes = array();
  3806. if (!empty($resql)) {
  3807. while ($res = $db->fetch_object($resql)) {
  3808. $TRes[] = $res->{$field_select};
  3809. }
  3810. }
  3811. return $TRes;
  3812. }
  3813. /**
  3814. * Function used to remove all items linked to an object id in association table
  3815. *
  3816. * @param int $fk_object_where id of object we need to remove linked items
  3817. * @param string $field_where name of field of object we need to delete linked items
  3818. * @param string $table_element name of association table
  3819. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3820. */
  3821. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3822. {
  3823. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3824. return -1;
  3825. }
  3826. global $db;
  3827. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3828. $resql = $db->query($sql);
  3829. if (empty($resql)) {
  3830. return 0;
  3831. }
  3832. return 1;
  3833. }
  3834. /**
  3835. * Set status of an object.
  3836. *
  3837. * @param int $status Status to set
  3838. * @param int $elementId Id of element to force (use this->id by default if null)
  3839. * @param string $elementType Type of element to force (use this->table_element by default)
  3840. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated.
  3841. * @param string $fieldstatus Name of status field in this->table_element
  3842. * @return int <0 if KO, >0 if OK
  3843. */
  3844. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3845. {
  3846. global $user, $langs, $conf;
  3847. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3848. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3849. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3850. $this->db->begin();
  3851. if ($elementTable == 'facture_rec') {
  3852. $fieldstatus = "suspended";
  3853. }
  3854. if ($elementTable == 'mailing') {
  3855. $fieldstatus = "statut";
  3856. }
  3857. if ($elementTable == 'cronjob') {
  3858. $fieldstatus = "status";
  3859. }
  3860. if ($elementTable == 'user') {
  3861. $fieldstatus = "statut";
  3862. }
  3863. if ($elementTable == 'expensereport') {
  3864. $fieldstatus = "fk_statut";
  3865. }
  3866. if ($elementTable == 'commande_fournisseur_dispatch') {
  3867. $fieldstatus = "status";
  3868. }
  3869. if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3870. $fieldstatus = 'status';
  3871. }
  3872. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3873. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3874. // If status = 1 = validated, update also fk_user_valid
  3875. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3876. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3877. $sql .= ", fk_user_valid = ".((int) $user->id);
  3878. }
  3879. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3880. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3881. }
  3882. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3883. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3884. }
  3885. $sql .= " WHERE rowid = ".((int) $elementId);
  3886. $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
  3887. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3888. $resql = $this->db->query($sql);
  3889. if ($resql) {
  3890. $error = 0;
  3891. $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
  3892. if ($nb_rows_affected > 0) {
  3893. if (empty($trigkey)) {
  3894. // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
  3895. if ($this->element == 'supplier_proposal' && $status == 2) {
  3896. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3897. }
  3898. if ($this->element == 'supplier_proposal' && $status == 3) {
  3899. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3900. }
  3901. if ($this->element == 'supplier_proposal' && $status == 4) {
  3902. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3903. }
  3904. if ($this->element == 'fichinter' && $status == 3) {
  3905. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3906. }
  3907. if ($this->element == 'fichinter' && $status == 2) {
  3908. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3909. }
  3910. if ($this->element == 'fichinter' && $status == 1) {
  3911. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3912. }
  3913. }
  3914. if ($trigkey) {
  3915. // Call trigger
  3916. $result = $this->call_trigger($trigkey, $user);
  3917. if ($result < 0) {
  3918. $error++;
  3919. }
  3920. // End call triggers
  3921. }
  3922. } else {
  3923. // The status was probably already good. We do nothing more, no triggers.
  3924. }
  3925. if (!$error) {
  3926. $this->db->commit();
  3927. if (empty($savElementId)) {
  3928. // If the element we update is $this (so $elementId was provided as null)
  3929. if ($fieldstatus == 'tosell') {
  3930. $this->status = $status;
  3931. } elseif ($fieldstatus == 'tobuy') {
  3932. $this->status_buy = $status;
  3933. } else {
  3934. $this->statut = $status;
  3935. $this->status = $status;
  3936. }
  3937. }
  3938. return 1;
  3939. } else {
  3940. $this->db->rollback();
  3941. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3942. return -1;
  3943. }
  3944. } else {
  3945. $this->error = $this->db->lasterror();
  3946. $this->db->rollback();
  3947. return -1;
  3948. }
  3949. }
  3950. /**
  3951. * Load type of canvas of an object if it exists
  3952. *
  3953. * @param int $id Record id
  3954. * @param string $ref Record ref
  3955. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3956. */
  3957. public function getCanvas($id = 0, $ref = '')
  3958. {
  3959. global $conf;
  3960. if (empty($id) && empty($ref)) {
  3961. return 0;
  3962. }
  3963. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3964. return 0; // To increase speed. Not enabled by default.
  3965. }
  3966. // Clean parameters
  3967. $ref = trim($ref);
  3968. $sql = "SELECT rowid, canvas";
  3969. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  3970. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3971. if (!empty($id)) {
  3972. $sql .= " AND rowid = ".((int) $id);
  3973. }
  3974. if (!empty($ref)) {
  3975. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3976. }
  3977. $resql = $this->db->query($sql);
  3978. if ($resql) {
  3979. $obj = $this->db->fetch_object($resql);
  3980. if ($obj) {
  3981. $this->canvas = $obj->canvas;
  3982. return 1;
  3983. } else {
  3984. return 0;
  3985. }
  3986. } else {
  3987. dol_print_error($this->db);
  3988. return -1;
  3989. }
  3990. }
  3991. /**
  3992. * Get special code of a line
  3993. *
  3994. * @param int $lineid Id of line
  3995. * @return int Special code
  3996. */
  3997. public function getSpecialCode($lineid)
  3998. {
  3999. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  4000. $sql .= " WHERE rowid = ".((int) $lineid);
  4001. $resql = $this->db->query($sql);
  4002. if ($resql) {
  4003. $row = $this->db->fetch_row($resql);
  4004. return $row[0];
  4005. }
  4006. return 0;
  4007. }
  4008. /**
  4009. * Function to check if an object is used by others (by children).
  4010. * Check is done into this->childtables. There is no check into llx_element_element.
  4011. *
  4012. * @param int $id Force id of object
  4013. * @param int $entity Force entity to check
  4014. * @return int <0 if KO, 0 if not used, >0 if already used
  4015. */
  4016. public function isObjectUsed($id = 0, $entity = 0)
  4017. {
  4018. global $langs;
  4019. if (empty($id)) {
  4020. $id = $this->id;
  4021. }
  4022. // Check parameters
  4023. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  4024. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  4025. return -1;
  4026. }
  4027. $arraytoscan = $this->childtables; // array('tablename'=>array('fk_element'=>'parentfield'), ...) or array('tablename'=>array('parent'=>table_parent, 'parentkey'=>'nameoffieldforparentfkkey'), ...)
  4028. // For backward compatibility, we check if array is old format array('tablename1', 'tablename2', ...)
  4029. $tmparray = array_keys($this->childtables);
  4030. if (is_numeric($tmparray[0])) {
  4031. $arraytoscan = array_flip($this->childtables);
  4032. }
  4033. // Test if child exists
  4034. $haschild = 0;
  4035. foreach ($arraytoscan as $table => $element) {
  4036. //print $id.'-'.$table.'-'.$elementname.'<br>';
  4037. // Check if element can be deleted
  4038. $sql = "SELECT COUNT(*) as nb";
  4039. $sql.= " FROM ".$this->db->prefix().$table." as c";
  4040. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4041. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  4042. }
  4043. if (!empty($element['fk_element'])) {
  4044. $sql.= " WHERE c.".$element['fk_element']." = ".((int) $id);
  4045. } else {
  4046. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  4047. }
  4048. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4049. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  4050. }
  4051. if (!empty($element['parent']) && !empty($element['parenttypefield']) && !empty($element['parenttypevalue'])) {
  4052. $sql.= " AND c.".$element['parenttypefield']." = '".$this->db->escape($element['parenttypevalue'])."'";
  4053. }
  4054. if (!empty($entity)) {
  4055. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4056. $sql.= " AND p.entity = ".((int) $entity);
  4057. } else {
  4058. $sql.= " AND c.entity = ".((int) $entity);
  4059. }
  4060. }
  4061. $resql = $this->db->query($sql);
  4062. if ($resql) {
  4063. $obj = $this->db->fetch_object($resql);
  4064. if ($obj->nb > 0) {
  4065. $langs->load("errors");
  4066. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4067. $haschild += $obj->nb;
  4068. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4069. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4070. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4071. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4072. } else { // new usage: $element['name']=Translation key
  4073. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4074. }
  4075. break; // We found at least one, we stop here
  4076. }
  4077. } else {
  4078. $this->errors[] = $this->db->lasterror();
  4079. return -1;
  4080. }
  4081. }
  4082. if ($haschild > 0) {
  4083. $this->errors[] = "ErrorRecordHasChildren";
  4084. return $haschild;
  4085. } else {
  4086. return 0;
  4087. }
  4088. }
  4089. /**
  4090. * Function to say how many lines object contains
  4091. *
  4092. * @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
  4093. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4094. */
  4095. public function hasProductsOrServices($predefined = -1)
  4096. {
  4097. $nb = 0;
  4098. foreach ($this->lines as $key => $val) {
  4099. $qualified = 0;
  4100. if ($predefined == -1) {
  4101. $qualified = 1;
  4102. }
  4103. if ($predefined == 1 && $val->fk_product > 0) {
  4104. $qualified = 1;
  4105. }
  4106. if ($predefined == 0 && $val->fk_product <= 0) {
  4107. $qualified = 1;
  4108. }
  4109. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4110. $qualified = 1;
  4111. }
  4112. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4113. $qualified = 1;
  4114. }
  4115. if ($qualified) {
  4116. $nb++;
  4117. }
  4118. }
  4119. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4120. return $nb;
  4121. }
  4122. /**
  4123. * Function that returns the total amount HT of discounts applied for all lines.
  4124. *
  4125. * @return float|string Total amout of discount
  4126. */
  4127. public function getTotalDiscount()
  4128. {
  4129. if (!empty($this->table_element_line) ) {
  4130. $total_discount = 0.00;
  4131. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4132. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4133. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4134. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4135. $resql = $this->db->query($sql);
  4136. if ($resql) {
  4137. $num = $this->db->num_rows($resql);
  4138. $i = 0;
  4139. while ($i < $num) {
  4140. $obj = $this->db->fetch_object($resql);
  4141. $pu_ht = $obj->pu_ht;
  4142. $qty = $obj->qty;
  4143. $total_ht = $obj->total_ht;
  4144. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4145. $total_discount += $total_discount_line;
  4146. $i++;
  4147. }
  4148. }
  4149. //print $total_discount; exit;
  4150. return price2num($total_discount);
  4151. }
  4152. return null;
  4153. }
  4154. /**
  4155. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4156. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4157. *
  4158. * @return array array('weight'=>...,'volume'=>...)
  4159. */
  4160. public function getTotalWeightVolume()
  4161. {
  4162. $totalWeight = 0;
  4163. $totalVolume = 0;
  4164. // defined for shipment only
  4165. $totalOrdered = '';
  4166. // defined for shipment only
  4167. $totalToShip = '';
  4168. foreach ($this->lines as $line) {
  4169. if (isset($line->qty_asked)) {
  4170. if (empty($totalOrdered)) {
  4171. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4172. }
  4173. $totalOrdered += $line->qty_asked; // defined for shipment only
  4174. }
  4175. if (isset($line->qty_shipped)) {
  4176. if (empty($totalToShip)) {
  4177. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4178. }
  4179. $totalToShip += $line->qty_shipped; // defined for shipment only
  4180. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4181. if (empty($totalToShip)) {
  4182. $totalToShip = 0;
  4183. }
  4184. $totalToShip += $line->qty; // defined for reception only
  4185. }
  4186. // Define qty, weight, volume, weight_units, volume_units
  4187. if ($this->element == 'shipping') {
  4188. // for shipments
  4189. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4190. } else {
  4191. $qty = $line->qty ? $line->qty : 0;
  4192. }
  4193. $weight = !empty($line->weight) ? $line->weight : 0;
  4194. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4195. $volume = !empty($line->volume) ? $line->volume : 0;
  4196. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4197. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4198. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4199. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4200. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4201. $weightUnit = 0;
  4202. $volumeUnit = 0;
  4203. if (!empty($weight_units)) {
  4204. $weightUnit = $weight_units;
  4205. }
  4206. if (!empty($volume_units)) {
  4207. $volumeUnit = $volume_units;
  4208. }
  4209. if (empty($totalWeight)) {
  4210. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4211. }
  4212. if (empty($totalVolume)) {
  4213. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4214. }
  4215. //var_dump($line->volume_units);
  4216. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4217. $trueWeightUnit = pow(10, $weightUnit);
  4218. $totalWeight += $weight * $qty * $trueWeightUnit;
  4219. } else {
  4220. if ($weight_units == 99) {
  4221. // conversion 1 Pound = 0.45359237 KG
  4222. $trueWeightUnit = 0.45359237;
  4223. $totalWeight += $weight * $qty * $trueWeightUnit;
  4224. } elseif ($weight_units == 98) {
  4225. // conversion 1 Ounce = 0.0283495 KG
  4226. $trueWeightUnit = 0.0283495;
  4227. $totalWeight += $weight * $qty * $trueWeightUnit;
  4228. } else {
  4229. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4230. }
  4231. }
  4232. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4233. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4234. $trueVolumeUnit = pow(10, $volumeUnit);
  4235. //print $line->volume;
  4236. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4237. } else {
  4238. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4239. }
  4240. }
  4241. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4242. }
  4243. /**
  4244. * Set extra parameters
  4245. *
  4246. * @return int <0 if KO, >0 if OK
  4247. */
  4248. public function setExtraParameters()
  4249. {
  4250. $this->db->begin();
  4251. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4252. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4253. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4254. $sql .= " WHERE rowid = ".((int) $this->id);
  4255. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4256. $resql = $this->db->query($sql);
  4257. if (!$resql) {
  4258. $this->error = $this->db->lasterror();
  4259. $this->db->rollback();
  4260. return -1;
  4261. } else {
  4262. $this->db->commit();
  4263. return 1;
  4264. }
  4265. }
  4266. // --------------------
  4267. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4268. // --------------------
  4269. /* This is to show add lines */
  4270. /**
  4271. * Show add free and predefined products/services form
  4272. *
  4273. * @param int $dateSelector 1=Show also date range input fields
  4274. * @param Societe $seller Object thirdparty who sell
  4275. * @param Societe $buyer Object thirdparty who buy
  4276. * @param string $defaulttpldir Directory where to find the template
  4277. * @return void
  4278. */
  4279. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4280. {
  4281. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4282. global $form;
  4283. // Line extrafield
  4284. if (!is_object($extrafields)) {
  4285. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4286. $extrafields = new ExtraFields($this->db);
  4287. }
  4288. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4289. // Output template part (modules that overwrite templates must declare this into descriptor)
  4290. // Use global variables + $dateSelector + $seller and $buyer
  4291. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4292. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4293. foreach ($dirtpls as $module => $reldir) {
  4294. if (!empty($module)) {
  4295. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4296. } else {
  4297. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4298. }
  4299. if (empty($conf->file->strict_mode)) {
  4300. $res = @include $tpl;
  4301. } else {
  4302. $res = include $tpl; // for debug
  4303. }
  4304. if ($res) {
  4305. break;
  4306. }
  4307. }
  4308. }
  4309. /* This is to show array of line of details */
  4310. /**
  4311. * Return HTML table for object lines
  4312. * TODO Move this into an output class file (htmlline.class.php)
  4313. * If lines are into a template, title must also be into a template
  4314. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4315. *
  4316. * @param string $action Action code
  4317. * @param Societe $seller Object of seller third party
  4318. * @param Societe $buyer Object of buyer third party
  4319. * @param int $selected ID line selected
  4320. * @param int $dateSelector 1=Show also date range input fields
  4321. * @param string $defaulttpldir Directory where to find the template
  4322. * @return void
  4323. */
  4324. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4325. {
  4326. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4327. // TODO We should not use global var for this
  4328. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4329. // Define usemargins
  4330. $usemargins = 0;
  4331. if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4332. $usemargins = 1;
  4333. }
  4334. $num = count($this->lines);
  4335. // Line extrafield
  4336. if (!is_object($extrafields)) {
  4337. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4338. $extrafields = new ExtraFields($this->db);
  4339. }
  4340. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4341. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4342. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4343. if (empty($reshook)) {
  4344. // Output template part (modules that overwrite templates must declare this into descriptor)
  4345. // Use global variables + $dateSelector + $seller and $buyer
  4346. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4347. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4348. foreach ($dirtpls as $module => $reldir) {
  4349. $res = 0;
  4350. if (!empty($module)) {
  4351. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4352. } else {
  4353. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4354. }
  4355. if (file_exists($tpl)) {
  4356. if (empty($conf->file->strict_mode)) {
  4357. $res = @include $tpl;
  4358. } else {
  4359. $res = include $tpl; // for debug
  4360. }
  4361. }
  4362. if ($res) {
  4363. break;
  4364. }
  4365. }
  4366. }
  4367. $i = 0;
  4368. print "<!-- begin printObjectLines() --><tbody>\n";
  4369. foreach ($this->lines as $line) {
  4370. //Line extrafield
  4371. $line->fetch_optionals();
  4372. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
  4373. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4374. if (empty($line->fk_parent_line)) {
  4375. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4376. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4377. } else {
  4378. $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);
  4379. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4380. }
  4381. }
  4382. if (empty($reshook)) {
  4383. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4384. }
  4385. $i++;
  4386. }
  4387. print "</tbody><!-- end printObjectLines() -->\n";
  4388. }
  4389. /**
  4390. * Return HTML content of a detail line
  4391. * TODO Move this into an output class file (htmlline.class.php)
  4392. *
  4393. * @param string $action GET/POST action
  4394. * @param CommonObjectLine $line Selected object line to output
  4395. * @param string $var Not used
  4396. * @param int $num Number of line (0)
  4397. * @param int $i I
  4398. * @param int $dateSelector 1=Show also date range input fields
  4399. * @param Societe $seller Object of seller third party
  4400. * @param Societe $buyer Object of buyer third party
  4401. * @param int $selected ID line selected
  4402. * @param Extrafields $extrafields Object of extrafields
  4403. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4404. * @return void
  4405. */
  4406. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4407. {
  4408. global $conf, $langs, $user, $object, $hookmanager;
  4409. global $form;
  4410. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4411. $object_rights = $this->getRights();
  4412. $text = '';
  4413. $description = '';
  4414. // Line in view mode
  4415. if ($action != 'editline' || $selected != $line->id) {
  4416. // Product
  4417. if (!empty($line->fk_product) && $line->fk_product > 0) {
  4418. $product_static = new Product($this->db);
  4419. $product_static->fetch($line->fk_product);
  4420. $product_static->ref = $line->ref; //can change ref in hook
  4421. $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
  4422. $text = $product_static->getNomUrl(1);
  4423. // Define output language and label
  4424. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  4425. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4426. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4427. return;
  4428. }
  4429. $prod = new Product($this->db);
  4430. $prod->fetch($line->fk_product);
  4431. $outputlangs = $langs;
  4432. $newlang = '';
  4433. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4434. $newlang = GETPOST('lang_id', 'aZ09');
  4435. }
  4436. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4437. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4438. }
  4439. if (!empty($newlang)) {
  4440. $outputlangs = new Translate("", $conf);
  4441. $outputlangs->setDefaultLang($newlang);
  4442. }
  4443. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4444. } else {
  4445. $label = $line->product_label;
  4446. }
  4447. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4448. $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.
  4449. }
  4450. $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
  4451. // Output template part (modules that overwrite templates must declare this into descriptor)
  4452. // Use global variables + $dateSelector + $seller and $buyer
  4453. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4454. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4455. foreach ($dirtpls as $module => $reldir) {
  4456. $res = 0;
  4457. if (!empty($module)) {
  4458. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4459. } else {
  4460. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4461. }
  4462. if (file_exists($tpl)) {
  4463. if (empty($conf->file->strict_mode)) {
  4464. $res = @include $tpl;
  4465. } else {
  4466. $res = include $tpl; // for debug
  4467. }
  4468. }
  4469. if ($res) {
  4470. break;
  4471. }
  4472. }
  4473. }
  4474. // Line in update mode
  4475. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4476. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4477. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4478. // Output template part (modules that overwrite templates must declare this into descriptor)
  4479. // Use global variables + $dateSelector + $seller and $buyer
  4480. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4481. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4482. foreach ($dirtpls as $module => $reldir) {
  4483. if (!empty($module)) {
  4484. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4485. } else {
  4486. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4487. }
  4488. if (empty($conf->file->strict_mode)) {
  4489. $res = @include $tpl;
  4490. } else {
  4491. $res = include $tpl; // for debug
  4492. }
  4493. if ($res) {
  4494. break;
  4495. }
  4496. }
  4497. }
  4498. }
  4499. /* This is to show array of line of details of source object */
  4500. /**
  4501. * Return HTML table table of source object lines
  4502. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4503. * If lines are into a template, title must also be into a template
  4504. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4505. *
  4506. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4507. * @param array $selectedLines Array of lines id for selected lines
  4508. * @return void
  4509. */
  4510. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4511. {
  4512. global $langs, $hookmanager, $conf, $form, $action;
  4513. print '<tr class="liste_titre">';
  4514. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4515. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4516. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4517. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4518. if (isModEnabled("multicurrency")) {
  4519. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4520. }
  4521. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4522. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  4523. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4524. }
  4525. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4526. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4527. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4528. print '</tr>';
  4529. $i = 0;
  4530. if (!empty($this->lines)) {
  4531. foreach ($this->lines as $line) {
  4532. $reshook = 0;
  4533. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4534. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4535. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4536. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4537. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4538. }
  4539. if (empty($reshook)) {
  4540. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4541. }
  4542. $i++;
  4543. }
  4544. }
  4545. }
  4546. /**
  4547. * Return HTML with a line of table array of source object lines
  4548. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4549. * If lines are into a template, title must also be into a template
  4550. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4551. *
  4552. * @param CommonObjectLine $line Line
  4553. * @param string $var Var
  4554. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4555. * @param string $defaulttpldir Directory where to find the template
  4556. * @param array $selectedLines Array of lines id for selected lines
  4557. * @return void
  4558. */
  4559. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4560. {
  4561. global $langs, $conf;
  4562. //var_dump($line);
  4563. if (!empty($line->date_start)) {
  4564. $date_start = $line->date_start;
  4565. } else {
  4566. $date_start = $line->date_debut_prevue;
  4567. if ($line->date_debut_reel) {
  4568. $date_start = $line->date_debut_reel;
  4569. }
  4570. }
  4571. if (!empty($line->date_end)) {
  4572. $date_end = $line->date_end;
  4573. } else {
  4574. $date_end = $line->date_fin_prevue;
  4575. if ($line->date_fin_reel) {
  4576. $date_end = $line->date_fin_reel;
  4577. }
  4578. }
  4579. $this->tpl['id'] = $line->id;
  4580. $this->tpl['label'] = '';
  4581. if (!empty($line->fk_parent_line)) {
  4582. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4583. }
  4584. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4585. $discount = new DiscountAbsolute($this->db);
  4586. $discount->fk_soc = $this->socid;
  4587. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4588. } elseif (!empty($line->fk_product)) {
  4589. $productstatic = new Product($this->db);
  4590. $productstatic->id = $line->fk_product;
  4591. $productstatic->ref = $line->ref;
  4592. $productstatic->type = $line->fk_product_type;
  4593. if (empty($productstatic->ref)) {
  4594. $line->fetch_product();
  4595. $productstatic = $line->product;
  4596. }
  4597. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4598. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4599. // Dates
  4600. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4601. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4602. }
  4603. } else {
  4604. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4605. if (!empty($line->desc)) {
  4606. $this->tpl['label'] .= $line->desc;
  4607. } else {
  4608. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4609. }
  4610. // Dates
  4611. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4612. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4613. }
  4614. }
  4615. if (!empty($line->desc)) {
  4616. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4617. $discount = new DiscountAbsolute($this->db);
  4618. $discount->fetch($line->fk_remise_except);
  4619. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4620. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4621. $discount = new DiscountAbsolute($this->db);
  4622. $discount->fetch($line->fk_remise_except);
  4623. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4624. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4625. $discount = new DiscountAbsolute($this->db);
  4626. $discount->fetch($line->fk_remise_except);
  4627. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4628. } elseif ($line->desc == '(EXCESS PAID)') {
  4629. $discount = new DiscountAbsolute($this->db);
  4630. $discount->fetch($line->fk_remise_except);
  4631. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4632. } else {
  4633. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4634. }
  4635. } else {
  4636. $this->tpl['description'] = '&nbsp;';
  4637. }
  4638. // VAT Rate
  4639. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4640. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4641. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4642. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4643. }
  4644. $this->tpl['price'] = price($line->subprice);
  4645. $this->tpl['total_ht'] = price($line->total_ht);
  4646. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4647. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4648. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  4649. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4650. }
  4651. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4652. // Is the line strike or not
  4653. $this->tpl['strike'] = 0;
  4654. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4655. $this->tpl['strike'] = 1;
  4656. }
  4657. // Output template part (modules that overwrite templates must declare this into descriptor)
  4658. // Use global variables + $dateSelector + $seller and $buyer
  4659. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4660. foreach ($dirtpls as $module => $reldir) {
  4661. if (!empty($module)) {
  4662. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4663. } else {
  4664. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4665. }
  4666. if (empty($conf->file->strict_mode)) {
  4667. $res = @include $tpl;
  4668. } else {
  4669. $res = include $tpl; // for debug
  4670. }
  4671. if ($res) {
  4672. break;
  4673. }
  4674. }
  4675. }
  4676. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4677. /**
  4678. * Add resources to the current object : add entry into llx_element_resources
  4679. * Need $this->element & $this->id
  4680. *
  4681. * @param int $resource_id Resource id
  4682. * @param string $resource_type 'resource'
  4683. * @param int $busy Busy or not
  4684. * @param int $mandatory Mandatory or not
  4685. * @return int <=0 if KO, >0 if OK
  4686. */
  4687. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4688. {
  4689. // phpcs:enable
  4690. $this->db->begin();
  4691. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4692. $sql .= "resource_id";
  4693. $sql .= ", resource_type";
  4694. $sql .= ", element_id";
  4695. $sql .= ", element_type";
  4696. $sql .= ", busy";
  4697. $sql .= ", mandatory";
  4698. $sql .= ") VALUES (";
  4699. $sql .= ((int) $resource_id);
  4700. $sql .= ", '".$this->db->escape($resource_type)."'";
  4701. $sql .= ", '".$this->db->escape($this->id)."'";
  4702. $sql .= ", '".$this->db->escape($this->element)."'";
  4703. $sql .= ", '".$this->db->escape($busy)."'";
  4704. $sql .= ", '".$this->db->escape($mandatory)."'";
  4705. $sql .= ")";
  4706. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4707. if ($this->db->query($sql)) {
  4708. $this->db->commit();
  4709. return 1;
  4710. } else {
  4711. $this->error = $this->db->lasterror();
  4712. $this->db->rollback();
  4713. return 0;
  4714. }
  4715. }
  4716. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4717. /**
  4718. * Delete a link to resource line
  4719. *
  4720. * @param int $rowid Id of resource line to delete
  4721. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4722. * @param int $notrigger Disable all triggers
  4723. * @return int >0 if OK, <0 if KO
  4724. */
  4725. public function delete_resource($rowid, $element, $notrigger = 0)
  4726. {
  4727. // phpcs:enable
  4728. global $user;
  4729. $this->db->begin();
  4730. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4731. $sql .= " WHERE rowid = ".((int) $rowid);
  4732. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4733. $resql = $this->db->query($sql);
  4734. if (!$resql) {
  4735. $this->error = $this->db->lasterror();
  4736. $this->db->rollback();
  4737. return -1;
  4738. } else {
  4739. if (!$notrigger) {
  4740. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4741. if ($result < 0) {
  4742. $this->db->rollback();
  4743. return -1;
  4744. }
  4745. }
  4746. $this->db->commit();
  4747. return 1;
  4748. }
  4749. }
  4750. /**
  4751. * Overwrite magic function to solve problem of cloning object that are kept as references
  4752. *
  4753. * @return void
  4754. */
  4755. public function __clone()
  4756. {
  4757. // Force a copy of this->lines, otherwise it will point to same object.
  4758. if (isset($this->lines) && is_array($this->lines)) {
  4759. $nboflines = count($this->lines);
  4760. for ($i = 0; $i < $nboflines; $i++) {
  4761. $this->lines[$i] = clone $this->lines[$i];
  4762. }
  4763. }
  4764. }
  4765. /**
  4766. * Common function for all objects extending CommonObject for generating documents
  4767. *
  4768. * @param string $modelspath Relative folder where generators are placed
  4769. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4770. * @param Translate $outputlangs Output language to use
  4771. * @param int $hidedetails 1 to hide details. 0 by default
  4772. * @param int $hidedesc 1 to hide product description. 0 by default
  4773. * @param int $hideref 1 to hide product reference. 0 by default
  4774. * @param null|array $moreparams Array to provide more information
  4775. * @return int >0 if OK, <0 if KO
  4776. * @see addFileIntoDatabaseIndex()
  4777. */
  4778. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4779. {
  4780. global $conf, $langs, $user, $hookmanager, $action;
  4781. $srctemplatepath = '';
  4782. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4783. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4784. if (!empty($reshook)) {
  4785. return $reshook;
  4786. }
  4787. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4788. if (empty($modele)) {
  4789. $this->error = 'BadValueForParameterModele';
  4790. return -1;
  4791. }
  4792. // Increase limit for PDF build
  4793. $err = error_reporting();
  4794. error_reporting(0);
  4795. @set_time_limit(120);
  4796. error_reporting($err);
  4797. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4798. $tmp = explode(':', $modele, 2);
  4799. if (!empty($tmp[1])) {
  4800. $modele = $tmp[0];
  4801. $srctemplatepath = $tmp[1];
  4802. }
  4803. // Search template files
  4804. $file = '';
  4805. $classname = '';
  4806. $filefound = '';
  4807. $dirmodels = array('/');
  4808. if (is_array($conf->modules_parts['models'])) {
  4809. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4810. }
  4811. foreach ($dirmodels as $reldir) {
  4812. foreach (array('doc', 'pdf') as $prefix) {
  4813. if (in_array(get_class($this), array('Adherent'))) {
  4814. // Member module use prefix_modele.class.php
  4815. $file = $prefix."_".$modele.".class.php";
  4816. } else {
  4817. // Other module use prefix_modele.modules.php
  4818. $file = $prefix."_".$modele.".modules.php";
  4819. }
  4820. // On verifie l'emplacement du modele
  4821. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4822. if (file_exists($file)) {
  4823. $filefound = $file;
  4824. $classname = $prefix.'_'.$modele;
  4825. break;
  4826. }
  4827. }
  4828. if ($filefound) {
  4829. break;
  4830. }
  4831. }
  4832. if (!$filefound) {
  4833. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4834. $this->errors[] = $this->error;
  4835. dol_syslog($this->error, LOG_ERR);
  4836. return -1;
  4837. }
  4838. // If generator was found
  4839. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4840. require_once $file;
  4841. $obj = new $classname($this->db);
  4842. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4843. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4844. $varfortemplatedir = $obj->scandir;
  4845. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4846. $dirtoscan = $conf->global->$varfortemplatedir;
  4847. $listoffiles = array();
  4848. // Now we add first model found in directories scanned
  4849. $listofdir = explode(',', $dirtoscan);
  4850. foreach ($listofdir as $key => $tmpdir) {
  4851. $tmpdir = trim($tmpdir);
  4852. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4853. if (!$tmpdir) {
  4854. unset($listofdir[$key]);
  4855. continue;
  4856. }
  4857. if (is_dir($tmpdir)) {
  4858. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4859. if (count($tmpfiles)) {
  4860. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4861. }
  4862. }
  4863. }
  4864. if (count($listoffiles)) {
  4865. foreach ($listoffiles as $record) {
  4866. $srctemplatepath = $record['fullname'];
  4867. break;
  4868. }
  4869. }
  4870. }
  4871. if (empty($srctemplatepath)) {
  4872. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4873. return -1;
  4874. }
  4875. }
  4876. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4877. if (!dol_is_file($srctemplatepath)) {
  4878. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4879. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4880. return -1;
  4881. }
  4882. }
  4883. // We save charset_output to restore it because write_file can change it if needed for
  4884. // output format that does not support UTF8.
  4885. $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
  4886. if (in_array(get_class($this), array('Adherent'))) {
  4887. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4888. } else {
  4889. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4890. }
  4891. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4892. if ($resultwritefile > 0) {
  4893. $outputlangs->charset_output = $sav_charset_output;
  4894. // We delete old preview
  4895. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4896. dol_delete_preview($this);
  4897. // Index file in database
  4898. if (!empty($obj->result['fullpath'])) {
  4899. $destfull = $obj->result['fullpath'];
  4900. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4901. $update_main_doc_field = 0;
  4902. if (!empty($obj->update_main_doc_field)) {
  4903. $update_main_doc_field = 1;
  4904. }
  4905. // Check that the file exists, before indexing it.
  4906. // Hint: It does not exist, if we create a PDF and auto delete the ODT File
  4907. if (dol_is_file($destfull)) {
  4908. $this->indexFile($destfull, $update_main_doc_field);
  4909. }
  4910. } else {
  4911. 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);
  4912. }
  4913. // Success in building document. We build meta file.
  4914. dol_meta_create($this);
  4915. return 1;
  4916. } else {
  4917. $outputlangs->charset_output = $sav_charset_output;
  4918. $this->error = $obj->error;
  4919. $this->errors = $obj->errors;
  4920. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  4921. return -1;
  4922. }
  4923. }
  4924. /**
  4925. * Index a file into the ECM database
  4926. *
  4927. * @param string $destfull Full path of file to index
  4928. * @param int $update_main_doc_field Update field main_doc fied into the table of object.
  4929. * This param is set when called for a document generation if document generator hase
  4930. * ->update_main_doc_field set and returns ->result['fullpath'].
  4931. * @return int <0 if KO, >0 if OK
  4932. */
  4933. public function indexFile($destfull, $update_main_doc_field)
  4934. {
  4935. global $conf, $user;
  4936. $upload_dir = dirname($destfull);
  4937. $destfile = basename($destfull);
  4938. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4939. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4940. $filename = basename($destfile);
  4941. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4942. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4943. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4944. $ecmfile = new EcmFiles($this->db);
  4945. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4946. // Set the public "share" key
  4947. $setsharekey = false;
  4948. if ($this->element == 'propal' || $this->element == 'proposal') {
  4949. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4950. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4951. }
  4952. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4953. $setsharekey = true;
  4954. }
  4955. }
  4956. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4957. $setsharekey = true;
  4958. }
  4959. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4960. $setsharekey = true;
  4961. }
  4962. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4963. $setsharekey = true;
  4964. }
  4965. if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4966. $setsharekey = true;
  4967. }
  4968. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4969. $setsharekey = true;
  4970. }
  4971. if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4972. $setsharekey = true;
  4973. }
  4974. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4975. $setsharekey = true;
  4976. }
  4977. if ($setsharekey) {
  4978. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4979. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4980. $ecmfile->share = getRandomPassword(true);
  4981. }
  4982. }
  4983. if ($result > 0) {
  4984. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4985. $ecmfile->fullpath_orig = '';
  4986. $ecmfile->gen_or_uploaded = 'generated';
  4987. $ecmfile->description = ''; // indexed content
  4988. $ecmfile->keywords = ''; // keyword content
  4989. $result = $ecmfile->update($user);
  4990. if ($result < 0) {
  4991. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4992. return -1;
  4993. }
  4994. } else {
  4995. $ecmfile->entity = $conf->entity;
  4996. $ecmfile->filepath = $rel_dir;
  4997. $ecmfile->filename = $filename;
  4998. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4999. $ecmfile->fullpath_orig = '';
  5000. $ecmfile->gen_or_uploaded = 'generated';
  5001. $ecmfile->description = ''; // indexed content
  5002. $ecmfile->keywords = ''; // keyword content
  5003. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  5004. $ecmfile->src_object_id = $this->id;
  5005. $result = $ecmfile->create($user);
  5006. if ($result < 0) {
  5007. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5008. return -1;
  5009. }
  5010. }
  5011. /*$this->result['fullname']=$destfull;
  5012. $this->result['filepath']=$ecmfile->filepath;
  5013. $this->result['filename']=$ecmfile->filename;*/
  5014. //var_dump($obj->update_main_doc_field);exit;
  5015. if ($update_main_doc_field && !empty($this->table_element)) {
  5016. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  5017. $sql .= " WHERE rowid = ".((int) $this->id);
  5018. $resql = $this->db->query($sql);
  5019. if (!$resql) {
  5020. dol_print_error($this->db);
  5021. return -1;
  5022. } else {
  5023. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  5024. }
  5025. }
  5026. }
  5027. return 1;
  5028. }
  5029. /**
  5030. * Build thumb
  5031. * @todo Move this into files.lib.php
  5032. *
  5033. * @param string $file Path file in UTF8 to original file to create thumbs from.
  5034. * @return void
  5035. */
  5036. public function addThumbs($file)
  5037. {
  5038. $file_osencoded = dol_osencode($file);
  5039. if (file_exists($file_osencoded)) {
  5040. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  5041. $tmparraysize = getDefaultImageSizes();
  5042. $maxwidthsmall = $tmparraysize['maxwidthsmall'];
  5043. $maxheightsmall = $tmparraysize['maxheightsmall'];
  5044. $maxwidthmini = $tmparraysize['maxwidthmini'];
  5045. $maxheightmini = $tmparraysize['maxheightmini'];
  5046. //$quality = $tmparraysize['quality'];
  5047. $quality = 50; // For thumbs, we force quality to 50
  5048. // Create small thumbs for company (Ratio is near 16/9)
  5049. // Used on logon for example
  5050. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  5051. // Create mini thumbs for company (Ratio is near 16/9)
  5052. // Used on menu or for setup page for example
  5053. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  5054. }
  5055. }
  5056. /**
  5057. * Delete thumbs
  5058. * @todo Move this into files.lib.php
  5059. *
  5060. * @param string $file Path file in UTF8 to original file to delete thumbs.
  5061. * @return void
  5062. */
  5063. public function delThumbs($file)
  5064. {
  5065. $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file
  5066. dol_delete_file($imgThumbName);
  5067. $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file
  5068. dol_delete_file($imgThumbName);
  5069. }
  5070. /* Functions common to commonobject and commonobjectline */
  5071. /* For default values */
  5072. /**
  5073. * Return the default value to use for a field when showing the create form of object.
  5074. * Return values in this order:
  5075. * 1) If parameter is available into POST, we return it first.
  5076. * 2) If not but an alternate value was provided as parameter of function, we return it.
  5077. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  5078. * 4) Return value found into database (TODO No yet implemented)
  5079. *
  5080. * @param string $fieldname Name of field
  5081. * @param string $alternatevalue Alternate value to use
  5082. * @param string $type Type of data
  5083. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  5084. **/
  5085. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml')
  5086. {
  5087. global $conf, $_POST;
  5088. // If param here has been posted, we use this value first.
  5089. if (GETPOSTISSET($fieldname)) {
  5090. return GETPOST($fieldname, $type, 3);
  5091. }
  5092. if (isset($alternatevalue)) {
  5093. return $alternatevalue;
  5094. }
  5095. $newelement = $this->element;
  5096. if ($newelement == 'facture') {
  5097. $newelement = 'invoice';
  5098. }
  5099. if ($newelement == 'commande') {
  5100. $newelement = 'order';
  5101. }
  5102. if (empty($newelement)) {
  5103. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5104. return '';
  5105. }
  5106. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  5107. //var_dump($keyforfieldname);
  5108. if (isset($conf->global->$keyforfieldname)) {
  5109. return $conf->global->$keyforfieldname;
  5110. }
  5111. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5112. // store content into $conf->cache['overwrite_default']
  5113. return '';
  5114. }
  5115. /* For triggers */
  5116. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5117. /**
  5118. * Call trigger based on this instance.
  5119. * Some context information may also be provided into array property this->context.
  5120. * NB: Error from trigger are stacked in interface->errors
  5121. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5122. *
  5123. * @param string $triggerName trigger's name to execute
  5124. * @param User $user Object user
  5125. * @return int Result of run_triggers
  5126. */
  5127. public function call_trigger($triggerName, $user)
  5128. {
  5129. // phpcs:enable
  5130. global $langs, $conf;
  5131. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5132. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5133. exit;
  5134. }
  5135. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5136. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5137. $langs = new Translate('', $conf);
  5138. }
  5139. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5140. $interface = new Interfaces($this->db);
  5141. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5142. if ($result < 0) {
  5143. if (!empty($this->errors)) {
  5144. $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.
  5145. } else {
  5146. $this->errors = $interface->errors;
  5147. }
  5148. }
  5149. return $result;
  5150. }
  5151. /* Functions for data in other language */
  5152. /**
  5153. * Function to get alternative languages of a data into $this->array_languages
  5154. * This method is NOT called by method fetch of objects but must be called separately.
  5155. *
  5156. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5157. * @see fetch_optionnals()
  5158. */
  5159. public function fetchValuesForExtraLanguages()
  5160. {
  5161. // To avoid SQL errors. Probably not the better solution though
  5162. if (!$this->element) {
  5163. return 0;
  5164. }
  5165. if (!($this->id > 0)) {
  5166. return 0;
  5167. }
  5168. if (is_array($this->array_languages)) {
  5169. return 1;
  5170. }
  5171. $this->array_languages = array();
  5172. $element = $this->element;
  5173. if ($element == 'categorie') {
  5174. $element = 'categories'; // For compatibility
  5175. }
  5176. // Request to get translation values for object
  5177. $sql = "SELECT rowid, property, lang , value";
  5178. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5179. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5180. $sql .= " AND fk_object = ".((int) $this->id);
  5181. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5182. $resql = $this->db->query($sql);
  5183. if ($resql) {
  5184. $numrows = $this->db->num_rows($resql);
  5185. if ($numrows) {
  5186. $i = 0;
  5187. while ($i < $numrows) {
  5188. $obj = $this->db->fetch_object($resql);
  5189. $key = $obj->property;
  5190. $value = $obj->value;
  5191. $codelang = $obj->lang;
  5192. $type = $this->fields[$key]['type'];
  5193. // we can add this attribute to object
  5194. if (preg_match('/date/', $type)) {
  5195. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5196. } else {
  5197. $this->array_languages[$key][$codelang] = $value;
  5198. }
  5199. $i++;
  5200. }
  5201. }
  5202. $this->db->free($resql);
  5203. if ($numrows) {
  5204. return $numrows;
  5205. } else {
  5206. return 0;
  5207. }
  5208. } else {
  5209. dol_print_error($this->db);
  5210. return -1;
  5211. }
  5212. }
  5213. /**
  5214. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5215. *
  5216. * @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.
  5217. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5218. */
  5219. public function setValuesForExtraLanguages($onlykey = '')
  5220. {
  5221. global $_POST, $langs;
  5222. // Get extra fields
  5223. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5224. $tmparray = explode('-', $postfieldkey);
  5225. if ($tmparray[0] != 'field') {
  5226. continue;
  5227. }
  5228. $element = $tmparray[1];
  5229. $key = $tmparray[2];
  5230. $codelang = $tmparray[3];
  5231. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5232. if (!empty($onlykey) && $key != $onlykey) {
  5233. continue;
  5234. }
  5235. if ($element != $this->element) {
  5236. continue;
  5237. }
  5238. $key_type = $this->fields[$key]['type'];
  5239. $enabled = 1;
  5240. if (isset($this->fields[$key]['enabled'])) {
  5241. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5242. }
  5243. /*$perms = 1;
  5244. if (isset($this->fields[$key]['perms']))
  5245. {
  5246. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5247. }*/
  5248. if (empty($enabled)) {
  5249. continue;
  5250. }
  5251. //if (empty($perms)) continue;
  5252. if (in_array($key_type, array('date'))) {
  5253. // Clean parameters
  5254. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5255. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5256. } elseif (in_array($key_type, array('datetime'))) {
  5257. // Clean parameters
  5258. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5259. $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'));
  5260. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5261. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5262. if (!empty($value_arr)) {
  5263. $value_key = implode(',', $value_arr);
  5264. } else {
  5265. $value_key = '';
  5266. }
  5267. } elseif (in_array($key_type, array('price', 'double'))) {
  5268. $value_arr = GETPOST($postfieldkey, 'alpha');
  5269. $value_key = price2num($value_arr);
  5270. } else {
  5271. $value_key = GETPOST($postfieldkey);
  5272. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5273. $value_key = '';
  5274. }
  5275. }
  5276. $this->array_languages[$key][$codelang] = $value_key;
  5277. /*if ($nofillrequired) {
  5278. $langs->load('errors');
  5279. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5280. return -1;
  5281. }*/
  5282. }
  5283. return 1;
  5284. }
  5285. /* Functions for extrafields */
  5286. /**
  5287. * Function to make a fetch but set environment to avoid to load computed values before.
  5288. *
  5289. * @param int $id ID of object
  5290. * @return int >0 if OK, 0 if not found, <0 if KO
  5291. */
  5292. public function fetchNoCompute($id)
  5293. {
  5294. global $conf;
  5295. $savDisableCompute = $conf->disable_compute;
  5296. $conf->disable_compute = 1;
  5297. $ret = $this->fetch($id);
  5298. $conf->disable_compute = $savDisableCompute;
  5299. return $ret;
  5300. }
  5301. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5302. /**
  5303. * Function to get extra fields of an object into $this->array_options
  5304. * This method is in most cases called by method fetch of objects but you can call it separately.
  5305. *
  5306. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5307. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5308. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5309. * @see fetchValuesForExtraLanguages()
  5310. */
  5311. public function fetch_optionals($rowid = null, $optionsArray = null)
  5312. {
  5313. // phpcs:enable
  5314. global $conf, $extrafields;
  5315. if (empty($rowid)) {
  5316. $rowid = $this->id;
  5317. }
  5318. if (empty($rowid) && isset($this->rowid)) {
  5319. $rowid = $this->rowid; // deprecated
  5320. }
  5321. // To avoid SQL errors. Probably not the better solution though
  5322. if (!$this->table_element) {
  5323. return 0;
  5324. }
  5325. $this->array_options = array();
  5326. if (!is_array($optionsArray)) {
  5327. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5328. if (!isset($extrafields) || !is_object($extrafields)) {
  5329. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5330. $extrafields = new ExtraFields($this->db);
  5331. }
  5332. // Load array of extrafields for elementype = $this->table_element
  5333. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5334. $extrafields->fetch_name_optionals_label($this->table_element);
  5335. }
  5336. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5337. } else {
  5338. global $extrafields;
  5339. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5340. }
  5341. $table_element = $this->table_element;
  5342. if ($table_element == 'categorie') {
  5343. $table_element = 'categories'; // For compatibility
  5344. }
  5345. // Request to get complementary values
  5346. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5347. $sql = "SELECT rowid";
  5348. foreach ($optionsArray as $name => $label) {
  5349. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5350. $sql .= ", ".$name;
  5351. }
  5352. }
  5353. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5354. $sql .= " WHERE fk_object = ".((int) $rowid);
  5355. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5356. $resql = $this->db->query($sql);
  5357. if ($resql) {
  5358. $numrows = $this->db->num_rows($resql);
  5359. if ($numrows) {
  5360. $tab = $this->db->fetch_array($resql);
  5361. foreach ($tab as $key => $value) {
  5362. // 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)
  5363. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5364. // we can add this attribute to object
  5365. if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5366. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5367. $this->array_options["options_".$key] = $this->db->jdate($value);
  5368. } else {
  5369. $this->array_options["options_".$key] = $value;
  5370. }
  5371. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5372. }
  5373. }
  5374. }
  5375. // If field is a computed field, value must become result of compute (regardless of whether a row exists
  5376. // in the element's extrafields table)
  5377. if (is_array($extrafields->attributes[$this->table_element]['label'])) {
  5378. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  5379. if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5380. //var_dump($conf->disable_compute);
  5381. if (empty($conf->disable_compute)) {
  5382. global $objectoffield; // We set a global variable to $objectoffield so
  5383. $objectoffield = $this; // we can use it inside computed formula
  5384. $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5385. }
  5386. }
  5387. }
  5388. }
  5389. $this->db->free($resql);
  5390. if ($numrows) {
  5391. return $numrows;
  5392. } else {
  5393. return 0;
  5394. }
  5395. } else {
  5396. $this->errors[]=$this->db->lasterror;
  5397. return -1;
  5398. }
  5399. }
  5400. return 0;
  5401. }
  5402. /**
  5403. * Delete all extra fields values for the current object.
  5404. *
  5405. * @return int <0 if KO, >0 if OK
  5406. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5407. */
  5408. public function deleteExtraFields()
  5409. {
  5410. global $conf;
  5411. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5412. return 0;
  5413. }
  5414. $this->db->begin();
  5415. $table_element = $this->table_element;
  5416. if ($table_element == 'categorie') {
  5417. $table_element = 'categories'; // For compatibility
  5418. }
  5419. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5420. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5421. $resql = $this->db->query($sql_del);
  5422. if (!$resql) {
  5423. $this->error = $this->db->lasterror();
  5424. $this->db->rollback();
  5425. return -1;
  5426. } else {
  5427. $this->db->commit();
  5428. return 1;
  5429. }
  5430. }
  5431. /**
  5432. * Add/Update all extra fields values for the current object.
  5433. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5434. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5435. *
  5436. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5437. * @param User $userused Object user
  5438. * @return int -1=error, O=did nothing, 1=OK
  5439. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5440. */
  5441. public function insertExtraFields($trigger = '', $userused = null)
  5442. {
  5443. global $conf, $langs, $user;
  5444. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5445. return 0;
  5446. }
  5447. if (empty($userused)) {
  5448. $userused = $user;
  5449. }
  5450. $error = 0;
  5451. if (!empty($this->array_options)) {
  5452. // Check parameters
  5453. $langs->load('admin');
  5454. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5455. $extrafields = new ExtraFields($this->db);
  5456. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5457. // Eliminate copied source object extra fields that do not exist in target object
  5458. $new_array_options = array();
  5459. foreach ($this->array_options as $key => $value) {
  5460. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5461. $new_array_options[$key] = $value;
  5462. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contain the 'options_' prefix
  5463. $new_array_options['options_'.$key] = $value;
  5464. }
  5465. }
  5466. foreach ($new_array_options as $key => $value) {
  5467. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5468. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5469. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5470. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5471. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5472. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5473. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5474. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5475. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5476. if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
  5477. $new_array_options[$key] = null;
  5478. }
  5479. // Similar code than into insertExtraFields
  5480. if ($attributeRequired) {
  5481. $mandatorypb = false;
  5482. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5483. $mandatorypb = true;
  5484. }
  5485. if ($this->array_options[$key] === '') {
  5486. $mandatorypb = true;
  5487. }
  5488. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5489. $mandatorypb = true;
  5490. }
  5491. if ($mandatorypb) {
  5492. $langs->load("errors");
  5493. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5494. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5495. return -1;
  5496. }
  5497. }
  5498. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5499. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5500. if (!empty($attrfieldcomputed)) {
  5501. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5502. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5503. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5504. $new_array_options[$key] = $value;
  5505. } else {
  5506. $new_array_options[$key] = null;
  5507. }
  5508. }
  5509. switch ($attributeType) {
  5510. case 'int':
  5511. if (!is_numeric($value) && $value != '') {
  5512. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5513. return -1;
  5514. } elseif ($value == '') {
  5515. $new_array_options[$key] = null;
  5516. }
  5517. break;
  5518. case 'price':
  5519. case 'double':
  5520. $value = price2num($value);
  5521. if (!is_numeric($value) && $value != '') {
  5522. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5523. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5524. return -1;
  5525. } elseif ($value == '') {
  5526. $value = null;
  5527. }
  5528. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5529. $new_array_options[$key] = $value;
  5530. break;
  5531. /*case 'select': // Not required, we chosed value='0' for undefined values
  5532. if ($value=='-1')
  5533. {
  5534. $this->array_options[$key] = null;
  5535. }
  5536. break;*/
  5537. case 'password':
  5538. $algo = '';
  5539. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5540. // If there is an encryption choice, we use it to crypt data before insert
  5541. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5542. $algo = reset($tmparrays);
  5543. if ($algo != '') {
  5544. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5545. //var_dump($action);
  5546. //var_dump($this->oldcopy);exit;
  5547. 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
  5548. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5549. 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.
  5550. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5551. } else {
  5552. // var_dump($algo);
  5553. $newvalue = dol_hash($this->array_options[$key], $algo);
  5554. $new_array_options[$key] = $newvalue;
  5555. }
  5556. } else {
  5557. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5558. }
  5559. }
  5560. } else // Common usage
  5561. {
  5562. $new_array_options[$key] = $this->array_options[$key];
  5563. }
  5564. break;
  5565. case 'date':
  5566. case 'datetime':
  5567. // If data is a string instead of a timestamp, we convert it
  5568. if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
  5569. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5570. }
  5571. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5572. break;
  5573. case 'datetimegmt':
  5574. // If data is a string instead of a timestamp, we convert it
  5575. if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
  5576. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5577. }
  5578. $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt');
  5579. break;
  5580. case 'link':
  5581. $param_list = array_keys($attributeParam['options']);
  5582. // 0 : ObjectName
  5583. // 1 : classPath
  5584. $InfoFieldList = explode(":", $param_list[0]);
  5585. dol_include_once($InfoFieldList[1]);
  5586. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5587. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5588. $new_array_options[$key] = '';
  5589. } elseif ($value) {
  5590. $object = new $InfoFieldList[0]($this->db);
  5591. if (is_numeric($value)) {
  5592. $res = $object->fetch($value); // Common case
  5593. } else {
  5594. $res = $object->fetch('', $value); // For compatibility
  5595. }
  5596. if ($res > 0) {
  5597. $new_array_options[$key] = $object->id;
  5598. } else {
  5599. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5600. return -1;
  5601. }
  5602. }
  5603. } else {
  5604. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5605. }
  5606. break;
  5607. case 'checkbox':
  5608. case 'chkbxlst':
  5609. if (is_array($this->array_options[$key])) {
  5610. $new_array_options[$key] = implode(',', $this->array_options[$key]);
  5611. } else {
  5612. $new_array_options[$key] = $this->array_options[$key];
  5613. }
  5614. break;
  5615. }
  5616. }
  5617. $this->db->begin();
  5618. $table_element = $this->table_element;
  5619. if ($table_element == 'categorie') {
  5620. $table_element = 'categories'; // For compatibility
  5621. }
  5622. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5623. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5624. $this->db->query($sql_del);
  5625. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5626. foreach ($new_array_options as $key => $value) {
  5627. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5628. // Add field of attribut
  5629. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5630. $sql .= ",".$attributeKey;
  5631. }
  5632. }
  5633. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5634. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5635. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5636. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5637. $sql .= ",".$tmpkey;
  5638. }
  5639. }
  5640. }
  5641. $sql .= ") VALUES (".$this->id;
  5642. foreach ($new_array_options as $key => $value) {
  5643. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5644. // Add field of attribute
  5645. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5646. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5647. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5648. } else {
  5649. $sql .= ",null";
  5650. }
  5651. }
  5652. }
  5653. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5654. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5655. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5656. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5657. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5658. $sql .= ", 0";
  5659. } else {
  5660. $sql .= ", ''";
  5661. }
  5662. }
  5663. }
  5664. }
  5665. $sql .= ")";
  5666. $resql = $this->db->query($sql);
  5667. if (!$resql) {
  5668. $this->error = $this->db->lasterror();
  5669. $error++;
  5670. }
  5671. if (!$error && $trigger) {
  5672. // Call trigger
  5673. $this->context = array('extrafieldaddupdate'=>1);
  5674. $result = $this->call_trigger($trigger, $userused);
  5675. if ($result < 0) {
  5676. $error++;
  5677. }
  5678. // End call trigger
  5679. }
  5680. if ($error) {
  5681. $this->db->rollback();
  5682. return -1;
  5683. } else {
  5684. $this->db->commit();
  5685. return 1;
  5686. }
  5687. } else {
  5688. return 0;
  5689. }
  5690. }
  5691. /**
  5692. * Add/Update all extra fields values for the current object.
  5693. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5694. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5695. *
  5696. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5697. * @param User $userused Object user
  5698. * @return int -1=error, O=did nothing, 1=OK
  5699. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5700. */
  5701. public function insertExtraLanguages($trigger = '', $userused = null)
  5702. {
  5703. global $conf, $langs, $user;
  5704. if (empty($userused)) {
  5705. $userused = $user;
  5706. }
  5707. $error = 0;
  5708. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5709. return 0; // For avoid conflicts if trigger used
  5710. }
  5711. if (is_array($this->array_languages)) {
  5712. $new_array_languages = $this->array_languages;
  5713. foreach ($new_array_languages as $key => $value) {
  5714. $attributeKey = $key;
  5715. $attributeType = $this->fields[$attributeKey]['type'];
  5716. $attributeLabel = $this->fields[$attributeKey]['label'];
  5717. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5718. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5719. switch ($attributeType) {
  5720. case 'int':
  5721. if (!is_numeric($value) && $value != '') {
  5722. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5723. return -1;
  5724. } elseif ($value == '') {
  5725. $new_array_languages[$key] = null;
  5726. }
  5727. break;
  5728. case 'double':
  5729. $value = price2num($value);
  5730. if (!is_numeric($value) && $value != '') {
  5731. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5732. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5733. return -1;
  5734. } elseif ($value == '') {
  5735. $new_array_languages[$key] = null;
  5736. } else {
  5737. $new_array_languages[$key] = $value;
  5738. }
  5739. break;
  5740. /*case 'select': // Not required, we chosed value='0' for undefined values
  5741. if ($value=='-1')
  5742. {
  5743. $this->array_options[$key] = null;
  5744. }
  5745. break;*/
  5746. }
  5747. }
  5748. $this->db->begin();
  5749. $table_element = $this->table_element;
  5750. if ($table_element == 'categorie') {
  5751. $table_element = 'categories'; // For compatibility
  5752. }
  5753. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5754. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5755. foreach ($langcodearray as $langcode => $value) {
  5756. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5757. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5758. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5759. $this->db->query($sql_del);
  5760. if ($value !== '') {
  5761. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5762. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5763. $sql .= ")";
  5764. $resql = $this->db->query($sql);
  5765. if (!$resql) {
  5766. $this->error = $this->db->lasterror();
  5767. $error++;
  5768. break;
  5769. }
  5770. }
  5771. }
  5772. }
  5773. if (!$error && $trigger) {
  5774. // Call trigger
  5775. $this->context = array('extralanguagesaddupdate'=>1);
  5776. $result = $this->call_trigger($trigger, $userused);
  5777. if ($result < 0) {
  5778. $error++;
  5779. }
  5780. // End call trigger
  5781. }
  5782. if ($error) {
  5783. $this->db->rollback();
  5784. return -1;
  5785. } else {
  5786. $this->db->commit();
  5787. return 1;
  5788. }
  5789. } else {
  5790. return 0;
  5791. }
  5792. }
  5793. /**
  5794. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5795. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5796. *
  5797. * @param string $key Key of the extrafield to update (without starting 'options_')
  5798. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5799. * @param User $userused Object user
  5800. * @return int -1=error, O=did nothing, 1=OK
  5801. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5802. */
  5803. public function updateExtraField($key, $trigger = null, $userused = null)
  5804. {
  5805. global $conf, $langs, $user;
  5806. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5807. return 0;
  5808. }
  5809. if (empty($userused)) {
  5810. $userused = $user;
  5811. }
  5812. $error = 0;
  5813. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5814. // Check parameters
  5815. $langs->load('admin');
  5816. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5817. $extrafields = new ExtraFields($this->db);
  5818. $extrafields->fetch_name_optionals_label($this->table_element);
  5819. $value = $this->array_options["options_".$key];
  5820. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5821. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5822. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5823. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5824. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5825. // Similar code than into insertExtraFields
  5826. if ($attributeRequired) {
  5827. $mandatorypb = false;
  5828. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5829. $mandatorypb = true;
  5830. }
  5831. if ($this->array_options["options_".$key] === '') {
  5832. $mandatorypb = true;
  5833. }
  5834. if ($mandatorypb) {
  5835. $langs->load("errors");
  5836. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5837. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5838. return -1;
  5839. }
  5840. }
  5841. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5842. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5843. if (!empty($attrfieldcomputed)) {
  5844. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5845. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5846. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5847. $this->array_options["options_".$key] = $value;
  5848. } else {
  5849. $this->array_options["options_".$key] = null;
  5850. }
  5851. }
  5852. switch ($attributeType) {
  5853. case 'int':
  5854. if (!is_numeric($value) && $value != '') {
  5855. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5856. return -1;
  5857. } elseif ($value === '') {
  5858. $this->array_options["options_".$key] = null;
  5859. }
  5860. break;
  5861. case 'double':
  5862. $value = price2num($value);
  5863. if (!is_numeric($value) && $value != '') {
  5864. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5865. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5866. return -1;
  5867. } elseif ($value === '') {
  5868. $value = null;
  5869. }
  5870. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5871. $this->array_options["options_".$key] = $value;
  5872. break;
  5873. /*case 'select': // Not required, we chosed value='0' for undefined values
  5874. if ($value=='-1')
  5875. {
  5876. $this->array_options[$key] = null;
  5877. }
  5878. break;*/
  5879. case 'price':
  5880. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5881. break;
  5882. case 'date':
  5883. case 'datetime':
  5884. if (empty($this->array_options["options_".$key])) {
  5885. $this->array_options["options_".$key] = null;
  5886. } else {
  5887. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5888. }
  5889. break;
  5890. case 'datetimegmt':
  5891. if (empty($this->array_options["options_".$key])) {
  5892. $this->array_options["options_".$key] = null;
  5893. } else {
  5894. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt');
  5895. }
  5896. break;
  5897. case 'boolean':
  5898. if (empty($this->array_options["options_".$key])) {
  5899. $this->array_options["options_".$key] = null;
  5900. }
  5901. break;
  5902. case 'link':
  5903. if ($this->array_options["options_".$key] === '') {
  5904. $this->array_options["options_".$key] = null;
  5905. }
  5906. break;
  5907. /*
  5908. case 'link':
  5909. $param_list = array_keys($attributeParam['options']);
  5910. // 0 : ObjectName
  5911. // 1 : classPath
  5912. $InfoFieldList = explode(":", $param_list[0]);
  5913. dol_include_once($InfoFieldList[1]);
  5914. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5915. {
  5916. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5917. {
  5918. $new_array_options[$key] = '';
  5919. } elseif ($value) {
  5920. $object = new $InfoFieldList[0]($this->db);
  5921. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5922. else $res = $object->fetch('', $value); // For compatibility
  5923. if ($res > 0) $new_array_options[$key] = $object->id;
  5924. else {
  5925. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5926. $this->db->rollback();
  5927. return -1;
  5928. }
  5929. }
  5930. } else {
  5931. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5932. }
  5933. break;
  5934. */
  5935. case 'checkbox':
  5936. case 'chkbxlst':
  5937. if (is_array($this->array_options[$key])) {
  5938. $new_array_options[$key] = implode(',', $this->array_options[$key]);
  5939. } else {
  5940. $new_array_options[$key] = $this->array_options[$key];
  5941. }
  5942. break;
  5943. }
  5944. $this->db->begin();
  5945. $linealreadyfound = 0;
  5946. // 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)
  5947. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5948. $resql = $this->db->query($sql);
  5949. if ($resql) {
  5950. $tmpobj = $this->db->fetch_object($resql);
  5951. if ($tmpobj) {
  5952. $linealreadyfound = $tmpobj->nb;
  5953. }
  5954. }
  5955. if ($linealreadyfound) {
  5956. if ($this->array_options["options_".$key] === null) {
  5957. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5958. } else {
  5959. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5960. }
  5961. $sql .= " WHERE fk_object = ".((int) $this->id);
  5962. } else {
  5963. $result = $this->insertExtraFields('', $user);
  5964. if ($result < 0) {
  5965. $error++;
  5966. }
  5967. }
  5968. $resql = $this->db->query($sql);
  5969. if (!$resql) {
  5970. $error++;
  5971. $this->error = $this->db->lasterror();
  5972. }
  5973. if (!$error && $trigger) {
  5974. // Call trigger
  5975. $this->context = array('extrafieldupdate'=>1);
  5976. $result = $this->call_trigger($trigger, $userused);
  5977. if ($result < 0) {
  5978. $error++;
  5979. }
  5980. // End call trigger
  5981. }
  5982. if ($error) {
  5983. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5984. $this->db->rollback();
  5985. return -1;
  5986. } else {
  5987. $this->db->commit();
  5988. return 1;
  5989. }
  5990. } else {
  5991. return 0;
  5992. }
  5993. }
  5994. /**
  5995. * Update an extra language value for the current object.
  5996. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5997. *
  5998. * @param string $key Key of the extrafield (without starting 'options_')
  5999. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  6000. * @param User $userused Object user
  6001. * @return int -1=error, O=did nothing, 1=OK
  6002. * @see updateExtraFields(), insertExtraLanguages()
  6003. */
  6004. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  6005. {
  6006. global $conf, $langs, $user;
  6007. if (empty($userused)) {
  6008. $userused = $user;
  6009. }
  6010. $error = 0;
  6011. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  6012. return 0; // For avoid conflicts if trigger used
  6013. }
  6014. return 0;
  6015. }
  6016. /**
  6017. * Return HTML string to put an input field into a page
  6018. * Code very similar with showInputField of extra fields
  6019. *
  6020. * @param array|null $val Array of properties for field to show (used only if ->fields not defined)
  6021. * @param string $key Key of attribute
  6022. * @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)
  6023. * @param string $moreparam To add more parameters on html input tag
  6024. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6025. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6026. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  6027. * @param int $nonewbutton Force to not show the new button on field that are links to object
  6028. * @return string
  6029. */
  6030. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  6031. {
  6032. global $conf, $langs, $form;
  6033. if (!is_object($form)) {
  6034. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6035. $form = new Form($this->db);
  6036. }
  6037. if (!empty($this->fields)) {
  6038. $val = $this->fields[$key];
  6039. }
  6040. // Validation tests and output
  6041. $fieldValidationErrorMsg = '';
  6042. $validationClass = '';
  6043. $fieldValidationErrorMsg = $this->getFieldError($key);
  6044. if (!empty($fieldValidationErrorMsg)) {
  6045. $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
  6046. } else {
  6047. $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
  6048. }
  6049. $out = '';
  6050. $type = '';
  6051. $isDependList = 0;
  6052. $param = array();
  6053. $param['options'] = array();
  6054. $reg = array();
  6055. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  6056. // Because we work on extrafields
  6057. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6058. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6059. $type = 'link';
  6060. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6061. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6062. $type = 'link';
  6063. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  6064. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6065. $type = 'link';
  6066. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6067. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6068. $type = 'sellist';
  6069. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6070. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6071. $type = 'sellist';
  6072. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  6073. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6074. $type = 'sellist';
  6075. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6076. $param['options'] = array($reg[1] => 'N');
  6077. $type = 'chkbxlst';
  6078. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  6079. $param['options'] = array();
  6080. $type = 'varchar';
  6081. $size = $reg[1];
  6082. } elseif (preg_match('/varchar/', $val['type'])) {
  6083. $param['options'] = array();
  6084. $type = 'varchar';
  6085. } else {
  6086. $param['options'] = array();
  6087. $type = $this->fields[$key]['type'];
  6088. }
  6089. // Special case that force options and type ($type can be integer, varchar, ...)
  6090. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  6091. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  6092. $type = 'select';
  6093. }
  6094. $label = $this->fields[$key]['label'];
  6095. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  6096. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  6097. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  6098. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  6099. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  6100. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  6101. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  6102. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  6103. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  6104. $objectid = $this->id;
  6105. if ($computed) {
  6106. if (!preg_match('/^search_/', $keyprefix)) {
  6107. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  6108. } else {
  6109. return '';
  6110. }
  6111. }
  6112. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  6113. if (empty($morecss) && !empty($val['css'])) {
  6114. $morecss = $val['css'];
  6115. } elseif (empty($morecss)) {
  6116. if ($type == 'date') {
  6117. $morecss = 'minwidth100imp';
  6118. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  6119. $morecss = 'minwidth200imp';
  6120. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6121. $morecss = 'maxwidth75';
  6122. } elseif ($type == 'url') {
  6123. $morecss = 'minwidth400';
  6124. } elseif ($type == 'boolean') {
  6125. $morecss = '';
  6126. } else {
  6127. if (round($size) < 12) {
  6128. $morecss = 'minwidth100';
  6129. } elseif (round($size) <= 48) {
  6130. $morecss = 'minwidth200';
  6131. } else {
  6132. $morecss = 'minwidth400';
  6133. }
  6134. }
  6135. }
  6136. // Add validation state class
  6137. if (!empty($validationClass)) {
  6138. $morecss.= $validationClass;
  6139. }
  6140. if (in_array($type, array('date'))) {
  6141. $tmp = explode(',', $size);
  6142. $newsize = $tmp[0];
  6143. $showtime = 0;
  6144. // Do not show current date when field not required (see selectDate() method)
  6145. if (!$required && $value == '') {
  6146. $value = '-1';
  6147. }
  6148. // TODO Must also support $moreparam
  6149. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6150. } elseif (in_array($type, array('datetime'))) {
  6151. $tmp = explode(',', $size);
  6152. $newsize = $tmp[0];
  6153. $showtime = 1;
  6154. // Do not show current date when field not required (see selectDate() method)
  6155. if (!$required && $value == '') $value = '-1';
  6156. // TODO Must also support $moreparam
  6157. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6158. } elseif (in_array($type, array('duration'))) {
  6159. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6160. } elseif (in_array($type, array('int', 'integer'))) {
  6161. $tmp = explode(',', $size);
  6162. $newsize = $tmp[0];
  6163. $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' : '').'>';
  6164. } elseif (in_array($type, array('real'))) {
  6165. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6166. } elseif (preg_match('/varchar/', $type)) {
  6167. $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' : '').'>';
  6168. } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
  6169. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6170. } elseif (preg_match('/^text/', $type)) {
  6171. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6172. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6173. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6174. $out = $doleditor->Create(1);
  6175. } else {
  6176. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6177. }
  6178. } elseif (preg_match('/^html/', $type)) {
  6179. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6180. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6181. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
  6182. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6183. } else {
  6184. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6185. }
  6186. } elseif ($type == 'boolean') {
  6187. $checked = '';
  6188. if (!empty($value)) {
  6189. $checked = ' checked value="1" ';
  6190. } else {
  6191. $checked = ' value="1" ';
  6192. }
  6193. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6194. } elseif ($type == 'price') {
  6195. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6196. $value = price($value);
  6197. }
  6198. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6199. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6200. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6201. $value = price($value);
  6202. }
  6203. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6204. } elseif ($type == 'select') {
  6205. $out = '';
  6206. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6207. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6208. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6209. }
  6210. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6211. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6212. $out .= '<option value="0">&nbsp;</option>';
  6213. }
  6214. foreach ($param['options'] as $keyb => $valb) {
  6215. if ((string) $keyb == '') {
  6216. continue;
  6217. }
  6218. if (strpos($valb, "|") !== false) {
  6219. list($valb, $parent) = explode('|', $valb);
  6220. }
  6221. $out .= '<option value="'.$keyb.'"';
  6222. $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
  6223. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6224. $out .= '>'.$valb.'</option>';
  6225. }
  6226. $out .= '</select>';
  6227. } elseif ($type == 'sellist') {
  6228. $out = '';
  6229. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6230. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6231. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6232. }
  6233. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6234. if (is_array($param['options'])) {
  6235. $param_list = array_keys($param['options']);
  6236. $InfoFieldList = explode(":", $param_list[0]);
  6237. $parentName = '';
  6238. $parentField = '';
  6239. // 0 : tableName
  6240. // 1 : label field name
  6241. // 2 : key fields name (if differ of rowid)
  6242. // 3 : key field parent (for dependent lists)
  6243. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6244. // 5 : id category type
  6245. // 6 : ids categories list separated by comma for category root
  6246. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6247. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6248. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6249. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6250. } else {
  6251. $keyList = $InfoFieldList[2].' as rowid';
  6252. }
  6253. }
  6254. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6255. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6256. $keyList .= ', '.$parentField;
  6257. }
  6258. $filter_categorie = false;
  6259. if (count($InfoFieldList) > 5) {
  6260. if ($InfoFieldList[0] == 'categorie') {
  6261. $filter_categorie = true;
  6262. }
  6263. }
  6264. if ($filter_categorie === false) {
  6265. $fields_label = explode('|', $InfoFieldList[1]);
  6266. if (is_array($fields_label)) {
  6267. $keyList .= ', ';
  6268. $keyList .= implode(', ', $fields_label);
  6269. }
  6270. $sqlwhere = '';
  6271. $sql = "SELECT " . $keyList;
  6272. $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
  6273. if (!empty($InfoFieldList[4])) {
  6274. // can use SELECT request
  6275. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6276. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6277. }
  6278. // current object id can be use into filter
  6279. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6280. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6281. } else {
  6282. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6283. }
  6284. //We have to join on extrafield table
  6285. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6286. $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra";
  6287. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6288. } else {
  6289. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6290. }
  6291. } else {
  6292. $sqlwhere .= ' WHERE 1=1';
  6293. }
  6294. // Some tables may have field, some other not. For the moment we disable it.
  6295. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6296. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6297. }
  6298. $sql .= $sqlwhere;
  6299. //print $sql;
  6300. $sql .= ' ORDER BY ' . implode(', ', $fields_label);
  6301. dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
  6302. $resql = $this->db->query($sql);
  6303. if ($resql) {
  6304. $out .= '<option value="0">&nbsp;</option>';
  6305. $num = $this->db->num_rows($resql);
  6306. $i = 0;
  6307. while ($i < $num) {
  6308. $labeltoshow = '';
  6309. $obj = $this->db->fetch_object($resql);
  6310. // Several field into label (eq table:code|libelle:rowid)
  6311. $notrans = false;
  6312. $fields_label = explode('|', $InfoFieldList[1]);
  6313. if (count($fields_label) > 1) {
  6314. $notrans = true;
  6315. foreach ($fields_label as $field_toshow) {
  6316. $labeltoshow .= $obj->$field_toshow . ' ';
  6317. }
  6318. } else {
  6319. $labeltoshow = $obj->{$InfoFieldList[1]};
  6320. }
  6321. $labeltoshow = dol_trunc($labeltoshow, 45);
  6322. if ($value == $obj->rowid) {
  6323. foreach ($fields_label as $field_toshow) {
  6324. $translabel = $langs->trans($obj->$field_toshow);
  6325. if ($translabel != $obj->$field_toshow) {
  6326. $labeltoshow = dol_trunc($translabel) . ' ';
  6327. } else {
  6328. $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
  6329. }
  6330. }
  6331. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6332. } else {
  6333. if (!$notrans) {
  6334. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6335. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6336. $labeltoshow = dol_trunc($translabel, 18);
  6337. } else {
  6338. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6339. }
  6340. }
  6341. if (empty($labeltoshow)) {
  6342. $labeltoshow = '(not defined)';
  6343. }
  6344. if ($value == $obj->rowid) {
  6345. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6346. }
  6347. if (!empty($InfoFieldList[3]) && $parentField) {
  6348. $parent = $parentName . ':' . $obj->{$parentField};
  6349. $isDependList = 1;
  6350. }
  6351. $out .= '<option value="' . $obj->rowid . '"';
  6352. $out .= ($value == $obj->rowid ? ' selected' : '');
  6353. $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
  6354. $out .= '>' . $labeltoshow . '</option>';
  6355. }
  6356. $i++;
  6357. }
  6358. $this->db->free($resql);
  6359. } else {
  6360. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6361. }
  6362. } else {
  6363. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6364. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6365. $out .= '<option value="0">&nbsp;</option>';
  6366. foreach ($data as $data_key => $data_value) {
  6367. $out .= '<option value="' . $data_key . '"';
  6368. $out .= ($value == $data_key ? ' selected' : '');
  6369. $out .= '>' . $data_value . '</option>';
  6370. }
  6371. }
  6372. }
  6373. $out .= '</select>';
  6374. } elseif ($type == 'checkbox') {
  6375. $value_arr = explode(',', $value);
  6376. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
  6377. } elseif ($type == 'radio') {
  6378. $out = '';
  6379. foreach ($param['options'] as $keyopt => $valopt) {
  6380. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6381. $out .= ' value="'.$keyopt.'"';
  6382. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6383. $out .= ($value == $keyopt ? 'checked' : '');
  6384. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
  6385. }
  6386. } elseif ($type == 'chkbxlst') {
  6387. if (is_array($value)) {
  6388. $value_arr = $value;
  6389. } else {
  6390. $value_arr = explode(',', $value);
  6391. }
  6392. if (is_array($param['options'])) {
  6393. $param_list = array_keys($param['options']);
  6394. $InfoFieldList = explode(":", $param_list[0]);
  6395. $parentName = '';
  6396. $parentField = '';
  6397. // 0 : tableName
  6398. // 1 : label field name
  6399. // 2 : key fields name (if differ of rowid)
  6400. // 3 : key field parent (for dependent lists)
  6401. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6402. // 5 : id category type
  6403. // 6 : ids categories list separated by comma for category root
  6404. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6405. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6406. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6407. $keyList .= ', '.$parentField;
  6408. }
  6409. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6410. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6411. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6412. } else {
  6413. $keyList = $InfoFieldList[2].' as rowid';
  6414. }
  6415. }
  6416. $filter_categorie = false;
  6417. if (count($InfoFieldList) > 5) {
  6418. if ($InfoFieldList[0] == 'categorie') {
  6419. $filter_categorie = true;
  6420. }
  6421. }
  6422. if ($filter_categorie === false) {
  6423. $fields_label = explode('|', $InfoFieldList[1]);
  6424. if (is_array($fields_label)) {
  6425. $keyList .= ', ';
  6426. $keyList .= implode(', ', $fields_label);
  6427. }
  6428. $sqlwhere = '';
  6429. $sql = "SELECT " . $keyList;
  6430. $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
  6431. if (!empty($InfoFieldList[4])) {
  6432. // can use SELECT request
  6433. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6434. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6435. }
  6436. // current object id can be use into filter
  6437. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6438. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6439. } else {
  6440. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6441. }
  6442. // We have to join on extrafield table
  6443. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6444. $sql .= ' as main, ' . $this->db->prefix() . $InfoFieldList[0] . '_extrafields as extra';
  6445. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6446. } else {
  6447. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6448. }
  6449. } else {
  6450. $sqlwhere .= ' WHERE 1=1';
  6451. }
  6452. // Some tables may have field, some other not. For the moment we disable it.
  6453. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6454. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6455. }
  6456. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6457. // print $sql;
  6458. $sql .= $sqlwhere;
  6459. dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
  6460. $resql = $this->db->query($sql);
  6461. if ($resql) {
  6462. $num = $this->db->num_rows($resql);
  6463. $i = 0;
  6464. $data = array();
  6465. while ($i < $num) {
  6466. $labeltoshow = '';
  6467. $obj = $this->db->fetch_object($resql);
  6468. $notrans = false;
  6469. // Several field into label (eq table:code|libelle:rowid)
  6470. $fields_label = explode('|', $InfoFieldList[1]);
  6471. if (count($fields_label) > 1) {
  6472. $notrans = true;
  6473. foreach ($fields_label as $field_toshow) {
  6474. $labeltoshow .= $obj->$field_toshow . ' ';
  6475. }
  6476. } else {
  6477. $labeltoshow = $obj->{$InfoFieldList[1]};
  6478. }
  6479. $labeltoshow = dol_trunc($labeltoshow, 45);
  6480. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6481. foreach ($fields_label as $field_toshow) {
  6482. $translabel = $langs->trans($obj->$field_toshow);
  6483. if ($translabel != $obj->$field_toshow) {
  6484. $labeltoshow = dol_trunc($translabel, 18) . ' ';
  6485. } else {
  6486. $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
  6487. }
  6488. }
  6489. $data[$obj->rowid] = $labeltoshow;
  6490. } else {
  6491. if (!$notrans) {
  6492. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6493. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6494. $labeltoshow = dol_trunc($translabel, 18);
  6495. } else {
  6496. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6497. }
  6498. }
  6499. if (empty($labeltoshow)) {
  6500. $labeltoshow = '(not defined)';
  6501. }
  6502. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6503. $data[$obj->rowid] = $labeltoshow;
  6504. }
  6505. if (!empty($InfoFieldList[3]) && $parentField) {
  6506. $parent = $parentName . ':' . $obj->{$parentField};
  6507. $isDependList = 1;
  6508. }
  6509. $data[$obj->rowid] = $labeltoshow;
  6510. }
  6511. $i++;
  6512. }
  6513. $this->db->free($resql);
  6514. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6515. } else {
  6516. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6517. }
  6518. } else {
  6519. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6520. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6521. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6522. }
  6523. }
  6524. } elseif ($type == 'link') {
  6525. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6526. $param_list_array = explode(':', $param_list[0]);
  6527. $showempty = (($required && $default != '') ? 0 : 1);
  6528. if (!preg_match('/search_/', $keyprefix)) {
  6529. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6530. if (!empty($this->fields[$key]['picto'])) {
  6531. $morecss .= ' widthcentpercentminusxx';
  6532. } else {
  6533. $morecss .= ' widthcentpercentminusx';
  6534. }
  6535. } else {
  6536. if (!empty($this->fields[$key]['picto'])) {
  6537. $morecss .= ' widthcentpercentminusx';
  6538. }
  6539. }
  6540. }
  6541. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6542. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6543. 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".
  6544. list($class, $classfile) = explode(':', $param_list[0]);
  6545. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6546. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6547. } else {
  6548. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6549. }
  6550. $paramforthenewlink = '';
  6551. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6552. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6553. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6554. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6555. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6556. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6557. $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>';
  6558. }
  6559. }
  6560. } elseif ($type == 'password') {
  6561. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6562. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6563. } elseif ($type == 'array') {
  6564. $newval = $val;
  6565. $newval['type'] = 'varchar(256)';
  6566. $out = '';
  6567. if (!empty($value)) {
  6568. foreach ($value as $option) {
  6569. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6570. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6571. }
  6572. }
  6573. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6574. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6575. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6576. if (!empty($conf->use_javascript_ajax)) {
  6577. $out .= '
  6578. <script nonce="'.getNonce().'">
  6579. $(document).ready(function() {
  6580. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6581. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6582. });
  6583. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6584. $(this).parent().remove();
  6585. });
  6586. });
  6587. </script>';
  6588. }
  6589. }
  6590. if (!empty($hidden)) {
  6591. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6592. }
  6593. if ($isDependList==1) {
  6594. $out .= $this->getJSListDependancies('_common');
  6595. }
  6596. /* Add comments
  6597. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6598. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6599. */
  6600. // Display error message for field
  6601. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6602. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6603. }
  6604. return $out;
  6605. }
  6606. /**
  6607. * Return HTML string to show a field into a page
  6608. * Code very similar with showOutputField of extra fields
  6609. *
  6610. * @param array $val Array of properties of field to show
  6611. * @param string $key Key of attribute
  6612. * @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)
  6613. * @param string $moreparam To add more parametes on html input tag
  6614. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6615. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6616. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6617. * @return string
  6618. */
  6619. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6620. {
  6621. global $conf, $langs, $form;
  6622. if (!is_object($form)) {
  6623. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6624. $form = new Form($this->db);
  6625. }
  6626. $label = empty($val['label']) ? '' : $val['label'];
  6627. $type = empty($val['type']) ? '' : $val['type'];
  6628. $size = empty($val['css']) ? '' : $val['css'];
  6629. $reg = array();
  6630. // Convert var to be able to share same code than showOutputField of extrafields
  6631. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6632. $type = 'varchar'; // convert varchar(xx) int varchar
  6633. $size = $reg[1];
  6634. } elseif (preg_match('/varchar/', $type)) {
  6635. $type = 'varchar'; // convert varchar(xx) int varchar
  6636. }
  6637. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6638. $type = 'select';
  6639. }
  6640. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6641. $type = 'link';
  6642. }
  6643. $default = empty($val['default']) ? '' : $val['default'];
  6644. $computed = empty($val['computed']) ? '' : $val['computed'];
  6645. $unique = empty($val['unique']) ? '' : $val['unique'];
  6646. $required = empty($val['required']) ? '' : $val['required'];
  6647. $param = array();
  6648. $param['options'] = array();
  6649. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6650. $param['options'] = $val['arrayofkeyval'];
  6651. }
  6652. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6653. $type = 'link';
  6654. $stringforoptions = $reg[1].':'.$reg[2];
  6655. if ($reg[1] == 'User') {
  6656. $stringforoptions .= ':-1';
  6657. }
  6658. $param['options'] = array($stringforoptions => $stringforoptions);
  6659. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6660. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6661. $type = 'sellist';
  6662. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6663. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6664. $type = 'sellist';
  6665. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6666. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6667. $type = 'sellist';
  6668. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6669. $param['options'] = array($reg[1] => 'N');
  6670. $type = 'chkbxlst';
  6671. }
  6672. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6673. $list = (empty($val['list']) ? '' : $val['list']);
  6674. $help = (empty($val['help']) ? '' : $val['help']);
  6675. $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)
  6676. if ($hidden) {
  6677. return '';
  6678. }
  6679. // If field is a computed field, value must become result of compute
  6680. if ($computed) {
  6681. // Make the eval of compute string
  6682. //var_dump($computed);
  6683. $value = dol_eval($computed, 1, 0, '');
  6684. }
  6685. if (empty($morecss)) {
  6686. if ($type == 'date') {
  6687. $morecss = 'minwidth100imp';
  6688. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6689. $morecss = 'minwidth200imp';
  6690. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6691. $morecss = 'maxwidth75';
  6692. } elseif ($type == 'url') {
  6693. $morecss = 'minwidth400';
  6694. } elseif ($type == 'boolean') {
  6695. $morecss = '';
  6696. } else {
  6697. if (is_numeric($size) && round($size) < 12) {
  6698. $morecss = 'minwidth100';
  6699. } elseif (is_numeric($size) && round($size) <= 48) {
  6700. $morecss = 'minwidth200';
  6701. } else {
  6702. $morecss = 'minwidth400';
  6703. }
  6704. }
  6705. }
  6706. // Format output value differently according to properties of field
  6707. if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
  6708. 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.
  6709. $value = $this->getNomUrl(1, '', 0, '', 1);
  6710. }
  6711. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6712. $value = $this->getLibStatut(3);
  6713. } elseif ($type == 'date') {
  6714. if (!empty($value)) {
  6715. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6716. } else {
  6717. $value = '';
  6718. }
  6719. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6720. if (!empty($value)) {
  6721. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6722. } else {
  6723. $value = '';
  6724. }
  6725. } elseif ($type == 'duration') {
  6726. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6727. if (!is_null($value) && $value !== '') {
  6728. $value = convertSecondToTime($value, 'allhourmin');
  6729. }
  6730. } elseif ($type == 'double' || $type == 'real') {
  6731. if (!is_null($value) && $value !== '') {
  6732. $value = price($value);
  6733. }
  6734. } elseif ($type == 'boolean') {
  6735. $checked = '';
  6736. if (!empty($value)) {
  6737. $checked = ' checked ';
  6738. }
  6739. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6740. } elseif ($type == 'mail' || $type == 'email') {
  6741. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6742. } elseif ($type == 'url') {
  6743. $value = dol_print_url($value, '_blank', 32, 1);
  6744. } elseif ($type == 'phone') {
  6745. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
  6746. } elseif ($type == 'ip') {
  6747. $value = dol_print_ip($value, 0);
  6748. } elseif ($type == 'price') {
  6749. if (!is_null($value) && $value !== '') {
  6750. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6751. }
  6752. } elseif ($type == 'select') {
  6753. $value = isset($param['options'][$value])?$param['options'][$value]:'';
  6754. } elseif ($type == 'sellist') {
  6755. $param_list = array_keys($param['options']);
  6756. $InfoFieldList = explode(":", $param_list[0]);
  6757. $selectkey = "rowid";
  6758. $keyList = 'rowid';
  6759. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6760. $selectkey = $InfoFieldList[2];
  6761. $keyList = $InfoFieldList[2].' as rowid';
  6762. }
  6763. $fields_label = explode('|', $InfoFieldList[1]);
  6764. if (is_array($fields_label)) {
  6765. $keyList .= ', ';
  6766. $keyList .= implode(', ', $fields_label);
  6767. }
  6768. $filter_categorie = false;
  6769. if (count($InfoFieldList) > 5) {
  6770. if ($InfoFieldList[0] == 'categorie') {
  6771. $filter_categorie = true;
  6772. }
  6773. }
  6774. $sql = "SELECT ".$keyList;
  6775. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6776. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6777. $sql .= ' as main';
  6778. }
  6779. if ($selectkey == 'rowid' && empty($value)) {
  6780. $sql .= " WHERE ".$selectkey." = 0";
  6781. } elseif ($selectkey == 'rowid') {
  6782. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6783. } else {
  6784. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6785. }
  6786. //$sql.= ' AND entity = '.$conf->entity;
  6787. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6788. $resql = $this->db->query($sql);
  6789. if ($resql) {
  6790. if ($filter_categorie === false) {
  6791. $value = ''; // value was used, so now we reste it to use it to build final output
  6792. $numrows = $this->db->num_rows($resql);
  6793. if ($numrows) {
  6794. $obj = $this->db->fetch_object($resql);
  6795. // Several field into label (eq table:code|libelle:rowid)
  6796. $fields_label = explode('|', $InfoFieldList[1]);
  6797. if (is_array($fields_label) && count($fields_label) > 1) {
  6798. foreach ($fields_label as $field_toshow) {
  6799. $translabel = '';
  6800. if (!empty($obj->$field_toshow)) {
  6801. $translabel = $langs->trans($obj->$field_toshow);
  6802. }
  6803. if ($translabel != $field_toshow) {
  6804. $value .= dol_trunc($translabel, 18) . ' ';
  6805. } else {
  6806. $value .= $obj->$field_toshow . ' ';
  6807. }
  6808. }
  6809. } else {
  6810. $translabel = '';
  6811. if (!empty($obj->{$InfoFieldList[1]})) {
  6812. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6813. }
  6814. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6815. $value = dol_trunc($translabel, 18);
  6816. } else {
  6817. $value = $obj->{$InfoFieldList[1]};
  6818. }
  6819. }
  6820. }
  6821. } else {
  6822. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6823. $toprint = array();
  6824. $obj = $this->db->fetch_object($resql);
  6825. $c = new Categorie($this->db);
  6826. $c->fetch($obj->rowid);
  6827. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  6828. foreach ($ways as $way) {
  6829. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  6830. }
  6831. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6832. }
  6833. } else {
  6834. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6835. }
  6836. } elseif ($type == 'radio') {
  6837. $value = $param['options'][$value];
  6838. } elseif ($type == 'checkbox') {
  6839. $value_arr = explode(',', $value);
  6840. $value = '';
  6841. if (is_array($value_arr) && count($value_arr) > 0) {
  6842. $toprint = array();
  6843. foreach ($value_arr as $keyval => $valueval) {
  6844. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6845. }
  6846. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6847. }
  6848. } elseif ($type == 'chkbxlst') {
  6849. $value_arr = explode(',', $value);
  6850. $param_list = array_keys($param['options']);
  6851. $InfoFieldList = explode(":", $param_list[0]);
  6852. $selectkey = "rowid";
  6853. $keyList = 'rowid';
  6854. if (count($InfoFieldList) >= 3) {
  6855. $selectkey = $InfoFieldList[2];
  6856. $keyList = $InfoFieldList[2].' as rowid';
  6857. }
  6858. $fields_label = explode('|', $InfoFieldList[1]);
  6859. if (is_array($fields_label)) {
  6860. $keyList .= ', ';
  6861. $keyList .= implode(', ', $fields_label);
  6862. }
  6863. $filter_categorie = false;
  6864. if (count($InfoFieldList) > 5) {
  6865. if ($InfoFieldList[0] == 'categorie') {
  6866. $filter_categorie = true;
  6867. }
  6868. }
  6869. $sql = "SELECT ".$keyList;
  6870. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6871. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6872. $sql .= ' as main';
  6873. }
  6874. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6875. // $sql.= ' AND entity = '.$conf->entity;
  6876. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6877. $resql = $this->db->query($sql);
  6878. if ($resql) {
  6879. if ($filter_categorie === false) {
  6880. $value = ''; // value was used, so now we reste it to use it to build final output
  6881. $toprint = array();
  6882. while ($obj = $this->db->fetch_object($resql)) {
  6883. // Several field into label (eq table:code|libelle:rowid)
  6884. $fields_label = explode('|', $InfoFieldList[1]);
  6885. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6886. if (is_array($fields_label) && count($fields_label) > 1) {
  6887. foreach ($fields_label as $field_toshow) {
  6888. $translabel = '';
  6889. if (!empty($obj->$field_toshow)) {
  6890. $translabel = $langs->trans($obj->$field_toshow);
  6891. }
  6892. if ($translabel != $field_toshow) {
  6893. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  6894. } else {
  6895. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
  6896. }
  6897. }
  6898. } else {
  6899. $translabel = '';
  6900. if (!empty($obj->{$InfoFieldList[1]})) {
  6901. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6902. }
  6903. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6904. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  6905. } else {
  6906. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
  6907. }
  6908. }
  6909. }
  6910. }
  6911. } else {
  6912. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6913. $toprint = array();
  6914. while ($obj = $this->db->fetch_object($resql)) {
  6915. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6916. $c = new Categorie($this->db);
  6917. $c->fetch($obj->rowid);
  6918. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  6919. foreach ($ways as $way) {
  6920. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  6921. }
  6922. }
  6923. }
  6924. }
  6925. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6926. } else {
  6927. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6928. }
  6929. } elseif ($type == 'link') {
  6930. $out = '';
  6931. // only if something to display (perf)
  6932. if ($value) {
  6933. $param_list = array_keys($param['options']); // Example: $param_list='ObjectName:classPath:-1::customer'
  6934. $InfoFieldList = explode(":", $param_list[0]);
  6935. $classname = $InfoFieldList[0];
  6936. $classpath = $InfoFieldList[1];
  6937. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6938. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6939. if (!empty($classpath)) {
  6940. dol_include_once($InfoFieldList[1]);
  6941. if ($classname && class_exists($classname)) {
  6942. $object = new $classname($this->db);
  6943. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6944. $result = $object->fetch($value, '', '', '', 0, 1, 1);
  6945. } else {
  6946. $result = $object->fetch($value);
  6947. }
  6948. if ($result > 0) {
  6949. if ($object->element === 'product') {
  6950. $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
  6951. if (isset($val['get_name_url_params'])) {
  6952. $get_name_url_params = explode(':', $val['get_name_url_params']);
  6953. if (!empty($get_name_url_params)) {
  6954. $param_num_max = count($get_name_url_param_arr) - 1;
  6955. foreach ($get_name_url_params as $param_num => $param_value) {
  6956. if ($param_num > $param_num_max) {
  6957. break;
  6958. }
  6959. $get_name_url_param_arr[$param_num] = $param_value;
  6960. }
  6961. }
  6962. }
  6963. /**
  6964. * @var Product $object
  6965. */
  6966. $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]);
  6967. } else {
  6968. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6969. }
  6970. } else {
  6971. $value = '';
  6972. }
  6973. }
  6974. } else {
  6975. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6976. return 'Error bad setup of extrafield';
  6977. }
  6978. } else {
  6979. $value = '';
  6980. }
  6981. } elseif ($type == 'password') {
  6982. $value = preg_replace('/./i', '*', $value);
  6983. } elseif ($type == 'array') {
  6984. $value = implode('<br>', $value);
  6985. } else { // text|html|varchar
  6986. $value = dol_htmlentitiesbr($value);
  6987. }
  6988. //print $type.'-'.$size.'-'.$value;
  6989. $out = $value;
  6990. return $out;
  6991. }
  6992. /**
  6993. * clear validation message result for a field
  6994. *
  6995. * @param string $fieldKey Key of attribute to clear
  6996. * @return void
  6997. */
  6998. public function clearFieldError($fieldKey)
  6999. {
  7000. $this->error = '';
  7001. unset($this->validateFieldsErrors[$fieldKey]);
  7002. }
  7003. /**
  7004. * set validation error message a field
  7005. *
  7006. * @param string $fieldKey Key of attribute
  7007. * @param string $msg the field error message
  7008. * @return void
  7009. */
  7010. public function setFieldError($fieldKey, $msg = '')
  7011. {
  7012. global $langs;
  7013. if (empty($msg)) {
  7014. $msg = $langs->trans("UnknowError");
  7015. }
  7016. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  7017. }
  7018. /**
  7019. * get field error message
  7020. *
  7021. * @param string $fieldKey Key of attribute
  7022. * @return string Error message of validation ('' if no error)
  7023. */
  7024. public function getFieldError($fieldKey)
  7025. {
  7026. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  7027. return $this->validateFieldsErrors[$fieldKey];
  7028. }
  7029. return '';
  7030. }
  7031. /**
  7032. * Return validation test result for a field
  7033. *
  7034. * @param array $fields Array of properties of field to show
  7035. * @param string $fieldKey Key of attribute
  7036. * @param string $fieldValue value of attribute
  7037. * @return bool return false if fail true on success, see $this->error for error message
  7038. */
  7039. public function validateField($fields, $fieldKey, $fieldValue)
  7040. {
  7041. global $langs;
  7042. if (!class_exists('Validate')) {
  7043. require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php';
  7044. }
  7045. $this->clearFieldError($fieldKey);
  7046. if (!isset($fields[$fieldKey])) {
  7047. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  7048. return false;
  7049. }
  7050. $val = $fields[$fieldKey];
  7051. $param = array();
  7052. $param['options'] = array();
  7053. $type = $val['type'];
  7054. $required = false;
  7055. if (isset($val['notnull']) && $val['notnull'] === 1) {
  7056. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  7057. $required = true;
  7058. }
  7059. $maxSize = 0;
  7060. $minSize = 0;
  7061. //
  7062. // PREPARE Elements
  7063. //
  7064. $reg = array();
  7065. // Convert var to be able to share same code than showOutputField of extrafields
  7066. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  7067. $type = 'varchar'; // convert varchar(xx) int varchar
  7068. $maxSize = $reg[1];
  7069. } elseif (preg_match('/varchar/', $type)) {
  7070. $type = 'varchar'; // convert varchar(xx) int varchar
  7071. }
  7072. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7073. $type = 'select';
  7074. }
  7075. if (!empty($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7076. $type = 'link';
  7077. }
  7078. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7079. $param['options'] = $val['arrayofkeyval'];
  7080. }
  7081. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7082. $type = 'link';
  7083. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  7084. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7085. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  7086. $type = 'sellist';
  7087. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7088. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  7089. $type = 'sellist';
  7090. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  7091. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  7092. $type = 'sellist';
  7093. }
  7094. //
  7095. // TEST Value
  7096. //
  7097. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  7098. $validate = new Validate($this->db, $langs);
  7099. // little trick : to perform tests with good performances sort tests by quick to low
  7100. //
  7101. // COMMON TESTS
  7102. //
  7103. // Required test and empty value
  7104. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  7105. $this->setFieldError($fieldKey, $validate->error);
  7106. return false;
  7107. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  7108. // if no value sent and the field is not mandatory, no need to perform tests
  7109. return true;
  7110. }
  7111. // MAX Size test
  7112. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  7113. $this->setFieldError($fieldKey, $validate->error);
  7114. return false;
  7115. }
  7116. // MIN Size test
  7117. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  7118. $this->setFieldError($fieldKey, $validate->error);
  7119. return false;
  7120. }
  7121. //
  7122. // TESTS for TYPE
  7123. //
  7124. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  7125. if (!$validate->isTimestamp($fieldValue)) {
  7126. $this->setFieldError($fieldKey, $validate->error);
  7127. return false;
  7128. } else { return true; }
  7129. } elseif ($type == 'duration') {
  7130. if (!$validate->isDuration($fieldValue)) {
  7131. $this->setFieldError($fieldKey, $validate->error);
  7132. return false;
  7133. } else { return true; }
  7134. } elseif (in_array($type, array('double', 'real', 'price'))) {
  7135. // is numeric
  7136. if (!$validate->isNumeric($fieldValue)) {
  7137. $this->setFieldError($fieldKey, $validate->error);
  7138. return false;
  7139. } else { return true; }
  7140. } elseif ($type == 'boolean') {
  7141. if (!$validate->isBool($fieldValue)) {
  7142. $this->setFieldError($fieldKey, $validate->error);
  7143. return false;
  7144. } else { return true; }
  7145. } elseif ($type == 'mail') {
  7146. if (!$validate->isEmail($fieldValue)) {
  7147. $this->setFieldError($fieldKey, $validate->error);
  7148. return false;
  7149. }
  7150. } elseif ($type == 'url') {
  7151. if (!$validate->isUrl($fieldValue)) {
  7152. $this->setFieldError($fieldKey, $validate->error);
  7153. return false;
  7154. } else { return true; }
  7155. } elseif ($type == 'phone') {
  7156. if (!$validate->isPhone($fieldValue)) {
  7157. $this->setFieldError($fieldKey, $validate->error);
  7158. return false;
  7159. } else { return true; }
  7160. } elseif ($type == 'select' || $type == 'radio') {
  7161. if (!isset($param['options'][$fieldValue])) {
  7162. $this->error = $langs->trans('RequireValidValue');
  7163. return false;
  7164. } else { return true; }
  7165. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  7166. $param_list = array_keys($param['options']);
  7167. $InfoFieldList = explode(":", $param_list[0]);
  7168. $value_arr = explode(',', $fieldValue);
  7169. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  7170. $selectkey = "rowid";
  7171. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  7172. $selectkey = $InfoFieldList[2];
  7173. }
  7174. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  7175. $this->setFieldError($fieldKey, $validate->error);
  7176. return false;
  7177. } else { return true; }
  7178. } elseif ($type == 'link') {
  7179. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  7180. $InfoFieldList = explode(":", $param_list[0]);
  7181. $classname = $InfoFieldList[0];
  7182. $classpath = $InfoFieldList[1];
  7183. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  7184. $this->setFieldError($fieldKey, $validate->error);
  7185. return false;
  7186. } else { return true; }
  7187. }
  7188. // if no test failled all is ok
  7189. return true;
  7190. }
  7191. /**
  7192. * Function to show lines of extrafields with output datas.
  7193. * 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
  7194. *
  7195. * @param Extrafields $extrafields Extrafield Object
  7196. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  7197. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  7198. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  7199. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  7200. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  7201. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  7202. * @return string String with html content to show
  7203. */
  7204. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  7205. {
  7206. global $db, $conf, $langs, $action, $form, $hookmanager;
  7207. if (!is_object($form)) {
  7208. $form = new Form($db);
  7209. }
  7210. if (!is_object($extrafields)) {
  7211. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  7212. return 'Bad parameter extrafields for showOptionals';
  7213. }
  7214. if (!is_array($extrafields->attributes[$this->table_element])) {
  7215. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  7216. }
  7217. $out = '';
  7218. $parameters = array('mode'=>$mode, 'params'=>$params, 'keysuffix'=>$keysuffix, 'keyprefix'=>$keyprefix, 'display_type'=>$display_type);
  7219. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  7220. if (empty($reshook)) {
  7221. 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) {
  7222. $out .= "\n";
  7223. $out .= '<!-- commonobject:showOptionals --> ';
  7224. $out .= "\n";
  7225. $nbofextrafieldsshown = 0;
  7226. $e = 0; // var to manage the modulo (odd/even)
  7227. $lastseparatorkeyfound = '';
  7228. $extrafields_collapse_num = '';
  7229. $extrafields_collapse_num_old = '';
  7230. $i = 0;
  7231. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  7232. $i++;
  7233. // Show only the key field in params
  7234. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  7235. continue;
  7236. }
  7237. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  7238. $enabled = 1;
  7239. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  7240. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
  7241. }
  7242. if (empty($enabled)) {
  7243. continue;
  7244. }
  7245. $visibility = 1;
  7246. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  7247. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
  7248. }
  7249. $perms = 1;
  7250. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  7251. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
  7252. }
  7253. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7254. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7255. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7256. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7257. } elseif ($mode == 'view' && empty($visibility)) {
  7258. continue;
  7259. }
  7260. if (empty($perms)) {
  7261. continue;
  7262. }
  7263. // Load language if required
  7264. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7265. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7266. }
  7267. $colspan = 0;
  7268. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  7269. if (array_key_exists('cols', $params)) {
  7270. $colspan = $params['cols'];
  7271. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7272. $reg = array();
  7273. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7274. $colspan = $reg[1];
  7275. } else {
  7276. $colspan = $params['colspan'];
  7277. }
  7278. }
  7279. }
  7280. $colspan = intval($colspan);
  7281. switch ($mode) {
  7282. case "view":
  7283. $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
  7284. break;
  7285. case "create":
  7286. case "edit":
  7287. // We get the value of property found with GETPOST so it takes into account:
  7288. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7289. $check = 'alphanohtml';
  7290. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7291. $check = 'restricthtml';
  7292. }
  7293. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7294. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7295. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7296. if (is_array($getposttemp)) {
  7297. // $getposttemp is an array but following code expects a comma separated string
  7298. $value = implode(",", $getposttemp);
  7299. } else {
  7300. $value = $getposttemp;
  7301. }
  7302. } else {
  7303. $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.
  7304. }
  7305. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7306. break;
  7307. }
  7308. $nbofextrafieldsshown++;
  7309. // Output value of the current field
  7310. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7311. $extrafields_collapse_num = $key;
  7312. /*
  7313. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7314. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7315. $extrafield_param_list = array_keys($extrafield_param['options']);
  7316. if (count($extrafield_param_list) > 0) {
  7317. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7318. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7319. //$extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7320. $extrafields_collapse_num = $key;
  7321. }
  7322. }
  7323. }
  7324. */
  7325. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7326. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7327. $lastseparatorkeyfound = $key;
  7328. } else {
  7329. $collapse_group = $extrafields_collapse_num.(!empty($this->id) ? '_'.$this->id : '');
  7330. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7331. $csstyle = '';
  7332. if (is_array($params) && count($params) > 0) {
  7333. if (array_key_exists('class', $params)) {
  7334. $class .= $params['class'].' ';
  7335. }
  7336. if (array_key_exists('style', $params)) {
  7337. $csstyle = $params['style'];
  7338. }
  7339. }
  7340. // add html5 elements
  7341. $domData = ' data-element="extrafield"';
  7342. $domData .= ' data-targetelement="'.$this->element.'"';
  7343. $domData .= ' data-targetid="'.$this->id.'"';
  7344. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7345. if ($display_type=='card') {
  7346. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7347. $colspan = 0;
  7348. }
  7349. if ($action == 'selectlines') {
  7350. $colspan++;
  7351. }
  7352. }
  7353. // Convert date into timestamp format (value in memory must be a timestamp)
  7354. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7355. $datenotinstring = null;
  7356. if (array_key_exists('options_'.$key, $this->array_options)) {
  7357. $datenotinstring = $this->array_options['options_'.$key];
  7358. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7359. $datenotinstring = $this->db->jdate($datenotinstring);
  7360. }
  7361. }
  7362. $datekey = $keyprefix.'options_'.$key.$keysuffix;
  7363. $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
  7364. }
  7365. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7366. $datenotinstring = null;
  7367. if (array_key_exists('options_'.$key, $this->array_options)) {
  7368. $datenotinstring = $this->array_options['options_'.$key];
  7369. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7370. $datenotinstring = $this->db->jdate($datenotinstring);
  7371. }
  7372. }
  7373. $timekey = $keyprefix.'options_'.$key.$keysuffix;
  7374. $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;
  7375. }
  7376. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7377. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7378. if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
  7379. $value = price2num($value);
  7380. } elseif (isset($this->array_options['options_'.$key])) {
  7381. $value = $this->array_options['options_'.$key];
  7382. }
  7383. }
  7384. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7385. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
  7386. if ($action == 'create') {
  7387. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7388. }
  7389. }
  7390. $labeltoshow = $langs->trans($label);
  7391. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7392. if ($display_type == 'card') {
  7393. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
  7394. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
  7395. $out .= '<td></td>';
  7396. }
  7397. $out .= '<td class="'.(empty($params['tdclass']) ? 'titlefieldcreate' : $params['tdclass']).' wordbreak';
  7398. } elseif ($display_type == 'line') {
  7399. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
  7400. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  7401. }
  7402. //$out .= "titlefield";
  7403. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7404. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7405. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7406. if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
  7407. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7408. $out .= ' fieldrequired';
  7409. }
  7410. }
  7411. $out .= '">';
  7412. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7413. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7414. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7415. } else {
  7416. $out .= $labeltoshow;
  7417. }
  7418. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7419. $out .= '&nbsp;<span style="color: red">*</span>';
  7420. }
  7421. } else {
  7422. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7423. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7424. } else {
  7425. $out .= $labeltoshow;
  7426. }
  7427. }
  7428. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7429. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7430. if ($display_type == 'card') {
  7431. // 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
  7432. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7433. } elseif ($display_type == 'line') {
  7434. $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].'">';
  7435. }
  7436. switch ($mode) {
  7437. case "view":
  7438. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7439. break;
  7440. case "create":
  7441. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7442. break;
  7443. case "edit":
  7444. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7445. break;
  7446. }
  7447. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7448. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7449. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7450. } else {
  7451. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7452. }
  7453. $e++;
  7454. }
  7455. }
  7456. $out .= "\n";
  7457. // Add code to manage list depending on others
  7458. if (!empty($conf->use_javascript_ajax)) {
  7459. $out .= $this->getJSListDependancies();
  7460. }
  7461. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7462. if (empty($nbofextrafieldsshown)) {
  7463. $out = '';
  7464. }
  7465. }
  7466. }
  7467. $out .= $hookmanager->resPrint;
  7468. return $out;
  7469. }
  7470. /**
  7471. * @param string $type Type for prefix
  7472. * @return string Javacript code to manage dependency
  7473. */
  7474. public function getJSListDependancies($type = '_extra')
  7475. {
  7476. $out = '
  7477. <script nonce="'.getNonce().'">
  7478. jQuery(document).ready(function() {
  7479. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7480. {
  7481. var val = $("select[name=\""+parent_list+"\"]").val();
  7482. var parentVal = parent_list + ":" + val;
  7483. if(typeof val == "string"){
  7484. if(val != "") {
  7485. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7486. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7487. $("select[name=\""+child_list+"\"]").append(options);
  7488. } else {
  7489. var options = orig_select.find("option[parent]").clone();
  7490. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7491. $("select[name=\""+child_list+"\"]").append(options);
  7492. }
  7493. } else if(val > 0) {
  7494. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7495. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7496. $("select[name=\""+child_list+"\"]").append(options);
  7497. } else {
  7498. var options = orig_select.find("option[parent]").clone();
  7499. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7500. $("select[name=\""+child_list+"\"]").append(options);
  7501. }
  7502. }
  7503. function setListDependencies'.$type.'() {
  7504. jQuery("select option[parent]").parent().each(function() {
  7505. var orig_select = {};
  7506. var child_list = $(this).attr("name");
  7507. orig_select[child_list] = $(this).clone();
  7508. var parent = $(this).find("option[parent]:first").attr("parent");
  7509. var infos = parent.split(":");
  7510. var parent_list = infos[0];
  7511. //Hide daughters lists
  7512. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7513. $("#"+child_list).hide();
  7514. //Show mother lists
  7515. } else if ($("#"+parent_list).val() != 0){
  7516. $("#"+parent_list).show();
  7517. }
  7518. //Show the child list if the parent list value is selected
  7519. $("select[name=\""+parent_list+"\"]").click(function() {
  7520. if ($(this).val() != 0){
  7521. $("#"+child_list).show()
  7522. }
  7523. });
  7524. //When we change parent list
  7525. $("select[name=\""+parent_list+"\"]").change(function() {
  7526. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7527. //Select the value 0 on child list after a change on the parent list
  7528. $("#"+child_list).val(0).trigger("change");
  7529. //Hide child lists if the parent value is set to 0
  7530. if ($(this).val() == 0){
  7531. $("#"+child_list).hide();
  7532. }
  7533. });
  7534. });
  7535. }
  7536. setListDependencies'.$type.'();
  7537. });
  7538. </script>'."\n";
  7539. return $out;
  7540. }
  7541. /**
  7542. * Returns the rights used for this class
  7543. * @return stdClass
  7544. */
  7545. public function getRights()
  7546. {
  7547. global $user;
  7548. $module = $this->module;
  7549. $element = $this->element;
  7550. if ($element == 'facturerec') {
  7551. $element = 'facture';
  7552. } elseif ($element == 'invoice_supplier_rec') {
  7553. return $user->rights->fournisseur->facture;
  7554. } elseif ($module && !empty($user->rights->$module->$element)) {
  7555. // for modules built with ModuleBuilder
  7556. return $user->rights->$module->$element;
  7557. }
  7558. return $user->rights->$element;
  7559. }
  7560. /**
  7561. * Function used to replace a thirdparty id with another one.
  7562. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7563. * Column name fk_soc MUST be used to identify thirdparties
  7564. *
  7565. * @param DoliDB $dbs Database handler
  7566. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7567. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7568. * @param string[] $tables Tables that need to be changed
  7569. * @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)
  7570. * @return bool True if success, False if error
  7571. */
  7572. public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7573. {
  7574. foreach ($tables as $table) {
  7575. $sql = 'UPDATE '.$dbs->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7576. if (!$dbs->query($sql)) {
  7577. if ($ignoreerrors) {
  7578. 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.
  7579. }
  7580. //$this->errors = $db->lasterror();
  7581. return false;
  7582. }
  7583. }
  7584. return true;
  7585. }
  7586. /**
  7587. * Function used to replace a product id with another one.
  7588. * This function is meant to be called from replaceProduct with the appropriate tables
  7589. * Column name fk_product MUST be used to identify products
  7590. *
  7591. * @param DoliDB $dbs Database handler
  7592. * @param int $origin_id Old product id (the product to delete)
  7593. * @param int $dest_id New product id (the product that will received element of the other)
  7594. * @param string[] $tables Tables that need to be changed
  7595. * @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)
  7596. * @return bool True if success, False if error
  7597. */
  7598. public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7599. {
  7600. foreach ($tables as $table) {
  7601. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7602. if (!$dbs->query($sql)) {
  7603. if ($ignoreerrors) {
  7604. 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.
  7605. }
  7606. //$this->errors = $db->lasterror();
  7607. return false;
  7608. }
  7609. }
  7610. return true;
  7611. }
  7612. /**
  7613. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7614. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7615. * elseif calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7616. * elseif calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7617. * else set min buy price as buy price
  7618. *
  7619. * @param float $unitPrice Product unit price
  7620. * @param float $discountPercent Line discount percent
  7621. * @param int $fk_product Product id
  7622. * @return float <0 if KO, buyprice if OK
  7623. */
  7624. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7625. {
  7626. global $conf;
  7627. $buyPrice = 0;
  7628. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7629. // When ForceBuyingPriceIfNull is set
  7630. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7631. } else {
  7632. // Get cost price for margin calculation
  7633. if (!empty($fk_product) && $fk_product > 0) {
  7634. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7635. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7636. $product = new Product($this->db);
  7637. $result = $product->fetch($fk_product);
  7638. if ($result <= 0) {
  7639. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7640. return -1;
  7641. }
  7642. if ($product->cost_price > 0) {
  7643. $buyPrice = $product->cost_price;
  7644. } elseif ($product->pmp > 0) {
  7645. $buyPrice = $product->pmp;
  7646. }
  7647. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7648. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7649. $product = new Product($this->db);
  7650. $result = $product->fetch($fk_product);
  7651. if ($result <= 0) {
  7652. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7653. return -1;
  7654. }
  7655. if ($product->pmp > 0) {
  7656. $buyPrice = $product->pmp;
  7657. }
  7658. }
  7659. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7660. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7661. $productFournisseur = new ProductFournisseur($this->db);
  7662. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7663. $buyPrice = $productFournisseur->fourn_unitprice;
  7664. } elseif ($result < 0) {
  7665. $this->errors[] = $productFournisseur->error;
  7666. return -2;
  7667. }
  7668. }
  7669. }
  7670. }
  7671. return $buyPrice;
  7672. }
  7673. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7674. /**
  7675. * Show photos of an object (nbmax maximum), into several columns
  7676. *
  7677. * @param string $modulepart 'product', 'ticket', ...
  7678. * @param string $sdir Directory to scan (full absolute path)
  7679. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7680. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7681. * @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'.
  7682. * @param int $showfilename 1=Show filename
  7683. * @param int $showaction 1=Show icon with action links (resize, delete)
  7684. * @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.
  7685. * @param int $maxWidth Max width of original image when size='small'
  7686. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7687. * @param int|string $overwritetitle Do not add title tag on image
  7688. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7689. * @param string $cache A string if we want to use a cached version of image
  7690. * @param string $addphotorefcss Add CSS to img of photos
  7691. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7692. */
  7693. 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')
  7694. {
  7695. // phpcs:enable
  7696. global $conf, $user, $langs;
  7697. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7698. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7699. $sortfield = 'position_name';
  7700. $sortorder = 'asc';
  7701. $dir = $sdir.'/';
  7702. $pdir = '/';
  7703. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7704. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7705. // For backward compatibility
  7706. if ($modulepart == 'product') {
  7707. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  7708. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7709. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7710. }
  7711. }
  7712. // Defined relative dir to DOL_DATA_ROOT
  7713. $relativedir = '';
  7714. if ($dir) {
  7715. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7716. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7717. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7718. }
  7719. $dirthumb = $dir.'thumbs/';
  7720. $pdirthumb = $pdir.'thumbs/';
  7721. $return = '<!-- Photo -->'."\n";
  7722. $nbphoto = 0;
  7723. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7724. /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatiblity, we scan also old dirs
  7725. {
  7726. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7727. $filearray=array_merge($filearray, $filearrayold);
  7728. }*/
  7729. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7730. if (count($filearray)) {
  7731. if ($sortfield && $sortorder) {
  7732. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7733. }
  7734. foreach ($filearray as $key => $val) {
  7735. $photo = '';
  7736. $file = $val['name'];
  7737. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7738. if (image_format_supported($file) >= 0) {
  7739. $nbphoto++;
  7740. $photo = $file;
  7741. $viewfilename = $file;
  7742. if ($size == 1 || $size == 'small') { // Format vignette
  7743. // Find name of thumb file
  7744. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7745. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7746. // The thumb does not exists, so we will use the original file
  7747. $dirthumb = $dir;
  7748. $pdirthumb = $pdir;
  7749. $photo_vignette = basename($file);
  7750. }
  7751. // Get filesize of original file
  7752. $imgarray = dol_getImageSize($dir.$photo);
  7753. if ($nbbyrow > 0) {
  7754. if ($nbphoto == 1) {
  7755. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7756. }
  7757. if ($nbphoto % $nbbyrow == 1) {
  7758. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7759. }
  7760. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">'."\n";
  7761. } elseif ($nbbyrow < 0) {
  7762. $return .= '<div class="inline-block">'."\n";
  7763. }
  7764. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7765. if (empty($nolink)) {
  7766. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7767. if ($urladvanced) {
  7768. $return .= '<a href="'.$urladvanced.'">';
  7769. } else {
  7770. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7771. }
  7772. }
  7773. // Show image (width height=$maxHeight)
  7774. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7775. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7776. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7777. if ($overwritetitle) {
  7778. if (is_numeric($overwritetitle)) {
  7779. $alt = '';
  7780. } else {
  7781. $alt = $overwritetitle;
  7782. }
  7783. }
  7784. if ($usesharelink) {
  7785. if ($val['share']) {
  7786. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7787. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7788. $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).'">';
  7789. } else {
  7790. $return .= '<!-- Show original file -->';
  7791. $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).'">';
  7792. }
  7793. } else {
  7794. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7795. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7796. }
  7797. } else {
  7798. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7799. $return .= '<!-- Show thumb -->';
  7800. $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).'">';
  7801. } else {
  7802. $return .= '<!-- Show original file -->';
  7803. $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).'">';
  7804. }
  7805. }
  7806. if (empty($nolink)) {
  7807. $return .= '</a>';
  7808. }
  7809. if ($showfilename) {
  7810. $return .= '<br>'.$viewfilename;
  7811. }
  7812. if ($showaction) {
  7813. $return .= '<br>';
  7814. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7815. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7816. $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>';
  7817. }
  7818. // Special cas for product
  7819. if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
  7820. // Link to resize
  7821. $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; ';
  7822. // Link to delete
  7823. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7824. $return .= img_delete().'</a>';
  7825. }
  7826. }
  7827. $return .= "\n";
  7828. if ($nbbyrow > 0) {
  7829. $return .= '</td>';
  7830. if (($nbphoto % $nbbyrow) == 0) {
  7831. $return .= '</tr>';
  7832. }
  7833. } elseif ($nbbyrow < 0) {
  7834. $return .= '</div>'."\n";
  7835. }
  7836. }
  7837. if (empty($size)) { // Format origine
  7838. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7839. if ($showfilename) {
  7840. $return .= '<br>'.$viewfilename;
  7841. }
  7842. if ($showaction) {
  7843. // Special case for product
  7844. if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
  7845. // Link to resize
  7846. $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; ';
  7847. // Link to delete
  7848. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7849. $return .= img_delete().'</a>';
  7850. }
  7851. }
  7852. }
  7853. // On continue ou on arrete de boucler ?
  7854. if ($nbmax && $nbphoto >= $nbmax) {
  7855. break;
  7856. }
  7857. }
  7858. }
  7859. if ($size == 1 || $size == 'small') {
  7860. if ($nbbyrow > 0) {
  7861. // Ferme tableau
  7862. while ($nbphoto % $nbbyrow) {
  7863. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7864. $nbphoto++;
  7865. }
  7866. if ($nbphoto) {
  7867. $return .= '</table>';
  7868. }
  7869. }
  7870. }
  7871. }
  7872. $this->nbphoto = $nbphoto;
  7873. return $return;
  7874. }
  7875. /**
  7876. * Function test if type is array
  7877. *
  7878. * @param array $info content informations of field
  7879. * @return bool true if array
  7880. */
  7881. protected function isArray($info)
  7882. {
  7883. if (is_array($info)) {
  7884. if (isset($info['type']) && $info['type'] == 'array') {
  7885. return true;
  7886. } else {
  7887. return false;
  7888. }
  7889. }
  7890. return false;
  7891. }
  7892. /**
  7893. * Function test if type is date
  7894. *
  7895. * @param array $info content informations of field
  7896. * @return bool true if date
  7897. */
  7898. public function isDate($info)
  7899. {
  7900. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7901. return true;
  7902. }
  7903. return false;
  7904. }
  7905. /**
  7906. * Function test if type is duration
  7907. *
  7908. * @param array $info content informations of field
  7909. * @return bool true if field of type duration
  7910. */
  7911. public function isDuration($info)
  7912. {
  7913. if (is_array($info)) {
  7914. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7915. return true;
  7916. } else {
  7917. return false;
  7918. }
  7919. } else {
  7920. return false;
  7921. }
  7922. }
  7923. /**
  7924. * Function test if type is integer
  7925. *
  7926. * @param array $info content informations of field
  7927. * @return bool true if integer
  7928. */
  7929. public function isInt($info)
  7930. {
  7931. if (is_array($info)) {
  7932. if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
  7933. return true;
  7934. } else {
  7935. return false;
  7936. }
  7937. } else {
  7938. return false;
  7939. }
  7940. }
  7941. /**
  7942. * Function test if type is float
  7943. *
  7944. * @param array $info content informations of field
  7945. * @return bool true if float
  7946. */
  7947. public function isFloat($info)
  7948. {
  7949. if (is_array($info)) {
  7950. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7951. return true;
  7952. } else {
  7953. return false;
  7954. }
  7955. }
  7956. return false;
  7957. }
  7958. /**
  7959. * Function test if type is text
  7960. *
  7961. * @param array $info content informations of field
  7962. * @return bool true if type text
  7963. */
  7964. public function isText($info)
  7965. {
  7966. if (is_array($info)) {
  7967. if (isset($info['type']) && $info['type'] == 'text') {
  7968. return true;
  7969. } else {
  7970. return false;
  7971. }
  7972. }
  7973. return false;
  7974. }
  7975. /**
  7976. * Function test if field can be null
  7977. *
  7978. * @param array $info content informations of field
  7979. * @return bool true if it can be null
  7980. */
  7981. protected function canBeNull($info)
  7982. {
  7983. if (is_array($info)) {
  7984. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7985. return true;
  7986. } else {
  7987. return false;
  7988. }
  7989. }
  7990. return true;
  7991. }
  7992. /**
  7993. * Function test if field is forced to null if zero or empty
  7994. *
  7995. * @param array $info content informations of field
  7996. * @return bool true if forced to null
  7997. */
  7998. protected function isForcedToNullIfZero($info)
  7999. {
  8000. if (is_array($info)) {
  8001. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  8002. return true;
  8003. } else {
  8004. return false;
  8005. }
  8006. }
  8007. return false;
  8008. }
  8009. /**
  8010. * Function test if is indexed
  8011. *
  8012. * @param array $info content informations of field
  8013. * @return bool
  8014. */
  8015. protected function isIndex($info)
  8016. {
  8017. if (is_array($info)) {
  8018. if (isset($info['index']) && $info['index'] == true) {
  8019. return true;
  8020. } else {
  8021. return false;
  8022. }
  8023. }
  8024. return false;
  8025. }
  8026. /**
  8027. * Function to prepare a part of the query for insert by returning an array with all properties of object.
  8028. *
  8029. * Note $this->${field} are set by the page that make the createCommon() or the updateCommon().
  8030. * $this->${field} should be a clean and string value (so date are formated for SQL insert).
  8031. *
  8032. * @return array Array with all values of each properties to update
  8033. */
  8034. protected function setSaveQuery()
  8035. {
  8036. global $conf;
  8037. $queryarray = array();
  8038. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  8039. // Depending on field type ('datetime', ...)
  8040. if ($this->isDate($info)) {
  8041. if (empty($this->{$field})) {
  8042. $queryarray[$field] = null;
  8043. } else {
  8044. $queryarray[$field] = $this->db->idate($this->{$field});
  8045. }
  8046. } elseif ($this->isDuration($info)) {
  8047. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8048. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8049. if (!isset($this->{$field})) {
  8050. if (!empty($info['default'])) {
  8051. $queryarray[$field] = $info['default'];
  8052. } else {
  8053. $queryarray[$field] = 0;
  8054. }
  8055. } else {
  8056. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8057. }
  8058. } else {
  8059. $queryarray[$field] = null;
  8060. }
  8061. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  8062. if ($field == 'entity' && is_null($this->{$field})) {
  8063. $queryarray[$field] = ((int) $conf->entity);
  8064. } else {
  8065. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8066. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8067. if (!isset($this->{$field})) {
  8068. $queryarray[$field] = 0;
  8069. } elseif ($this->isInt($info)) {
  8070. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8071. } elseif ($this->isFloat($info)) {
  8072. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8073. }
  8074. } else {
  8075. $queryarray[$field] = null;
  8076. }
  8077. }
  8078. } else {
  8079. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  8080. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  8081. $queryarray[$field] = $this->{$field};
  8082. }
  8083. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  8084. unset($queryarray[$field]);
  8085. }
  8086. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  8087. $queryarray[$field] = null; // May force 0 to null
  8088. }
  8089. }
  8090. return $queryarray;
  8091. }
  8092. /**
  8093. * Function to load data from a SQL pointer into properties of current object $this
  8094. *
  8095. * @param stdClass $obj Contain data of object from database
  8096. * @return void
  8097. */
  8098. public function setVarsFromFetchObj(&$obj)
  8099. {
  8100. global $db;
  8101. foreach ($this->fields as $field => $info) {
  8102. if ($this->isDate($info)) {
  8103. if (is_null($obj->$field) || $obj->$field === '' || $obj->$field === '0000-00-00 00:00:00' || $obj->$field === '1000-01-01 00:00:00') {
  8104. $this->$field = '';
  8105. } else {
  8106. $this->$field = $db->jdate($obj->$field);
  8107. }
  8108. } elseif ($this->isInt($info)) {
  8109. if ($field == 'rowid') {
  8110. $this->id = (int) $obj->$field;
  8111. } else {
  8112. if ($this->isForcedToNullIfZero($info)) {
  8113. if (empty($obj->$field)) {
  8114. $this->$field = null;
  8115. } else {
  8116. $this->$field = (double) $obj->$field;
  8117. }
  8118. } else {
  8119. if (!is_null($obj->$field) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8120. $this->$field = (int) $obj->$field;
  8121. } else {
  8122. $this->$field = null;
  8123. }
  8124. }
  8125. }
  8126. } elseif ($this->isFloat($info)) {
  8127. if ($this->isForcedToNullIfZero($info)) {
  8128. if (empty($obj->$field)) {
  8129. $this->$field = null;
  8130. } else {
  8131. $this->$field = (double) $obj->$field;
  8132. }
  8133. } else {
  8134. if (!is_null($obj->$field) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8135. $this->$field = (double) $obj->$field;
  8136. } else {
  8137. $this->$field = null;
  8138. }
  8139. }
  8140. } else {
  8141. $this->$field = isset($obj->$field) ? $obj->$field : null;
  8142. }
  8143. }
  8144. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  8145. if (!isset($this->fields['ref']) && isset($this->id)) {
  8146. $this->ref = $this->id;
  8147. }
  8148. }
  8149. /**
  8150. * Sets all object fields to null. Useful for example in lists, when printing multiple lines and a different object os fetched for each line.
  8151. * @return void
  8152. */
  8153. public function emtpyObjectVars()
  8154. {
  8155. foreach ($this->fields as $field => $arr) {
  8156. $this->$field = null;
  8157. }
  8158. }
  8159. /**
  8160. * Function to concat keys of fields
  8161. *
  8162. * @param string $alias String of alias of table for fields. For example 't'. It is recommended to use '' and set alias into fields defintion.
  8163. * @return string list of alias fields
  8164. */
  8165. public function getFieldList($alias = '')
  8166. {
  8167. $keys = array_keys($this->fields);
  8168. if (!empty($alias)) {
  8169. $keys_with_alias = array();
  8170. foreach ($keys as $fieldname) {
  8171. $keys_with_alias[] = $alias . '.' . $fieldname;
  8172. }
  8173. return implode(',', $keys_with_alias);
  8174. } else {
  8175. return implode(',', $keys);
  8176. }
  8177. }
  8178. /**
  8179. * Add quote to field value if necessary
  8180. *
  8181. * @param string|int $value Value to protect
  8182. * @param array $fieldsentry Properties of field
  8183. * @return string
  8184. */
  8185. protected function quote($value, $fieldsentry)
  8186. {
  8187. if (is_null($value)) {
  8188. return 'NULL';
  8189. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  8190. return price2num("$value");
  8191. } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
  8192. return (int) $value;
  8193. } elseif ($fieldsentry['type'] == 'boolean') {
  8194. if ($value) {
  8195. return 'true';
  8196. } else {
  8197. return 'false';
  8198. }
  8199. } else {
  8200. return "'".$this->db->escape($value)."'";
  8201. }
  8202. }
  8203. /**
  8204. * Create object into database
  8205. *
  8206. * @param User $user User that creates
  8207. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8208. * @return int <0 if KO, Id of created object if OK
  8209. */
  8210. public function createCommon(User $user, $notrigger = false)
  8211. {
  8212. global $langs;
  8213. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  8214. $error = 0;
  8215. $now = dol_now();
  8216. $fieldvalues = $this->setSaveQuery();
  8217. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  8218. $fieldvalues['date_creation'] = $this->db->idate($now);
  8219. }
  8220. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  8221. $fieldvalues['fk_user_creat'] = $user->id;
  8222. }
  8223. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  8224. if (array_key_exists('ref', $fieldvalues)) {
  8225. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8226. }
  8227. $keys = array();
  8228. $values = array(); // Array to store string forged for SQL syntax
  8229. foreach ($fieldvalues as $k => $v) {
  8230. $keys[$k] = $k;
  8231. $value = $this->fields[$k];
  8232. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  8233. }
  8234. // Clean and check mandatory
  8235. foreach ($keys as $key) {
  8236. // If field is an implicit foreign key field (so type = 'integer:...')
  8237. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8238. $values[$key] = '';
  8239. }
  8240. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8241. $values[$key] = '';
  8242. }
  8243. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  8244. $error++;
  8245. $langs->load("errors");
  8246. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  8247. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8248. }
  8249. // If value is null and there is a default value for field
  8250. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  8251. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  8252. }
  8253. // If field is an implicit foreign key field (so type = 'integer:...')
  8254. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  8255. if (isset($this->fields[$key]['default'])) {
  8256. $values[$key] = ((int) $this->fields[$key]['default']);
  8257. } else {
  8258. $values[$key] = 'null';
  8259. }
  8260. }
  8261. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  8262. $values[$key] = 'null';
  8263. }
  8264. }
  8265. if ($error) {
  8266. return -1;
  8267. }
  8268. $this->db->begin();
  8269. if (!$error) {
  8270. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  8271. $sql .= " (".implode(", ", $keys).')';
  8272. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  8273. $res = $this->db->query($sql);
  8274. if (!$res) {
  8275. $error++;
  8276. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  8277. $this->errors[] = "ErrorRefAlreadyExists";
  8278. } else {
  8279. $this->errors[] = $this->db->lasterror();
  8280. }
  8281. }
  8282. }
  8283. if (!$error) {
  8284. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  8285. }
  8286. // If we have a field ref with a default value of (PROV)
  8287. if (!$error) {
  8288. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  8289. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  8290. $resqlupdate = $this->db->query($sql);
  8291. if ($resqlupdate === false) {
  8292. $error++;
  8293. $this->errors[] = $this->db->lasterror();
  8294. } else {
  8295. $this->ref = '(PROV'.$this->id.')';
  8296. }
  8297. }
  8298. }
  8299. // Create extrafields
  8300. if (!$error) {
  8301. $result = $this->insertExtraFields();
  8302. if ($result < 0) {
  8303. $error++;
  8304. }
  8305. }
  8306. // Create lines
  8307. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8308. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8309. for ($i = 0; $i < $num; $i++) {
  8310. $line = $this->lines[$i];
  8311. $keyforparent = $this->fk_element;
  8312. $line->$keyforparent = $this->id;
  8313. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8314. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8315. if (!is_object($line)) {
  8316. $line = (object) $line;
  8317. }
  8318. $result = $line->create($user, 1);
  8319. if ($result < 0) {
  8320. $this->error = $line->error;
  8321. $this->db->rollback();
  8322. return -1;
  8323. }
  8324. }
  8325. }
  8326. // Triggers
  8327. if (!$error && !$notrigger) {
  8328. // Call triggers
  8329. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  8330. if ($result < 0) {
  8331. $error++;
  8332. }
  8333. // End call triggers
  8334. }
  8335. // Commit or rollback
  8336. if ($error) {
  8337. $this->db->rollback();
  8338. return -1;
  8339. } else {
  8340. $this->db->commit();
  8341. return $this->id;
  8342. }
  8343. }
  8344. /**
  8345. * Load object in memory from the database
  8346. *
  8347. * @param int $id Id object
  8348. * @param string $ref Ref
  8349. * @param string $morewhere More SQL filters (' AND ...')
  8350. * @return int <0 if KO, 0 if not found, >0 if OK
  8351. */
  8352. public function fetchCommon($id, $ref = null, $morewhere = '')
  8353. {
  8354. if (empty($id) && empty($ref) && empty($morewhere)) {
  8355. return -1;
  8356. }
  8357. $fieldlist = $this->getFieldList('t');
  8358. if (empty($fieldlist)) {
  8359. return 0;
  8360. }
  8361. $sql = "SELECT ".$fieldlist;
  8362. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8363. if (!empty($id)) {
  8364. $sql .= ' WHERE t.rowid = '.((int) $id);
  8365. } elseif (!empty($ref)) {
  8366. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8367. } else {
  8368. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8369. }
  8370. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8371. $sql .= ' AND t.entity IN ('.getEntity($this->element).')';
  8372. }
  8373. if ($morewhere) {
  8374. $sql .= $morewhere;
  8375. }
  8376. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8377. $res = $this->db->query($sql);
  8378. if ($res) {
  8379. $obj = $this->db->fetch_object($res);
  8380. if ($obj) {
  8381. $this->setVarsFromFetchObj($obj);
  8382. // Retrieve all extrafield
  8383. // fetch optionals attributes and labels
  8384. $this->fetch_optionals();
  8385. return $this->id;
  8386. } else {
  8387. return 0;
  8388. }
  8389. } else {
  8390. $this->error = $this->db->lasterror();
  8391. $this->errors[] = $this->error;
  8392. return -1;
  8393. }
  8394. }
  8395. /**
  8396. * Load object in memory from the database
  8397. *
  8398. * @param string $morewhere More SQL filters (' AND ...')
  8399. * @return int <0 if KO, 0 if not found, >0 if OK
  8400. */
  8401. public function fetchLinesCommon($morewhere = '')
  8402. {
  8403. $objectlineclassname = get_class($this).'Line';
  8404. if (!class_exists($objectlineclassname)) {
  8405. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8406. return -1;
  8407. }
  8408. $objectline = new $objectlineclassname($this->db);
  8409. $sql = "SELECT ".$objectline->getFieldList('l');
  8410. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8411. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8412. if ($morewhere) {
  8413. $sql .= $morewhere;
  8414. }
  8415. if (isset($objectline->fields['position'])) {
  8416. $sql .= $this->db->order('position', 'ASC');
  8417. }
  8418. $resql = $this->db->query($sql);
  8419. if ($resql) {
  8420. $num_rows = $this->db->num_rows($resql);
  8421. $i = 0;
  8422. while ($i < $num_rows) {
  8423. $obj = $this->db->fetch_object($resql);
  8424. if ($obj) {
  8425. $newline = new $objectlineclassname($this->db);
  8426. $newline->setVarsFromFetchObj($obj);
  8427. $this->lines[] = $newline;
  8428. }
  8429. $i++;
  8430. }
  8431. return 1;
  8432. } else {
  8433. $this->error = $this->db->lasterror();
  8434. $this->errors[] = $this->error;
  8435. return -1;
  8436. }
  8437. }
  8438. /**
  8439. * Update object into database
  8440. *
  8441. * @param User $user User that modifies
  8442. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8443. * @return int <0 if KO, >0 if OK
  8444. */
  8445. public function updateCommon(User $user, $notrigger = false)
  8446. {
  8447. global $conf, $langs;
  8448. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8449. $error = 0;
  8450. $now = dol_now();
  8451. // $this->oldcopy should have been set by the caller of update
  8452. //if (empty($this->oldcopy)) {
  8453. // $this->oldcopy = dol_clone($this);
  8454. //}
  8455. $fieldvalues = $this->setSaveQuery();
  8456. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8457. $fieldvalues['date_modification'] = $this->db->idate($now);
  8458. }
  8459. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8460. $fieldvalues['fk_user_modif'] = $user->id;
  8461. }
  8462. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8463. if (array_key_exists('ref', $fieldvalues)) {
  8464. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8465. }
  8466. // Add quotes and escape on fields with type string
  8467. $keys = array();
  8468. $values = array();
  8469. $tmp = array();
  8470. foreach ($fieldvalues as $k => $v) {
  8471. $keys[$k] = $k;
  8472. $value = $this->fields[$k];
  8473. $values[$k] = $this->quote($v, $value);
  8474. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8475. }
  8476. // Clean and check mandatory fields
  8477. foreach ($keys as $key) {
  8478. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8479. $values[$key] = ''; // This is an implicit foreign key field
  8480. }
  8481. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8482. $values[$key] = ''; // This is an explicit foreign key field
  8483. }
  8484. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8485. /*
  8486. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8487. {
  8488. $error++;
  8489. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8490. }*/
  8491. }
  8492. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8493. $this->db->begin();
  8494. if (!$error) {
  8495. $res = $this->db->query($sql);
  8496. if (!$res) {
  8497. $error++;
  8498. $this->errors[] = $this->db->lasterror();
  8499. }
  8500. }
  8501. // Update extrafield
  8502. if (!$error) {
  8503. $result = $this->insertExtraFields();
  8504. if ($result < 0) {
  8505. $error++;
  8506. }
  8507. }
  8508. // Triggers
  8509. if (!$error && !$notrigger) {
  8510. // Call triggers
  8511. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8512. if ($result < 0) {
  8513. $error++;
  8514. } //Do also here what you must do to rollback action if trigger fail
  8515. // End call triggers
  8516. }
  8517. // Commit or rollback
  8518. if ($error) {
  8519. $this->db->rollback();
  8520. return -1;
  8521. } else {
  8522. $this->db->commit();
  8523. return $this->id;
  8524. }
  8525. }
  8526. /**
  8527. * Delete object in database
  8528. *
  8529. * @param User $user User that deletes
  8530. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8531. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8532. * @return int <0 if KO, 0=Nothing done because object has child, >0 if OK
  8533. */
  8534. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8535. {
  8536. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8537. $error = 0;
  8538. $this->db->begin();
  8539. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8540. foreach ($this->childtables as $table) {
  8541. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8542. $resql = $this->db->query($sql);
  8543. if (!$resql) {
  8544. $this->error = $this->db->lasterror();
  8545. $this->errors[] = $this->error;
  8546. $this->db->rollback();
  8547. return -1;
  8548. }
  8549. }
  8550. } elseif (!empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8551. $objectisused = $this->isObjectUsed($this->id);
  8552. if (!empty($objectisused)) {
  8553. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8554. $this->error = 'ErrorRecordHasChildren';
  8555. $this->errors[] = $this->error;
  8556. $this->db->rollback();
  8557. return 0;
  8558. }
  8559. }
  8560. // Delete cascade first
  8561. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8562. foreach ($this->childtablesoncascade as $table) {
  8563. $deleteFromObject = explode(':', $table);
  8564. if (count($deleteFromObject) >= 2) {
  8565. $className = str_replace('@', '', $deleteFromObject[0]);
  8566. $filePath = $deleteFromObject[1];
  8567. $columnName = $deleteFromObject[2];
  8568. $TMoreSQL = array();
  8569. $more_sql = $deleteFromObject[3];
  8570. if (!empty($more_sql)) {
  8571. $TMoreSQL['customsql'] = $more_sql;
  8572. }
  8573. if (dol_include_once($filePath)) {
  8574. $childObject = new $className($this->db);
  8575. if (method_exists($childObject, 'deleteByParentField')) {
  8576. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8577. if ($result < 0) {
  8578. $error++;
  8579. $this->errors[] = $childObject->error;
  8580. break;
  8581. }
  8582. } else {
  8583. $error++;
  8584. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8585. break;
  8586. }
  8587. } else {
  8588. $error++;
  8589. $this->errors[] = 'Cannot include child class file '.$filePath;
  8590. break;
  8591. }
  8592. } else {
  8593. // Delete record in child table
  8594. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8595. $resql = $this->db->query($sql);
  8596. if (!$resql) {
  8597. $error++;
  8598. $this->error = $this->db->lasterror();
  8599. $this->errors[] = $this->error;
  8600. break;
  8601. }
  8602. }
  8603. }
  8604. }
  8605. if (!$error) {
  8606. if (!$notrigger) {
  8607. // Call triggers
  8608. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8609. if ($result < 0) {
  8610. $error++;
  8611. } // Do also here what you must do to rollback action if trigger fail
  8612. // End call triggers
  8613. }
  8614. }
  8615. // Delete llx_ecm_files
  8616. if (!$error) {
  8617. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8618. if (!$res) {
  8619. $error++;
  8620. }
  8621. }
  8622. // Delete linked object
  8623. $res = $this->deleteObjectLinked();
  8624. if ($res < 0) {
  8625. $error++;
  8626. }
  8627. if (!$error && !empty($this->isextrafieldmanaged)) {
  8628. $result = $this->deleteExtraFields();
  8629. if ($result < 0) {
  8630. $error++;
  8631. }
  8632. }
  8633. if (!$error) {
  8634. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8635. $resql = $this->db->query($sql);
  8636. if (!$resql) {
  8637. $error++;
  8638. $this->errors[] = $this->db->lasterror();
  8639. }
  8640. }
  8641. // Commit or rollback
  8642. if ($error) {
  8643. $this->db->rollback();
  8644. return -1;
  8645. } else {
  8646. $this->db->commit();
  8647. return 1;
  8648. }
  8649. }
  8650. /**
  8651. * Delete all child object from a parent ID
  8652. *
  8653. * @param int $parentId Parent Id
  8654. * @param string $parentField Name of Foreign key parent column
  8655. * @param array $filter an array filter
  8656. * @param string $filtermode AND or OR
  8657. * @return int <0 if KO, >0 if OK
  8658. * @throws Exception
  8659. */
  8660. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8661. {
  8662. global $user;
  8663. $error = 0;
  8664. $deleted = 0;
  8665. if (!empty($parentId) && !empty($parentField)) {
  8666. $this->db->begin();
  8667. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8668. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8669. // Manage filters
  8670. $sqlwhere = array();
  8671. if (count($filter) > 0) {
  8672. foreach ($filter as $key => $value) {
  8673. if ($key == 'customsql') {
  8674. $sqlwhere[] = $value;
  8675. } elseif (strpos($value, '%') === false) {
  8676. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8677. } else {
  8678. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8679. }
  8680. }
  8681. }
  8682. if (count($sqlwhere) > 0) {
  8683. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8684. }
  8685. $resql = $this->db->query($sql);
  8686. if (!$resql) {
  8687. $this->errors[] = $this->db->lasterror();
  8688. $error++;
  8689. } else {
  8690. while ($obj = $this->db->fetch_object($resql)) {
  8691. $result = $this->fetch($obj->rowid);
  8692. if ($result < 0) {
  8693. $error++;
  8694. $this->errors[] = $this->error;
  8695. } else {
  8696. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8697. $result = $this->delete();
  8698. } else {
  8699. $result = $this->delete($user);
  8700. }
  8701. if ($result < 0) {
  8702. $error++;
  8703. $this->errors[] = $this->error;
  8704. } else {
  8705. $deleted++;
  8706. }
  8707. }
  8708. }
  8709. }
  8710. if (empty($error)) {
  8711. $this->db->commit();
  8712. return $deleted;
  8713. } else {
  8714. $this->error = implode(', ', $this->errors);
  8715. $this->db->rollback();
  8716. return $error * -1;
  8717. }
  8718. }
  8719. return $deleted;
  8720. }
  8721. /**
  8722. * Delete a line of object in database
  8723. *
  8724. * @param User $user User that delete
  8725. * @param int $idline Id of line to delete
  8726. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8727. * @return int >0 if OK, <0 if KO
  8728. */
  8729. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8730. {
  8731. global $conf;
  8732. $error = 0;
  8733. $tmpforobjectclass = get_class($this);
  8734. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8735. $this->db->begin();
  8736. // Call trigger
  8737. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8738. if ($result < 0) {
  8739. $error++;
  8740. }
  8741. // End call triggers
  8742. if (empty($error)) {
  8743. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8744. $sql .= " WHERE rowid = ".((int) $idline);
  8745. $resql = $this->db->query($sql);
  8746. if (!$resql) {
  8747. $this->error = "Error ".$this->db->lasterror();
  8748. $error++;
  8749. }
  8750. }
  8751. if (empty($error)) {
  8752. // Remove extrafields
  8753. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8754. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8755. $tmpobjectline->id = $idline;
  8756. $result = $tmpobjectline->deleteExtraFields();
  8757. if ($result < 0) {
  8758. $error++;
  8759. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8760. }
  8761. }
  8762. }
  8763. if (empty($error)) {
  8764. $this->db->commit();
  8765. return 1;
  8766. } else {
  8767. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8768. $this->db->rollback();
  8769. return -1;
  8770. }
  8771. }
  8772. /**
  8773. * Set to a status
  8774. *
  8775. * @param User $user Object user that modify
  8776. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8777. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8778. * @param string $triggercode Trigger code to use
  8779. * @return int <0 if KO, >0 if OK
  8780. */
  8781. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8782. {
  8783. $error = 0;
  8784. $this->db->begin();
  8785. $statusfield = 'status';
  8786. if (in_array($this->element, array('don', 'donation', 'shipping'))) {
  8787. $statusfield = 'fk_statut';
  8788. }
  8789. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8790. $sql .= " SET ".$statusfield." = ".((int) $status);
  8791. $sql .= " WHERE rowid = ".((int) $this->id);
  8792. if ($this->db->query($sql)) {
  8793. if (!$error) {
  8794. $this->oldcopy = clone $this;
  8795. }
  8796. if (!$error && !$notrigger) {
  8797. // Call trigger
  8798. $result = $this->call_trigger($triggercode, $user);
  8799. if ($result < 0) {
  8800. $error++;
  8801. }
  8802. }
  8803. if (!$error) {
  8804. $this->status = $status;
  8805. $this->db->commit();
  8806. return 1;
  8807. } else {
  8808. $this->db->rollback();
  8809. return -1;
  8810. }
  8811. } else {
  8812. $this->error = $this->db->error();
  8813. $this->db->rollback();
  8814. return -1;
  8815. }
  8816. }
  8817. /**
  8818. * Initialise object with example values
  8819. * Id must be 0 if object instance is a specimen
  8820. *
  8821. * @return int
  8822. */
  8823. public function initAsSpecimenCommon()
  8824. {
  8825. global $user;
  8826. $this->id = 0;
  8827. $this->specimen = 1;
  8828. $fields = array(
  8829. 'label' => 'This is label',
  8830. 'ref' => 'ABCD1234',
  8831. 'description' => 'This is a description',
  8832. 'qty' => 123.12,
  8833. 'note_public' => 'Public note',
  8834. 'note_private' => 'Private note',
  8835. 'date_creation' => (dol_now() - 3600 * 48),
  8836. 'date_modification' => (dol_now() - 3600 * 24),
  8837. 'fk_user_creat' => $user->id,
  8838. 'fk_user_modif' => $user->id,
  8839. 'date' => dol_now(),
  8840. );
  8841. foreach ($fields as $key => $value) {
  8842. if (array_key_exists($key, $this->fields)) {
  8843. $this->{$key} = $value;
  8844. }
  8845. }
  8846. // Force values to default values when known
  8847. if (property_exists($this, 'fields')) {
  8848. foreach ($this->fields as $key => $value) {
  8849. // If fields are already set, do nothing
  8850. if (array_key_exists($key, $fields)) {
  8851. continue;
  8852. }
  8853. if (!empty($value['default'])) {
  8854. $this->$key = $value['default'];
  8855. }
  8856. }
  8857. }
  8858. return 1;
  8859. }
  8860. /* Part for comments */
  8861. /**
  8862. * Load comments linked with current task
  8863. * @return boolean 1 if ok
  8864. */
  8865. public function fetchComments()
  8866. {
  8867. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8868. $comment = new Comment($this->db);
  8869. $result = $comment->fetchAllFor($this->element, $this->id);
  8870. if ($result < 0) {
  8871. $this->errors = array_merge($this->errors, $comment->errors);
  8872. return -1;
  8873. } else {
  8874. $this->comments = $comment->comments;
  8875. }
  8876. return count($this->comments);
  8877. }
  8878. /**
  8879. * Return nb comments already posted
  8880. *
  8881. * @return int
  8882. */
  8883. public function getNbComments()
  8884. {
  8885. return count($this->comments);
  8886. }
  8887. /**
  8888. * Trim object parameters
  8889. *
  8890. * @param string[] $parameters array of parameters to trim
  8891. * @return void
  8892. */
  8893. public function trimParameters($parameters)
  8894. {
  8895. if (!is_array($parameters)) {
  8896. return;
  8897. }
  8898. foreach ($parameters as $parameter) {
  8899. if (isset($this->$parameter)) {
  8900. $this->$parameter = trim($this->$parameter);
  8901. }
  8902. }
  8903. }
  8904. /* Part for categories/tags */
  8905. /**
  8906. * Sets object to given categories.
  8907. *
  8908. * Deletes object from existing categories not supplied.
  8909. * Adds it to non existing supplied categories.
  8910. * Existing categories are left untouch.
  8911. *
  8912. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8913. * @return int Array of category objects or < 0 if KO
  8914. */
  8915. public function getCategoriesCommon($type_categ)
  8916. {
  8917. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8918. // Get current categories
  8919. $c = new Categorie($this->db);
  8920. $existing = $c->containing($this->id, $type_categ, 'id');
  8921. return $existing;
  8922. }
  8923. /**
  8924. * Sets object to given categories.
  8925. *
  8926. * Adds it to non existing supplied categories.
  8927. * Deletes object from existing categories not supplied (if remove_existing==true).
  8928. * Existing categories are left untouch.
  8929. *
  8930. * @param int[]|int $categories Category ID or array of Categories IDs
  8931. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8932. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8933. * @return int <0 if KO, >0 if OK
  8934. */
  8935. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8936. {
  8937. // Handle single category
  8938. if (!is_array($categories)) {
  8939. $categories = array($categories);
  8940. }
  8941. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8942. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8943. if (empty($type_categ)) {
  8944. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8945. return -1;
  8946. }
  8947. // Get current categories
  8948. $c = new Categorie($this->db);
  8949. $existing = $c->containing($this->id, $type_categ, 'id');
  8950. if ($remove_existing) {
  8951. // Diff
  8952. if (is_array($existing)) {
  8953. $to_del = array_diff($existing, $categories);
  8954. $to_add = array_diff($categories, $existing);
  8955. } else {
  8956. $to_del = array(); // Nothing to delete
  8957. $to_add = $categories;
  8958. }
  8959. } else {
  8960. $to_del = array(); // Nothing to delete
  8961. $to_add = array_diff($categories, $existing);
  8962. }
  8963. $error = 0;
  8964. $ok = 0;
  8965. // Process
  8966. foreach ($to_del as $del) {
  8967. if ($c->fetch($del) > 0) {
  8968. $result=$c->del_type($this, $type_categ);
  8969. if ($result < 0) {
  8970. $error++;
  8971. $this->error = $c->error;
  8972. $this->errors = $c->errors;
  8973. break;
  8974. } else {
  8975. $ok += $result;
  8976. }
  8977. }
  8978. }
  8979. foreach ($to_add as $add) {
  8980. if ($c->fetch($add) > 0) {
  8981. $result = $c->add_type($this, $type_categ);
  8982. if ($result < 0) {
  8983. $error++;
  8984. $this->error = $c->error;
  8985. $this->errors = $c->errors;
  8986. break;
  8987. } else {
  8988. $ok += $result;
  8989. }
  8990. }
  8991. }
  8992. return $error ? (-1 * $error) : $ok;
  8993. }
  8994. /**
  8995. * Copy related categories to another object
  8996. *
  8997. * @param int $fromId Id object source
  8998. * @param int $toId Id object cible
  8999. * @param string $type Type of category ('product', ...)
  9000. * @return int < 0 if error, > 0 if ok
  9001. */
  9002. public function cloneCategories($fromId, $toId, $type = '')
  9003. {
  9004. $this->db->begin();
  9005. if (empty($type)) {
  9006. $type = $this->table_element;
  9007. }
  9008. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  9009. $categorystatic = new Categorie($this->db);
  9010. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  9011. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  9012. $sql .= " WHERE fk_product = ".((int) $fromId);
  9013. if (!$this->db->query($sql)) {
  9014. $this->error = $this->db->lasterror();
  9015. $this->db->rollback();
  9016. return -1;
  9017. }
  9018. $this->db->commit();
  9019. return 1;
  9020. }
  9021. /**
  9022. * Delete related files of object in database
  9023. *
  9024. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  9025. * @return bool True if OK, False if KO
  9026. */
  9027. public function deleteEcmFiles($mode = 0)
  9028. {
  9029. global $conf;
  9030. $this->db->begin();
  9031. // Delete in database with mode 0
  9032. if ($mode == 0) {
  9033. switch ($this->element) {
  9034. case 'propal':
  9035. $element = 'propale';
  9036. break;
  9037. case 'product':
  9038. $element = 'produit';
  9039. break;
  9040. case 'order_supplier':
  9041. $element = 'fournisseur/commande';
  9042. break;
  9043. case 'invoice_supplier':
  9044. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  9045. break;
  9046. case 'shipping':
  9047. $element = 'expedition/sending';
  9048. break;
  9049. default:
  9050. $element = $this->element;
  9051. }
  9052. // Delete ecm_files extrafields
  9053. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  9054. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  9055. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  9056. $sql .= ")";
  9057. if (!$this->db->query($sql)) {
  9058. $this->error = $this->db->lasterror();
  9059. $this->db->rollback();
  9060. return false;
  9061. }
  9062. // Delete ecm_files
  9063. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  9064. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  9065. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  9066. if (!$this->db->query($sql)) {
  9067. $this->error = $this->db->lasterror();
  9068. $this->db->rollback();
  9069. return false;
  9070. }
  9071. }
  9072. // Delete in database with mode 1
  9073. if ($mode == 1) {
  9074. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  9075. $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).")";
  9076. $resql = $this->db->query($sql);
  9077. if (!$resql) {
  9078. $this->error = $this->db->lasterror();
  9079. $this->db->rollback();
  9080. return false;
  9081. }
  9082. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  9083. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  9084. $resql = $this->db->query($sql);
  9085. if (!$resql) {
  9086. $this->error = $this->db->lasterror();
  9087. $this->db->rollback();
  9088. return false;
  9089. }
  9090. }
  9091. $this->db->commit();
  9092. return true;
  9093. }
  9094. }