commonobject.class.php 347 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2019 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015-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-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/core/class/commonobject.class.php
  35. * \ingroup core
  36. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  37. */
  38. /**
  39. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  40. */
  41. abstract class CommonObject
  42. {
  43. const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
  44. /**
  45. * @var DoliDb Database handler (result of a new DoliDB)
  46. */
  47. public $db;
  48. /**
  49. * @var int The object identifier
  50. */
  51. public $id;
  52. /**
  53. * @var int The environment ID when using a multicompany module
  54. */
  55. public $entity;
  56. /**
  57. * @var string Error string
  58. * @see $errors
  59. */
  60. public $error;
  61. /**
  62. * @var string Error string that is hidden but can be used to store complementatry technical code.
  63. */
  64. public $errorhidden;
  65. /**
  66. * @var string[] Array of error strings
  67. */
  68. public $errors = array();
  69. /**
  70. * @var array To store error results of ->validateField()
  71. */
  72. public $validateFieldsErrors = array();
  73. /**
  74. * @var string ID to identify managed object
  75. */
  76. public $element;
  77. /**
  78. * @var string Name to use for 'features' parameter to check module permissions with restrictedArea(). Undefined means same value than $element.
  79. */
  80. public $element_for_permission;
  81. /**
  82. * @var string Name of table without prefix where object is stored
  83. */
  84. public $table_element;
  85. /**
  86. * @var string Name of subtable line
  87. */
  88. public $table_element_line = '';
  89. /**
  90. * @var string Key value used to track if data is coming from import wizard
  91. */
  92. public $import_key;
  93. /**
  94. * @var mixed Contains data to manage extrafields
  95. */
  96. public $array_options = array();
  97. /**
  98. * @var mixed Array to store alternative languages values of object
  99. */
  100. public $array_languages = null; // Value is array() when load already tried
  101. /**
  102. * @var array To store result of ->liste_contact()
  103. */
  104. public $contacts_ids;
  105. /**
  106. * @var mixed Array of linked objects, set and used when calling ->create() to be able to create links during the creation of object
  107. */
  108. public $linked_objects;
  109. /**
  110. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  111. */
  112. public $linkedObjectsIds;
  113. /**
  114. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  115. */
  116. public $linkedObjects;
  117. /**
  118. * @var boolean Array of boolean with object id as key and value as true if linkedObjects full loaded. Loaded by ->fetchObjectLinked. Important for pdf generation time reduction.
  119. */
  120. public $linkedObjectsFullLoaded = array();
  121. /**
  122. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  123. */
  124. public $oldcopy;
  125. /**
  126. * @var string Column name of the ref field.
  127. */
  128. protected $table_ref_field = '';
  129. /**
  130. * @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
  131. */
  132. public $restrictiononfksoc = 0;
  133. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  134. /**
  135. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  136. */
  137. public $context = array();
  138. /**
  139. * @var string Contains canvas name if record is an alternative canvas record
  140. */
  141. public $canvas;
  142. /**
  143. * @var Project The related project object
  144. * @see fetch_projet()
  145. */
  146. public $project;
  147. /**
  148. * @var int The related project ID
  149. * @see setProject(), project
  150. */
  151. public $fk_project;
  152. /**
  153. * @deprecated
  154. * @see project
  155. */
  156. public $projet;
  157. /**
  158. * @deprecated
  159. * @see $fk_project
  160. */
  161. public $fk_projet;
  162. /**
  163. * @var Contact A related contact object
  164. * @see fetch_contact()
  165. */
  166. public $contact;
  167. /**
  168. * @var int The related contact ID
  169. * @see fetch_contact()
  170. */
  171. public $contact_id;
  172. /**
  173. * @var Societe A related thirdparty object
  174. * @see fetch_thirdparty()
  175. */
  176. public $thirdparty;
  177. /**
  178. * @var User A related user
  179. * @see fetch_user()
  180. */
  181. public $user;
  182. /**
  183. * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type
  184. * @see fetch_origin()
  185. */
  186. public $origin;
  187. /**
  188. * @var int The id of originating object
  189. * @see fetch_origin()
  190. */
  191. public $origin_id;
  192. /**
  193. * @var string The object's reference
  194. */
  195. public $ref;
  196. /**
  197. * @var string An external reference for the object
  198. */
  199. public $ref_ext;
  200. /**
  201. * @var string The object's previous reference
  202. */
  203. public $ref_previous;
  204. /**
  205. * @var string The object's next reference
  206. */
  207. public $ref_next;
  208. /**
  209. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  210. */
  211. public $newref;
  212. /**
  213. * @var int The object's status. Prefer use of status.
  214. * @see setStatut()
  215. */
  216. public $statut;
  217. /**
  218. * @var int The object's status
  219. * @see setStatut()
  220. */
  221. public $status;
  222. /**
  223. * @var string
  224. * @see getFullAddress()
  225. */
  226. public $country;
  227. /**
  228. * @var int
  229. * @see getFullAddress(), country
  230. */
  231. public $country_id;
  232. /**
  233. * @var string The ISO country code on 2 chars.
  234. * @see getFullAddress(), isInEEC(), country
  235. */
  236. public $country_code;
  237. /**
  238. * @var string
  239. * @see getFullAddress()
  240. */
  241. public $state;
  242. /**
  243. * @var int
  244. * @see getFullAddress(), state
  245. */
  246. public $state_id;
  247. /**
  248. * @var string
  249. * @see getFullAddress(), $state
  250. */
  251. public $state_code;
  252. /**
  253. * @var int
  254. * @see getFullAddress(), $region_code, $region
  255. */
  256. public $region_id;
  257. /**
  258. * @var string
  259. * @see getFullAddress(), $region_id, $region
  260. */
  261. public $region_code;
  262. /**
  263. * @var string
  264. * @see getFullAddress(), $region_id, $region_code
  265. */
  266. public $region;
  267. /**
  268. * @var int
  269. * @see fetch_barcode()
  270. */
  271. public $barcode_type;
  272. /**
  273. * @var string
  274. * @see fetch_barcode(), barcode_type
  275. */
  276. public $barcode_type_code;
  277. /**
  278. * @var string
  279. * @see fetch_barcode(), barcode_type
  280. */
  281. public $barcode_type_label;
  282. /**
  283. * @var string
  284. * @see fetch_barcode(), barcode_type
  285. */
  286. public $barcode_type_coder;
  287. /**
  288. * @var int Payment method ID (cheque, cash, ...)
  289. * @see setPaymentMethods()
  290. */
  291. public $mode_reglement_id;
  292. /**
  293. * @var int Payment terms ID
  294. * @see setPaymentTerms()
  295. */
  296. public $cond_reglement_id;
  297. /**
  298. * @var int Demand reason ID
  299. */
  300. public $demand_reason_id;
  301. /**
  302. * @var int Transport mode ID (For module intracomm report)
  303. * @see setTransportMode()
  304. */
  305. public $transport_mode_id;
  306. /**
  307. * @var int Payment terms ID
  308. * @deprecated Kept for compatibility
  309. * @see cond_reglement_id;
  310. */
  311. public $cond_reglement;
  312. /**
  313. * @var int Delivery address ID
  314. * @see setDeliveryAddress()
  315. * @deprecated
  316. */
  317. public $fk_delivery_address;
  318. /**
  319. * @var int Shipping method ID
  320. * @see setShippingMethod()
  321. */
  322. public $shipping_method_id;
  323. /**
  324. * @var string
  325. * @see SetDocModel()
  326. */
  327. public $model_pdf;
  328. /**
  329. * @var string
  330. * @deprecated
  331. * @see $model_pdf
  332. */
  333. public $modelpdf;
  334. /**
  335. * @var string
  336. * Contains relative path of last generated main file
  337. */
  338. public $last_main_doc;
  339. /**
  340. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  341. * @deprecated
  342. * @see $fk_account
  343. */
  344. public $fk_bank;
  345. /**
  346. * @var int Bank account ID
  347. * @see SetBankAccount()
  348. */
  349. public $fk_account;
  350. /**
  351. * @var string Open ID
  352. */
  353. public $openid;
  354. /**
  355. * @var string Public note
  356. * @see update_note()
  357. */
  358. public $note_public;
  359. /**
  360. * @var string Private note
  361. * @see update_note()
  362. */
  363. public $note_private;
  364. /**
  365. * @deprecated
  366. * @see $note_private
  367. */
  368. public $note;
  369. /**
  370. * @var float Total amount before taxes
  371. * @see update_price()
  372. */
  373. public $total_ht;
  374. /**
  375. * @var float Total VAT amount
  376. * @see update_price()
  377. */
  378. public $total_tva;
  379. /**
  380. * @var float Total local tax 1 amount
  381. * @see update_price()
  382. */
  383. public $total_localtax1;
  384. /**
  385. * @var float Total local tax 2 amount
  386. * @see update_price()
  387. */
  388. public $total_localtax2;
  389. /**
  390. * @var float Total amount with taxes
  391. * @see update_price()
  392. */
  393. public $total_ttc;
  394. /**
  395. * @var CommonObjectLine[]
  396. */
  397. public $lines;
  398. /**
  399. * @var mixed Contains comments
  400. * @see fetchComments()
  401. */
  402. public $comments = array();
  403. /**
  404. * @var string The name
  405. */
  406. public $name;
  407. /**
  408. * @var string The lastname
  409. */
  410. public $lastname;
  411. /**
  412. * @var string The firstname
  413. */
  414. public $firstname;
  415. /**
  416. * @var string The civility code, not an integer
  417. */
  418. public $civility_id;
  419. // Dates
  420. /**
  421. * @var integer|string date_creation
  422. */
  423. public $date_creation;
  424. /**
  425. * @var integer|string $date_validation;
  426. */
  427. public $date_validation; // Date validation
  428. /**
  429. * @var integer|string $date_modification;
  430. */
  431. public $date_modification; // Date last change (tms field)
  432. /**
  433. * @var integer|string $date_cloture;
  434. */
  435. public $date_cloture; // Date closing (tms field)
  436. /**
  437. * @var User|int User author/creation
  438. * @TODO Merge with user_creation
  439. */
  440. public $user_author;
  441. /**
  442. * @var User|int User author/creation
  443. * @TODO Remove type id
  444. */
  445. public $user_creation;
  446. /**
  447. * @var int User id author/creation
  448. */
  449. public $user_creation_id;
  450. /**
  451. * @var User|int User of validation
  452. * @TODO Merge with user_validation
  453. */
  454. public $user_valid;
  455. /**
  456. * @var User|int User of validation
  457. * @TODO Remove type id
  458. */
  459. public $user_validation;
  460. /**
  461. * @var int User id of validation
  462. */
  463. public $user_validation_id;
  464. /**
  465. * @var int User id closing object
  466. */
  467. public $user_closing_id;
  468. /**
  469. * @var User|int User last modifier
  470. * @TODO Remove type id
  471. */
  472. public $user_modification;
  473. /**
  474. * @var int User id last modifier
  475. */
  476. public $user_modification_id;
  477. public $next_prev_filter;
  478. /**
  479. * @var int 1 if object is specimen
  480. */
  481. public $specimen = 0;
  482. /**
  483. * @var int Id of contact to send object (used by the trigger of module Agenda)
  484. */
  485. public $sendtoid;
  486. /**
  487. * @var float Amount already paid (used to show correct status)
  488. */
  489. public $alreadypaid;
  490. /**
  491. * @var array List of child tables. To test if we can delete object.
  492. */
  493. protected $childtables = array();
  494. /**
  495. * @var array List of child tables. To know object to delete on cascade.
  496. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  497. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  498. */
  499. protected $childtablesoncascade = array();
  500. // No constructor as it is an abstract class
  501. /**
  502. * Check an object id/ref exists
  503. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  504. *
  505. * @param string $element String of element ('product', 'facture', ...)
  506. * @param int $id Id of object
  507. * @param string $ref Ref of object to check
  508. * @param string $ref_ext Ref ext of object to check
  509. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  510. */
  511. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  512. {
  513. global $db, $conf;
  514. $sql = "SELECT rowid, ref, ref_ext";
  515. $sql .= " FROM ".$db->prefix().$element;
  516. $sql .= " WHERE entity IN (".getEntity($element).")";
  517. if ($id > 0) {
  518. $sql .= " AND rowid = ".((int) $id);
  519. } elseif ($ref) {
  520. $sql .= " AND ref = '".$db->escape($ref)."'";
  521. } elseif ($ref_ext) {
  522. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  523. } else {
  524. $error = 'ErrorWrongParameters';
  525. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  526. return -1;
  527. }
  528. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  529. $sql .= " AND entity = ".((int) $conf->entity);
  530. }
  531. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  532. $resql = $db->query($sql);
  533. if ($resql) {
  534. $num = $db->num_rows($resql);
  535. if ($num > 0) {
  536. return 1;
  537. } else {
  538. return 0;
  539. }
  540. }
  541. return -1;
  542. }
  543. /**
  544. * Method to output saved errors
  545. *
  546. * @return string String with errors
  547. */
  548. public function errorsToString()
  549. {
  550. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  551. }
  552. /**
  553. * Return customer ref for screen output.
  554. *
  555. * @param string $objref Customer ref
  556. * @return string Customer ref formated
  557. */
  558. public function getFormatedCustomerRef($objref)
  559. {
  560. global $hookmanager;
  561. $parameters = array('objref'=>$objref);
  562. $action = '';
  563. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  564. if ($reshook > 0) {
  565. return $hookmanager->resArray['objref'];
  566. }
  567. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  568. }
  569. /**
  570. * Return supplier ref for screen output.
  571. *
  572. * @param string $objref Supplier ref
  573. * @return string Supplier ref formated
  574. */
  575. public function getFormatedSupplierRef($objref)
  576. {
  577. global $hookmanager;
  578. $parameters = array('objref'=>$objref);
  579. $action = '';
  580. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  581. if ($reshook > 0) {
  582. return $hookmanager->resArray['objref'];
  583. }
  584. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  585. }
  586. /**
  587. * Return full name (civility+' '+name+' '+lastname)
  588. *
  589. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  590. * @param int $option 0=No option, 1=Add civility
  591. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  592. * @param int $maxlen Maximum length
  593. * @return string String with full name
  594. */
  595. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  596. {
  597. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  598. $lastname = $this->lastname;
  599. $firstname = $this->firstname;
  600. if (empty($lastname)) {
  601. $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
  602. }
  603. $ret = '';
  604. if (!empty($option) && !empty($this->civility_code)) {
  605. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  606. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  607. } else {
  608. $ret .= $this->civility_code.' ';
  609. }
  610. }
  611. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  612. return dol_trunc($ret, $maxlen);
  613. }
  614. /**
  615. * Set to upper or ucwords/lower if needed
  616. *
  617. * @return void;
  618. */
  619. public function setUpperOrLowerCase()
  620. {
  621. global $conf;
  622. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  623. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  624. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  625. $this->name = dol_ucwords(dol_strtolower($this->name));
  626. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  627. }
  628. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  629. $this->lastname = dol_strtoupper($this->lastname);
  630. $this->name = dol_strtoupper($this->name);
  631. $this->name_alias = dol_strtoupper($this->name_alias);
  632. }
  633. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  634. $this->address = dol_strtoupper($this->address);
  635. $this->town = dol_strtoupper($this->town);
  636. }
  637. }
  638. /**
  639. * Return clicable link of object (with eventually picto)
  640. *
  641. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  642. * @return string HTML Code for Kanban thumb.
  643. */
  644. public function getKanbanView($option = '')
  645. {
  646. $return = '<div class="box-flex-item box-flex-grow-zero">';
  647. $return .= '<div class="info-box info-box-sm">';
  648. $return .= '<span class="info-box-icon bg-infobox-action">';
  649. $return .= img_picto('', $this->picto);
  650. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  651. $return .= '</span>';
  652. $return .= '<div class="info-box-content">';
  653. $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  654. if (property_exists($this, 'label')) {
  655. $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
  656. }
  657. if (method_exists($this, 'getLibStatut')) {
  658. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
  659. }
  660. $return .= '</div>';
  661. $return .= '</div>';
  662. $return .= '</div>';
  663. return $return;
  664. }
  665. /**
  666. * Return full address of contact
  667. *
  668. * @param int $withcountry 1=Add country into address string
  669. * @param string $sep Separator to use to build string
  670. * @param int $withregion 1=Add region into address string
  671. * @param string $extralangcode User extralanguages as value
  672. * @return string Full address string
  673. */
  674. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  675. {
  676. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  677. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  678. $tmparray = getCountry($this->country_id, 'all');
  679. $this->country_code = $tmparray['code'];
  680. $this->country = $tmparray['label'];
  681. }
  682. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  683. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  684. $tmparray = getState($this->state_id, 'all', 0, 1);
  685. $this->state_code = $tmparray['code'];
  686. $this->state = $tmparray['label'];
  687. $this->region_code = $tmparray['region_code'];
  688. $this->region = $tmparray['region'];
  689. }
  690. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  691. }
  692. /**
  693. * Return full address for banner
  694. *
  695. * @param string $htmlkey HTML id to make banner content unique
  696. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  697. * @return string Full address string
  698. */
  699. public function getBannerAddress($htmlkey, $object)
  700. {
  701. global $conf, $langs, $form, $extralanguages;
  702. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  703. $contactid = 0;
  704. $thirdpartyid = 0;
  705. $elementforaltlanguage = $this->element;
  706. if ($this->element == 'societe') {
  707. $thirdpartyid = $this->id;
  708. }
  709. if ($this->element == 'contact') {
  710. $contactid = $this->id;
  711. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  712. }
  713. if ($this->element == 'user') {
  714. $contactid = $this->contact_id;
  715. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  716. }
  717. $out = '';
  718. $outdone = 0;
  719. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  720. if ($coords) {
  721. if (!empty($conf->use_javascript_ajax)) {
  722. // Add picto with tooltip on map
  723. $namecoords = '';
  724. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  725. $namecoords .= $object->name.'<br>';
  726. }
  727. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  728. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  729. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  730. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  731. $out .= '</a> ';
  732. }
  733. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  734. $outdone++;
  735. $outdone++;
  736. // List of extra languages
  737. $arrayoflangcode = array();
  738. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  739. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  740. }
  741. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  742. if (!is_object($extralanguages)) {
  743. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  744. $extralanguages = new ExtraLanguages($this->db);
  745. }
  746. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  747. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  748. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  749. $this->fetchValuesForExtraLanguages();
  750. if (!is_object($form)) {
  751. $form = new Form($this->db);
  752. }
  753. $htmltext = '';
  754. // If there is extra languages
  755. foreach ($arrayoflangcode as $extralangcode) {
  756. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  757. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  758. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  759. }
  760. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  761. }
  762. }
  763. }
  764. if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
  765. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  766. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  767. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  768. } else {
  769. $out .= ($outdone ? ' - ' : '').$this->state;
  770. }
  771. $outdone++;
  772. }
  773. if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) {
  774. $out .= ($outdone ? '<br>' : '');
  775. }
  776. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  777. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  778. $outdone++;
  779. }
  780. if (!empty($this->phone_pro)) {
  781. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  782. $outdone++;
  783. }
  784. if (!empty($this->phone_mobile)) {
  785. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  786. $outdone++;
  787. }
  788. if (!empty($this->phone_perso)) {
  789. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  790. $outdone++;
  791. }
  792. if (!empty($this->office_phone)) {
  793. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  794. $outdone++;
  795. }
  796. if (!empty($this->user_mobile)) {
  797. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  798. $outdone++;
  799. }
  800. if (!empty($this->fax)) {
  801. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  802. $outdone++;
  803. }
  804. if (!empty($this->office_fax)) {
  805. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  806. $outdone++;
  807. }
  808. if ($out) {
  809. $out .= '<div style="clear: both;"></div>';
  810. }
  811. $outdone = 0;
  812. if (!empty($this->email)) {
  813. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  814. $outdone++;
  815. }
  816. if (!empty($this->url)) {
  817. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  818. $out .= dol_print_url($this->url, '_blank', 0, 1);
  819. $outdone++;
  820. }
  821. if (!empty($conf->socialnetworks->enabled)) {
  822. $outsocialnetwork = '';
  823. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  824. $socialnetworksdict = getArrayOfSocialNetworks();
  825. foreach ($this->socialnetworks as $key => $value) {
  826. if ($value) {
  827. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  828. }
  829. $outdone++;
  830. }
  831. } else { // Old code to remove
  832. if (!empty($this->skype)) {
  833. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  834. }
  835. $outdone++;
  836. if (!empty($this->jabberid)) {
  837. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  838. }
  839. $outdone++;
  840. if (!empty($this->twitter)) {
  841. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  842. }
  843. $outdone++;
  844. if (!empty($this->facebook)) {
  845. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  846. }
  847. $outdone++;
  848. if (!empty($this->linkedin)) {
  849. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  850. }
  851. $outdone++;
  852. }
  853. if ($outsocialnetwork) {
  854. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  855. }
  856. }
  857. if ($out) {
  858. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  859. } else {
  860. return '';
  861. }
  862. }
  863. /**
  864. * Return the link of last main doc file for direct public download.
  865. *
  866. * @param string $modulepart Module related to document
  867. * @param int $initsharekey Init the share key if it was not yet defined
  868. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  869. * @return string Link or empty string if there is no download link
  870. */
  871. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  872. {
  873. global $user, $dolibarr_main_url_root;
  874. if (empty($this->last_main_doc)) {
  875. return ''; // No way to known which document name to use
  876. }
  877. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  878. $ecmfile = new EcmFiles($this->db);
  879. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  880. if ($result < 0) {
  881. $this->error = $ecmfile->error;
  882. $this->errors = $ecmfile->errors;
  883. return -1;
  884. }
  885. if (empty($ecmfile->id)) {
  886. // Add entry into index
  887. if ($initsharekey) {
  888. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  889. // 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
  890. /*
  891. $ecmfile->filepath = $rel_dir;
  892. $ecmfile->filename = $filename;
  893. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  894. $ecmfile->fullpath_orig = '';
  895. $ecmfile->gen_or_uploaded = 'generated';
  896. $ecmfile->description = ''; // indexed content
  897. $ecmfile->keywords = ''; // keyword content
  898. $ecmfile->share = getRandomPassword(true);
  899. $result = $ecmfile->create($user);
  900. if ($result < 0)
  901. {
  902. $this->error = $ecmfile->error;
  903. $this->errors = $ecmfile->errors;
  904. }
  905. */
  906. } else {
  907. return '';
  908. }
  909. } elseif (empty($ecmfile->share)) {
  910. // Add entry into index
  911. if ($initsharekey) {
  912. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  913. $ecmfile->share = getRandomPassword(true);
  914. $ecmfile->update($user);
  915. } else {
  916. return '';
  917. }
  918. }
  919. // Define $urlwithroot
  920. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  921. // This is to use external domain name found into config file
  922. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  923. //else
  924. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  925. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  926. $forcedownload = 0;
  927. $paramlink = '';
  928. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  929. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  930. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  931. if (!empty($ecmfile->share)) {
  932. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  933. }
  934. if ($forcedownload) {
  935. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  936. }
  937. if ($relativelink) {
  938. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  939. } else {
  940. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  941. }
  942. // Here $ecmfile->share is defined
  943. return $linktoreturn;
  944. }
  945. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  946. /**
  947. * Add a link between element $this->element and a contact
  948. *
  949. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  950. * @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
  951. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  952. * @param int $notrigger Disable all triggers
  953. * @return int <0 if KO, 0 if already added, >0 if OK
  954. */
  955. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  956. {
  957. // phpcs:enable
  958. global $user, $langs;
  959. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  960. // Check parameters
  961. if ($fk_socpeople <= 0) {
  962. $langs->load("errors");
  963. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  964. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  965. return -1;
  966. }
  967. if (!$type_contact) {
  968. $langs->load("errors");
  969. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  970. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  971. return -2;
  972. }
  973. $id_type_contact = 0;
  974. if (is_numeric($type_contact)) {
  975. $id_type_contact = $type_contact;
  976. } else {
  977. // We look for id type_contact
  978. $sql = "SELECT tc.rowid";
  979. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  980. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  981. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  982. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  983. //print $sql;
  984. $resql = $this->db->query($sql);
  985. if ($resql) {
  986. $obj = $this->db->fetch_object($resql);
  987. if ($obj) {
  988. $id_type_contact = $obj->rowid;
  989. }
  990. }
  991. }
  992. if ($id_type_contact == 0) {
  993. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  994. 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");
  995. return -3;
  996. }
  997. $datecreate = dol_now();
  998. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  999. $TListeContacts = $this->liste_contact(-1, $source);
  1000. $already_added = false;
  1001. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  1002. foreach ($TListeContacts as $array_contact) {
  1003. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  1004. $already_added = true;
  1005. break;
  1006. }
  1007. }
  1008. }
  1009. if (!$already_added) {
  1010. $this->db->begin();
  1011. // Insert into database
  1012. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  1013. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  1014. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  1015. $sql .= "'".$this->db->idate($datecreate)."'";
  1016. $sql .= ", 4, ".((int) $id_type_contact);
  1017. $sql .= ")";
  1018. $resql = $this->db->query($sql);
  1019. if ($resql) {
  1020. if (!$notrigger) {
  1021. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  1022. if ($result < 0) {
  1023. $this->db->rollback();
  1024. return -1;
  1025. }
  1026. }
  1027. $this->db->commit();
  1028. return 1;
  1029. } else {
  1030. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1031. $this->error = $this->db->errno();
  1032. $this->db->rollback();
  1033. return -2;
  1034. } else {
  1035. $this->error = $this->db->lasterror();
  1036. $this->db->rollback();
  1037. return -1;
  1038. }
  1039. }
  1040. } else {
  1041. return 0;
  1042. }
  1043. }
  1044. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1045. /**
  1046. * Copy contact from one element to current
  1047. *
  1048. * @param CommonObject $objFrom Source element
  1049. * @param string $source Nature of contact ('internal' or 'external')
  1050. * @return int >0 if OK, <0 if KO
  1051. */
  1052. public function copy_linked_contact($objFrom, $source = 'internal')
  1053. {
  1054. // phpcs:enable
  1055. $contacts = $objFrom->liste_contact(-1, $source);
  1056. foreach ($contacts as $contact) {
  1057. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  1058. return -1;
  1059. }
  1060. }
  1061. return 1;
  1062. }
  1063. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1064. /**
  1065. * Update a link to contact line
  1066. *
  1067. * @param int $rowid Id of line contact-element
  1068. * @param int $statut New status of link
  1069. * @param int $type_contact_id Id of contact type (not modified if 0)
  1070. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1071. * @return int <0 if KO, >= 0 if OK
  1072. */
  1073. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1074. {
  1075. // phpcs:enable
  1076. // Insert into database
  1077. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  1078. $sql .= " statut = ".$statut;
  1079. if ($type_contact_id) {
  1080. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1081. }
  1082. if ($fk_socpeople) {
  1083. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1084. }
  1085. $sql .= " where rowid = ".((int) $rowid);
  1086. $resql = $this->db->query($sql);
  1087. if ($resql) {
  1088. return 0;
  1089. } else {
  1090. $this->error = $this->db->lasterror();
  1091. return -1;
  1092. }
  1093. }
  1094. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1095. /**
  1096. * Delete a link to contact line
  1097. *
  1098. * @param int $rowid Id of contact link line to delete
  1099. * @param int $notrigger Disable all triggers
  1100. * @return int >0 if OK, <0 if KO
  1101. */
  1102. public function delete_contact($rowid, $notrigger = 0)
  1103. {
  1104. // phpcs:enable
  1105. global $user;
  1106. $this->db->begin();
  1107. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1108. $sql .= " WHERE rowid = ".((int) $rowid);
  1109. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1110. if ($this->db->query($sql)) {
  1111. if (!$notrigger) {
  1112. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1113. if ($result < 0) {
  1114. $this->db->rollback();
  1115. return -1;
  1116. }
  1117. }
  1118. $this->db->commit();
  1119. return 1;
  1120. } else {
  1121. $this->error = $this->db->lasterror();
  1122. $this->db->rollback();
  1123. return -1;
  1124. }
  1125. }
  1126. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1127. /**
  1128. * Delete all links between an object $this and all its contacts in llx_element_contact
  1129. *
  1130. * @param string $source '' or 'internal' or 'external'
  1131. * @param string $code Type of contact (code or id)
  1132. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1133. */
  1134. public function delete_linked_contact($source = '', $code = '')
  1135. {
  1136. // phpcs:enable
  1137. $listId = '';
  1138. $temp = array();
  1139. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1140. if (!empty($typeContact)) {
  1141. foreach ($typeContact as $key => $value) {
  1142. array_push($temp, $key);
  1143. }
  1144. $listId = implode(",", $temp);
  1145. }
  1146. // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
  1147. // any type or record instead of only the ones of the current object. So we do nothing in such a case.
  1148. if (empty($listId)) {
  1149. return 0;
  1150. }
  1151. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1152. $sql .= " WHERE element_id = ".((int) $this->id);
  1153. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1154. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1155. if ($this->db->query($sql)) {
  1156. return 1;
  1157. } else {
  1158. $this->error = $this->db->lasterror();
  1159. return -1;
  1160. }
  1161. }
  1162. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1163. /**
  1164. * Get array of all contacts for an object
  1165. *
  1166. * @param int $status Status of links to get (-1=all)
  1167. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1168. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1169. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1170. * @return array|int Array of contacts, -1 if error
  1171. */
  1172. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1173. {
  1174. // phpcs:enable
  1175. global $langs;
  1176. $tab = array();
  1177. $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
  1178. if ($source == 'internal') {
  1179. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1180. }
  1181. if ($source == 'external' || $source == 'thirdparty') {
  1182. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1183. }
  1184. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1185. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1186. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
  1187. $sql .= ", ".$this->db->prefix()."element_contact ec";
  1188. if ($source == 'internal') {
  1189. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1190. }
  1191. if ($source == 'external' || $source == 'thirdparty') {
  1192. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1193. }
  1194. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1195. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1196. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1197. if ($code) {
  1198. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1199. }
  1200. if ($source == 'internal') {
  1201. $sql .= " AND tc.source = 'internal'";
  1202. }
  1203. if ($source == 'external' || $source == 'thirdparty') {
  1204. $sql .= " AND tc.source = 'external'";
  1205. }
  1206. $sql .= " AND tc.active=1";
  1207. if ($status >= 0) {
  1208. $sql .= " AND ec.statut = ".((int) $status);
  1209. }
  1210. $sql .= " ORDER BY t.lastname ASC";
  1211. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1212. $resql = $this->db->query($sql);
  1213. if ($resql) {
  1214. $num = $this->db->num_rows($resql);
  1215. $i = 0;
  1216. while ($i < $num) {
  1217. $obj = $this->db->fetch_object($resql);
  1218. if (!$list) {
  1219. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1220. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1221. $tab[$i] = array(
  1222. 'source' => $obj->source,
  1223. 'socid' => $obj->socid,
  1224. 'id' => $obj->id,
  1225. 'nom' => $obj->lastname, // For backward compatibility
  1226. 'civility' => $obj->civility,
  1227. 'lastname' => $obj->lastname,
  1228. 'firstname' => $obj->firstname,
  1229. 'email'=>$obj->email,
  1230. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1231. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1232. 'statuscontact' => $obj->statuscontact,
  1233. 'rowid' => $obj->rowid,
  1234. 'code' => $obj->code,
  1235. 'libelle' => $libelle_type,
  1236. 'status' => $obj->statuslink,
  1237. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1238. );
  1239. } else {
  1240. $tab[$i] = $obj->id;
  1241. }
  1242. $i++;
  1243. }
  1244. return $tab;
  1245. } else {
  1246. $this->error = $this->db->lasterror();
  1247. dol_print_error($this->db);
  1248. return -1;
  1249. }
  1250. }
  1251. /**
  1252. * Update status of a contact linked to object
  1253. *
  1254. * @param int $rowid Id of link between object and contact
  1255. * @return int <0 if KO, >=0 if OK
  1256. */
  1257. public function swapContactStatus($rowid)
  1258. {
  1259. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1260. $sql .= " tc.code, tc.libelle";
  1261. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1262. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1263. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1264. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1265. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1266. $resql = $this->db->query($sql);
  1267. if ($resql) {
  1268. $obj = $this->db->fetch_object($resql);
  1269. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1270. $result = $this->update_contact($rowid, $newstatut);
  1271. $this->db->free($resql);
  1272. return $result;
  1273. } else {
  1274. $this->error = $this->db->error();
  1275. dol_print_error($this->db);
  1276. return -1;
  1277. }
  1278. }
  1279. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1280. /**
  1281. * Return array with list of possible values for type of contacts
  1282. *
  1283. * @param string $source 'internal', 'external' or 'all'
  1284. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1285. * @param int $option 0=Return array id->label, 1=Return array code->label
  1286. * @param int $activeonly 0=all status of contact, 1=only the active
  1287. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1288. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1289. */
  1290. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1291. {
  1292. // phpcs:enable
  1293. global $langs;
  1294. if (empty($order)) {
  1295. $order = 'position';
  1296. }
  1297. if ($order == 'position') {
  1298. $order .= ',code';
  1299. }
  1300. $tab = array();
  1301. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1302. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1303. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1304. if ($activeonly == 1) {
  1305. $sql .= " AND tc.active=1"; // only the active types
  1306. }
  1307. if (!empty($source) && $source != 'all') {
  1308. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1309. }
  1310. if (!empty($code)) {
  1311. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1312. }
  1313. $sql .= $this->db->order($order, 'ASC');
  1314. //print "sql=".$sql;
  1315. $resql = $this->db->query($sql);
  1316. if ($resql) {
  1317. $num = $this->db->num_rows($resql);
  1318. $i = 0;
  1319. while ($i < $num) {
  1320. $obj = $this->db->fetch_object($resql);
  1321. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1322. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1323. if (empty($option)) {
  1324. $tab[$obj->rowid] = $libelle_type;
  1325. } else {
  1326. $tab[$obj->code] = $libelle_type;
  1327. }
  1328. $i++;
  1329. }
  1330. return $tab;
  1331. } else {
  1332. $this->error = $this->db->lasterror();
  1333. //dol_print_error($this->db);
  1334. return null;
  1335. }
  1336. }
  1337. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1338. /**
  1339. * Return array with list of possible values for type of contacts
  1340. *
  1341. * @param string $source 'internal', 'external' or 'all'
  1342. * @param int $option 0=Return array id->label, 1=Return array code->label
  1343. * @param int $activeonly 0=all status of contact, 1=only the active
  1344. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1345. * @param string $element Filter on 1 element type
  1346. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1347. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1348. */
  1349. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1350. {
  1351. // phpcs:enable
  1352. global $langs, $conf;
  1353. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1354. $tab = array();
  1355. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1356. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1357. $sqlWhere = array();
  1358. if (!empty($element)) {
  1359. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1360. }
  1361. if (!empty($excludeelement)) {
  1362. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1363. }
  1364. if ($activeonly == 1) {
  1365. $sqlWhere[] = " tc.active=1"; // only the active types
  1366. }
  1367. if (!empty($source) && $source != 'all') {
  1368. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1369. }
  1370. if (!empty($code)) {
  1371. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1372. }
  1373. if (count($sqlWhere) > 0) {
  1374. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1375. }
  1376. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1377. dol_syslog(__METHOD__, LOG_DEBUG);
  1378. $resql = $this->db->query($sql);
  1379. if ($resql) {
  1380. $num = $this->db->num_rows($resql);
  1381. if ($num > 0) {
  1382. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1383. while ($obj = $this->db->fetch_object($resql)) {
  1384. $modulename = $obj->element;
  1385. if (strpos($obj->element, 'project') !== false) {
  1386. $modulename = 'projet';
  1387. } elseif ($obj->element == 'contrat') {
  1388. $element = 'contract';
  1389. } elseif ($obj->element == 'action') {
  1390. $modulename = 'agenda';
  1391. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1392. $modulename = 'fournisseur';
  1393. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1394. $modulename = 'fournisseur';
  1395. }
  1396. if (!empty($conf->{$modulename}->enabled)) {
  1397. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1398. $tmpelement = $obj->element;
  1399. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1400. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1401. if (empty($option)) {
  1402. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1403. } else {
  1404. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1405. }
  1406. }
  1407. }
  1408. }
  1409. return $tab;
  1410. } else {
  1411. $this->error = $this->db->lasterror();
  1412. return null;
  1413. }
  1414. }
  1415. /**
  1416. * Return id of contacts for a source and a contact code.
  1417. * Example: contact client de facturation ('external', 'BILLING')
  1418. * Example: contact client de livraison ('external', 'SHIPPING')
  1419. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1420. *
  1421. * @param string $source 'external' or 'internal'
  1422. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1423. * @param int $status limited to a certain status
  1424. * @return array List of id for such contacts
  1425. */
  1426. public function getIdContact($source, $code, $status = 0)
  1427. {
  1428. global $conf;
  1429. $result = array();
  1430. $i = 0;
  1431. //cas particulier pour les expeditions
  1432. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1433. $id = $this->origin_id;
  1434. $element = 'commande';
  1435. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1436. $id = $this->origin_id;
  1437. $element = 'order_supplier';
  1438. } else {
  1439. $id = $this->id;
  1440. $element = $this->element;
  1441. }
  1442. $sql = "SELECT ec.fk_socpeople";
  1443. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1444. if ($source == 'internal') {
  1445. $sql .= " ".$this->db->prefix()."user as c,";
  1446. }
  1447. if ($source == 'external') {
  1448. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1449. }
  1450. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1451. $sql .= " WHERE ec.element_id = ".((int) $id);
  1452. $sql .= " AND ec.fk_socpeople = c.rowid";
  1453. if ($source == 'internal') {
  1454. $sql .= " AND c.entity IN (".getEntity('user').")";
  1455. }
  1456. if ($source == 'external') {
  1457. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1458. }
  1459. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1460. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1461. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1462. if ($code) {
  1463. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1464. }
  1465. $sql .= " AND tc.active = 1";
  1466. if ($status) {
  1467. $sql .= " AND ec.statut = ".((int) $status);
  1468. }
  1469. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1470. $resql = $this->db->query($sql);
  1471. if ($resql) {
  1472. while ($obj = $this->db->fetch_object($resql)) {
  1473. $result[$i] = $obj->fk_socpeople;
  1474. $i++;
  1475. }
  1476. } else {
  1477. $this->error = $this->db->error();
  1478. return null;
  1479. }
  1480. return $result;
  1481. }
  1482. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1483. /**
  1484. * Load object contact with id=$this->contact_id into $this->contact
  1485. *
  1486. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1487. * @return int <0 if KO, >0 if OK
  1488. */
  1489. public function fetch_contact($contactid = null)
  1490. {
  1491. // phpcs:enable
  1492. if (empty($contactid)) {
  1493. $contactid = $this->contact_id;
  1494. }
  1495. if (empty($contactid)) {
  1496. return 0;
  1497. }
  1498. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1499. $contact = new Contact($this->db);
  1500. $result = $contact->fetch($contactid);
  1501. $this->contact = $contact;
  1502. return $result;
  1503. }
  1504. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1505. /**
  1506. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1507. *
  1508. * @param int $force_thirdparty_id Force thirdparty id
  1509. * @return int <0 if KO, >0 if OK
  1510. */
  1511. public function fetch_thirdparty($force_thirdparty_id = 0)
  1512. {
  1513. // phpcs:enable
  1514. global $conf;
  1515. if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
  1516. return 0;
  1517. }
  1518. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1519. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
  1520. if ($force_thirdparty_id) {
  1521. $idtofetch = $force_thirdparty_id;
  1522. }
  1523. if ($idtofetch) {
  1524. $thirdparty = new Societe($this->db);
  1525. $result = $thirdparty->fetch($idtofetch);
  1526. if ($result<0) {
  1527. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1528. }
  1529. $this->thirdparty = $thirdparty;
  1530. // Use first price level if level not defined for third party
  1531. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1532. $this->thirdparty->price_level = 1;
  1533. }
  1534. return $result;
  1535. } else {
  1536. return -1;
  1537. }
  1538. }
  1539. /**
  1540. * Looks for an object with ref matching the wildcard provided
  1541. * It does only work when $this->table_ref_field is set
  1542. *
  1543. * @param string $ref Wildcard
  1544. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1545. */
  1546. public function fetchOneLike($ref)
  1547. {
  1548. if (!$this->table_ref_field) {
  1549. return 0;
  1550. }
  1551. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1552. $query = $this->db->query($sql);
  1553. if (!$this->db->num_rows($query)) {
  1554. return 0;
  1555. }
  1556. $result = $this->db->fetch_object($query);
  1557. return $this->fetch($result->rowid);
  1558. }
  1559. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1560. /**
  1561. * Load data for barcode into properties ->barcode_type*
  1562. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1563. * if it is not defined, ->element must be defined to know default barcode type.
  1564. *
  1565. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1566. */
  1567. public function fetch_barcode()
  1568. {
  1569. // phpcs:enable
  1570. global $conf;
  1571. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1572. $idtype = $this->barcode_type;
  1573. 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
  1574. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1575. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1576. } elseif ($this->element == 'societe') {
  1577. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1578. } else {
  1579. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1580. }
  1581. }
  1582. if ($idtype > 0) {
  1583. 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
  1584. $sql = "SELECT rowid, code, libelle as label, coder";
  1585. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1586. $sql .= " WHERE rowid = ".((int) $idtype);
  1587. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1588. $resql = $this->db->query($sql);
  1589. if ($resql) {
  1590. $obj = $this->db->fetch_object($resql);
  1591. $this->barcode_type = $obj->rowid;
  1592. $this->barcode_type_code = $obj->code;
  1593. $this->barcode_type_label = $obj->label;
  1594. $this->barcode_type_coder = $obj->coder;
  1595. return 1;
  1596. } else {
  1597. dol_print_error($this->db);
  1598. return -1;
  1599. }
  1600. }
  1601. }
  1602. return 0;
  1603. }
  1604. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1605. /**
  1606. * Load the project with id $this->fk_project into this->project
  1607. *
  1608. * @return int <0 if KO, >=0 if OK
  1609. */
  1610. public function fetch_project()
  1611. {
  1612. // phpcs:enable
  1613. return $this->fetch_projet();
  1614. }
  1615. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1616. /**
  1617. * Load the project with id $this->fk_project into this->project
  1618. *
  1619. * @return int <0 if KO, >=0 if OK
  1620. */
  1621. public function fetch_projet()
  1622. {
  1623. // phpcs:enable
  1624. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1625. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1626. $this->fk_project = $this->fk_projet; // For backward compatibility
  1627. }
  1628. if (empty($this->fk_project)) {
  1629. return 0;
  1630. }
  1631. $project = new Project($this->db);
  1632. $result = $project->fetch($this->fk_project);
  1633. $this->projet = $project; // deprecated
  1634. $this->project = $project;
  1635. return $result;
  1636. }
  1637. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1638. /**
  1639. * Load the product with id $this->fk_product into this->product
  1640. *
  1641. * @return int <0 if KO, >=0 if OK
  1642. */
  1643. public function fetch_product()
  1644. {
  1645. // phpcs:enable
  1646. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1647. if (empty($this->fk_product)) {
  1648. return 0;
  1649. }
  1650. $product = new Product($this->db);
  1651. $result = $product->fetch($this->fk_product);
  1652. $this->product = $product;
  1653. return $result;
  1654. }
  1655. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1656. /**
  1657. * Load the user with id $userid into this->user
  1658. *
  1659. * @param int $userid Id du contact
  1660. * @return int <0 if KO, >0 if OK
  1661. */
  1662. public function fetch_user($userid)
  1663. {
  1664. // phpcs:enable
  1665. $user = new User($this->db);
  1666. $result = $user->fetch($userid);
  1667. $this->user = $user;
  1668. return $result;
  1669. }
  1670. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1671. /**
  1672. * Read linked origin object
  1673. *
  1674. * @return void
  1675. */
  1676. public function fetch_origin()
  1677. {
  1678. // phpcs:enable
  1679. if ($this->origin == 'shipping') {
  1680. $this->origin = 'expedition';
  1681. }
  1682. if ($this->origin == 'delivery') {
  1683. $this->origin = 'livraison';
  1684. }
  1685. if ($this->origin == 'order_supplier') {
  1686. $this->origin = 'commandeFournisseur';
  1687. }
  1688. $origin = $this->origin;
  1689. $classname = ucfirst($origin);
  1690. $this->$origin = new $classname($this->db);
  1691. $this->$origin->fetch($this->origin_id);
  1692. }
  1693. /**
  1694. * Load object from specific field
  1695. *
  1696. * @param string $table Table element or element line
  1697. * @param string $field Field selected
  1698. * @param string $key Import key
  1699. * @param string $element Element name
  1700. * @return int <0 if KO, >0 if OK
  1701. */
  1702. public function fetchObjectFrom($table, $field, $key, $element = null)
  1703. {
  1704. global $conf;
  1705. $result = false;
  1706. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1707. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1708. if (!empty($element)) {
  1709. $sql .= " AND entity IN (".getEntity($element).")";
  1710. } else {
  1711. $sql .= " AND entity = ".((int) $conf->entity);
  1712. }
  1713. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1714. $resql = $this->db->query($sql);
  1715. if ($resql) {
  1716. $row = $this->db->fetch_row($resql);
  1717. // Test for avoid error -1
  1718. if ($row[0] > 0) {
  1719. $result = $this->fetch($row[0]);
  1720. }
  1721. }
  1722. return $result;
  1723. }
  1724. /**
  1725. * Getter generic. Load value from a specific field
  1726. *
  1727. * @param string $table Table of element or element line
  1728. * @param int $id Element id
  1729. * @param string $field Field selected
  1730. * @return int <0 if KO, >0 if OK
  1731. */
  1732. public function getValueFrom($table, $id, $field)
  1733. {
  1734. $result = false;
  1735. if (!empty($id) && !empty($field) && !empty($table)) {
  1736. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1737. $sql .= " WHERE rowid = ".((int) $id);
  1738. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1739. $resql = $this->db->query($sql);
  1740. if ($resql) {
  1741. $row = $this->db->fetch_row($resql);
  1742. $result = $row[0];
  1743. }
  1744. }
  1745. return $result;
  1746. }
  1747. /**
  1748. * Setter generic. Update a specific field into database.
  1749. * Warning: Trigger is run only if param trigkey is provided.
  1750. *
  1751. * @param string $field Field to update
  1752. * @param mixed $value New value
  1753. * @param string $table To force other table element or element line (should not be used)
  1754. * @param int $id To force other object id (should not be used)
  1755. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1756. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1757. * @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'
  1758. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1759. * @param string $fk_user_field Name of field to save user id making change
  1760. * @return int <0 if KO, >0 if OK
  1761. * @see updateExtraField()
  1762. */
  1763. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1764. {
  1765. global $user, $langs, $conf;
  1766. if (empty($table)) {
  1767. $table = $this->table_element;
  1768. }
  1769. if (empty($id)) {
  1770. $id = $this->id;
  1771. }
  1772. if (empty($format)) {
  1773. $format = 'text';
  1774. }
  1775. if (empty($id_field)) {
  1776. $id_field = 'rowid';
  1777. }
  1778. $error = 0;
  1779. $this->db->begin();
  1780. // Special case
  1781. if ($table == 'product' && $field == 'note_private') {
  1782. $field = 'note';
  1783. }
  1784. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1785. $fk_user_field = 'fk_user_mod';
  1786. }
  1787. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1788. if ($format == 'text') {
  1789. $sql .= $field." = '".$this->db->escape($value)."'";
  1790. } elseif ($format == 'int') {
  1791. $sql .= $field." = ".((int) $value);
  1792. } elseif ($format == 'date') {
  1793. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1794. }
  1795. if ($fk_user_field) {
  1796. if (!empty($fuser) && is_object($fuser)) {
  1797. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1798. } elseif (empty($fuser) || $fuser != 'none') {
  1799. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1800. }
  1801. }
  1802. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1803. dol_syslog(__METHOD__."", LOG_DEBUG);
  1804. $resql = $this->db->query($sql);
  1805. if ($resql) {
  1806. if ($trigkey) {
  1807. // call trigger with updated object values
  1808. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1809. $result = $this->fetch($id);
  1810. } else {
  1811. $result = $this->fetchCommon($id);
  1812. }
  1813. if ($result >= 0) {
  1814. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1815. }
  1816. if ($result < 0) {
  1817. $error++;
  1818. }
  1819. }
  1820. if (!$error) {
  1821. if (property_exists($this, $field)) {
  1822. $this->$field = $value;
  1823. }
  1824. $this->db->commit();
  1825. return 1;
  1826. } else {
  1827. $this->db->rollback();
  1828. return -2;
  1829. }
  1830. } else {
  1831. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1832. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1833. } else {
  1834. $this->error = $this->db->lasterror();
  1835. }
  1836. $this->db->rollback();
  1837. return -1;
  1838. }
  1839. }
  1840. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1841. /**
  1842. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1843. *
  1844. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1845. * @param string $fieldid Name of field to use for the select MAX and MIN
  1846. * @param int $nodbprefix Do not include DB prefix to forge table name
  1847. * @return int <0 if KO, >0 if OK
  1848. */
  1849. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1850. {
  1851. // phpcs:enable
  1852. global $conf, $user;
  1853. if (!$this->table_element) {
  1854. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1855. return -1;
  1856. }
  1857. if ($fieldid == 'none') {
  1858. return 1;
  1859. }
  1860. // For backward compatibility
  1861. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1862. $fieldid = 'titre';
  1863. }
  1864. // Security on socid
  1865. $socid = 0;
  1866. if ($user->socid > 0) {
  1867. $socid = $user->socid;
  1868. }
  1869. // this->ismultientitymanaged contains
  1870. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1871. $aliastablesociete = 's';
  1872. if ($this->element == 'societe') {
  1873. $aliastablesociete = 'te'; // te as table_element
  1874. }
  1875. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1876. $sql = "SELECT MAX(te.".$fieldid.")";
  1877. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1878. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1879. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1880. }
  1881. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1882. $tmparray = explode('@', $this->ismultientitymanaged);
  1883. $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
  1884. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1885. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1886. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1887. $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
  1888. }
  1889. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1890. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1891. }
  1892. $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1893. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1894. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1895. }
  1896. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1897. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1898. }
  1899. if (!empty($filter)) {
  1900. if (!preg_match('/^\s*AND/i', $filter)) {
  1901. $sql .= " AND "; // For backward compatibility
  1902. }
  1903. $sql .= $filter;
  1904. }
  1905. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1906. $tmparray = explode('@', $this->ismultientitymanaged);
  1907. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1908. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1909. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1910. }
  1911. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1912. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1913. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1914. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1915. } else {
  1916. $sql .= " AND ug.fk_user = te.rowid";
  1917. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1918. }
  1919. } else {
  1920. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1921. }
  1922. }
  1923. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1924. $tmparray = explode('@', $this->ismultientitymanaged);
  1925. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1926. }
  1927. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1928. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1929. }
  1930. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1931. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1932. }
  1933. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1934. $sql .= ' AND te.rowid = '.((int) $socid);
  1935. }
  1936. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1937. $result = $this->db->query($sql);
  1938. if (!$result) {
  1939. $this->error = $this->db->lasterror();
  1940. return -1;
  1941. }
  1942. $row = $this->db->fetch_row($result);
  1943. $this->ref_previous = $row[0];
  1944. $sql = "SELECT MIN(te.".$fieldid.")";
  1945. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1946. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1947. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1948. }
  1949. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1950. $tmparray = explode('@', $this->ismultientitymanaged);
  1951. $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
  1952. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1953. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1954. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1955. $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
  1956. }
  1957. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1958. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1959. }
  1960. $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1961. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1962. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1963. }
  1964. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1965. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1966. }
  1967. if (!empty($filter)) {
  1968. if (!preg_match('/^\s*AND/i', $filter)) {
  1969. $sql .= " AND "; // For backward compatibility
  1970. }
  1971. $sql .= $filter;
  1972. }
  1973. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1974. $tmparray = explode('@', $this->ismultientitymanaged);
  1975. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1976. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1977. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1978. }
  1979. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1980. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1981. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1982. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1983. } else {
  1984. $sql .= " AND ug.fk_user = te.rowid";
  1985. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1986. }
  1987. } else {
  1988. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1989. }
  1990. }
  1991. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1992. $tmparray = explode('@', $this->ismultientitymanaged);
  1993. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1994. }
  1995. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1996. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1997. }
  1998. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1999. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  2000. }
  2001. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  2002. $sql .= ' AND te.rowid = '.((int) $socid);
  2003. }
  2004. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  2005. // 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
  2006. $result = $this->db->query($sql);
  2007. if (!$result) {
  2008. $this->error = $this->db->lasterror();
  2009. return -2;
  2010. }
  2011. $row = $this->db->fetch_row($result);
  2012. $this->ref_next = $row[0];
  2013. return 1;
  2014. }
  2015. /**
  2016. * Return list of id of contacts of object
  2017. *
  2018. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  2019. * @return array Array of id of contacts (if source=external or internal)
  2020. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  2021. */
  2022. public function getListContactId($source = 'external')
  2023. {
  2024. $contactAlreadySelected = array();
  2025. $tab = $this->liste_contact(-1, $source);
  2026. $num = count($tab);
  2027. $i = 0;
  2028. while ($i < $num) {
  2029. if ($source == 'thirdparty') {
  2030. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  2031. } else {
  2032. $contactAlreadySelected[$i] = $tab[$i]['id'];
  2033. }
  2034. $i++;
  2035. }
  2036. return $contactAlreadySelected;
  2037. }
  2038. /**
  2039. * Link element with a project
  2040. *
  2041. * @param int $projectid Project id to link element to
  2042. * @param int $notrigger Disable the trigger
  2043. * @return int <0 if KO, >0 if OK
  2044. */
  2045. public function setProject($projectid, $notrigger = 0)
  2046. {
  2047. global $user;
  2048. $error = 0;
  2049. if (!$this->table_element) {
  2050. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  2051. return -1;
  2052. }
  2053. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2054. if (!empty($this->fields['fk_project'])) { // Common case
  2055. if ($projectid) {
  2056. $sql .= " SET fk_project = ".((int) $projectid);
  2057. } else {
  2058. $sql .= " SET fk_project = NULL";
  2059. }
  2060. $sql .= ' WHERE rowid = '.((int) $this->id);
  2061. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  2062. if ($projectid) {
  2063. $sql .= " SET fk_project = ".((int) $projectid);
  2064. } else {
  2065. $sql .= " SET fk_project = NULL";
  2066. }
  2067. $sql .= ' WHERE id = '.((int) $this->id);
  2068. } else // Special case for old architecture objects
  2069. {
  2070. if ($projectid) {
  2071. $sql .= ' SET fk_projet = '.((int) $projectid);
  2072. } else {
  2073. $sql .= ' SET fk_projet = NULL';
  2074. }
  2075. $sql .= " WHERE rowid = ".((int) $this->id);
  2076. }
  2077. $this->db->begin();
  2078. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2079. if ($this->db->query($sql)) {
  2080. $this->fk_project = ((int) $projectid);
  2081. } else {
  2082. dol_print_error($this->db);
  2083. $error++;
  2084. }
  2085. // Triggers
  2086. if (!$error && !$notrigger) {
  2087. // Call triggers
  2088. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2089. if ($result < 0) {
  2090. $error++;
  2091. } //Do also here what you must do to rollback action if trigger fail
  2092. // End call triggers
  2093. }
  2094. // Commit or rollback
  2095. if ($error) {
  2096. $this->db->rollback();
  2097. return -1;
  2098. } else {
  2099. $this->db->commit();
  2100. return 1;
  2101. }
  2102. }
  2103. /**
  2104. * Change the payments methods
  2105. *
  2106. * @param int $id Id of new payment method
  2107. * @return int >0 if OK, <0 if KO
  2108. */
  2109. public function setPaymentMethods($id)
  2110. {
  2111. global $user;
  2112. $error = 0; $notrigger = 0;
  2113. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2114. if ($this->statut >= 0 || $this->element == 'societe') {
  2115. // TODO uniformize field name
  2116. $fieldname = 'fk_mode_reglement';
  2117. if ($this->element == 'societe') {
  2118. $fieldname = 'mode_reglement';
  2119. }
  2120. if (get_class($this) == 'Fournisseur') {
  2121. $fieldname = 'mode_reglement_supplier';
  2122. }
  2123. if (get_class($this) == 'Tva') {
  2124. $fieldname = 'fk_typepayment';
  2125. }
  2126. if (get_class($this) == 'Salary') {
  2127. $fieldname = 'fk_typepayment';
  2128. }
  2129. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2130. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2131. $sql .= ' WHERE rowid='.((int) $this->id);
  2132. if ($this->db->query($sql)) {
  2133. $this->mode_reglement_id = $id;
  2134. // for supplier
  2135. if (get_class($this) == 'Fournisseur') {
  2136. $this->mode_reglement_supplier_id = $id;
  2137. }
  2138. // Triggers
  2139. if (!$error && !$notrigger) {
  2140. // Call triggers
  2141. if (get_class($this) == 'Commande') {
  2142. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2143. } else {
  2144. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2145. }
  2146. if ($result < 0) {
  2147. $error++;
  2148. }
  2149. // End call triggers
  2150. }
  2151. return 1;
  2152. } else {
  2153. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2154. $this->error = $this->db->error();
  2155. return -1;
  2156. }
  2157. } else {
  2158. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2159. $this->error = 'Status of the object is incompatible '.$this->statut;
  2160. return -2;
  2161. }
  2162. }
  2163. /**
  2164. * Change the multicurrency code
  2165. *
  2166. * @param string $code multicurrency code
  2167. * @return int >0 if OK, <0 if KO
  2168. */
  2169. public function setMulticurrencyCode($code)
  2170. {
  2171. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2172. if ($this->statut >= 0 || $this->element == 'societe') {
  2173. $fieldname = 'multicurrency_code';
  2174. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2175. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2176. $sql .= ' WHERE rowid='.((int) $this->id);
  2177. if ($this->db->query($sql)) {
  2178. $this->multicurrency_code = $code;
  2179. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2180. if ($rate) {
  2181. $this->setMulticurrencyRate($rate, 2);
  2182. }
  2183. return 1;
  2184. } else {
  2185. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2186. $this->error = $this->db->error();
  2187. return -1;
  2188. }
  2189. } else {
  2190. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2191. $this->error = 'Status of the object is incompatible '.$this->statut;
  2192. return -2;
  2193. }
  2194. }
  2195. /**
  2196. * Change the multicurrency rate
  2197. *
  2198. * @param double $rate multicurrency rate
  2199. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2200. * @return int >0 if OK, <0 if KO
  2201. */
  2202. public function setMulticurrencyRate($rate, $mode = 1)
  2203. {
  2204. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2205. if ($this->statut >= 0 || $this->element == 'societe') {
  2206. $fieldname = 'multicurrency_tx';
  2207. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2208. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2209. $sql .= ' WHERE rowid='.((int) $this->id);
  2210. if ($this->db->query($sql)) {
  2211. $this->multicurrency_tx = $rate;
  2212. // Update line price
  2213. if (!empty($this->lines)) {
  2214. foreach ($this->lines as &$line) {
  2215. // Amounts in company currency will be recalculated
  2216. if ($mode == 1) {
  2217. $line->subprice = 0;
  2218. }
  2219. // Amounts in foreign currency will be recalculated
  2220. if ($mode == 2) {
  2221. $line->multicurrency_subprice = 0;
  2222. }
  2223. switch ($this->element) {
  2224. case 'propal':
  2225. $this->updateline(
  2226. $line->id,
  2227. $line->subprice,
  2228. $line->qty,
  2229. $line->remise_percent,
  2230. $line->tva_tx,
  2231. $line->localtax1_tx,
  2232. $line->localtax2_tx,
  2233. ($line->description ? $line->description : $line->desc),
  2234. 'HT',
  2235. $line->info_bits,
  2236. $line->special_code,
  2237. $line->fk_parent_line,
  2238. $line->skip_update_total,
  2239. $line->fk_fournprice,
  2240. $line->pa_ht,
  2241. $line->label,
  2242. $line->product_type,
  2243. $line->date_start,
  2244. $line->date_end,
  2245. $line->array_options,
  2246. $line->fk_unit,
  2247. $line->multicurrency_subprice
  2248. );
  2249. break;
  2250. case 'commande':
  2251. $this->updateline(
  2252. $line->id,
  2253. ($line->description ? $line->description : $line->desc),
  2254. $line->subprice,
  2255. $line->qty,
  2256. $line->remise_percent,
  2257. $line->tva_tx,
  2258. $line->localtax1_tx,
  2259. $line->localtax2_tx,
  2260. 'HT',
  2261. $line->info_bits,
  2262. $line->date_start,
  2263. $line->date_end,
  2264. $line->product_type,
  2265. $line->fk_parent_line,
  2266. $line->skip_update_total,
  2267. $line->fk_fournprice,
  2268. $line->pa_ht,
  2269. $line->label,
  2270. $line->special_code,
  2271. $line->array_options,
  2272. $line->fk_unit,
  2273. $line->multicurrency_subprice
  2274. );
  2275. break;
  2276. case 'facture':
  2277. $this->updateline(
  2278. $line->id,
  2279. ($line->description ? $line->description : $line->desc),
  2280. $line->subprice,
  2281. $line->qty,
  2282. $line->remise_percent,
  2283. $line->date_start,
  2284. $line->date_end,
  2285. $line->tva_tx,
  2286. $line->localtax1_tx,
  2287. $line->localtax2_tx,
  2288. 'HT',
  2289. $line->info_bits,
  2290. $line->product_type,
  2291. $line->fk_parent_line,
  2292. $line->skip_update_total,
  2293. $line->fk_fournprice,
  2294. $line->pa_ht,
  2295. $line->label,
  2296. $line->special_code,
  2297. $line->array_options,
  2298. $line->situation_percent,
  2299. $line->fk_unit,
  2300. $line->multicurrency_subprice
  2301. );
  2302. break;
  2303. case 'supplier_proposal':
  2304. $this->updateline(
  2305. $line->id,
  2306. $line->subprice,
  2307. $line->qty,
  2308. $line->remise_percent,
  2309. $line->tva_tx,
  2310. $line->localtax1_tx,
  2311. $line->localtax2_tx,
  2312. ($line->description ? $line->description : $line->desc),
  2313. 'HT',
  2314. $line->info_bits,
  2315. $line->special_code,
  2316. $line->fk_parent_line,
  2317. $line->skip_update_total,
  2318. $line->fk_fournprice,
  2319. $line->pa_ht,
  2320. $line->label,
  2321. $line->product_type,
  2322. $line->array_options,
  2323. $line->ref_fourn,
  2324. $line->multicurrency_subprice
  2325. );
  2326. break;
  2327. case 'order_supplier':
  2328. $this->updateline(
  2329. $line->id,
  2330. ($line->description ? $line->description : $line->desc),
  2331. $line->subprice,
  2332. $line->qty,
  2333. $line->remise_percent,
  2334. $line->tva_tx,
  2335. $line->localtax1_tx,
  2336. $line->localtax2_tx,
  2337. 'HT',
  2338. $line->info_bits,
  2339. $line->product_type,
  2340. false,
  2341. $line->date_start,
  2342. $line->date_end,
  2343. $line->array_options,
  2344. $line->fk_unit,
  2345. $line->multicurrency_subprice,
  2346. $line->ref_supplier
  2347. );
  2348. break;
  2349. case 'invoice_supplier':
  2350. $this->updateline(
  2351. $line->id,
  2352. ($line->description ? $line->description : $line->desc),
  2353. $line->subprice,
  2354. $line->tva_tx,
  2355. $line->localtax1_tx,
  2356. $line->localtax2_tx,
  2357. $line->qty,
  2358. 0,
  2359. 'HT',
  2360. $line->info_bits,
  2361. $line->product_type,
  2362. $line->remise_percent,
  2363. false,
  2364. $line->date_start,
  2365. $line->date_end,
  2366. $line->array_options,
  2367. $line->fk_unit,
  2368. $line->multicurrency_subprice,
  2369. $line->ref_supplier
  2370. );
  2371. break;
  2372. default:
  2373. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2374. break;
  2375. }
  2376. }
  2377. }
  2378. return 1;
  2379. } else {
  2380. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2381. $this->error = $this->db->error();
  2382. return -1;
  2383. }
  2384. } else {
  2385. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2386. $this->error = 'Status of the object is incompatible '.$this->statut;
  2387. return -2;
  2388. }
  2389. }
  2390. /**
  2391. * Change the payments terms
  2392. *
  2393. * @param int $id Id of new payment terms
  2394. * @param string $deposit_percent % of deposit if needed by payment terms
  2395. * @return int >0 if OK, <0 if KO
  2396. */
  2397. public function setPaymentTerms($id, $deposit_percent = null)
  2398. {
  2399. dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
  2400. if ($this->statut >= 0 || $this->element == 'societe') {
  2401. // TODO uniformize field name
  2402. $fieldname = 'fk_cond_reglement';
  2403. if ($this->element == 'societe') {
  2404. $fieldname = 'cond_reglement';
  2405. }
  2406. if (get_class($this) == 'Fournisseur') {
  2407. $fieldname = 'cond_reglement_supplier';
  2408. }
  2409. if (empty($deposit_percent) || $deposit_percent < 0) {
  2410. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2411. }
  2412. if ($deposit_percent > 100) {
  2413. $deposit_percent = 100;
  2414. }
  2415. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2416. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2417. if (in_array($this->table_element, array('propal', 'commande'))) {
  2418. $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
  2419. }
  2420. $sql .= ' WHERE rowid='.((int) $this->id);
  2421. if ($this->db->query($sql)) {
  2422. $this->cond_reglement_id = $id;
  2423. // for supplier
  2424. if (get_class($this) == 'Fournisseur') {
  2425. $this->cond_reglement_supplier_id = $id;
  2426. }
  2427. $this->cond_reglement = $id; // for compatibility
  2428. $this->deposit_percent = $deposit_percent;
  2429. return 1;
  2430. } else {
  2431. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2432. $this->error = $this->db->error();
  2433. return -1;
  2434. }
  2435. } else {
  2436. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2437. $this->error = 'Status of the object is incompatible '.$this->statut;
  2438. return -2;
  2439. }
  2440. }
  2441. /**
  2442. * Change the transport mode methods
  2443. *
  2444. * @param int $id Id of transport mode
  2445. * @return int >0 if OK, <0 if KO
  2446. */
  2447. public function setTransportMode($id)
  2448. {
  2449. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2450. if ($this->statut >= 0 || $this->element == 'societe') {
  2451. $fieldname = 'fk_transport_mode';
  2452. if ($this->element == 'societe') {
  2453. $fieldname = 'transport_mode';
  2454. }
  2455. if (get_class($this) == 'Fournisseur') {
  2456. $fieldname = 'transport_mode_supplier';
  2457. }
  2458. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2459. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2460. $sql .= ' WHERE rowid='.((int) $this->id);
  2461. if ($this->db->query($sql)) {
  2462. $this->transport_mode_id = $id;
  2463. // for supplier
  2464. if (get_class($this) == 'Fournisseur') {
  2465. $this->transport_mode_supplier_id = $id;
  2466. }
  2467. return 1;
  2468. } else {
  2469. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2470. $this->error = $this->db->error();
  2471. return -1;
  2472. }
  2473. } else {
  2474. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2475. $this->error = 'Status of the object is incompatible '.$this->statut;
  2476. return -2;
  2477. }
  2478. }
  2479. /**
  2480. * Change the retained warranty payments terms
  2481. *
  2482. * @param int $id Id of new payment terms
  2483. * @return int >0 if OK, <0 if KO
  2484. */
  2485. public function setRetainedWarrantyPaymentTerms($id)
  2486. {
  2487. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2488. if ($this->statut >= 0 || $this->element == 'societe') {
  2489. $fieldname = 'retained_warranty_fk_cond_reglement';
  2490. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2491. $sql .= " SET ".$fieldname." = ".((int) $id);
  2492. $sql .= ' WHERE rowid='.((int) $this->id);
  2493. if ($this->db->query($sql)) {
  2494. $this->retained_warranty_fk_cond_reglement = $id;
  2495. return 1;
  2496. } else {
  2497. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2498. $this->error = $this->db->error();
  2499. return -1;
  2500. }
  2501. } else {
  2502. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2503. $this->error = 'Status of the object is incompatible '.$this->statut;
  2504. return -2;
  2505. }
  2506. }
  2507. /**
  2508. * Define delivery address
  2509. * @deprecated
  2510. *
  2511. * @param int $id Address id
  2512. * @return int <0 si ko, >0 si ok
  2513. */
  2514. public function setDeliveryAddress($id)
  2515. {
  2516. $fieldname = 'fk_delivery_address';
  2517. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2518. $fieldname = 'fk_address';
  2519. }
  2520. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2521. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2522. if ($this->db->query($sql)) {
  2523. $this->fk_delivery_address = $id;
  2524. return 1;
  2525. } else {
  2526. $this->error = $this->db->error();
  2527. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2528. return -1;
  2529. }
  2530. }
  2531. /**
  2532. * Change the shipping method
  2533. *
  2534. * @param int $shipping_method_id Id of shipping method
  2535. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2536. * @param User $userused Object user
  2537. *
  2538. * @return int 1 if OK, 0 if KO
  2539. */
  2540. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2541. {
  2542. global $user;
  2543. if (empty($userused)) {
  2544. $userused = $user;
  2545. }
  2546. $error = 0;
  2547. if (!$this->table_element) {
  2548. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2549. return -1;
  2550. }
  2551. $this->db->begin();
  2552. if ($shipping_method_id < 0) {
  2553. $shipping_method_id = 'NULL';
  2554. }
  2555. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2556. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2557. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2558. $sql .= " WHERE rowid=".((int) $this->id);
  2559. $resql = $this->db->query($sql);
  2560. if (!$resql) {
  2561. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2562. $this->error = $this->db->lasterror();
  2563. $error++;
  2564. } else {
  2565. if (!$notrigger) {
  2566. // Call trigger
  2567. $this->context = array('shippingmethodupdate'=>1);
  2568. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2569. if ($result < 0) {
  2570. $error++;
  2571. }
  2572. // End call trigger
  2573. }
  2574. }
  2575. if ($error) {
  2576. $this->db->rollback();
  2577. return -1;
  2578. } else {
  2579. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2580. $this->db->commit();
  2581. return 1;
  2582. }
  2583. }
  2584. /**
  2585. * Change the warehouse
  2586. *
  2587. * @param int $warehouse_id Id of warehouse
  2588. * @return int 1 if OK, 0 if KO
  2589. */
  2590. public function setWarehouse($warehouse_id)
  2591. {
  2592. if (!$this->table_element) {
  2593. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2594. return -1;
  2595. }
  2596. if ($warehouse_id < 0) {
  2597. $warehouse_id = 'NULL';
  2598. }
  2599. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2600. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2601. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2602. $sql .= " WHERE rowid=".((int) $this->id);
  2603. if ($this->db->query($sql)) {
  2604. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2605. return 1;
  2606. } else {
  2607. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2608. $this->error = $this->db->error();
  2609. return 0;
  2610. }
  2611. }
  2612. /**
  2613. * Set last model used by doc generator
  2614. *
  2615. * @param User $user User object that make change
  2616. * @param string $modelpdf Modele name
  2617. * @return int <0 if KO, >0 if OK
  2618. */
  2619. public function setDocModel($user, $modelpdf)
  2620. {
  2621. if (!$this->table_element) {
  2622. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2623. return -1;
  2624. }
  2625. $newmodelpdf = dol_trunc($modelpdf, 255);
  2626. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2627. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2628. $sql .= " WHERE rowid = ".((int) $this->id);
  2629. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2630. $resql = $this->db->query($sql);
  2631. if ($resql) {
  2632. $this->model_pdf = $modelpdf;
  2633. $this->modelpdf = $modelpdf; // For bakward compatibility
  2634. return 1;
  2635. } else {
  2636. dol_print_error($this->db);
  2637. return 0;
  2638. }
  2639. }
  2640. /**
  2641. * Change the bank account
  2642. *
  2643. * @param int $fk_account Id of bank account
  2644. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2645. * @param User $userused Object user
  2646. * @return int 1 if OK, 0 if KO
  2647. */
  2648. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2649. {
  2650. global $user;
  2651. if (empty($userused)) {
  2652. $userused = $user;
  2653. }
  2654. $error = 0;
  2655. if (!$this->table_element) {
  2656. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2657. return -1;
  2658. }
  2659. $this->db->begin();
  2660. if ($fk_account < 0) {
  2661. $fk_account = 'NULL';
  2662. }
  2663. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2664. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2665. $sql .= " SET fk_account = ".((int) $fk_account);
  2666. $sql .= " WHERE rowid=".((int) $this->id);
  2667. $resql = $this->db->query($sql);
  2668. if (!$resql) {
  2669. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2670. $this->error = $this->db->lasterror();
  2671. $error++;
  2672. } else {
  2673. if (!$notrigger) {
  2674. // Call trigger
  2675. $this->context = array('bankaccountupdate'=>1);
  2676. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2677. if ($result < 0) {
  2678. $error++;
  2679. }
  2680. // End call trigger
  2681. }
  2682. }
  2683. if ($error) {
  2684. $this->db->rollback();
  2685. return -1;
  2686. } else {
  2687. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2688. $this->db->commit();
  2689. return 1;
  2690. }
  2691. }
  2692. // TODO: Move line related operations to CommonObjectLine?
  2693. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2694. /**
  2695. * Save a new position (field rang) for details lines.
  2696. * You can choose to set position for lines with already a position or lines without any position defined.
  2697. *
  2698. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2699. * @param string $rowidorder ASC or DESC
  2700. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2701. * @return int <0 if KO, >0 if OK
  2702. */
  2703. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2704. {
  2705. // phpcs:enable
  2706. if (!$this->table_element_line) {
  2707. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2708. return -1;
  2709. }
  2710. if (!$this->fk_element) {
  2711. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2712. return -1;
  2713. }
  2714. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2715. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2716. $fieldposition = 'position';
  2717. }
  2718. // Count number of lines to reorder (according to choice $renum)
  2719. $nl = 0;
  2720. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2721. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2722. if (!$renum) {
  2723. $sql .= " AND " . $fieldposition . " = 0";
  2724. }
  2725. if ($renum) {
  2726. $sql .= " AND " . $fieldposition . " <> 0";
  2727. }
  2728. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2729. $resql = $this->db->query($sql);
  2730. if ($resql) {
  2731. $row = $this->db->fetch_row($resql);
  2732. $nl = $row[0];
  2733. } else {
  2734. dol_print_error($this->db);
  2735. }
  2736. if ($nl > 0) {
  2737. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2738. $rows = array();
  2739. // We first search all lines that are parent lines (for multilevel details lines)
  2740. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2741. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2742. if ($fk_parent_line) {
  2743. $sql .= ' AND fk_parent_line IS NULL';
  2744. }
  2745. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2746. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2747. $resql = $this->db->query($sql);
  2748. if ($resql) {
  2749. $i = 0;
  2750. $num = $this->db->num_rows($resql);
  2751. while ($i < $num) {
  2752. $row = $this->db->fetch_row($resql);
  2753. $rows[] = $row[0]; // Add parent line into array rows
  2754. $childrens = $this->getChildrenOfLine($row[0]);
  2755. if (!empty($childrens)) {
  2756. foreach ($childrens as $child) {
  2757. array_push($rows, $child);
  2758. }
  2759. }
  2760. $i++;
  2761. }
  2762. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2763. if (!empty($rows)) {
  2764. foreach ($rows as $key => $row) {
  2765. $this->updateRangOfLine($row, ($key + 1));
  2766. }
  2767. }
  2768. } else {
  2769. dol_print_error($this->db);
  2770. }
  2771. }
  2772. return 1;
  2773. }
  2774. /**
  2775. * Get children of line
  2776. *
  2777. * @param int $id Id of parent line
  2778. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2779. * @return array Array with list of children lines id
  2780. */
  2781. public function getChildrenOfLine($id, $includealltree = 0)
  2782. {
  2783. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2784. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2785. $fieldposition = 'position';
  2786. }
  2787. $rows = array();
  2788. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2789. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2790. $sql .= ' AND fk_parent_line = '.((int) $id);
  2791. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2792. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2793. $resql = $this->db->query($sql);
  2794. if ($resql) {
  2795. if ($this->db->num_rows($resql) > 0) {
  2796. while ($row = $this->db->fetch_row($resql)) {
  2797. $rows[] = $row[0];
  2798. if (!empty($includealltree)) {
  2799. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2800. }
  2801. }
  2802. }
  2803. }
  2804. return $rows;
  2805. }
  2806. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2807. /**
  2808. * Update a line to have a lower rank
  2809. *
  2810. * @param int $rowid Id of line
  2811. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2812. * @return void
  2813. */
  2814. public function line_up($rowid, $fk_parent_line = true)
  2815. {
  2816. // phpcs:enable
  2817. $this->line_order(false, 'ASC', $fk_parent_line);
  2818. // Get rang of line
  2819. $rang = $this->getRangOfLine($rowid);
  2820. // Update position of line
  2821. $this->updateLineUp($rowid, $rang);
  2822. }
  2823. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2824. /**
  2825. * Update a line to have a higher rank
  2826. *
  2827. * @param int $rowid Id of line
  2828. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2829. * @return void
  2830. */
  2831. public function line_down($rowid, $fk_parent_line = true)
  2832. {
  2833. // phpcs:enable
  2834. $this->line_order(false, 'ASC', $fk_parent_line);
  2835. // Get rang of line
  2836. $rang = $this->getRangOfLine($rowid);
  2837. // Get max value for rang
  2838. $max = $this->line_max();
  2839. // Update position of line
  2840. $this->updateLineDown($rowid, $rang, $max);
  2841. }
  2842. /**
  2843. * Update position of line (rang)
  2844. *
  2845. * @param int $rowid Id of line
  2846. * @param int $rang Position
  2847. * @return int <0 if KO, >0 if OK
  2848. */
  2849. public function updateRangOfLine($rowid, $rang)
  2850. {
  2851. global $hookmanager;
  2852. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2853. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2854. $fieldposition = 'position';
  2855. }
  2856. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2857. $sql .= ' WHERE rowid = '.((int) $rowid);
  2858. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2859. if (!$this->db->query($sql)) {
  2860. dol_print_error($this->db);
  2861. return -1;
  2862. } else {
  2863. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2864. $action='';
  2865. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2866. return 1;
  2867. }
  2868. }
  2869. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2870. /**
  2871. * Update position of line with ajax (rang)
  2872. *
  2873. * @param array $rows Array of rows
  2874. * @return void
  2875. */
  2876. public function line_ajaxorder($rows)
  2877. {
  2878. // phpcs:enable
  2879. $num = count($rows);
  2880. for ($i = 0; $i < $num; $i++) {
  2881. $this->updateRangOfLine($rows[$i], ($i + 1));
  2882. }
  2883. }
  2884. /**
  2885. * Update position of line up (rang)
  2886. *
  2887. * @param int $rowid Id of line
  2888. * @param int $rang Position
  2889. * @return void
  2890. */
  2891. public function updateLineUp($rowid, $rang)
  2892. {
  2893. if ($rang > 1) {
  2894. $fieldposition = 'rang';
  2895. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2896. $fieldposition = 'position';
  2897. }
  2898. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2899. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2900. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2901. if ($this->db->query($sql)) {
  2902. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2903. $sql .= ' WHERE rowid = '.((int) $rowid);
  2904. if (!$this->db->query($sql)) {
  2905. dol_print_error($this->db);
  2906. }
  2907. } else {
  2908. dol_print_error($this->db);
  2909. }
  2910. }
  2911. }
  2912. /**
  2913. * Update position of line down (rang)
  2914. *
  2915. * @param int $rowid Id of line
  2916. * @param int $rang Position
  2917. * @param int $max Max
  2918. * @return void
  2919. */
  2920. public function updateLineDown($rowid, $rang, $max)
  2921. {
  2922. if ($rang < $max) {
  2923. $fieldposition = 'rang';
  2924. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2925. $fieldposition = 'position';
  2926. }
  2927. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2928. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2929. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2930. if ($this->db->query($sql)) {
  2931. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2932. $sql .= ' WHERE rowid = '.((int) $rowid);
  2933. if (!$this->db->query($sql)) {
  2934. dol_print_error($this->db);
  2935. }
  2936. } else {
  2937. dol_print_error($this->db);
  2938. }
  2939. }
  2940. }
  2941. /**
  2942. * Get position of line (rang)
  2943. *
  2944. * @param int $rowid Id of line
  2945. * @return int Value of rang in table of lines
  2946. */
  2947. public function getRangOfLine($rowid)
  2948. {
  2949. $fieldposition = 'rang';
  2950. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2951. $fieldposition = 'position';
  2952. }
  2953. $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  2954. $sql .= " WHERE rowid = ".((int) $rowid);
  2955. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2956. $resql = $this->db->query($sql);
  2957. if ($resql) {
  2958. $row = $this->db->fetch_row($resql);
  2959. return $row[0];
  2960. }
  2961. }
  2962. /**
  2963. * Get rowid of the line relative to its position
  2964. *
  2965. * @param int $rang Rang value
  2966. * @return int Rowid of the line
  2967. */
  2968. public function getIdOfLine($rang)
  2969. {
  2970. $fieldposition = 'rang';
  2971. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2972. $fieldposition = 'position';
  2973. }
  2974. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2975. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2976. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  2977. $resql = $this->db->query($sql);
  2978. if ($resql) {
  2979. $row = $this->db->fetch_row($resql);
  2980. return $row[0];
  2981. }
  2982. }
  2983. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2984. /**
  2985. * Get max value used for position of line (rang)
  2986. *
  2987. * @param int $fk_parent_line Parent line id
  2988. * @return int Max value of rang in table of lines
  2989. */
  2990. public function line_max($fk_parent_line = 0)
  2991. {
  2992. // phpcs:enable
  2993. $positionfield = 'rang';
  2994. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  2995. $positionfield = 'position';
  2996. }
  2997. // Search the last rang with fk_parent_line
  2998. if ($fk_parent_line) {
  2999. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  3000. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3001. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  3002. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3003. $resql = $this->db->query($sql);
  3004. if ($resql) {
  3005. $row = $this->db->fetch_row($resql);
  3006. if (!empty($row[0])) {
  3007. return $row[0];
  3008. } else {
  3009. return $this->getRangOfLine($fk_parent_line);
  3010. }
  3011. }
  3012. } else {
  3013. // If not, search the last rang of element
  3014. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  3015. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3016. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3017. $resql = $this->db->query($sql);
  3018. if ($resql) {
  3019. $row = $this->db->fetch_row($resql);
  3020. return $row[0];
  3021. }
  3022. }
  3023. }
  3024. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3025. /**
  3026. * Update external ref of element
  3027. *
  3028. * @param string $ref_ext Update field ref_ext
  3029. * @return int <0 if KO, >0 if OK
  3030. */
  3031. public function update_ref_ext($ref_ext)
  3032. {
  3033. // phpcs:enable
  3034. if (!$this->table_element) {
  3035. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  3036. return -1;
  3037. }
  3038. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3039. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  3040. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  3041. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  3042. if ($this->db->query($sql)) {
  3043. $this->ref_ext = $ref_ext;
  3044. return 1;
  3045. } else {
  3046. $this->error = $this->db->error();
  3047. return -1;
  3048. }
  3049. }
  3050. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3051. /**
  3052. * Update note of element
  3053. *
  3054. * @param string $note New value for note
  3055. * @param string $suffix '', '_public' or '_private'
  3056. * @return int <0 if KO, >0 if OK
  3057. */
  3058. public function update_note($note, $suffix = '')
  3059. {
  3060. // phpcs:enable
  3061. global $user;
  3062. if (!$this->table_element) {
  3063. $this->error = 'update_note was called on objet with property table_element not defined';
  3064. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  3065. return -1;
  3066. }
  3067. if (!in_array($suffix, array('', '_public', '_private'))) {
  3068. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3069. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3070. return -2;
  3071. }
  3072. $newsuffix = $suffix;
  3073. // Special cas
  3074. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3075. $newsuffix = '';
  3076. }
  3077. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3078. $fieldusermod = "fk_user_mod";
  3079. } elseif ($this->table_element == 'ecm_files') {
  3080. $fieldusermod = "fk_user_m";
  3081. } else {
  3082. $fieldusermod = "fk_user_modif";
  3083. }
  3084. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3085. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  3086. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  3087. $sql .= " WHERE rowid = ".((int) $this->id);
  3088. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  3089. if ($this->db->query($sql)) {
  3090. if ($suffix == '_public') {
  3091. $this->note_public = $note;
  3092. } elseif ($suffix == '_private') {
  3093. $this->note_private = $note;
  3094. } else {
  3095. $this->note = $note; // deprecated
  3096. $this->note_private = $note;
  3097. }
  3098. return 1;
  3099. } else {
  3100. $this->error = $this->db->lasterror();
  3101. return -1;
  3102. }
  3103. }
  3104. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3105. /**
  3106. * Update public note (kept for backward compatibility)
  3107. *
  3108. * @param string $note New value for note
  3109. * @return int <0 if KO, >0 if OK
  3110. * @deprecated
  3111. * @see update_note()
  3112. */
  3113. public function update_note_public($note)
  3114. {
  3115. // phpcs:enable
  3116. return $this->update_note($note, '_public');
  3117. }
  3118. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3119. /**
  3120. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3121. * Must be called at end of methods addline or updateline.
  3122. *
  3123. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3124. * @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
  3125. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  3126. * @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).
  3127. * @return int <0 if KO, >0 if OK
  3128. */
  3129. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3130. {
  3131. // phpcs:enable
  3132. global $conf, $hookmanager, $action;
  3133. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3134. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3135. if ($reshook > 0) {
  3136. return 1; // replacement code
  3137. } elseif ($reshook < 0) {
  3138. return -1; // failure
  3139. } // reshook = 0 => execute normal code
  3140. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3141. $MODULE = "";
  3142. if ($this->element == 'propal') {
  3143. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3144. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3145. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3146. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3147. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3148. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3149. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3150. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3151. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3152. } elseif ($this->element == 'supplier_proposal') {
  3153. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3154. }
  3155. if (!empty($MODULE)) {
  3156. if (!empty($conf->global->$MODULE)) {
  3157. $modsactivated = explode(',', $conf->global->$MODULE);
  3158. foreach ($modsactivated as $mod) {
  3159. if ($conf->$mod->enabled) {
  3160. return 1; // update was disabled by specific setup
  3161. }
  3162. }
  3163. }
  3164. }
  3165. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3166. if ($roundingadjust == '-1') {
  3167. $roundingadjust = 'auto'; // For backward compatibility
  3168. }
  3169. $forcedroundingmode = $roundingadjust;
  3170. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3171. $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
  3172. } elseif ($forcedroundingmode == 'auto') {
  3173. $forcedroundingmode = '0';
  3174. }
  3175. $error = 0;
  3176. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3177. // Define constants to find lines to sum
  3178. $fieldtva = 'total_tva';
  3179. $fieldlocaltax1 = 'total_localtax1';
  3180. $fieldlocaltax2 = 'total_localtax2';
  3181. $fieldup = 'subprice';
  3182. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3183. $fieldtva = 'tva';
  3184. $fieldup = 'pu_ht';
  3185. }
  3186. if ($this->element == 'invoice_supplier_rec') {
  3187. $fieldup = 'pu_ht';
  3188. }
  3189. if ($this->element == 'expensereport') {
  3190. $fieldup = 'value_unit';
  3191. }
  3192. $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,";
  3193. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3194. if ($this->table_element_line == 'facturedet') {
  3195. $sql .= ', situation_percent';
  3196. }
  3197. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3198. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3199. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3200. if ($exclspec) {
  3201. $product_field = 'product_type';
  3202. if ($this->table_element_line == 'contratdet') {
  3203. $product_field = ''; // contratdet table has no product_type field
  3204. }
  3205. if ($product_field) {
  3206. $sql .= " AND ".$product_field." <> 9";
  3207. }
  3208. }
  3209. $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
  3210. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3211. $resql = $this->db->query($sql);
  3212. if ($resql) {
  3213. $this->total_ht = 0;
  3214. $this->total_tva = 0;
  3215. $this->total_localtax1 = 0;
  3216. $this->total_localtax2 = 0;
  3217. $this->total_ttc = 0;
  3218. $total_ht_by_vats = array();
  3219. $total_tva_by_vats = array();
  3220. $total_ttc_by_vats = array();
  3221. $this->multicurrency_total_ht = 0;
  3222. $this->multicurrency_total_tva = 0;
  3223. $this->multicurrency_total_ttc = 0;
  3224. $num = $this->db->num_rows($resql);
  3225. $i = 0;
  3226. while ($i < $num) {
  3227. $obj = $this->db->fetch_object($resql);
  3228. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3229. $parameters = array('fk_element' => $obj->rowid);
  3230. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3231. 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'
  3232. // This part of code is to fix data. We should not call it too often.
  3233. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3234. $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);
  3235. $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price adn unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
  3236. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3237. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3238. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3239. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3240. $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);
  3241. dol_syslog('We found unconsistent data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
  3242. $resqlfix = $this->db->query($sqlfix);
  3243. if (!$resqlfix) {
  3244. dol_print_error($this->db, 'Failed to update line');
  3245. }
  3246. $obj->total_tva = $tmpcal[1];
  3247. $obj->total_ttc = $tmpcal[2];
  3248. }
  3249. }
  3250. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3251. $this->total_tva += $obj->total_tva;
  3252. $this->total_localtax1 += $obj->total_localtax1;
  3253. $this->total_localtax2 += $obj->total_localtax2;
  3254. $this->total_ttc += $obj->total_ttc;
  3255. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3256. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3257. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3258. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3259. $total_ht_by_vats[$obj->vatrate] = 0;
  3260. }
  3261. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3262. $total_tva_by_vats[$obj->vatrate] = 0;
  3263. }
  3264. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3265. $total_ttc_by_vats[$obj->vatrate] = 0;
  3266. }
  3267. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3268. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3269. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3270. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3271. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3272. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3273. //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";
  3274. if ($diff) {
  3275. if (abs($diff) > 0.1) {
  3276. $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your line may be corrupted. Try to edit each line manually.';
  3277. dol_syslog($errmsg, LOG_WARNING);
  3278. dol_print_error('', $errmsg);
  3279. exit;
  3280. }
  3281. $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);
  3282. 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);
  3283. $resqlfix = $this->db->query($sqlfix);
  3284. if (!$resqlfix) {
  3285. dol_print_error($this->db, 'Failed to update line');
  3286. }
  3287. $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
  3288. $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
  3289. $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
  3290. $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
  3291. }
  3292. }
  3293. $i++;
  3294. }
  3295. // Add revenue stamp to total
  3296. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3297. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3298. // Situations totals
  3299. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3300. $prev_sits = $this->get_prev_sits();
  3301. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3302. $this->total_ht -= $sit->total_ht;
  3303. $this->total_tva -= $sit->total_tva;
  3304. $this->total_localtax1 -= $sit->total_localtax1;
  3305. $this->total_localtax2 -= $sit->total_localtax2;
  3306. $this->total_ttc -= $sit->total_ttc;
  3307. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3308. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3309. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3310. }
  3311. }
  3312. // Clean total
  3313. $this->total_ht = (float) price2num($this->total_ht);
  3314. $this->total_tva = (float) price2num($this->total_tva);
  3315. $this->total_localtax1 = (float) price2num($this->total_localtax1);
  3316. $this->total_localtax2 = (float) price2num($this->total_localtax2);
  3317. $this->total_ttc = (float) price2num($this->total_ttc);
  3318. $this->db->free($resql);
  3319. // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
  3320. $fieldht = 'total_ht';
  3321. $fieldtva = 'tva';
  3322. $fieldlocaltax1 = 'localtax1';
  3323. $fieldlocaltax2 = 'localtax2';
  3324. $fieldttc = 'total_ttc';
  3325. // Specific code for backward compatibility with old field names
  3326. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3327. $fieldtva = 'total_tva';
  3328. }
  3329. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3330. $fieldtva = 'total_tva';
  3331. }
  3332. if ($this->element == 'propal') {
  3333. $fieldtva = 'total_tva';
  3334. }
  3335. if ($this->element == 'expensereport') {
  3336. $fieldtva = 'total_tva';
  3337. }
  3338. if ($this->element == 'supplier_proposal') {
  3339. $fieldtva = 'total_tva';
  3340. }
  3341. if ($this->element == 'commande') {
  3342. $fieldtva = 'total_tva';
  3343. }
  3344. if ($this->element == 'order_supplier') {
  3345. $fieldtva = 'total_tva';
  3346. }
  3347. if (empty($nodatabaseupdate)) {
  3348. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3349. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
  3350. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
  3351. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
  3352. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
  3353. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
  3354. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3355. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3356. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3357. $sql .= " WHERE rowid = ".((int) $this->id);
  3358. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3359. $resql = $this->db->query($sql);
  3360. if (!$resql) {
  3361. $error++;
  3362. $this->error = $this->db->lasterror();
  3363. $this->errors[] = $this->db->lasterror();
  3364. }
  3365. }
  3366. if (!$error) {
  3367. return 1;
  3368. } else {
  3369. return -1;
  3370. }
  3371. } else {
  3372. dol_print_error($this->db, 'Bad request in update_price');
  3373. return -1;
  3374. }
  3375. }
  3376. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3377. /**
  3378. * Add an object link into llx_element_element.
  3379. *
  3380. * @param string $origin Linked element type
  3381. * @param int $origin_id Linked element id
  3382. * @param User $f_user User that create
  3383. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3384. * @return int <=0 if KO, >0 if OK
  3385. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3386. */
  3387. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3388. {
  3389. // phpcs:enable
  3390. global $user, $hookmanager, $action;
  3391. $origin = (!empty($origin) ? $origin : $this->origin);
  3392. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3393. $f_user = isset($f_user) ? $f_user : $user;
  3394. // Special case
  3395. if ($origin == 'order') {
  3396. $origin = 'commande';
  3397. }
  3398. if ($origin == 'invoice') {
  3399. $origin = 'facture';
  3400. }
  3401. if ($origin == 'invoice_template') {
  3402. $origin = 'facturerec';
  3403. }
  3404. if ($origin == 'supplierorder') {
  3405. $origin = 'order_supplier';
  3406. }
  3407. // 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.
  3408. // 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.
  3409. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3410. // Add module part to target type if object has $module property and isn't in core modules.
  3411. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3412. $parameters = array('targettype'=>$targettype);
  3413. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3414. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3415. if ($reshook > 0) {
  3416. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3417. }
  3418. $this->db->begin();
  3419. $error = 0;
  3420. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3421. $sql .= "fk_source";
  3422. $sql .= ", sourcetype";
  3423. $sql .= ", fk_target";
  3424. $sql .= ", targettype";
  3425. $sql .= ") VALUES (";
  3426. $sql .= ((int) $origin_id);
  3427. $sql .= ", '" . $this->db->escape($origin) . "'";
  3428. $sql .= ", " . ((int) $this->id);
  3429. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3430. $sql .= ")";
  3431. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3432. if ($this->db->query($sql)) {
  3433. if (!$notrigger) {
  3434. // Call trigger
  3435. $this->context['link_origin'] = $origin;
  3436. $this->context['link_origin_id'] = $origin_id;
  3437. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3438. if ($result < 0) {
  3439. $error++;
  3440. }
  3441. // End call triggers
  3442. }
  3443. } else {
  3444. $this->error = $this->db->lasterror();
  3445. $error++;
  3446. }
  3447. if (!$error) {
  3448. $this->db->commit();
  3449. return 1;
  3450. } else {
  3451. $this->db->rollback();
  3452. return 0;
  3453. }
  3454. }
  3455. /**
  3456. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3457. * this->linkedObjectsIds array +
  3458. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3459. * Possible usage for parameters:
  3460. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3461. * - source id+type -> will get list of targets linked to source
  3462. * - target id+type -> will get list of sources linked to target
  3463. * - source id+type + target type -> will get list of targets of the type linked to source
  3464. * - target id+type + source type -> will get list of sources of the type linked to target
  3465. *
  3466. * @param int $sourceid Object source id (if not defined, id of object)
  3467. * @param string $sourcetype Object source type (if not defined, element name of object)
  3468. * @param int $targetid Object target id (if not defined, id of object)
  3469. * @param string $targettype Object target type (if not defined, element name of object)
  3470. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3471. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3472. * @param string $orderby SQL 'ORDER BY' clause
  3473. * @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.
  3474. * @return int <0 if KO, >0 if OK
  3475. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3476. */
  3477. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3478. {
  3479. global $conf, $hookmanager, $action;
  3480. // Important for pdf generation time reduction
  3481. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3482. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3483. return 1;
  3484. }
  3485. $this->linkedObjectsIds = array();
  3486. $this->linkedObjects = array();
  3487. $justsource = false;
  3488. $justtarget = false;
  3489. $withtargettype = false;
  3490. $withsourcetype = false;
  3491. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3492. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3493. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3494. if ($reshook > 0) {
  3495. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3496. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3497. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3498. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3499. }
  3500. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3501. $justsource = true; // the source (id and type) is a search criteria
  3502. if (!empty($targettype)) {
  3503. $withtargettype = true;
  3504. }
  3505. }
  3506. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3507. $justtarget = true; // the target (id and type) is a search criteria
  3508. if (!empty($sourcetype)) {
  3509. $withsourcetype = true;
  3510. }
  3511. }
  3512. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3513. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3514. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3515. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3516. /*if (empty($sourceid) && empty($targetid))
  3517. {
  3518. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3519. return -1;
  3520. }*/
  3521. // Links between objects are stored in table element_element
  3522. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3523. $sql .= " FROM ".$this->db->prefix()."element_element";
  3524. $sql .= " WHERE ";
  3525. if ($justsource || $justtarget) {
  3526. if ($justsource) {
  3527. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3528. if ($withtargettype) {
  3529. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3530. }
  3531. } elseif ($justtarget) {
  3532. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3533. if ($withsourcetype) {
  3534. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3535. }
  3536. }
  3537. } else {
  3538. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3539. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3540. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3541. $this->linkedObjectsFullLoaded[$this->id] = true;
  3542. }
  3543. }
  3544. $sql .= " ORDER BY ".$orderby;
  3545. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3546. $resql = $this->db->query($sql);
  3547. if ($resql) {
  3548. $num = $this->db->num_rows($resql);
  3549. $i = 0;
  3550. while ($i < $num) {
  3551. $obj = $this->db->fetch_object($resql);
  3552. if ($justsource || $justtarget) {
  3553. if ($justsource) {
  3554. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3555. } elseif ($justtarget) {
  3556. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3557. }
  3558. } else {
  3559. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3560. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3561. }
  3562. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3563. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3564. }
  3565. }
  3566. $i++;
  3567. }
  3568. if (!empty($this->linkedObjectsIds)) {
  3569. $tmparray = $this->linkedObjectsIds;
  3570. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3571. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3572. $module = $element = $subelement = $objecttype;
  3573. $regs = array();
  3574. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3575. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3576. $module = $element = $regs[1];
  3577. $subelement = $regs[2];
  3578. }
  3579. $classpath = $element.'/class';
  3580. // To work with non standard classpath or module name
  3581. if ($objecttype == 'facture') {
  3582. $classpath = 'compta/facture/class';
  3583. } elseif ($objecttype == 'facturerec') {
  3584. $classpath = 'compta/facture/class';
  3585. $module = 'facture';
  3586. } elseif ($objecttype == 'propal') {
  3587. $classpath = 'comm/propal/class';
  3588. } elseif ($objecttype == 'supplier_proposal') {
  3589. $classpath = 'supplier_proposal/class';
  3590. } elseif ($objecttype == 'shipping') {
  3591. $classpath = 'expedition/class';
  3592. $subelement = 'expedition';
  3593. $module = 'expedition_bon';
  3594. } elseif ($objecttype == 'delivery') {
  3595. $classpath = 'delivery/class';
  3596. $subelement = 'delivery';
  3597. $module = 'delivery_note';
  3598. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3599. $classpath = 'fourn/class';
  3600. $module = 'fournisseur';
  3601. } elseif ($objecttype == 'fichinter') {
  3602. $classpath = 'fichinter/class';
  3603. $subelement = 'fichinter';
  3604. $module = 'ficheinter';
  3605. } elseif ($objecttype == 'subscription') {
  3606. $classpath = 'adherents/class';
  3607. $module = 'adherent';
  3608. } elseif ($objecttype == 'contact') {
  3609. $module = 'societe';
  3610. }
  3611. // Set classfile
  3612. $classfile = strtolower($subelement);
  3613. $classname = ucfirst($subelement);
  3614. if ($objecttype == 'order') {
  3615. $classfile = 'commande';
  3616. $classname = 'Commande';
  3617. } elseif ($objecttype == 'invoice_supplier') {
  3618. $classfile = 'fournisseur.facture';
  3619. $classname = 'FactureFournisseur';
  3620. } elseif ($objecttype == 'order_supplier') {
  3621. $classfile = 'fournisseur.commande';
  3622. $classname = 'CommandeFournisseur';
  3623. } elseif ($objecttype == 'supplier_proposal') {
  3624. $classfile = 'supplier_proposal';
  3625. $classname = 'SupplierProposal';
  3626. } elseif ($objecttype == 'facturerec') {
  3627. $classfile = 'facture-rec';
  3628. $classname = 'FactureRec';
  3629. } elseif ($objecttype == 'subscription') {
  3630. $classfile = 'subscription';
  3631. $classname = 'Subscription';
  3632. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3633. $classpath = 'projet/class';
  3634. $classfile = 'project';
  3635. $classname = 'Project';
  3636. } elseif ($objecttype == 'conferenceorboothattendee') {
  3637. $classpath = 'eventorganization/class';
  3638. $classfile = 'conferenceorboothattendee';
  3639. $classname = 'ConferenceOrBoothAttendee';
  3640. $module = 'eventorganization';
  3641. } elseif ($objecttype == 'conferenceorbooth') {
  3642. $classpath = 'eventorganization/class';
  3643. $classfile = 'conferenceorbooth';
  3644. $classname = 'ConferenceOrBooth';
  3645. $module = 'eventorganization';
  3646. } elseif ($objecttype == 'mo') {
  3647. $classpath = 'mrp/class';
  3648. $classfile = 'mo';
  3649. $classname = 'Mo';
  3650. $module = 'mrp';
  3651. }
  3652. // Here $module, $classfile and $classname are set, we can use them.
  3653. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3654. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3655. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3656. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3657. if (class_exists($classname)) {
  3658. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3659. $object = new $classname($this->db);
  3660. $ret = $object->fetch($objectid);
  3661. if ($ret >= 0) {
  3662. $this->linkedObjects[$objecttype][$i] = $object;
  3663. }
  3664. }
  3665. }
  3666. }
  3667. } else {
  3668. unset($this->linkedObjectsIds[$objecttype]);
  3669. }
  3670. }
  3671. }
  3672. return 1;
  3673. } else {
  3674. dol_print_error($this->db);
  3675. return -1;
  3676. }
  3677. }
  3678. /**
  3679. * Clear the cache saying that all linked object were already loaded. So next fetchObjectLinked will reload all links.
  3680. *
  3681. * @return int <0 if KO, >0 if OK
  3682. * @see fetchObjectLinked()
  3683. */
  3684. public function clearObjectLinkedCache()
  3685. {
  3686. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3687. unset($this->linkedObjectsFullLoaded[$this->id]);
  3688. }
  3689. return 1;
  3690. }
  3691. /**
  3692. * Update object linked of a current object
  3693. *
  3694. * @param int $sourceid Object source id
  3695. * @param string $sourcetype Object source type
  3696. * @param int $targetid Object target id
  3697. * @param string $targettype Object target type
  3698. * @param User $f_user User that create
  3699. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3700. * @return int >0 if OK, <0 if KO
  3701. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3702. */
  3703. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3704. {
  3705. global $user;
  3706. $updatesource = false;
  3707. $updatetarget = false;
  3708. $f_user = isset($f_user) ? $f_user : $user;
  3709. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3710. $updatesource = true;
  3711. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3712. $updatetarget = true;
  3713. }
  3714. $this->db->begin();
  3715. $error = 0;
  3716. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3717. if ($updatesource) {
  3718. $sql .= "fk_source = " . ((int) $sourceid);
  3719. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3720. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3721. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3722. } elseif ($updatetarget) {
  3723. $sql .= "fk_target = " . ((int) $targetid);
  3724. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3725. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3726. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3727. }
  3728. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3729. if ($this->db->query($sql)) {
  3730. if (!$notrigger) {
  3731. // Call trigger
  3732. $this->context['link_source_id'] = $sourceid;
  3733. $this->context['link_source_type'] = $sourcetype;
  3734. $this->context['link_target_id'] = $targetid;
  3735. $this->context['link_target_type'] = $targettype;
  3736. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3737. if ($result < 0) {
  3738. $error++;
  3739. }
  3740. // End call triggers
  3741. }
  3742. } else {
  3743. $this->error = $this->db->lasterror();
  3744. $error++;
  3745. }
  3746. if (!$error) {
  3747. $this->db->commit();
  3748. return 1;
  3749. } else {
  3750. $this->db->rollback();
  3751. return -1;
  3752. }
  3753. }
  3754. /**
  3755. * Delete all links between an object $this
  3756. *
  3757. * @param int $sourceid Object source id
  3758. * @param string $sourcetype Object source type
  3759. * @param int $targetid Object target id
  3760. * @param string $targettype Object target type
  3761. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3762. * @param User $f_user User that create
  3763. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3764. * @return int >0 if OK, <0 if KO
  3765. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3766. */
  3767. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3768. {
  3769. global $user;
  3770. $deletesource = false;
  3771. $deletetarget = false;
  3772. $f_user = isset($f_user) ? $f_user : $user;
  3773. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3774. $deletesource = true;
  3775. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3776. $deletetarget = true;
  3777. }
  3778. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3779. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3780. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3781. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3782. $this->db->begin();
  3783. $error = 0;
  3784. if (!$notrigger) {
  3785. // Call trigger
  3786. $this->context['link_id'] = $rowid;
  3787. $this->context['link_source_id'] = $sourceid;
  3788. $this->context['link_source_type'] = $sourcetype;
  3789. $this->context['link_target_id'] = $targetid;
  3790. $this->context['link_target_type'] = $targettype;
  3791. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3792. if ($result < 0) {
  3793. $error++;
  3794. }
  3795. // End call triggers
  3796. }
  3797. if (!$error) {
  3798. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3799. $sql .= " WHERE";
  3800. if ($rowid > 0) {
  3801. $sql .= " rowid = " . ((int) $rowid);
  3802. } else {
  3803. if ($deletesource) {
  3804. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3805. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3806. } elseif ($deletetarget) {
  3807. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3808. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3809. } else {
  3810. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3811. $sql .= " OR";
  3812. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3813. }
  3814. }
  3815. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3816. if (!$this->db->query($sql)) {
  3817. $this->error = $this->db->lasterror();
  3818. $this->errors[] = $this->error;
  3819. $error++;
  3820. }
  3821. }
  3822. if (!$error) {
  3823. $this->db->commit();
  3824. return 1;
  3825. } else {
  3826. $this->db->rollback();
  3827. return 0;
  3828. }
  3829. }
  3830. /**
  3831. * Function used to get an array with all items linked to an object id in association table
  3832. *
  3833. * @param int $fk_object_where id of object we need to get linked items
  3834. * @param string $field_select name of field we need to get a list
  3835. * @param string $field_where name of field of object we need to get linked items
  3836. * @param string $table_element name of association table
  3837. * @return array Array of record
  3838. */
  3839. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3840. {
  3841. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3842. return -1;
  3843. }
  3844. global $db;
  3845. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3846. $resql = $db->query($sql);
  3847. $TRes = array();
  3848. if (!empty($resql)) {
  3849. while ($res = $db->fetch_object($resql)) {
  3850. $TRes[] = $res->{$field_select};
  3851. }
  3852. }
  3853. return $TRes;
  3854. }
  3855. /**
  3856. * Function used to remove all items linked to an object id in association table
  3857. *
  3858. * @param int $fk_object_where id of object we need to remove linked items
  3859. * @param string $field_where name of field of object we need to delete linked items
  3860. * @param string $table_element name of association table
  3861. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3862. */
  3863. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3864. {
  3865. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3866. return -1;
  3867. }
  3868. global $db;
  3869. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3870. $resql = $db->query($sql);
  3871. if (empty($resql)) {
  3872. return 0;
  3873. }
  3874. return 1;
  3875. }
  3876. /**
  3877. * Set status of an object
  3878. *
  3879. * @param int $status Status to set
  3880. * @param int $elementId Id of element to force (use this->id by default if null)
  3881. * @param string $elementType Type of element to force (use this->table_element by default)
  3882. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated.
  3883. * @param string $fieldstatus Name of status field in this->table_element
  3884. * @return int <0 if KO, >0 if OK
  3885. */
  3886. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3887. {
  3888. global $user, $langs, $conf;
  3889. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3890. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3891. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3892. $this->db->begin();
  3893. if ($elementTable == 'facture_rec') {
  3894. $fieldstatus = "suspended";
  3895. }
  3896. if ($elementTable == 'mailing') {
  3897. $fieldstatus = "statut";
  3898. }
  3899. if ($elementTable == 'cronjob') {
  3900. $fieldstatus = "status";
  3901. }
  3902. if ($elementTable == 'user') {
  3903. $fieldstatus = "statut";
  3904. }
  3905. if ($elementTable == 'expensereport') {
  3906. $fieldstatus = "fk_statut";
  3907. }
  3908. if ($elementTable == 'commande_fournisseur_dispatch') {
  3909. $fieldstatus = "status";
  3910. }
  3911. if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3912. $fieldstatus = 'status';
  3913. }
  3914. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3915. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3916. // If status = 1 = validated, update also fk_user_valid
  3917. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3918. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3919. $sql .= ", fk_user_valid = ".((int) $user->id);
  3920. }
  3921. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3922. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3923. }
  3924. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3925. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3926. }
  3927. $sql .= " WHERE rowid = ".((int) $elementId);
  3928. $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
  3929. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3930. $resql = $this->db->query($sql);
  3931. if ($resql) {
  3932. $error = 0;
  3933. $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
  3934. if ($nb_rows_affected > 0) {
  3935. if (empty($trigkey)) {
  3936. // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
  3937. if ($this->element == 'supplier_proposal' && $status == 2) {
  3938. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3939. }
  3940. if ($this->element == 'supplier_proposal' && $status == 3) {
  3941. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3942. }
  3943. if ($this->element == 'supplier_proposal' && $status == 4) {
  3944. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3945. }
  3946. if ($this->element == 'fichinter' && $status == 3) {
  3947. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3948. }
  3949. if ($this->element == 'fichinter' && $status == 2) {
  3950. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3951. }
  3952. if ($this->element == 'fichinter' && $status == 1) {
  3953. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3954. }
  3955. }
  3956. if ($trigkey) {
  3957. // Call trigger
  3958. $result = $this->call_trigger($trigkey, $user);
  3959. if ($result < 0) {
  3960. $error++;
  3961. }
  3962. // End call triggers
  3963. }
  3964. } else {
  3965. // The status was probably already good. We do nothing more, no triggers.
  3966. }
  3967. if (!$error) {
  3968. $this->db->commit();
  3969. if (empty($savElementId)) {
  3970. // If the element we update is $this (so $elementId was provided as null)
  3971. if ($fieldstatus == 'tosell') {
  3972. $this->status = $status;
  3973. } elseif ($fieldstatus == 'tobuy') {
  3974. $this->status_buy = $status;
  3975. } else {
  3976. $this->statut = $status;
  3977. $this->status = $status;
  3978. }
  3979. }
  3980. return 1;
  3981. } else {
  3982. $this->db->rollback();
  3983. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3984. return -1;
  3985. }
  3986. } else {
  3987. $this->error = $this->db->lasterror();
  3988. $this->db->rollback();
  3989. return -1;
  3990. }
  3991. }
  3992. /**
  3993. * Load type of canvas of an object if it exists
  3994. *
  3995. * @param int $id Record id
  3996. * @param string $ref Record ref
  3997. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3998. */
  3999. public function getCanvas($id = 0, $ref = '')
  4000. {
  4001. global $conf;
  4002. if (empty($id) && empty($ref)) {
  4003. return 0;
  4004. }
  4005. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  4006. return 0; // To increase speed. Not enabled by default.
  4007. }
  4008. // Clean parameters
  4009. $ref = trim($ref);
  4010. $sql = "SELECT rowid, canvas";
  4011. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  4012. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  4013. if (!empty($id)) {
  4014. $sql .= " AND rowid = ".((int) $id);
  4015. }
  4016. if (!empty($ref)) {
  4017. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  4018. }
  4019. $resql = $this->db->query($sql);
  4020. if ($resql) {
  4021. $obj = $this->db->fetch_object($resql);
  4022. if ($obj) {
  4023. $this->canvas = $obj->canvas;
  4024. return 1;
  4025. } else {
  4026. return 0;
  4027. }
  4028. } else {
  4029. dol_print_error($this->db);
  4030. return -1;
  4031. }
  4032. }
  4033. /**
  4034. * Get special code of a line
  4035. *
  4036. * @param int $lineid Id of line
  4037. * @return int Special code
  4038. */
  4039. public function getSpecialCode($lineid)
  4040. {
  4041. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  4042. $sql .= " WHERE rowid = ".((int) $lineid);
  4043. $resql = $this->db->query($sql);
  4044. if ($resql) {
  4045. $row = $this->db->fetch_row($resql);
  4046. return $row[0];
  4047. }
  4048. }
  4049. /**
  4050. * Function to check if an object is used by others.
  4051. * Check is done into this->childtables. There is no check into llx_element_element.
  4052. *
  4053. * @param int $id Force id of object
  4054. * @param int $entity Force entity to check
  4055. * @return int <0 if KO, 0 if not used, >0 if already used
  4056. */
  4057. public function isObjectUsed($id = 0, $entity = 0)
  4058. {
  4059. global $langs;
  4060. if (empty($id)) {
  4061. $id = $this->id;
  4062. }
  4063. // Check parameters
  4064. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  4065. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  4066. return -1;
  4067. }
  4068. $arraytoscan = $this->childtables;
  4069. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  4070. $tmparray = array_keys($this->childtables);
  4071. if (is_numeric($tmparray[0])) {
  4072. $arraytoscan = array_flip($this->childtables);
  4073. }
  4074. // Test if child exists
  4075. $haschild = 0;
  4076. foreach ($arraytoscan as $table => $element) {
  4077. //print $id.'-'.$table.'-'.$elementname.'<br>';
  4078. // Check if element can be deleted
  4079. $sql = "SELECT COUNT(*) as nb";
  4080. $sql.= " FROM ".$this->db->prefix().$table." as c";
  4081. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4082. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  4083. }
  4084. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  4085. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4086. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  4087. }
  4088. if (!empty($entity)) {
  4089. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4090. $sql.= " AND p.entity = ".((int) $entity);
  4091. } else {
  4092. $sql.= " AND c.entity = ".((int) $entity);
  4093. }
  4094. }
  4095. $resql = $this->db->query($sql);
  4096. if ($resql) {
  4097. $obj = $this->db->fetch_object($resql);
  4098. if ($obj->nb > 0) {
  4099. $langs->load("errors");
  4100. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4101. $haschild += $obj->nb;
  4102. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4103. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4104. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4105. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4106. } else { // new usage: $element['name']=Translation key
  4107. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4108. }
  4109. break; // We found at least one, we stop here
  4110. }
  4111. } else {
  4112. $this->errors[] = $this->db->lasterror();
  4113. return -1;
  4114. }
  4115. }
  4116. if ($haschild > 0) {
  4117. $this->errors[] = "ErrorRecordHasChildren";
  4118. return $haschild;
  4119. } else {
  4120. return 0;
  4121. }
  4122. }
  4123. /**
  4124. * Function to say how many lines object contains
  4125. *
  4126. * @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
  4127. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4128. */
  4129. public function hasProductsOrServices($predefined = -1)
  4130. {
  4131. $nb = 0;
  4132. foreach ($this->lines as $key => $val) {
  4133. $qualified = 0;
  4134. if ($predefined == -1) {
  4135. $qualified = 1;
  4136. }
  4137. if ($predefined == 1 && $val->fk_product > 0) {
  4138. $qualified = 1;
  4139. }
  4140. if ($predefined == 0 && $val->fk_product <= 0) {
  4141. $qualified = 1;
  4142. }
  4143. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4144. $qualified = 1;
  4145. }
  4146. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4147. $qualified = 1;
  4148. }
  4149. if ($qualified) {
  4150. $nb++;
  4151. }
  4152. }
  4153. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4154. return $nb;
  4155. }
  4156. /**
  4157. * Function that returns the total amount HT of discounts applied for all lines.
  4158. *
  4159. * @return float|string Total amout of discount
  4160. */
  4161. public function getTotalDiscount()
  4162. {
  4163. if (!empty($this->table_element_line) ) {
  4164. $total_discount = 0.00;
  4165. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4166. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4167. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4168. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4169. $resql = $this->db->query($sql);
  4170. if ($resql) {
  4171. $num = $this->db->num_rows($resql);
  4172. $i = 0;
  4173. while ($i < $num) {
  4174. $obj = $this->db->fetch_object($resql);
  4175. $pu_ht = $obj->pu_ht;
  4176. $qty = $obj->qty;
  4177. $total_ht = $obj->total_ht;
  4178. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4179. $total_discount += $total_discount_line;
  4180. $i++;
  4181. }
  4182. }
  4183. //print $total_discount; exit;
  4184. return price2num($total_discount);
  4185. }
  4186. return null;
  4187. }
  4188. /**
  4189. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4190. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4191. *
  4192. * @return array array('weight'=>...,'volume'=>...)
  4193. */
  4194. public function getTotalWeightVolume()
  4195. {
  4196. $totalWeight = 0;
  4197. $totalVolume = 0;
  4198. // defined for shipment only
  4199. $totalOrdered = '';
  4200. // defined for shipment only
  4201. $totalToShip = '';
  4202. foreach ($this->lines as $line) {
  4203. if (isset($line->qty_asked)) {
  4204. if (empty($totalOrdered)) {
  4205. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4206. }
  4207. $totalOrdered += $line->qty_asked; // defined for shipment only
  4208. }
  4209. if (isset($line->qty_shipped)) {
  4210. if (empty($totalToShip)) {
  4211. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4212. }
  4213. $totalToShip += $line->qty_shipped; // defined for shipment only
  4214. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4215. if (empty($totalToShip)) {
  4216. $totalToShip = 0;
  4217. }
  4218. $totalToShip += $line->qty; // defined for reception only
  4219. }
  4220. // Define qty, weight, volume, weight_units, volume_units
  4221. if ($this->element == 'shipping') {
  4222. // for shipments
  4223. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4224. } else {
  4225. $qty = $line->qty ? $line->qty : 0;
  4226. }
  4227. $weight = !empty($line->weight) ? $line->weight : 0;
  4228. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4229. $volume = !empty($line->volume) ? $line->volume : 0;
  4230. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4231. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4232. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4233. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4234. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4235. $weightUnit = 0;
  4236. $volumeUnit = 0;
  4237. if (!empty($weight_units)) {
  4238. $weightUnit = $weight_units;
  4239. }
  4240. if (!empty($volume_units)) {
  4241. $volumeUnit = $volume_units;
  4242. }
  4243. if (empty($totalWeight)) {
  4244. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4245. }
  4246. if (empty($totalVolume)) {
  4247. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4248. }
  4249. //var_dump($line->volume_units);
  4250. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4251. $trueWeightUnit = pow(10, $weightUnit);
  4252. $totalWeight += $weight * $qty * $trueWeightUnit;
  4253. } else {
  4254. if ($weight_units == 99) {
  4255. // conversion 1 Pound = 0.45359237 KG
  4256. $trueWeightUnit = 0.45359237;
  4257. $totalWeight += $weight * $qty * $trueWeightUnit;
  4258. } elseif ($weight_units == 98) {
  4259. // conversion 1 Ounce = 0.0283495 KG
  4260. $trueWeightUnit = 0.0283495;
  4261. $totalWeight += $weight * $qty * $trueWeightUnit;
  4262. } else {
  4263. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4264. }
  4265. }
  4266. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4267. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4268. $trueVolumeUnit = pow(10, $volumeUnit);
  4269. //print $line->volume;
  4270. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4271. } else {
  4272. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4273. }
  4274. }
  4275. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4276. }
  4277. /**
  4278. * Set extra parameters
  4279. *
  4280. * @return int <0 if KO, >0 if OK
  4281. */
  4282. public function setExtraParameters()
  4283. {
  4284. $this->db->begin();
  4285. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4286. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4287. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4288. $sql .= " WHERE rowid = ".((int) $this->id);
  4289. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4290. $resql = $this->db->query($sql);
  4291. if (!$resql) {
  4292. $this->error = $this->db->lasterror();
  4293. $this->db->rollback();
  4294. return -1;
  4295. } else {
  4296. $this->db->commit();
  4297. return 1;
  4298. }
  4299. }
  4300. // --------------------
  4301. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4302. // --------------------
  4303. /* This is to show add lines */
  4304. /**
  4305. * Show add free and predefined products/services form
  4306. *
  4307. * @param int $dateSelector 1=Show also date range input fields
  4308. * @param Societe $seller Object thirdparty who sell
  4309. * @param Societe $buyer Object thirdparty who buy
  4310. * @param string $defaulttpldir Directory where to find the template
  4311. * @return void
  4312. */
  4313. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4314. {
  4315. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4316. global $form;
  4317. // Line extrafield
  4318. if (!is_object($extrafields)) {
  4319. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4320. $extrafields = new ExtraFields($this->db);
  4321. }
  4322. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4323. // Output template part (modules that overwrite templates must declare this into descriptor)
  4324. // Use global variables + $dateSelector + $seller and $buyer
  4325. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4326. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4327. foreach ($dirtpls as $module => $reldir) {
  4328. if (!empty($module)) {
  4329. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4330. } else {
  4331. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4332. }
  4333. if (empty($conf->file->strict_mode)) {
  4334. $res = @include $tpl;
  4335. } else {
  4336. $res = include $tpl; // for debug
  4337. }
  4338. if ($res) {
  4339. break;
  4340. }
  4341. }
  4342. }
  4343. /* This is to show array of line of details */
  4344. /**
  4345. * Return HTML table for object lines
  4346. * TODO Move this into an output class file (htmlline.class.php)
  4347. * If lines are into a template, title must also be into a template
  4348. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4349. *
  4350. * @param string $action Action code
  4351. * @param string $seller Object of seller third party
  4352. * @param string $buyer Object of buyer third party
  4353. * @param int $selected Object line selected
  4354. * @param int $dateSelector 1=Show also date range input fields
  4355. * @param string $defaulttpldir Directory where to find the template
  4356. * @return void
  4357. */
  4358. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4359. {
  4360. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4361. // TODO We should not use global var for this
  4362. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4363. // Define usemargins
  4364. $usemargins = 0;
  4365. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4366. $usemargins = 1;
  4367. }
  4368. $num = count($this->lines);
  4369. // Line extrafield
  4370. if (!is_object($extrafields)) {
  4371. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4372. $extrafields = new ExtraFields($this->db);
  4373. }
  4374. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4375. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4376. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4377. if (empty($reshook)) {
  4378. // Output template part (modules that overwrite templates must declare this into descriptor)
  4379. // Use global variables + $dateSelector + $seller and $buyer
  4380. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4381. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4382. foreach ($dirtpls as $module => $reldir) {
  4383. if (!empty($module)) {
  4384. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4385. } else {
  4386. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4387. }
  4388. if (empty($conf->file->strict_mode)) {
  4389. $res = @include $tpl;
  4390. } else {
  4391. $res = include $tpl; // for debug
  4392. }
  4393. if ($res) {
  4394. break;
  4395. }
  4396. }
  4397. }
  4398. $i = 0;
  4399. print "<!-- begin printObjectLines() --><tbody>\n";
  4400. foreach ($this->lines as $line) {
  4401. //Line extrafield
  4402. $line->fetch_optionals();
  4403. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4404. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4405. if (empty($line->fk_parent_line)) {
  4406. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4407. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4408. } else {
  4409. $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);
  4410. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4411. }
  4412. }
  4413. if (empty($reshook)) {
  4414. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4415. }
  4416. $i++;
  4417. }
  4418. print "</tbody><!-- end printObjectLines() -->\n";
  4419. }
  4420. /**
  4421. * Return HTML content of a detail line
  4422. * TODO Move this into an output class file (htmlline.class.php)
  4423. *
  4424. * @param string $action GET/POST action
  4425. * @param CommonObjectLine $line Selected object line to output
  4426. * @param string $var Is it a an odd line (true)
  4427. * @param int $num Number of line (0)
  4428. * @param int $i I
  4429. * @param int $dateSelector 1=Show also date range input fields
  4430. * @param string $seller Object of seller third party
  4431. * @param string $buyer Object of buyer third party
  4432. * @param int $selected Object line selected
  4433. * @param Extrafields $extrafields Object of extrafields
  4434. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4435. * @return void
  4436. */
  4437. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4438. {
  4439. global $conf, $langs, $user, $object, $hookmanager;
  4440. global $form;
  4441. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4442. $object_rights = $this->getRights();
  4443. $element = $this->element;
  4444. $text = '';
  4445. $description = '';
  4446. // Line in view mode
  4447. if ($action != 'editline' || $selected != $line->id) {
  4448. // Product
  4449. if ($line->fk_product > 0) {
  4450. $product_static = new Product($this->db);
  4451. $product_static->fetch($line->fk_product);
  4452. $product_static->ref = $line->ref; //can change ref in hook
  4453. $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
  4454. $text = $product_static->getNomUrl(1);
  4455. // Define output language and label
  4456. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4457. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4458. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4459. return;
  4460. }
  4461. $prod = new Product($this->db);
  4462. $prod->fetch($line->fk_product);
  4463. $outputlangs = $langs;
  4464. $newlang = '';
  4465. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4466. $newlang = GETPOST('lang_id', 'aZ09');
  4467. }
  4468. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4469. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4470. }
  4471. if (!empty($newlang)) {
  4472. $outputlangs = new Translate("", $conf);
  4473. $outputlangs->setDefaultLang($newlang);
  4474. }
  4475. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4476. } else {
  4477. $label = $line->product_label;
  4478. }
  4479. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4480. $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
  4481. }
  4482. $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
  4483. // Output template part (modules that overwrite templates must declare this into descriptor)
  4484. // Use global variables + $dateSelector + $seller and $buyer
  4485. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4486. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4487. foreach ($dirtpls as $module => $reldir) {
  4488. if (!empty($module)) {
  4489. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4490. } else {
  4491. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4492. }
  4493. if (empty($conf->file->strict_mode)) {
  4494. $res = @include $tpl;
  4495. } else {
  4496. $res = include $tpl; // for debug
  4497. }
  4498. if ($res) {
  4499. break;
  4500. }
  4501. }
  4502. }
  4503. // Line in update mode
  4504. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4505. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4506. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4507. // Output template part (modules that overwrite templates must declare this into descriptor)
  4508. // Use global variables + $dateSelector + $seller and $buyer
  4509. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4510. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4511. foreach ($dirtpls as $module => $reldir) {
  4512. if (!empty($module)) {
  4513. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4514. } else {
  4515. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4516. }
  4517. if (empty($conf->file->strict_mode)) {
  4518. $res = @include $tpl;
  4519. } else {
  4520. $res = include $tpl; // for debug
  4521. }
  4522. if ($res) {
  4523. break;
  4524. }
  4525. }
  4526. }
  4527. }
  4528. /* This is to show array of line of details of source object */
  4529. /**
  4530. * Return HTML table table of source object lines
  4531. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4532. * If lines are into a template, title must also be into a template
  4533. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4534. *
  4535. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4536. * @param array $selectedLines Array of lines id for selected lines
  4537. * @return void
  4538. */
  4539. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4540. {
  4541. global $langs, $hookmanager, $conf, $form, $action;
  4542. print '<tr class="liste_titre">';
  4543. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4544. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4545. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4546. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4547. if (!empty($conf->multicurrency->enabled)) {
  4548. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4549. }
  4550. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4551. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4552. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4553. }
  4554. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4555. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4556. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4557. print '</tr>';
  4558. $i = 0;
  4559. if (!empty($this->lines)) {
  4560. foreach ($this->lines as $line) {
  4561. $reshook = 0;
  4562. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4563. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4564. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4565. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4566. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4567. }
  4568. if (empty($reshook)) {
  4569. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4570. }
  4571. $i++;
  4572. }
  4573. }
  4574. }
  4575. /**
  4576. * Return HTML with a line of table array of source object lines
  4577. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4578. * If lines are into a template, title must also be into a template
  4579. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4580. *
  4581. * @param CommonObjectLine $line Line
  4582. * @param string $var Var
  4583. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4584. * @param string $defaulttpldir Directory where to find the template
  4585. * @param array $selectedLines Array of lines id for selected lines
  4586. * @return void
  4587. */
  4588. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4589. {
  4590. global $langs, $conf;
  4591. //var_dump($line);
  4592. if (!empty($line->date_start)) {
  4593. $date_start = $line->date_start;
  4594. } else {
  4595. $date_start = $line->date_debut_prevue;
  4596. if ($line->date_debut_reel) {
  4597. $date_start = $line->date_debut_reel;
  4598. }
  4599. }
  4600. if (!empty($line->date_end)) {
  4601. $date_end = $line->date_end;
  4602. } else {
  4603. $date_end = $line->date_fin_prevue;
  4604. if ($line->date_fin_reel) {
  4605. $date_end = $line->date_fin_reel;
  4606. }
  4607. }
  4608. $this->tpl['id'] = $line->id;
  4609. $this->tpl['label'] = '';
  4610. if (!empty($line->fk_parent_line)) {
  4611. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4612. }
  4613. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4614. $discount = new DiscountAbsolute($this->db);
  4615. $discount->fk_soc = $this->socid;
  4616. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4617. } elseif (!empty($line->fk_product)) {
  4618. $productstatic = new Product($this->db);
  4619. $productstatic->id = $line->fk_product;
  4620. $productstatic->ref = $line->ref;
  4621. $productstatic->type = $line->fk_product_type;
  4622. if (empty($productstatic->ref)) {
  4623. $line->fetch_product();
  4624. $productstatic = $line->product;
  4625. }
  4626. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4627. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4628. // Dates
  4629. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4630. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4631. }
  4632. } else {
  4633. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4634. if (!empty($line->desc)) {
  4635. $this->tpl['label'] .= $line->desc;
  4636. } else {
  4637. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4638. }
  4639. // Dates
  4640. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4641. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4642. }
  4643. }
  4644. if (!empty($line->desc)) {
  4645. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4646. $discount = new DiscountAbsolute($this->db);
  4647. $discount->fetch($line->fk_remise_except);
  4648. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4649. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4650. $discount = new DiscountAbsolute($this->db);
  4651. $discount->fetch($line->fk_remise_except);
  4652. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4653. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4654. $discount = new DiscountAbsolute($this->db);
  4655. $discount->fetch($line->fk_remise_except);
  4656. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4657. } elseif ($line->desc == '(EXCESS PAID)') {
  4658. $discount = new DiscountAbsolute($this->db);
  4659. $discount->fetch($line->fk_remise_except);
  4660. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4661. } else {
  4662. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4663. }
  4664. } else {
  4665. $this->tpl['description'] = '&nbsp;';
  4666. }
  4667. // VAT Rate
  4668. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4669. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4670. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4671. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4672. }
  4673. $this->tpl['price'] = price($line->subprice);
  4674. $this->tpl['total_ht'] = price($line->total_ht);
  4675. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4676. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4677. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4678. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4679. }
  4680. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4681. // Is the line strike or not
  4682. $this->tpl['strike'] = 0;
  4683. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4684. $this->tpl['strike'] = 1;
  4685. }
  4686. // Output template part (modules that overwrite templates must declare this into descriptor)
  4687. // Use global variables + $dateSelector + $seller and $buyer
  4688. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4689. foreach ($dirtpls as $module => $reldir) {
  4690. if (!empty($module)) {
  4691. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4692. } else {
  4693. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4694. }
  4695. if (empty($conf->file->strict_mode)) {
  4696. $res = @include $tpl;
  4697. } else {
  4698. $res = include $tpl; // for debug
  4699. }
  4700. if ($res) {
  4701. break;
  4702. }
  4703. }
  4704. }
  4705. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4706. /**
  4707. * Add resources to the current object : add entry into llx_element_resources
  4708. * Need $this->element & $this->id
  4709. *
  4710. * @param int $resource_id Resource id
  4711. * @param string $resource_type 'resource'
  4712. * @param int $busy Busy or not
  4713. * @param int $mandatory Mandatory or not
  4714. * @return int <=0 if KO, >0 if OK
  4715. */
  4716. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4717. {
  4718. // phpcs:enable
  4719. $this->db->begin();
  4720. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4721. $sql .= "resource_id";
  4722. $sql .= ", resource_type";
  4723. $sql .= ", element_id";
  4724. $sql .= ", element_type";
  4725. $sql .= ", busy";
  4726. $sql .= ", mandatory";
  4727. $sql .= ") VALUES (";
  4728. $sql .= $resource_id;
  4729. $sql .= ", '".$this->db->escape($resource_type)."'";
  4730. $sql .= ", '".$this->db->escape($this->id)."'";
  4731. $sql .= ", '".$this->db->escape($this->element)."'";
  4732. $sql .= ", '".$this->db->escape($busy)."'";
  4733. $sql .= ", '".$this->db->escape($mandatory)."'";
  4734. $sql .= ")";
  4735. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4736. if ($this->db->query($sql)) {
  4737. $this->db->commit();
  4738. return 1;
  4739. } else {
  4740. $this->error = $this->db->lasterror();
  4741. $this->db->rollback();
  4742. return 0;
  4743. }
  4744. }
  4745. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4746. /**
  4747. * Delete a link to resource line
  4748. *
  4749. * @param int $rowid Id of resource line to delete
  4750. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4751. * @param int $notrigger Disable all triggers
  4752. * @return int >0 if OK, <0 if KO
  4753. */
  4754. public function delete_resource($rowid, $element, $notrigger = 0)
  4755. {
  4756. // phpcs:enable
  4757. global $user;
  4758. $this->db->begin();
  4759. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4760. $sql .= " WHERE rowid = ".((int) $rowid);
  4761. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4762. $resql = $this->db->query($sql);
  4763. if (!$resql) {
  4764. $this->error = $this->db->lasterror();
  4765. $this->db->rollback();
  4766. return -1;
  4767. } else {
  4768. if (!$notrigger) {
  4769. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4770. if ($result < 0) {
  4771. $this->db->rollback();
  4772. return -1;
  4773. }
  4774. }
  4775. $this->db->commit();
  4776. return 1;
  4777. }
  4778. }
  4779. /**
  4780. * Overwrite magic function to solve problem of cloning object that are kept as references
  4781. *
  4782. * @return void
  4783. */
  4784. public function __clone()
  4785. {
  4786. // Force a copy of this->lines, otherwise it will point to same object.
  4787. if (isset($this->lines) && is_array($this->lines)) {
  4788. $nboflines = count($this->lines);
  4789. for ($i = 0; $i < $nboflines; $i++) {
  4790. $this->lines[$i] = clone $this->lines[$i];
  4791. }
  4792. }
  4793. }
  4794. /**
  4795. * Common function for all objects extending CommonObject for generating documents
  4796. *
  4797. * @param string $modelspath Relative folder where generators are placed
  4798. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4799. * @param Translate $outputlangs Output language to use
  4800. * @param int $hidedetails 1 to hide details. 0 by default
  4801. * @param int $hidedesc 1 to hide product description. 0 by default
  4802. * @param int $hideref 1 to hide product reference. 0 by default
  4803. * @param null|array $moreparams Array to provide more information
  4804. * @return int >0 if OK, <0 if KO
  4805. * @see addFileIntoDatabaseIndex()
  4806. */
  4807. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4808. {
  4809. global $conf, $langs, $user, $hookmanager, $action;
  4810. $srctemplatepath = '';
  4811. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4812. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4813. if (empty($reshook)) {
  4814. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4815. if (empty($modele)) {
  4816. $this->error = 'BadValueForParameterModele';
  4817. return -1;
  4818. }
  4819. // Increase limit for PDF build
  4820. $err = error_reporting();
  4821. error_reporting(0);
  4822. @set_time_limit(120);
  4823. error_reporting($err);
  4824. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4825. $tmp = explode(':', $modele, 2);
  4826. if (!empty($tmp[1])) {
  4827. $modele = $tmp[0];
  4828. $srctemplatepath = $tmp[1];
  4829. }
  4830. // Search template files
  4831. $file = '';
  4832. $classname = '';
  4833. $filefound = '';
  4834. $dirmodels = array('/');
  4835. if (is_array($conf->modules_parts['models'])) {
  4836. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4837. }
  4838. foreach ($dirmodels as $reldir) {
  4839. foreach (array('doc', 'pdf') as $prefix) {
  4840. if (in_array(get_class($this), array('Adherent'))) {
  4841. // Member module use prefix_modele.class.php
  4842. $file = $prefix."_".$modele.".class.php";
  4843. } else {
  4844. // Other module use prefix_modele.modules.php
  4845. $file = $prefix."_".$modele.".modules.php";
  4846. }
  4847. // On verifie l'emplacement du modele
  4848. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4849. if (file_exists($file)) {
  4850. $filefound = $file;
  4851. $classname = $prefix.'_'.$modele;
  4852. break;
  4853. }
  4854. }
  4855. if ($filefound) {
  4856. break;
  4857. }
  4858. }
  4859. // If generator was found
  4860. if ($filefound) {
  4861. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4862. require_once $file;
  4863. $obj = new $classname($this->db);
  4864. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4865. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4866. $varfortemplatedir = $obj->scandir;
  4867. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4868. $dirtoscan = $conf->global->$varfortemplatedir;
  4869. $listoffiles = array();
  4870. // Now we add first model found in directories scanned
  4871. $listofdir = explode(',', $dirtoscan);
  4872. foreach ($listofdir as $key => $tmpdir) {
  4873. $tmpdir = trim($tmpdir);
  4874. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4875. if (!$tmpdir) {
  4876. unset($listofdir[$key]);
  4877. continue;
  4878. }
  4879. if (is_dir($tmpdir)) {
  4880. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4881. if (count($tmpfiles)) {
  4882. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4883. }
  4884. }
  4885. }
  4886. if (count($listoffiles)) {
  4887. foreach ($listoffiles as $record) {
  4888. $srctemplatepath = $record['fullname'];
  4889. break;
  4890. }
  4891. }
  4892. }
  4893. if (empty($srctemplatepath)) {
  4894. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4895. return -1;
  4896. }
  4897. }
  4898. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4899. if (!dol_is_file($srctemplatepath)) {
  4900. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4901. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4902. return -1;
  4903. }
  4904. }
  4905. // We save charset_output to restore it because write_file can change it if needed for
  4906. // output format that does not support UTF8.
  4907. $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
  4908. if (in_array(get_class($this), array('Adherent'))) {
  4909. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4910. } else {
  4911. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4912. }
  4913. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4914. if ($resultwritefile > 0) {
  4915. $outputlangs->charset_output = $sav_charset_output;
  4916. // We delete old preview
  4917. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4918. dol_delete_preview($this);
  4919. // Index file in database
  4920. if (!empty($obj->result['fullpath'])) {
  4921. $destfull = $obj->result['fullpath'];
  4922. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4923. $update_main_doc_field = 0;
  4924. if (!empty($obj->update_main_doc_field)) {
  4925. $update_main_doc_field = 1;
  4926. }
  4927. $this->indexFile($destfull, $update_main_doc_field);
  4928. } else {
  4929. 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);
  4930. }
  4931. // Success in building document. We build meta file.
  4932. dol_meta_create($this);
  4933. return 1;
  4934. } else {
  4935. $outputlangs->charset_output = $sav_charset_output;
  4936. $this->error = $obj->error;
  4937. $this->errors = $obj->errors;
  4938. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  4939. return -1;
  4940. }
  4941. } else {
  4942. if (!$filefound) {
  4943. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4944. $this->errors[] = $this->error;
  4945. dol_syslog($this->error, LOG_ERR);
  4946. } else {
  4947. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4948. $this->errors[] = $this->error;
  4949. dol_syslog($this->error, LOG_ERR);
  4950. }
  4951. return -1;
  4952. }
  4953. } else {
  4954. return $reshook;
  4955. }
  4956. }
  4957. /**
  4958. * Index a file into the ECM database
  4959. *
  4960. * @param string $destfull Full path of file to index
  4961. * @param int $update_main_doc_field Update field main_doc fied into the table of object.
  4962. * This param is set when called for a document generation if document generator hase
  4963. * ->update_main_doc_field set and returns ->result['fullpath'].
  4964. * @return int <0 if KO, >0 if OK
  4965. */
  4966. public function indexFile($destfull, $update_main_doc_field)
  4967. {
  4968. global $conf, $user;
  4969. $upload_dir = dirname($destfull);
  4970. $destfile = basename($destfull);
  4971. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4972. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4973. $filename = basename($destfile);
  4974. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4975. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4976. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4977. $ecmfile = new EcmFiles($this->db);
  4978. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4979. // Set the public "share" key
  4980. $setsharekey = false;
  4981. if ($this->element == 'propal' || $this->element == 'proposal') {
  4982. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4983. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4984. }
  4985. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4986. $setsharekey = true;
  4987. }
  4988. }
  4989. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4990. $setsharekey = true;
  4991. }
  4992. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4993. $setsharekey = true;
  4994. }
  4995. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4996. $setsharekey = true;
  4997. }
  4998. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4999. $setsharekey = true;
  5000. }
  5001. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  5002. $setsharekey = true;
  5003. }
  5004. if ($setsharekey) {
  5005. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  5006. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  5007. $ecmfile->share = getRandomPassword(true);
  5008. }
  5009. }
  5010. if ($result > 0) {
  5011. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5012. $ecmfile->fullpath_orig = '';
  5013. $ecmfile->gen_or_uploaded = 'generated';
  5014. $ecmfile->description = ''; // indexed content
  5015. $ecmfile->keywords = ''; // keyword content
  5016. $result = $ecmfile->update($user);
  5017. if ($result < 0) {
  5018. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5019. return -1;
  5020. }
  5021. } else {
  5022. $ecmfile->entity = $conf->entity;
  5023. $ecmfile->filepath = $rel_dir;
  5024. $ecmfile->filename = $filename;
  5025. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5026. $ecmfile->fullpath_orig = '';
  5027. $ecmfile->gen_or_uploaded = 'generated';
  5028. $ecmfile->description = ''; // indexed content
  5029. $ecmfile->keywords = ''; // keyword content
  5030. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  5031. $ecmfile->src_object_id = $this->id;
  5032. $result = $ecmfile->create($user);
  5033. if ($result < 0) {
  5034. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5035. return -1;
  5036. }
  5037. }
  5038. /*$this->result['fullname']=$destfull;
  5039. $this->result['filepath']=$ecmfile->filepath;
  5040. $this->result['filename']=$ecmfile->filename;*/
  5041. //var_dump($obj->update_main_doc_field);exit;
  5042. if ($update_main_doc_field && !empty($this->table_element)) {
  5043. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  5044. $sql .= " WHERE rowid = ".((int) $this->id);
  5045. $resql = $this->db->query($sql);
  5046. if (!$resql) {
  5047. dol_print_error($this->db);
  5048. return -1;
  5049. } else {
  5050. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  5051. }
  5052. }
  5053. }
  5054. return 1;
  5055. }
  5056. /**
  5057. * Build thumb
  5058. * @todo Move this into files.lib.php
  5059. *
  5060. * @param string $file Path file in UTF8 to original file to create thumbs from.
  5061. * @return void
  5062. */
  5063. public function addThumbs($file)
  5064. {
  5065. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  5066. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  5067. $file_osencoded = dol_osencode($file);
  5068. if (file_exists($file_osencoded)) {
  5069. // Create small thumbs for company (Ratio is near 16/9)
  5070. // Used on logon for example
  5071. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  5072. // Create mini thumbs for company (Ratio is near 16/9)
  5073. // Used on menu or for setup page for example
  5074. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  5075. }
  5076. }
  5077. /* Functions common to commonobject and commonobjectline */
  5078. /* For default values */
  5079. /**
  5080. * Return the default value to use for a field when showing the create form of object.
  5081. * Return values in this order:
  5082. * 1) If parameter is available into POST, we return it first.
  5083. * 2) If not but an alternate value was provided as parameter of function, we return it.
  5084. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  5085. * 4) Return value found into database (TODO No yet implemented)
  5086. *
  5087. * @param string $fieldname Name of field
  5088. * @param string $alternatevalue Alternate value to use
  5089. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  5090. **/
  5091. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  5092. {
  5093. global $conf, $_POST;
  5094. // If param here has been posted, we use this value first.
  5095. if (GETPOSTISSET($fieldname)) {
  5096. return GETPOST($fieldname, 'alphanohtml', 3);
  5097. }
  5098. if (isset($alternatevalue)) {
  5099. return $alternatevalue;
  5100. }
  5101. $newelement = $this->element;
  5102. if ($newelement == 'facture') {
  5103. $newelement = 'invoice';
  5104. }
  5105. if ($newelement == 'commande') {
  5106. $newelement = 'order';
  5107. }
  5108. if (empty($newelement)) {
  5109. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5110. return '';
  5111. }
  5112. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  5113. //var_dump($keyforfieldname);
  5114. if (isset($conf->global->$keyforfieldname)) {
  5115. return $conf->global->$keyforfieldname;
  5116. }
  5117. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5118. }
  5119. /* For triggers */
  5120. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5121. /**
  5122. * Call trigger based on this instance.
  5123. * Some context information may also be provided into array property this->context.
  5124. * NB: Error from trigger are stacked in interface->errors
  5125. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5126. *
  5127. * @param string $triggerName trigger's name to execute
  5128. * @param User $user Object user
  5129. * @return int Result of run_triggers
  5130. */
  5131. public function call_trigger($triggerName, $user)
  5132. {
  5133. // phpcs:enable
  5134. global $langs, $conf;
  5135. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5136. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5137. exit;
  5138. }
  5139. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5140. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5141. $langs = new Translate('', $conf);
  5142. }
  5143. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5144. $interface = new Interfaces($this->db);
  5145. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5146. if ($result < 0) {
  5147. if (!empty($this->errors)) {
  5148. $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.
  5149. } else {
  5150. $this->errors = $interface->errors;
  5151. }
  5152. }
  5153. return $result;
  5154. }
  5155. /* Functions for data in other language */
  5156. /**
  5157. * Function to get alternative languages of a data into $this->array_languages
  5158. * This method is NOT called by method fetch of objects but must be called separately.
  5159. *
  5160. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5161. * @see fetch_optionnals()
  5162. */
  5163. public function fetchValuesForExtraLanguages()
  5164. {
  5165. // To avoid SQL errors. Probably not the better solution though
  5166. if (!$this->element) {
  5167. return 0;
  5168. }
  5169. if (!($this->id > 0)) {
  5170. return 0;
  5171. }
  5172. if (is_array($this->array_languages)) {
  5173. return 1;
  5174. }
  5175. $this->array_languages = array();
  5176. $element = $this->element;
  5177. if ($element == 'categorie') {
  5178. $element = 'categories'; // For compatibility
  5179. }
  5180. // Request to get translation values for object
  5181. $sql = "SELECT rowid, property, lang , value";
  5182. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5183. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5184. $sql .= " AND fk_object = ".((int) $this->id);
  5185. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5186. $resql = $this->db->query($sql);
  5187. if ($resql) {
  5188. $numrows = $this->db->num_rows($resql);
  5189. if ($numrows) {
  5190. $i = 0;
  5191. while ($i < $numrows) {
  5192. $obj = $this->db->fetch_object($resql);
  5193. $key = $obj->property;
  5194. $value = $obj->value;
  5195. $codelang = $obj->lang;
  5196. $type = $this->fields[$key]['type'];
  5197. // we can add this attribute to object
  5198. if (preg_match('/date/', $type)) {
  5199. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5200. } else {
  5201. $this->array_languages[$key][$codelang] = $value;
  5202. }
  5203. $i++;
  5204. }
  5205. }
  5206. $this->db->free($resql);
  5207. if ($numrows) {
  5208. return $numrows;
  5209. } else {
  5210. return 0;
  5211. }
  5212. } else {
  5213. dol_print_error($this->db);
  5214. return -1;
  5215. }
  5216. }
  5217. /**
  5218. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5219. *
  5220. * @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.
  5221. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5222. */
  5223. public function setValuesForExtraLanguages($onlykey = '')
  5224. {
  5225. global $_POST, $langs;
  5226. // Get extra fields
  5227. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5228. $tmparray = explode('-', $postfieldkey);
  5229. if ($tmparray[0] != 'field') {
  5230. continue;
  5231. }
  5232. $element = $tmparray[1];
  5233. $key = $tmparray[2];
  5234. $codelang = $tmparray[3];
  5235. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5236. if (!empty($onlykey) && $key != $onlykey) {
  5237. continue;
  5238. }
  5239. if ($element != $this->element) {
  5240. continue;
  5241. }
  5242. $key_type = $this->fields[$key]['type'];
  5243. $enabled = 1;
  5244. if (isset($this->fields[$key]['enabled'])) {
  5245. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5246. }
  5247. /*$perms = 1;
  5248. if (isset($this->fields[$key]['perms']))
  5249. {
  5250. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5251. }*/
  5252. if (empty($enabled)) {
  5253. continue;
  5254. }
  5255. //if (empty($perms)) continue;
  5256. if (in_array($key_type, array('date'))) {
  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(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5260. } elseif (in_array($key_type, array('datetime'))) {
  5261. // Clean parameters
  5262. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5263. $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'));
  5264. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5265. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5266. if (!empty($value_arr)) {
  5267. $value_key = implode(',', $value_arr);
  5268. } else {
  5269. $value_key = '';
  5270. }
  5271. } elseif (in_array($key_type, array('price', 'double'))) {
  5272. $value_arr = GETPOST($postfieldkey, 'alpha');
  5273. $value_key = price2num($value_arr);
  5274. } else {
  5275. $value_key = GETPOST($postfieldkey);
  5276. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5277. $value_key = '';
  5278. }
  5279. }
  5280. $this->array_languages[$key][$codelang] = $value_key;
  5281. /*if ($nofillrequired) {
  5282. $langs->load('errors');
  5283. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5284. return -1;
  5285. }*/
  5286. }
  5287. return 1;
  5288. }
  5289. /* Functions for extrafields */
  5290. /**
  5291. * Function to make a fetch but set environment to avoid to load computed values before.
  5292. *
  5293. * @param int $id ID of object
  5294. * @return int >0 if OK, 0 if not found, <0 if KO
  5295. */
  5296. public function fetchNoCompute($id)
  5297. {
  5298. global $conf;
  5299. $savDisableCompute = $conf->disable_compute;
  5300. $conf->disable_compute = 1;
  5301. $ret = $this->fetch($id);
  5302. $conf->disable_compute = $savDisableCompute;
  5303. return $ret;
  5304. }
  5305. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5306. /**
  5307. * Function to get extra fields of an object into $this->array_options
  5308. * This method is in most cases called by method fetch of objects but you can call it separately.
  5309. *
  5310. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5311. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5312. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5313. * @see fetchValuesForExtraLanguages()
  5314. */
  5315. public function fetch_optionals($rowid = null, $optionsArray = null)
  5316. {
  5317. // phpcs:enable
  5318. global $conf, $extrafields;
  5319. if (empty($rowid)) {
  5320. $rowid = $this->id;
  5321. }
  5322. if (empty($rowid) && isset($this->rowid)) {
  5323. $rowid = $this->rowid; // deprecated
  5324. }
  5325. // To avoid SQL errors. Probably not the better solution though
  5326. if (!$this->table_element) {
  5327. return 0;
  5328. }
  5329. $this->array_options = array();
  5330. if (!is_array($optionsArray)) {
  5331. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5332. if (!isset($extrafields) || !is_object($extrafields)) {
  5333. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5334. $extrafields = new ExtraFields($this->db);
  5335. }
  5336. // Load array of extrafields for elementype = $this->table_element
  5337. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5338. $extrafields->fetch_name_optionals_label($this->table_element);
  5339. }
  5340. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5341. } else {
  5342. global $extrafields;
  5343. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5344. }
  5345. $table_element = $this->table_element;
  5346. if ($table_element == 'categorie') {
  5347. $table_element = 'categories'; // For compatibility
  5348. }
  5349. // Request to get complementary values
  5350. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5351. $sql = "SELECT rowid";
  5352. foreach ($optionsArray as $name => $label) {
  5353. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5354. $sql .= ", ".$name;
  5355. }
  5356. }
  5357. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5358. $sql .= " WHERE fk_object = ".((int) $rowid);
  5359. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5360. $resql = $this->db->query($sql);
  5361. if ($resql) {
  5362. $numrows = $this->db->num_rows($resql);
  5363. if ($numrows) {
  5364. $tab = $this->db->fetch_array($resql);
  5365. foreach ($tab as $key => $value) {
  5366. // 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)
  5367. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5368. // we can add this attribute to object
  5369. if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5370. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5371. $this->array_options["options_".$key] = $this->db->jdate($value);
  5372. } else {
  5373. $this->array_options["options_".$key] = $value;
  5374. }
  5375. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5376. }
  5377. }
  5378. }
  5379. // If field is a computed field, value must become result of compute (regardless of whether a row exists
  5380. // in the element's extrafields table)
  5381. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  5382. if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5383. //var_dump($conf->disable_compute);
  5384. if (empty($conf->disable_compute)) {
  5385. global $objectoffield; // We set a global variable to $objectoffield so
  5386. $objectoffield = $this; // we can use it inside computed formula
  5387. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5388. }
  5389. }
  5390. }
  5391. $this->db->free($resql);
  5392. if ($numrows) {
  5393. return $numrows;
  5394. } else {
  5395. return 0;
  5396. }
  5397. } else {
  5398. $this->errors[]=$this->db->lasterror;
  5399. return -1;
  5400. }
  5401. }
  5402. return 0;
  5403. }
  5404. /**
  5405. * Delete all extra fields values for the current object.
  5406. *
  5407. * @return int <0 if KO, >0 if OK
  5408. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5409. */
  5410. public function deleteExtraFields()
  5411. {
  5412. global $conf;
  5413. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5414. return 0;
  5415. }
  5416. $this->db->begin();
  5417. $table_element = $this->table_element;
  5418. if ($table_element == 'categorie') {
  5419. $table_element = 'categories'; // For compatibility
  5420. }
  5421. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5422. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5423. $resql = $this->db->query($sql_del);
  5424. if (!$resql) {
  5425. $this->error = $this->db->lasterror();
  5426. $this->db->rollback();
  5427. return -1;
  5428. } else {
  5429. $this->db->commit();
  5430. return 1;
  5431. }
  5432. }
  5433. /**
  5434. * Add/Update all extra fields values for the current object.
  5435. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5436. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5437. *
  5438. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5439. * @param User $userused Object user
  5440. * @return int -1=error, O=did nothing, 1=OK
  5441. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5442. */
  5443. public function insertExtraFields($trigger = '', $userused = null)
  5444. {
  5445. global $conf, $langs, $user;
  5446. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5447. return 0;
  5448. }
  5449. if (empty($userused)) {
  5450. $userused = $user;
  5451. }
  5452. $error = 0;
  5453. if (!empty($this->array_options)) {
  5454. // Check parameters
  5455. $langs->load('admin');
  5456. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5457. $extrafields = new ExtraFields($this->db);
  5458. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5459. // Eliminate copied source object extra fields that do not exist in target object
  5460. $new_array_options = array();
  5461. foreach ($this->array_options as $key => $value) {
  5462. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5463. $new_array_options[$key] = $value;
  5464. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5465. $new_array_options['options_'.$key] = $value;
  5466. }
  5467. }
  5468. foreach ($new_array_options as $key => $value) {
  5469. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5470. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5471. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5472. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5473. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5474. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5475. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5476. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5477. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5478. if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
  5479. $new_array_options[$key] = null;
  5480. }
  5481. // Similar code than into insertExtraFields
  5482. if ($attributeRequired) {
  5483. $mandatorypb = false;
  5484. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5485. $mandatorypb = true;
  5486. }
  5487. if ($this->array_options[$key] === '') {
  5488. $mandatorypb = true;
  5489. }
  5490. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5491. $mandatorypb = true;
  5492. }
  5493. if ($mandatorypb) {
  5494. $langs->load("errors");
  5495. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5496. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5497. return -1;
  5498. }
  5499. }
  5500. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5501. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5502. if (!empty($attrfieldcomputed)) {
  5503. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5504. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5505. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5506. $new_array_options[$key] = $value;
  5507. } else {
  5508. $new_array_options[$key] = null;
  5509. }
  5510. }
  5511. switch ($attributeType) {
  5512. case 'int':
  5513. if (!is_numeric($value) && $value != '') {
  5514. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5515. return -1;
  5516. } elseif ($value == '') {
  5517. $new_array_options[$key] = null;
  5518. }
  5519. break;
  5520. case 'price':
  5521. case 'double':
  5522. $value = price2num($value);
  5523. if (!is_numeric($value) && $value != '') {
  5524. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5525. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5526. return -1;
  5527. } elseif ($value == '') {
  5528. $value = null;
  5529. }
  5530. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5531. $new_array_options[$key] = $value;
  5532. break;
  5533. /*case 'select': // Not required, we chosed value='0' for undefined values
  5534. if ($value=='-1')
  5535. {
  5536. $this->array_options[$key] = null;
  5537. }
  5538. break;*/
  5539. case 'password':
  5540. $algo = '';
  5541. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5542. // If there is an encryption choice, we use it to crypt data before insert
  5543. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5544. $algo = reset($tmparrays);
  5545. if ($algo != '') {
  5546. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5547. //var_dump($action);
  5548. //var_dump($this->oldcopy);exit;
  5549. 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
  5550. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5551. 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.
  5552. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5553. } else {
  5554. // var_dump($algo);
  5555. $newvalue = dol_hash($this->array_options[$key], $algo);
  5556. $new_array_options[$key] = $newvalue;
  5557. }
  5558. } else {
  5559. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5560. }
  5561. }
  5562. } else // Common usage
  5563. {
  5564. $new_array_options[$key] = $this->array_options[$key];
  5565. }
  5566. break;
  5567. case 'date':
  5568. case 'datetime':
  5569. // If data is a string instead of a timestamp, we convert it
  5570. if (!is_int($this->array_options[$key])) {
  5571. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5572. }
  5573. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5574. break;
  5575. case 'link':
  5576. $param_list = array_keys($attributeParam['options']);
  5577. // 0 : ObjectName
  5578. // 1 : classPath
  5579. $InfoFieldList = explode(":", $param_list[0]);
  5580. dol_include_once($InfoFieldList[1]);
  5581. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5582. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5583. $new_array_options[$key] = '';
  5584. } elseif ($value) {
  5585. $object = new $InfoFieldList[0]($this->db);
  5586. if (is_numeric($value)) {
  5587. $res = $object->fetch($value); // Common case
  5588. } else {
  5589. $res = $object->fetch('', $value); // For compatibility
  5590. }
  5591. if ($res > 0) {
  5592. $new_array_options[$key] = $object->id;
  5593. } else {
  5594. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5595. return -1;
  5596. }
  5597. }
  5598. } else {
  5599. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5600. }
  5601. break;
  5602. }
  5603. }
  5604. $this->db->begin();
  5605. $table_element = $this->table_element;
  5606. if ($table_element == 'categorie') {
  5607. $table_element = 'categories'; // For compatibility
  5608. }
  5609. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5610. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5611. $this->db->query($sql_del);
  5612. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5613. foreach ($new_array_options as $key => $value) {
  5614. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5615. // Add field of attribut
  5616. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5617. $sql .= ",".$attributeKey;
  5618. }
  5619. }
  5620. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5621. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5622. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5623. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5624. $sql .= ",".$tmpkey;
  5625. }
  5626. }
  5627. }
  5628. $sql .= ") VALUES (".$this->id;
  5629. foreach ($new_array_options as $key => $value) {
  5630. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5631. // Add field of attribute
  5632. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5633. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5634. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5635. } else {
  5636. $sql .= ",null";
  5637. }
  5638. }
  5639. }
  5640. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5641. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5642. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5643. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5644. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5645. $sql .= ", 0";
  5646. } else {
  5647. $sql .= ", ''";
  5648. }
  5649. }
  5650. }
  5651. }
  5652. $sql .= ")";
  5653. $resql = $this->db->query($sql);
  5654. if (!$resql) {
  5655. $this->error = $this->db->lasterror();
  5656. $error++;
  5657. }
  5658. if (!$error && $trigger) {
  5659. // Call trigger
  5660. $this->context = array('extrafieldaddupdate'=>1);
  5661. $result = $this->call_trigger($trigger, $userused);
  5662. if ($result < 0) {
  5663. $error++;
  5664. }
  5665. // End call trigger
  5666. }
  5667. if ($error) {
  5668. $this->db->rollback();
  5669. return -1;
  5670. } else {
  5671. $this->db->commit();
  5672. return 1;
  5673. }
  5674. } else {
  5675. return 0;
  5676. }
  5677. }
  5678. /**
  5679. * Add/Update all extra fields values for the current object.
  5680. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5681. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5682. *
  5683. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5684. * @param User $userused Object user
  5685. * @return int -1=error, O=did nothing, 1=OK
  5686. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5687. */
  5688. public function insertExtraLanguages($trigger = '', $userused = null)
  5689. {
  5690. global $conf, $langs, $user;
  5691. if (empty($userused)) {
  5692. $userused = $user;
  5693. }
  5694. $error = 0;
  5695. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5696. return 0; // For avoid conflicts if trigger used
  5697. }
  5698. if (is_array($this->array_languages)) {
  5699. $new_array_languages = $this->array_languages;
  5700. foreach ($new_array_languages as $key => $value) {
  5701. $attributeKey = $key;
  5702. $attributeType = $this->fields[$attributeKey]['type'];
  5703. $attributeLabel = $this->fields[$attributeKey]['label'];
  5704. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5705. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5706. switch ($attributeType) {
  5707. case 'int':
  5708. if (!is_numeric($value) && $value != '') {
  5709. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5710. return -1;
  5711. } elseif ($value == '') {
  5712. $new_array_languages[$key] = null;
  5713. }
  5714. break;
  5715. case 'double':
  5716. $value = price2num($value);
  5717. if (!is_numeric($value) && $value != '') {
  5718. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5719. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5720. return -1;
  5721. } elseif ($value == '') {
  5722. $new_array_languages[$key] = null;
  5723. }
  5724. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5725. $new_array_languages[$key] = $value;
  5726. break;
  5727. /*case 'select': // Not required, we chosed value='0' for undefined values
  5728. if ($value=='-1')
  5729. {
  5730. $this->array_options[$key] = null;
  5731. }
  5732. break;*/
  5733. }
  5734. }
  5735. $this->db->begin();
  5736. $table_element = $this->table_element;
  5737. if ($table_element == 'categorie') {
  5738. $table_element = 'categories'; // For compatibility
  5739. }
  5740. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5741. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5742. foreach ($langcodearray as $langcode => $value) {
  5743. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5744. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5745. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5746. $this->db->query($sql_del);
  5747. if ($value !== '') {
  5748. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5749. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5750. $sql .= ")";
  5751. $resql = $this->db->query($sql);
  5752. if (!$resql) {
  5753. $this->error = $this->db->lasterror();
  5754. $error++;
  5755. break;
  5756. }
  5757. }
  5758. }
  5759. }
  5760. if (!$error && $trigger) {
  5761. // Call trigger
  5762. $this->context = array('extralanguagesaddupdate'=>1);
  5763. $result = $this->call_trigger($trigger, $userused);
  5764. if ($result < 0) {
  5765. $error++;
  5766. }
  5767. // End call trigger
  5768. }
  5769. if ($error) {
  5770. $this->db->rollback();
  5771. return -1;
  5772. } else {
  5773. $this->db->commit();
  5774. return 1;
  5775. }
  5776. } else {
  5777. return 0;
  5778. }
  5779. }
  5780. /**
  5781. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5782. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5783. *
  5784. * @param string $key Key of the extrafield to update (without starting 'options_')
  5785. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5786. * @param User $userused Object user
  5787. * @return int -1=error, O=did nothing, 1=OK
  5788. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5789. */
  5790. public function updateExtraField($key, $trigger = null, $userused = null)
  5791. {
  5792. global $conf, $langs, $user;
  5793. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5794. return 0;
  5795. }
  5796. if (empty($userused)) {
  5797. $userused = $user;
  5798. }
  5799. $error = 0;
  5800. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5801. // Check parameters
  5802. $langs->load('admin');
  5803. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5804. $extrafields = new ExtraFields($this->db);
  5805. $extrafields->fetch_name_optionals_label($this->table_element);
  5806. $value = $this->array_options["options_".$key];
  5807. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5808. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5809. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5810. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5811. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5812. // Similar code than into insertExtraFields
  5813. if ($attributeRequired) {
  5814. $mandatorypb = false;
  5815. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5816. $mandatorypb = true;
  5817. }
  5818. if ($this->array_options["options_".$key] === '') {
  5819. $mandatorypb = true;
  5820. }
  5821. if ($mandatorypb) {
  5822. $langs->load("errors");
  5823. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5824. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5825. return -1;
  5826. }
  5827. }
  5828. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5829. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5830. if (!empty($attrfieldcomputed)) {
  5831. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5832. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5833. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5834. $this->array_options["options_".$key] = $value;
  5835. } else {
  5836. $this->array_options["options_".$key] = null;
  5837. }
  5838. }
  5839. switch ($attributeType) {
  5840. case 'int':
  5841. if (!is_numeric($value) && $value != '') {
  5842. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5843. return -1;
  5844. } elseif ($value === '') {
  5845. $this->array_options["options_".$key] = null;
  5846. }
  5847. break;
  5848. case 'double':
  5849. $value = price2num($value);
  5850. if (!is_numeric($value) && $value != '') {
  5851. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5852. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5853. return -1;
  5854. } elseif ($value === '') {
  5855. $value = null;
  5856. }
  5857. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5858. $this->array_options["options_".$key] = $value;
  5859. break;
  5860. /*case 'select': // Not required, we chosed value='0' for undefined values
  5861. if ($value=='-1')
  5862. {
  5863. $this->array_options[$key] = null;
  5864. }
  5865. break;*/
  5866. case 'price':
  5867. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5868. break;
  5869. case 'date':
  5870. case 'datetime':
  5871. if (empty($this->array_options["options_".$key])) {
  5872. $this->array_options["options_".$key] = null;
  5873. } else {
  5874. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5875. }
  5876. break;
  5877. case 'boolean':
  5878. if (empty($this->array_options["options_".$key])) {
  5879. $this->array_options["options_".$key] = null;
  5880. }
  5881. break;
  5882. /*
  5883. case 'link':
  5884. $param_list = array_keys($attributeParam['options']);
  5885. // 0 : ObjectName
  5886. // 1 : classPath
  5887. $InfoFieldList = explode(":", $param_list[0]);
  5888. dol_include_once($InfoFieldList[1]);
  5889. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5890. {
  5891. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5892. {
  5893. $new_array_options[$key] = '';
  5894. } elseif ($value) {
  5895. $object = new $InfoFieldList[0]($this->db);
  5896. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5897. else $res = $object->fetch('', $value); // For compatibility
  5898. if ($res > 0) $new_array_options[$key] = $object->id;
  5899. else {
  5900. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5901. $this->db->rollback();
  5902. return -1;
  5903. }
  5904. }
  5905. } else {
  5906. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5907. }
  5908. break;
  5909. */
  5910. }
  5911. $this->db->begin();
  5912. $linealreadyfound = 0;
  5913. // 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)
  5914. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5915. $resql = $this->db->query($sql);
  5916. if ($resql) {
  5917. $tmpobj = $this->db->fetch_object($resql);
  5918. if ($tmpobj) {
  5919. $linealreadyfound = $tmpobj->nb;
  5920. }
  5921. }
  5922. if ($linealreadyfound) {
  5923. if ($this->array_options["options_".$key] === null) {
  5924. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5925. } else {
  5926. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5927. }
  5928. $sql .= " WHERE fk_object = ".((int) $this->id);
  5929. } else {
  5930. $result = $this->insertExtraFields('', $user);
  5931. if ($result < 0) {
  5932. $error++;
  5933. }
  5934. }
  5935. $resql = $this->db->query($sql);
  5936. if (!$resql) {
  5937. $error++;
  5938. $this->error = $this->db->lasterror();
  5939. }
  5940. if (!$error && $trigger) {
  5941. // Call trigger
  5942. $this->context = array('extrafieldupdate'=>1);
  5943. $result = $this->call_trigger($trigger, $userused);
  5944. if ($result < 0) {
  5945. $error++;
  5946. }
  5947. // End call trigger
  5948. }
  5949. if ($error) {
  5950. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5951. $this->db->rollback();
  5952. return -1;
  5953. } else {
  5954. $this->db->commit();
  5955. return 1;
  5956. }
  5957. } else {
  5958. return 0;
  5959. }
  5960. }
  5961. /**
  5962. * Update an extra language value for the current object.
  5963. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5964. *
  5965. * @param string $key Key of the extrafield (without starting 'options_')
  5966. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5967. * @param User $userused Object user
  5968. * @return int -1=error, O=did nothing, 1=OK
  5969. * @see updateExtraFields(), insertExtraLanguages()
  5970. */
  5971. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5972. {
  5973. global $conf, $langs, $user;
  5974. if (empty($userused)) {
  5975. $userused = $user;
  5976. }
  5977. $error = 0;
  5978. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5979. return 0; // For avoid conflicts if trigger used
  5980. }
  5981. return 0;
  5982. }
  5983. /**
  5984. * Return HTML string to put an input field into a page
  5985. * Code very similar with showInputField of extra fields
  5986. *
  5987. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5988. * @param string $key Key of attribute
  5989. * @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)
  5990. * @param string $moreparam To add more parameters on html input tag
  5991. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5992. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5993. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5994. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5995. * @return string
  5996. */
  5997. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5998. {
  5999. global $conf, $langs, $form;
  6000. if (!is_object($form)) {
  6001. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6002. $form = new Form($this->db);
  6003. }
  6004. if (!empty($this->fields)) {
  6005. $val = $this->fields[$key];
  6006. }
  6007. // Validation tests and output
  6008. $fieldValidationErrorMsg = '';
  6009. $validationClass = '';
  6010. $fieldValidationErrorMsg = $this->getFieldError($key);
  6011. if (!empty($fieldValidationErrorMsg)) {
  6012. $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
  6013. } else {
  6014. $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
  6015. }
  6016. $out = '';
  6017. $type = '';
  6018. $isDependList = 0;
  6019. $param = array();
  6020. $param['options'] = array();
  6021. $reg = array();
  6022. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  6023. // Because we work on extrafields
  6024. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6025. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6026. $type = 'link';
  6027. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6028. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6029. $type = 'link';
  6030. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  6031. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6032. $type = 'link';
  6033. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6034. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6035. $type = 'sellist';
  6036. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6037. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6038. $type = 'sellist';
  6039. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  6040. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6041. $type = 'sellist';
  6042. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  6043. $param['options'] = array();
  6044. $type = 'varchar';
  6045. $size = $reg[1];
  6046. } elseif (preg_match('/varchar/', $val['type'])) {
  6047. $param['options'] = array();
  6048. $type = 'varchar';
  6049. } else {
  6050. $param['options'] = array();
  6051. $type = $this->fields[$key]['type'];
  6052. }
  6053. // Special case that force options and type ($type can be integer, varchar, ...)
  6054. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  6055. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  6056. $type = 'select';
  6057. }
  6058. $label = $this->fields[$key]['label'];
  6059. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  6060. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  6061. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  6062. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  6063. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  6064. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  6065. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  6066. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  6067. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  6068. $objectid = $this->id;
  6069. if ($computed) {
  6070. if (!preg_match('/^search_/', $keyprefix)) {
  6071. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  6072. } else {
  6073. return '';
  6074. }
  6075. }
  6076. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  6077. if (empty($morecss) && !empty($val['css'])) {
  6078. $morecss = $val['css'];
  6079. } elseif (empty($morecss)) {
  6080. if ($type == 'date') {
  6081. $morecss = 'minwidth100imp';
  6082. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  6083. $morecss = 'minwidth200imp';
  6084. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6085. $morecss = 'maxwidth75';
  6086. } elseif ($type == 'url') {
  6087. $morecss = 'minwidth400';
  6088. } elseif ($type == 'boolean') {
  6089. $morecss = '';
  6090. } else {
  6091. if (round($size) < 12) {
  6092. $morecss = 'minwidth100';
  6093. } elseif (round($size) <= 48) {
  6094. $morecss = 'minwidth200';
  6095. } else {
  6096. $morecss = 'minwidth400';
  6097. }
  6098. }
  6099. }
  6100. // Add validation state class
  6101. if (!empty($validationClass)) {
  6102. $morecss.= $validationClass;
  6103. }
  6104. if (in_array($type, array('date'))) {
  6105. $tmp = explode(',', $size);
  6106. $newsize = $tmp[0];
  6107. $showtime = 0;
  6108. // Do not show current date when field not required (see selectDate() method)
  6109. if (!$required && $value == '') {
  6110. $value = '-1';
  6111. }
  6112. // TODO Must also support $moreparam
  6113. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6114. } elseif (in_array($type, array('datetime'))) {
  6115. $tmp = explode(',', $size);
  6116. $newsize = $tmp[0];
  6117. $showtime = 1;
  6118. // Do not show current date when field not required (see selectDate() method)
  6119. if (!$required && $value == '') $value = '-1';
  6120. // TODO Must also support $moreparam
  6121. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6122. } elseif (in_array($type, array('duration'))) {
  6123. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6124. } elseif (in_array($type, array('int', 'integer'))) {
  6125. $tmp = explode(',', $size);
  6126. $newsize = $tmp[0];
  6127. $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' : '').'>';
  6128. } elseif (in_array($type, array('real'))) {
  6129. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6130. } elseif (preg_match('/varchar/', $type)) {
  6131. $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' : '').'>';
  6132. } elseif (in_array($type, array('email', 'mail', 'phone', 'url'))) {
  6133. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6134. } elseif (preg_match('/^text/', $type)) {
  6135. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6136. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6137. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6138. $out = $doleditor->Create(1);
  6139. } else {
  6140. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6141. }
  6142. } elseif (preg_match('/^html/', $type)) {
  6143. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6144. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6145. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
  6146. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6147. } else {
  6148. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6149. }
  6150. } elseif ($type == 'boolean') {
  6151. $checked = '';
  6152. if (!empty($value)) {
  6153. $checked = ' checked value="1" ';
  6154. } else {
  6155. $checked = ' value="1" ';
  6156. }
  6157. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6158. } elseif ($type == 'price') {
  6159. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6160. $value = price($value);
  6161. }
  6162. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6163. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6164. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6165. $value = price($value);
  6166. }
  6167. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6168. } elseif ($type == 'select') {
  6169. $out = '';
  6170. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6171. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6172. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6173. }
  6174. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6175. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6176. $out .= '<option value="0">&nbsp;</option>';
  6177. }
  6178. foreach ($param['options'] as $keyb => $valb) {
  6179. if ((string) $keyb == '') {
  6180. continue;
  6181. }
  6182. if (strpos($valb, "|") !== false) {
  6183. list($valb, $parent) = explode('|', $valb);
  6184. }
  6185. $out .= '<option value="'.$keyb.'"';
  6186. $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
  6187. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6188. $out .= '>'.$valb.'</option>';
  6189. }
  6190. $out .= '</select>';
  6191. } elseif ($type == 'sellist') {
  6192. $out = '';
  6193. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6194. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6195. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6196. }
  6197. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6198. if (is_array($param['options'])) {
  6199. $param_list = array_keys($param['options']);
  6200. $InfoFieldList = explode(":", $param_list[0]);
  6201. $parentName = '';
  6202. $parentField = '';
  6203. // 0 : tableName
  6204. // 1 : label field name
  6205. // 2 : key fields name (if differ of rowid)
  6206. // 3 : key field parent (for dependent lists)
  6207. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6208. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6209. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6210. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6211. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6212. } else {
  6213. $keyList = $InfoFieldList[2].' as rowid';
  6214. }
  6215. }
  6216. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6217. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6218. $keyList .= ', '.$parentField;
  6219. }
  6220. $fields_label = explode('|', $InfoFieldList[1]);
  6221. if (is_array($fields_label)) {
  6222. $keyList .= ', ';
  6223. $keyList .= implode(', ', $fields_label);
  6224. }
  6225. $sqlwhere = '';
  6226. $sql = "SELECT ".$keyList;
  6227. $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
  6228. if (!empty($InfoFieldList[4])) {
  6229. // can use SELECT request
  6230. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6231. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6232. }
  6233. // current object id can be use into filter
  6234. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6235. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6236. } else {
  6237. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6238. }
  6239. //We have to join on extrafield table
  6240. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6241. $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
  6242. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6243. } else {
  6244. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6245. }
  6246. } else {
  6247. $sqlwhere .= ' WHERE 1=1';
  6248. }
  6249. // Some tables may have field, some other not. For the moment we disable it.
  6250. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6251. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6252. }
  6253. $sql .= $sqlwhere;
  6254. //print $sql;
  6255. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6256. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6257. $resql = $this->db->query($sql);
  6258. if ($resql) {
  6259. $out .= '<option value="0">&nbsp;</option>';
  6260. $num = $this->db->num_rows($resql);
  6261. $i = 0;
  6262. while ($i < $num) {
  6263. $labeltoshow = '';
  6264. $obj = $this->db->fetch_object($resql);
  6265. // Several field into label (eq table:code|libelle:rowid)
  6266. $notrans = false;
  6267. $fields_label = explode('|', $InfoFieldList[1]);
  6268. if (count($fields_label) > 1) {
  6269. $notrans = true;
  6270. foreach ($fields_label as $field_toshow) {
  6271. $labeltoshow .= $obj->$field_toshow.' ';
  6272. }
  6273. } else {
  6274. $labeltoshow = $obj->{$InfoFieldList[1]};
  6275. }
  6276. $labeltoshow = dol_trunc($labeltoshow, 45);
  6277. if ($value == $obj->rowid) {
  6278. foreach ($fields_label as $field_toshow) {
  6279. $translabel = $langs->trans($obj->$field_toshow);
  6280. if ($translabel != $obj->$field_toshow) {
  6281. $labeltoshow = dol_trunc($translabel).' ';
  6282. } else {
  6283. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6284. }
  6285. }
  6286. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6287. } else {
  6288. if (!$notrans) {
  6289. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6290. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6291. $labeltoshow = dol_trunc($translabel, 18);
  6292. } else {
  6293. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6294. }
  6295. }
  6296. if (empty($labeltoshow)) {
  6297. $labeltoshow = '(not defined)';
  6298. }
  6299. if ($value == $obj->rowid) {
  6300. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6301. }
  6302. if (!empty($InfoFieldList[3]) && $parentField) {
  6303. $parent = $parentName.':'.$obj->{$parentField};
  6304. $isDependList = 1;
  6305. }
  6306. $out .= '<option value="'.$obj->rowid.'"';
  6307. $out .= ($value == $obj->rowid ? ' selected' : '');
  6308. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6309. $out .= '>'.$labeltoshow.'</option>';
  6310. }
  6311. $i++;
  6312. }
  6313. $this->db->free($resql);
  6314. } else {
  6315. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6316. }
  6317. }
  6318. $out .= '</select>';
  6319. } elseif ($type == 'checkbox') {
  6320. $value_arr = explode(',', $value);
  6321. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
  6322. } elseif ($type == 'radio') {
  6323. $out = '';
  6324. foreach ($param['options'] as $keyopt => $valopt) {
  6325. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6326. $out .= ' value="'.$keyopt.'"';
  6327. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6328. $out .= ($value == $keyopt ? 'checked' : '');
  6329. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
  6330. }
  6331. } elseif ($type == 'chkbxlst') {
  6332. if (is_array($value)) {
  6333. $value_arr = $value;
  6334. } else {
  6335. $value_arr = explode(',', $value);
  6336. }
  6337. if (is_array($param['options'])) {
  6338. $param_list = array_keys($param['options']);
  6339. $InfoFieldList = explode(":", $param_list[0]);
  6340. $parentName = '';
  6341. $parentField = '';
  6342. // 0 : tableName
  6343. // 1 : label field name
  6344. // 2 : key fields name (if differ of rowid)
  6345. // 3 : key field parent (for dependent lists)
  6346. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6347. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6348. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6349. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6350. $keyList .= ', '.$parentField;
  6351. }
  6352. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6353. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6354. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6355. } else {
  6356. $keyList = $InfoFieldList[2].' as rowid';
  6357. }
  6358. }
  6359. $fields_label = explode('|', $InfoFieldList[1]);
  6360. if (is_array($fields_label)) {
  6361. $keyList .= ', ';
  6362. $keyList .= implode(', ', $fields_label);
  6363. }
  6364. $sqlwhere = '';
  6365. $sql = "SELECT ".$keyList;
  6366. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6367. if (!empty($InfoFieldList[4])) {
  6368. // can use SELECT request
  6369. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6370. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6371. }
  6372. // current object id can be use into filter
  6373. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6374. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6375. } else {
  6376. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6377. }
  6378. // We have to join on extrafield table
  6379. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6380. $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
  6381. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6382. } else {
  6383. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6384. }
  6385. } else {
  6386. $sqlwhere .= ' WHERE 1=1';
  6387. }
  6388. // Some tables may have field, some other not. For the moment we disable it.
  6389. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6390. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6391. }
  6392. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6393. // print $sql;
  6394. $sql .= $sqlwhere;
  6395. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6396. $resql = $this->db->query($sql);
  6397. if ($resql) {
  6398. $num = $this->db->num_rows($resql);
  6399. $i = 0;
  6400. $data = array();
  6401. while ($i < $num) {
  6402. $labeltoshow = '';
  6403. $obj = $this->db->fetch_object($resql);
  6404. $notrans = false;
  6405. // Several field into label (eq table:code|libelle:rowid)
  6406. $fields_label = explode('|', $InfoFieldList[1]);
  6407. if (count($fields_label) > 1) {
  6408. $notrans = true;
  6409. foreach ($fields_label as $field_toshow) {
  6410. $labeltoshow .= $obj->$field_toshow.' ';
  6411. }
  6412. } else {
  6413. $labeltoshow = $obj->{$InfoFieldList[1]};
  6414. }
  6415. $labeltoshow = dol_trunc($labeltoshow, 45);
  6416. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6417. foreach ($fields_label as $field_toshow) {
  6418. $translabel = $langs->trans($obj->$field_toshow);
  6419. if ($translabel != $obj->$field_toshow) {
  6420. $labeltoshow = dol_trunc($translabel, 18).' ';
  6421. } else {
  6422. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6423. }
  6424. }
  6425. $data[$obj->rowid] = $labeltoshow;
  6426. } else {
  6427. if (!$notrans) {
  6428. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6429. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6430. $labeltoshow = dol_trunc($translabel, 18);
  6431. } else {
  6432. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6433. }
  6434. }
  6435. if (empty($labeltoshow)) {
  6436. $labeltoshow = '(not defined)';
  6437. }
  6438. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6439. $data[$obj->rowid] = $labeltoshow;
  6440. }
  6441. if (!empty($InfoFieldList[3]) && $parentField) {
  6442. $parent = $parentName.':'.$obj->{$parentField};
  6443. $isDependList = 1;
  6444. }
  6445. $data[$obj->rowid] = $labeltoshow;
  6446. }
  6447. $i++;
  6448. }
  6449. $this->db->free($resql);
  6450. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6451. } else {
  6452. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6453. }
  6454. }
  6455. } elseif ($type == 'link') {
  6456. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6457. $param_list_array = explode(':', $param_list[0]);
  6458. $showempty = (($required && $default != '') ? 0 : 1);
  6459. if (!preg_match('/search_/', $keyprefix)) {
  6460. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6461. if (!empty($this->fields[$key]['picto'])) {
  6462. $morecss .= ' widthcentpercentminusxx';
  6463. } else {
  6464. $morecss .= ' widthcentpercentminusx';
  6465. }
  6466. } else {
  6467. if (!empty($this->fields[$key]['picto'])) {
  6468. $morecss .= ' widthcentpercentminusx';
  6469. }
  6470. }
  6471. }
  6472. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6473. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6474. 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".
  6475. list($class, $classfile) = explode(':', $param_list[0]);
  6476. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6477. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6478. } else {
  6479. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6480. }
  6481. $paramforthenewlink = '';
  6482. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6483. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6484. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6485. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6486. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6487. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6488. $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>';
  6489. }
  6490. }
  6491. } elseif ($type == 'password') {
  6492. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6493. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6494. } elseif ($type == 'array') {
  6495. $newval = $val;
  6496. $newval['type'] = 'varchar(256)';
  6497. $out = '';
  6498. if (!empty($value)) {
  6499. foreach ($value as $option) {
  6500. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6501. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6502. }
  6503. }
  6504. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6505. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6506. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6507. if (!empty($conf->use_javascript_ajax)) {
  6508. $out .= '
  6509. <script>
  6510. $(document).ready(function() {
  6511. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6512. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6513. });
  6514. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6515. $(this).parent().remove();
  6516. });
  6517. });
  6518. </script>';
  6519. }
  6520. }
  6521. if (!empty($hidden)) {
  6522. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6523. }
  6524. if ($isDependList==1) {
  6525. $out .= $this->getJSListDependancies('_common');
  6526. }
  6527. /* Add comments
  6528. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6529. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6530. */
  6531. // Display error message for field
  6532. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6533. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6534. }
  6535. return $out;
  6536. }
  6537. /**
  6538. * Return HTML string to show a field into a page
  6539. * Code very similar with showOutputField of extra fields
  6540. *
  6541. * @param array $val Array of properties of field to show
  6542. * @param string $key Key of attribute
  6543. * @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)
  6544. * @param string $moreparam To add more parametes on html input tag
  6545. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6546. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6547. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6548. * @return string
  6549. */
  6550. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6551. {
  6552. global $conf, $langs, $form;
  6553. if (!is_object($form)) {
  6554. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6555. $form = new Form($this->db);
  6556. }
  6557. $objectid = $this->id; // Not used ???
  6558. $label = empty($val['label']) ? '' : $val['label'];
  6559. $type = empty($val['type']) ? '' : $val['type'];
  6560. $size = empty($val['css']) ? '' : $val['css'];
  6561. $reg = array();
  6562. // Convert var to be able to share same code than showOutputField of extrafields
  6563. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6564. $type = 'varchar'; // convert varchar(xx) int varchar
  6565. $size = $reg[1];
  6566. } elseif (preg_match('/varchar/', $type)) {
  6567. $type = 'varchar'; // convert varchar(xx) int varchar
  6568. }
  6569. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6570. $type = 'select';
  6571. }
  6572. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6573. $type = 'link';
  6574. }
  6575. $default = empty($val['default']) ? '' : $val['default'];
  6576. $computed = empty($val['computed']) ? '' : $val['computed'];
  6577. $unique = empty($val['unique']) ? '' : $val['unique'];
  6578. $required = empty($val['required']) ? '' : $val['required'];
  6579. $param = array();
  6580. $param['options'] = array();
  6581. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6582. $param['options'] = $val['arrayofkeyval'];
  6583. }
  6584. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6585. $type = 'link';
  6586. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6587. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6588. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6589. $type = 'sellist';
  6590. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6591. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6592. $type = 'sellist';
  6593. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6594. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6595. $type = 'sellist';
  6596. }
  6597. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6598. $list = (empty($val['list']) ? '' : $val['list']);
  6599. $help = (empty($val['help']) ? '' : $val['help']);
  6600. $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)
  6601. if ($hidden) {
  6602. return '';
  6603. }
  6604. // If field is a computed field, value must become result of compute
  6605. if ($computed) {
  6606. // Make the eval of compute string
  6607. //var_dump($computed);
  6608. $value = dol_eval($computed, 1, 0, '');
  6609. }
  6610. if (empty($morecss)) {
  6611. if ($type == 'date') {
  6612. $morecss = 'minwidth100imp';
  6613. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6614. $morecss = 'minwidth200imp';
  6615. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6616. $morecss = 'maxwidth75';
  6617. } elseif ($type == 'url') {
  6618. $morecss = 'minwidth400';
  6619. } elseif ($type == 'boolean') {
  6620. $morecss = '';
  6621. } else {
  6622. if (is_numeric($size) && round($size) < 12) {
  6623. $morecss = 'minwidth100';
  6624. } elseif (is_numeric($size) && round($size) <= 48) {
  6625. $morecss = 'minwidth200';
  6626. } else {
  6627. $morecss = 'minwidth400';
  6628. }
  6629. }
  6630. }
  6631. // Format output value differently according to properties of field
  6632. if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
  6633. 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.
  6634. $value = $this->getNomUrl(1, '', 0, '', 1);
  6635. }
  6636. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6637. $value = $this->getLibStatut(3);
  6638. } elseif ($type == 'date') {
  6639. if (!empty($value)) {
  6640. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6641. } else {
  6642. $value = '';
  6643. }
  6644. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6645. if (!empty($value)) {
  6646. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6647. } else {
  6648. $value = '';
  6649. }
  6650. } elseif ($type == 'duration') {
  6651. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6652. if (!is_null($value) && $value !== '') {
  6653. $value = convertSecondToTime($value, 'allhourmin');
  6654. }
  6655. } elseif ($type == 'double' || $type == 'real') {
  6656. if (!is_null($value) && $value !== '') {
  6657. $value = price($value);
  6658. }
  6659. } elseif ($type == 'boolean') {
  6660. $checked = '';
  6661. if (!empty($value)) {
  6662. $checked = ' checked ';
  6663. }
  6664. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6665. } elseif ($type == 'mail' || $type == 'email') {
  6666. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6667. } elseif ($type == 'url') {
  6668. $value = dol_print_url($value, '_blank', 32, 1);
  6669. } elseif ($type == 'phone') {
  6670. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
  6671. } elseif ($type == 'price') {
  6672. if (!is_null($value) && $value !== '') {
  6673. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6674. }
  6675. } elseif ($type == 'select') {
  6676. $value = isset($param['options'][$value])?$param['options'][$value]:'';
  6677. } elseif ($type == 'sellist') {
  6678. $param_list = array_keys($param['options']);
  6679. $InfoFieldList = explode(":", $param_list[0]);
  6680. $selectkey = "rowid";
  6681. $keyList = 'rowid';
  6682. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6683. $selectkey = $InfoFieldList[2];
  6684. $keyList = $InfoFieldList[2].' as rowid';
  6685. }
  6686. $fields_label = explode('|', $InfoFieldList[1]);
  6687. if (is_array($fields_label)) {
  6688. $keyList .= ', ';
  6689. $keyList .= implode(', ', $fields_label);
  6690. }
  6691. $sql = "SELECT ".$keyList;
  6692. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6693. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6694. $sql .= ' as main';
  6695. }
  6696. if ($selectkey == 'rowid' && empty($value)) {
  6697. $sql .= " WHERE ".$selectkey." = 0";
  6698. } elseif ($selectkey == 'rowid') {
  6699. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6700. } else {
  6701. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6702. }
  6703. //$sql.= ' AND entity = '.$conf->entity;
  6704. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6705. $resql = $this->db->query($sql);
  6706. if ($resql) {
  6707. $value = ''; // value was used, so now we reste it to use it to build final output
  6708. $numrows = $this->db->num_rows($resql);
  6709. if ($numrows) {
  6710. $obj = $this->db->fetch_object($resql);
  6711. // Several field into label (eq table:code|libelle:rowid)
  6712. $fields_label = explode('|', $InfoFieldList[1]);
  6713. if (is_array($fields_label) && count($fields_label) > 1) {
  6714. foreach ($fields_label as $field_toshow) {
  6715. $translabel = '';
  6716. if (!empty($obj->$field_toshow)) {
  6717. $translabel = $langs->trans($obj->$field_toshow);
  6718. }
  6719. if ($translabel != $field_toshow) {
  6720. $value .= dol_trunc($translabel, 18).' ';
  6721. } else {
  6722. $value .= $obj->$field_toshow.' ';
  6723. }
  6724. }
  6725. } else {
  6726. $translabel = '';
  6727. if (!empty($obj->{$InfoFieldList[1]})) {
  6728. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6729. }
  6730. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6731. $value = dol_trunc($translabel, 18);
  6732. } else {
  6733. $value = $obj->{$InfoFieldList[1]};
  6734. }
  6735. }
  6736. }
  6737. } else {
  6738. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6739. }
  6740. } elseif ($type == 'radio') {
  6741. $value = $param['options'][$value];
  6742. } elseif ($type == 'checkbox') {
  6743. $value_arr = explode(',', $value);
  6744. $value = '';
  6745. if (is_array($value_arr) && count($value_arr) > 0) {
  6746. $toprint = array();
  6747. foreach ($value_arr as $keyval => $valueval) {
  6748. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6749. }
  6750. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6751. }
  6752. } elseif ($type == 'chkbxlst') {
  6753. $value_arr = explode(',', $value);
  6754. $param_list = array_keys($param['options']);
  6755. $InfoFieldList = explode(":", $param_list[0]);
  6756. $selectkey = "rowid";
  6757. $keyList = 'rowid';
  6758. if (count($InfoFieldList) >= 3) {
  6759. $selectkey = $InfoFieldList[2];
  6760. $keyList = $InfoFieldList[2].' as rowid';
  6761. }
  6762. $fields_label = explode('|', $InfoFieldList[1]);
  6763. if (is_array($fields_label)) {
  6764. $keyList .= ', ';
  6765. $keyList .= implode(', ', $fields_label);
  6766. }
  6767. $sql = "SELECT ".$keyList;
  6768. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6769. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6770. $sql .= ' as main';
  6771. }
  6772. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6773. // $sql.= ' AND entity = '.$conf->entity;
  6774. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6775. $resql = $this->db->query($sql);
  6776. if ($resql) {
  6777. $value = ''; // value was used, so now we reste it to use it to build final output
  6778. $toprint = array();
  6779. while ($obj = $this->db->fetch_object($resql)) {
  6780. // Several field into label (eq table:code|libelle:rowid)
  6781. $fields_label = explode('|', $InfoFieldList[1]);
  6782. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6783. if (is_array($fields_label) && count($fields_label) > 1) {
  6784. foreach ($fields_label as $field_toshow) {
  6785. $translabel = '';
  6786. if (!empty($obj->$field_toshow)) {
  6787. $translabel = $langs->trans($obj->$field_toshow);
  6788. }
  6789. if ($translabel != $field_toshow) {
  6790. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6791. } else {
  6792. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6793. }
  6794. }
  6795. } else {
  6796. $translabel = '';
  6797. if (!empty($obj->{$InfoFieldList[1]})) {
  6798. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6799. }
  6800. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6801. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6802. } else {
  6803. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6804. }
  6805. }
  6806. }
  6807. }
  6808. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6809. } else {
  6810. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6811. }
  6812. } elseif ($type == 'link') {
  6813. $out = '';
  6814. // only if something to display (perf)
  6815. if ($value) {
  6816. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6817. $InfoFieldList = explode(":", $param_list[0]);
  6818. $classname = $InfoFieldList[0];
  6819. $classpath = $InfoFieldList[1];
  6820. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6821. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6822. if (!empty($classpath)) {
  6823. dol_include_once($InfoFieldList[1]);
  6824. if ($classname && class_exists($classname)) {
  6825. $object = new $classname($this->db);
  6826. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6827. $result = $object->fetch($value, '', '', '', 0, 1, 1);
  6828. } else {
  6829. $result = $object->fetch($value);
  6830. }
  6831. if ($result > 0) {
  6832. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6833. } else {
  6834. $value = '';
  6835. }
  6836. }
  6837. } else {
  6838. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6839. return 'Error bad setup of extrafield';
  6840. }
  6841. } else {
  6842. $value = '';
  6843. }
  6844. } elseif ($type == 'password') {
  6845. $value = preg_replace('/./i', '*', $value);
  6846. } elseif ($type == 'array') {
  6847. $value = implode('<br>', $value);
  6848. } else { // text|html|varchar
  6849. $value = dol_htmlentitiesbr($value);
  6850. }
  6851. //print $type.'-'.$size.'-'.$value;
  6852. $out = $value;
  6853. return $out;
  6854. }
  6855. /**
  6856. * clear validation message result for a field
  6857. *
  6858. * @param string $fieldKey Key of attribute to clear
  6859. * @return null
  6860. */
  6861. public function clearFieldError($fieldKey)
  6862. {
  6863. $this->error = '';
  6864. unset($this->validateFieldsErrors[$fieldKey]);
  6865. }
  6866. /**
  6867. * set validation error message a field
  6868. *
  6869. * @param string $fieldKey Key of attribute
  6870. * @param string $msg the field error message
  6871. * @return null
  6872. */
  6873. public function setFieldError($fieldKey, $msg = '')
  6874. {
  6875. global $langs;
  6876. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6877. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6878. }
  6879. /**
  6880. * get field error message
  6881. *
  6882. * @param string $fieldKey Key of attribute
  6883. * @return string
  6884. */
  6885. public function getFieldError($fieldKey)
  6886. {
  6887. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6888. return $this->validateFieldsErrors[$fieldKey];
  6889. }
  6890. return '';
  6891. }
  6892. /**
  6893. * Return validation test result for a field
  6894. *
  6895. * @param array $val Array of properties of field to show
  6896. * @param string $fieldKey Key of attribute
  6897. * @param string $fieldValue value of attribute
  6898. * @return bool return false if fail true on success, see $this->error for error message
  6899. */
  6900. public function validateField($val, $fieldKey, $fieldValue)
  6901. {
  6902. global $langs;
  6903. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6904. $this->clearFieldError($fieldKey);
  6905. if (!isset($val[$fieldKey])) {
  6906. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6907. return false;
  6908. }
  6909. $param = array();
  6910. $param['options'] = array();
  6911. $type = $val[$fieldKey]['type'];
  6912. $required = false;
  6913. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6914. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6915. $required = true;
  6916. }
  6917. $maxSize = 0;
  6918. $minSize = 0;
  6919. //
  6920. // PREPARE Elements
  6921. //
  6922. // Convert var to be able to share same code than showOutputField of extrafields
  6923. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6924. $type = 'varchar'; // convert varchar(xx) int varchar
  6925. $maxSize = $reg[1];
  6926. } elseif (preg_match('/varchar/', $type)) {
  6927. $type = 'varchar'; // convert varchar(xx) int varchar
  6928. }
  6929. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6930. $type = 'select';
  6931. }
  6932. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6933. $type = 'link';
  6934. }
  6935. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6936. $param['options'] = $val['arrayofkeyval'];
  6937. }
  6938. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6939. $type = 'link';
  6940. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6941. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6942. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6943. $type = 'sellist';
  6944. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6945. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6946. $type = 'sellist';
  6947. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6948. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6949. $type = 'sellist';
  6950. }
  6951. //
  6952. // TEST Value
  6953. //
  6954. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6955. $validate = new Validate($this->db, $langs);
  6956. // little trick : to perform tests with good performances sort tests by quick to low
  6957. //
  6958. // COMMON TESTS
  6959. //
  6960. // Required test and empty value
  6961. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6962. $this->setFieldError($fieldKey, $validate->error);
  6963. return false;
  6964. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6965. // if no value sent and the field is not mandatory, no need to perform tests
  6966. return true;
  6967. }
  6968. // MAX Size test
  6969. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6970. $this->setFieldError($fieldKey, $validate->error);
  6971. return false;
  6972. }
  6973. // MIN Size test
  6974. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6975. $this->setFieldError($fieldKey, $validate->error);
  6976. return false;
  6977. }
  6978. //
  6979. // TESTS for TYPE
  6980. //
  6981. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6982. if (!$validate->isTimestamp($fieldValue)) {
  6983. $this->setFieldError($fieldKey, $validate->error);
  6984. return false;
  6985. } else { return true; }
  6986. } elseif ($type == 'duration') {
  6987. if (!$validate->isDuration($fieldValue)) {
  6988. $this->setFieldError($fieldKey, $validate->error);
  6989. return false;
  6990. } else { return true; }
  6991. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6992. // is numeric
  6993. if (!$validate->isNumeric($fieldValue)) {
  6994. $this->setFieldError($fieldKey, $validate->error);
  6995. return false;
  6996. } else { return true; }
  6997. } elseif ($type == 'boolean') {
  6998. if (!$validate->isBool($fieldValue)) {
  6999. $this->setFieldError($fieldKey, $validate->error);
  7000. return false;
  7001. } else { return true; }
  7002. } elseif ($type == 'mail') {
  7003. if (!$validate->isEmail($fieldValue)) {
  7004. $this->setFieldError($fieldKey, $validate->error);
  7005. return false;
  7006. }
  7007. } elseif ($type == 'url') {
  7008. if (!$validate->isUrl($fieldValue)) {
  7009. $this->setFieldError($fieldKey, $validate->error);
  7010. return false;
  7011. } else { return true; }
  7012. } elseif ($type == 'phone') {
  7013. if (!$validate->isPhone($fieldValue)) {
  7014. $this->setFieldError($fieldKey, $validate->error);
  7015. return false;
  7016. } else { return true; }
  7017. } elseif ($type == 'select' || $type == 'radio') {
  7018. if (!isset($param['options'][$fieldValue])) {
  7019. $this->error = $langs->trans('RequireValidValue');
  7020. return false;
  7021. } else { return true; }
  7022. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  7023. $param_list = array_keys($param['options']);
  7024. $InfoFieldList = explode(":", $param_list[0]);
  7025. $value_arr = explode(',', $fieldValue);
  7026. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  7027. $selectkey = "rowid";
  7028. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  7029. $selectkey = $InfoFieldList[2];
  7030. }
  7031. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  7032. $this->setFieldError($fieldKey, $validate->error);
  7033. return false;
  7034. } else { return true; }
  7035. } elseif ($type == 'link') {
  7036. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  7037. $InfoFieldList = explode(":", $param_list[0]);
  7038. $classname = $InfoFieldList[0];
  7039. $classpath = $InfoFieldList[1];
  7040. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  7041. $this->setFieldError($fieldKey, $validate->error);
  7042. return false;
  7043. } else { return true; }
  7044. }
  7045. // if no test failled all is ok
  7046. return true;
  7047. }
  7048. /**
  7049. * Function to show lines of extrafields with output datas.
  7050. * 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
  7051. *
  7052. * @param Extrafields $extrafields Extrafield Object
  7053. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  7054. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  7055. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  7056. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  7057. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  7058. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  7059. * @return string String with html content to show
  7060. */
  7061. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  7062. {
  7063. global $db, $conf, $langs, $action, $form, $hookmanager;
  7064. if (!is_object($form)) {
  7065. $form = new Form($db);
  7066. }
  7067. if (!is_object($extrafields)) {
  7068. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  7069. return 'Bad parameter extrafields for showOptionals';
  7070. }
  7071. if (!is_array($extrafields->attributes[$this->table_element])) {
  7072. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  7073. }
  7074. $out = '';
  7075. $parameters = array();
  7076. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  7077. if (empty($reshook)) {
  7078. 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) {
  7079. $out .= "\n";
  7080. $out .= '<!-- commonobject:showOptionals --> ';
  7081. $out .= "\n";
  7082. $extrafields_collapse_num = '';
  7083. $e = 0;
  7084. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  7085. // Show only the key field in params
  7086. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  7087. continue;
  7088. }
  7089. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  7090. $enabled = 1;
  7091. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  7092. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
  7093. }
  7094. if (empty($enabled)) {
  7095. continue;
  7096. }
  7097. $visibility = 1;
  7098. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  7099. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
  7100. }
  7101. $perms = 1;
  7102. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  7103. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
  7104. }
  7105. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7106. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7107. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7108. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7109. } elseif ($mode == 'view' && empty($visibility)) {
  7110. continue;
  7111. }
  7112. if (empty($perms)) {
  7113. continue;
  7114. }
  7115. // Load language if required
  7116. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7117. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7118. }
  7119. $colspan = 0;
  7120. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  7121. if (array_key_exists('cols', $params)) {
  7122. $colspan = $params['cols'];
  7123. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7124. $reg = array();
  7125. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7126. $colspan = $reg[1];
  7127. } else {
  7128. $colspan = $params['colspan'];
  7129. }
  7130. }
  7131. }
  7132. $colspan = intval($colspan);
  7133. switch ($mode) {
  7134. case "view":
  7135. $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
  7136. break;
  7137. case "create":
  7138. case "edit":
  7139. // We get the value of property found with GETPOST so it takes into account:
  7140. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7141. $check = 'alphanohtml';
  7142. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7143. $check = 'restricthtml';
  7144. }
  7145. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7146. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7147. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7148. if (is_array($getposttemp)) {
  7149. // $getposttemp is an array but following code expects a comma separated string
  7150. $value = implode(",", $getposttemp);
  7151. } else {
  7152. $value = $getposttemp;
  7153. }
  7154. } else {
  7155. $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.
  7156. }
  7157. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7158. break;
  7159. }
  7160. // Output value of the current field
  7161. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7162. $extrafields_collapse_num = '';
  7163. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7164. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7165. $extrafield_param_list = array_keys($extrafield_param['options']);
  7166. if (count($extrafield_param_list) > 0) {
  7167. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7168. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7169. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7170. }
  7171. }
  7172. }
  7173. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7174. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7175. } else {
  7176. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7177. $csstyle = '';
  7178. if (is_array($params) && count($params) > 0) {
  7179. if (array_key_exists('class', $params)) {
  7180. $class .= $params['class'].' ';
  7181. }
  7182. if (array_key_exists('style', $params)) {
  7183. $csstyle = $params['style'];
  7184. }
  7185. }
  7186. // add html5 elements
  7187. $domData = ' data-element="extrafield"';
  7188. $domData .= ' data-targetelement="'.$this->element.'"';
  7189. $domData .= ' data-targetid="'.$this->id.'"';
  7190. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7191. if ($display_type=='card') {
  7192. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7193. $colspan = 0;
  7194. }
  7195. if ($action == 'selectlines') {
  7196. $colspan++;
  7197. }
  7198. }
  7199. // Convert date into timestamp format (value in memory must be a timestamp)
  7200. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7201. $datenotinstring = null;
  7202. if (array_key_exists('options_'.$key, $this->array_options)) {
  7203. $datenotinstring = $this->array_options['options_'.$key];
  7204. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7205. $datenotinstring = $this->db->jdate($datenotinstring);
  7206. }
  7207. }
  7208. $datekey = $keyprefix.'options_'.$key.$keysuffix;
  7209. $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
  7210. }
  7211. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7212. $datenotinstring = null;
  7213. if (array_key_exists('options_'.$key, $this->array_options)) {
  7214. $datenotinstring = $this->array_options['options_'.$key];
  7215. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7216. $datenotinstring = $this->db->jdate($datenotinstring);
  7217. }
  7218. }
  7219. $timekey = $keyprefix.'options_'.$key.$keysuffix;
  7220. $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;
  7221. }
  7222. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7223. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7224. if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
  7225. $value = price2num($value);
  7226. } elseif (isset($this->array_options['options_'.$key])) {
  7227. $value = $this->array_options['options_'.$key];
  7228. }
  7229. }
  7230. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7231. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
  7232. if ($action == 'create') {
  7233. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7234. }
  7235. }
  7236. $labeltoshow = $langs->trans($label);
  7237. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7238. if ($display_type == 'card') {
  7239. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7240. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
  7241. $out .= '<td></td>';
  7242. }
  7243. $out .= '<td class="titlefieldcreate wordbreak';
  7244. } elseif ($display_type == 'line') {
  7245. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  7246. $out .= '<div style="display: inline-block; padding-right:4px" class="titlefieldcreate wordbreak';
  7247. }
  7248. //$out .= "titlefield";
  7249. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7250. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7251. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7252. if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
  7253. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7254. $out .= ' fieldrequired';
  7255. }
  7256. }
  7257. $out .= '">';
  7258. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7259. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7260. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7261. } else {
  7262. $out .= $labeltoshow;
  7263. }
  7264. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7265. $out .= '&nbsp;<span style="color: red">*</span>';
  7266. }
  7267. } else {
  7268. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7269. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7270. } else {
  7271. $out .= $labeltoshow;
  7272. }
  7273. }
  7274. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7275. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7276. if ($display_type == 'card') {
  7277. // 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
  7278. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7279. } elseif ($display_type == 'line') {
  7280. $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].'">';
  7281. }
  7282. switch ($mode) {
  7283. case "view":
  7284. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7285. break;
  7286. case "create":
  7287. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7288. break;
  7289. case "edit":
  7290. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7291. break;
  7292. }
  7293. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7294. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7295. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7296. } else {
  7297. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7298. }
  7299. $e++;
  7300. }
  7301. }
  7302. $out .= "\n";
  7303. // Add code to manage list depending on others
  7304. if (!empty($conf->use_javascript_ajax)) {
  7305. $out .= $this->getJSListDependancies();
  7306. }
  7307. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7308. }
  7309. }
  7310. $out .= $hookmanager->resPrint;
  7311. return $out;
  7312. }
  7313. /**
  7314. * @param string $type Type for prefix
  7315. * @return string Javacript code to manage dependency
  7316. */
  7317. public function getJSListDependancies($type = '_extra')
  7318. {
  7319. $out = '
  7320. <script>
  7321. jQuery(document).ready(function() {
  7322. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7323. {
  7324. var val = $("select[name=\""+parent_list+"\"]").val();
  7325. var parentVal = parent_list + ":" + val;
  7326. if(typeof val == "string"){
  7327. if(val != "") {
  7328. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7329. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7330. $("select[name=\""+child_list+"\"]").append(options);
  7331. } else {
  7332. var options = orig_select.find("option[parent]").clone();
  7333. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7334. $("select[name=\""+child_list+"\"]").append(options);
  7335. }
  7336. } else if(val > 0) {
  7337. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7338. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7339. $("select[name=\""+child_list+"\"]").append(options);
  7340. } else {
  7341. var options = orig_select.find("option[parent]").clone();
  7342. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7343. $("select[name=\""+child_list+"\"]").append(options);
  7344. }
  7345. }
  7346. function setListDependencies'.$type.'() {
  7347. jQuery("select option[parent]").parent().each(function() {
  7348. var orig_select = {};
  7349. var child_list = $(this).attr("name");
  7350. orig_select[child_list] = $(this).clone();
  7351. var parent = $(this).find("option[parent]:first").attr("parent");
  7352. var infos = parent.split(":");
  7353. var parent_list = infos[0];
  7354. //Hide daughters lists
  7355. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7356. $("#"+child_list).hide();
  7357. //Show mother lists
  7358. } else if ($("#"+parent_list).val() != 0){
  7359. $("#"+parent_list).show();
  7360. }
  7361. //Show the child list if the parent list value is selected
  7362. $("select[name=\""+parent_list+"\"]").click(function() {
  7363. if ($(this).val() != 0){
  7364. $("#"+child_list).show()
  7365. }
  7366. });
  7367. //When we change parent list
  7368. $("select[name=\""+parent_list+"\"]").change(function() {
  7369. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7370. //Select the value 0 on child list after a change on the parent list
  7371. $("#"+child_list).val(0).trigger("change");
  7372. //Hide child lists if the parent value is set to 0
  7373. if ($(this).val() == 0){
  7374. $("#"+child_list).hide();
  7375. }
  7376. });
  7377. });
  7378. }
  7379. setListDependencies'.$type.'();
  7380. });
  7381. </script>'."\n";
  7382. return $out;
  7383. }
  7384. /**
  7385. * Returns the rights used for this class
  7386. * @return stdClass
  7387. */
  7388. public function getRights()
  7389. {
  7390. global $user;
  7391. $element = $this->element;
  7392. if ($element == 'facturerec') {
  7393. $element = 'facture';
  7394. } elseif ($element == 'invoice_supplier_rec') {
  7395. return $user->rights->fournisseur->facture;
  7396. }
  7397. return $user->rights->{$element};
  7398. }
  7399. /**
  7400. * Function used to replace a thirdparty id with another one.
  7401. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7402. * Column name fk_soc MUST be used to identify thirdparties
  7403. *
  7404. * @param DoliDB $db Database handler
  7405. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7406. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7407. * @param string[] $tables Tables that need to be changed
  7408. * @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)
  7409. * @return bool True if success, False if error
  7410. */
  7411. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7412. {
  7413. foreach ($tables as $table) {
  7414. $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7415. if (!$db->query($sql)) {
  7416. if ($ignoreerrors) {
  7417. 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.
  7418. }
  7419. //$this->errors = $db->lasterror();
  7420. return false;
  7421. }
  7422. }
  7423. return true;
  7424. }
  7425. /**
  7426. * Function used to replace a product id with another one.
  7427. * This function is meant to be called from replaceProduct with the appropriate tables
  7428. * Column name fk_product MUST be used to identify products
  7429. *
  7430. * @param DoliDB $db Database handler
  7431. * @param int $origin_id Old product id (the product to delete)
  7432. * @param int $dest_id New product id (the product that will received element of the other)
  7433. * @param string[] $tables Tables that need to be changed
  7434. * @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)
  7435. * @return bool True if success, False if error
  7436. */
  7437. public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7438. {
  7439. foreach ($tables as $table) {
  7440. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7441. if (!$db->query($sql)) {
  7442. if ($ignoreerrors) {
  7443. 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.
  7444. }
  7445. //$this->errors = $db->lasterror();
  7446. return false;
  7447. }
  7448. }
  7449. return true;
  7450. }
  7451. /**
  7452. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7453. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7454. * elseif calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7455. * elseif calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7456. * else set min buy price as buy price
  7457. *
  7458. * @param float $unitPrice Product unit price
  7459. * @param float $discountPercent Line discount percent
  7460. * @param int $fk_product Product id
  7461. * @return float <0 if KO, buyprice if OK
  7462. */
  7463. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7464. {
  7465. global $conf;
  7466. $buyPrice = 0;
  7467. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7468. // When ForceBuyingPriceIfNull is set
  7469. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7470. } else {
  7471. // Get cost price for margin calculation
  7472. if (!empty($fk_product) && $fk_product > 0) {
  7473. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7474. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7475. $product = new Product($this->db);
  7476. $result = $product->fetch($fk_product);
  7477. if ($result <= 0) {
  7478. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7479. return -1;
  7480. }
  7481. if ($product->cost_price > 0) {
  7482. $buyPrice = $product->cost_price;
  7483. } elseif ($product->pmp > 0) {
  7484. $buyPrice = $product->pmp;
  7485. }
  7486. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7487. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7488. $product = new Product($this->db);
  7489. $result = $product->fetch($fk_product);
  7490. if ($result <= 0) {
  7491. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7492. return -1;
  7493. }
  7494. if ($product->pmp > 0) {
  7495. $buyPrice = $product->pmp;
  7496. }
  7497. }
  7498. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7499. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7500. $productFournisseur = new ProductFournisseur($this->db);
  7501. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7502. $buyPrice = $productFournisseur->fourn_unitprice;
  7503. } elseif ($result < 0) {
  7504. $this->errors[] = $productFournisseur->error;
  7505. return -2;
  7506. }
  7507. }
  7508. }
  7509. }
  7510. return $buyPrice;
  7511. }
  7512. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7513. /**
  7514. * Show photos of an object (nbmax maximum), into several columns
  7515. *
  7516. * @param string $modulepart 'product', 'ticket', ...
  7517. * @param string $sdir Directory to scan (full absolute path)
  7518. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7519. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7520. * @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'.
  7521. * @param int $showfilename 1=Show filename
  7522. * @param int $showaction 1=Show icon with action links (resize, delete)
  7523. * @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.
  7524. * @param int $maxWidth Max width of original image when size='small'
  7525. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7526. * @param int $notitle Do not add title tag on image
  7527. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7528. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7529. */
  7530. public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $notitle = 0, $usesharelink = 0)
  7531. {
  7532. // phpcs:enable
  7533. global $conf, $user, $langs;
  7534. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7535. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7536. $sortfield = 'position_name';
  7537. $sortorder = 'asc';
  7538. $dir = $sdir.'/';
  7539. $pdir = '/';
  7540. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7541. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7542. // For backward compatibility
  7543. if ($modulepart == 'product') {
  7544. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7545. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7546. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7547. }
  7548. }
  7549. // Defined relative dir to DOL_DATA_ROOT
  7550. $relativedir = '';
  7551. if ($dir) {
  7552. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7553. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7554. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7555. }
  7556. $dirthumb = $dir.'thumbs/';
  7557. $pdirthumb = $pdir.'thumbs/';
  7558. $return = '<!-- Photo -->'."\n";
  7559. $nbphoto = 0;
  7560. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7561. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7562. {
  7563. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7564. $filearray=array_merge($filearray, $filearrayold);
  7565. }*/
  7566. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7567. if (count($filearray)) {
  7568. if ($sortfield && $sortorder) {
  7569. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7570. }
  7571. foreach ($filearray as $key => $val) {
  7572. $photo = '';
  7573. $file = $val['name'];
  7574. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7575. if (image_format_supported($file) >= 0) {
  7576. $nbphoto++;
  7577. $photo = $file;
  7578. $viewfilename = $file;
  7579. if ($size == 1 || $size == 'small') { // Format vignette
  7580. // Find name of thumb file
  7581. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7582. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7583. $photo_vignette = '';
  7584. }
  7585. // Get filesize of original file
  7586. $imgarray = dol_getImageSize($dir.$photo);
  7587. if ($nbbyrow > 0) {
  7588. if ($nbphoto == 1) {
  7589. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7590. }
  7591. if ($nbphoto % $nbbyrow == 1) {
  7592. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7593. }
  7594. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7595. } elseif ($nbbyrow < 0) {
  7596. $return .= '<div class="inline-block">';
  7597. }
  7598. $return .= "\n";
  7599. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7600. if (empty($nolink)) {
  7601. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7602. if ($urladvanced) {
  7603. $return .= '<a href="'.$urladvanced.'">';
  7604. } else {
  7605. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7606. }
  7607. }
  7608. // Show image (width height=$maxHeight)
  7609. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7610. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7611. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7612. if ($notitle) {
  7613. $alt = '';
  7614. }
  7615. $addphotorefcss = 1;
  7616. if ($usesharelink) {
  7617. if ($val['share']) {
  7618. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7619. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7620. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7621. } else {
  7622. $return .= '<!-- Show original file -->';
  7623. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7624. }
  7625. } else {
  7626. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7627. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7628. }
  7629. } else {
  7630. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7631. $return .= '<!-- Show thumb -->';
  7632. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').' maxwidth150onsmartphone maxwidth200" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7633. } else {
  7634. $return .= '<!-- Show original file -->';
  7635. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7636. }
  7637. }
  7638. if (empty($nolink)) {
  7639. $return .= '</a>';
  7640. }
  7641. $return .= "\n";
  7642. if ($showfilename) {
  7643. $return .= '<br>'.$viewfilename;
  7644. }
  7645. if ($showaction) {
  7646. $return .= '<br>';
  7647. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7648. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7649. $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>';
  7650. }
  7651. // Special cas for product
  7652. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7653. // Link to resize
  7654. $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; ';
  7655. // Link to delete
  7656. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7657. $return .= img_delete().'</a>';
  7658. }
  7659. }
  7660. $return .= "\n";
  7661. if ($nbbyrow > 0) {
  7662. $return .= '</td>';
  7663. if (($nbphoto % $nbbyrow) == 0) {
  7664. $return .= '</tr>';
  7665. }
  7666. } elseif ($nbbyrow < 0) {
  7667. $return .= '</div>';
  7668. }
  7669. }
  7670. if (empty($size)) { // Format origine
  7671. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7672. if ($showfilename) {
  7673. $return .= '<br>'.$viewfilename;
  7674. }
  7675. if ($showaction) {
  7676. // Special case for product
  7677. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7678. // Link to resize
  7679. $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; ';
  7680. // Link to delete
  7681. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7682. $return .= img_delete().'</a>';
  7683. }
  7684. }
  7685. }
  7686. // On continue ou on arrete de boucler ?
  7687. if ($nbmax && $nbphoto >= $nbmax) {
  7688. break;
  7689. }
  7690. }
  7691. }
  7692. if ($size == 1 || $size == 'small') {
  7693. if ($nbbyrow > 0) {
  7694. // Ferme tableau
  7695. while ($nbphoto % $nbbyrow) {
  7696. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7697. $nbphoto++;
  7698. }
  7699. if ($nbphoto) {
  7700. $return .= '</table>';
  7701. }
  7702. }
  7703. }
  7704. }
  7705. $this->nbphoto = $nbphoto;
  7706. return $return;
  7707. }
  7708. /**
  7709. * Function test if type is array
  7710. *
  7711. * @param array $info content informations of field
  7712. * @return bool true if array
  7713. */
  7714. protected function isArray($info)
  7715. {
  7716. if (is_array($info)) {
  7717. if (isset($info['type']) && $info['type'] == 'array') {
  7718. return true;
  7719. } else {
  7720. return false;
  7721. }
  7722. }
  7723. return false;
  7724. }
  7725. /**
  7726. * Function test if type is date
  7727. *
  7728. * @param array $info content informations of field
  7729. * @return bool true if date
  7730. */
  7731. public function isDate($info)
  7732. {
  7733. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7734. return true;
  7735. }
  7736. return false;
  7737. }
  7738. /**
  7739. * Function test if type is duration
  7740. *
  7741. * @param array $info content informations of field
  7742. * @return bool true if field of type duration
  7743. */
  7744. public function isDuration($info)
  7745. {
  7746. if (is_array($info)) {
  7747. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7748. return true;
  7749. } else {
  7750. return false;
  7751. }
  7752. } else {
  7753. return false;
  7754. }
  7755. }
  7756. /**
  7757. * Function test if type is integer
  7758. *
  7759. * @param array $info content informations of field
  7760. * @return bool true if integer
  7761. */
  7762. public function isInt($info)
  7763. {
  7764. if (is_array($info)) {
  7765. if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
  7766. return true;
  7767. } else {
  7768. return false;
  7769. }
  7770. } else {
  7771. return false;
  7772. }
  7773. }
  7774. /**
  7775. * Function test if type is float
  7776. *
  7777. * @param array $info content informations of field
  7778. * @return bool true if float
  7779. */
  7780. public function isFloat($info)
  7781. {
  7782. if (is_array($info)) {
  7783. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7784. return true;
  7785. } else {
  7786. return false;
  7787. }
  7788. }
  7789. return false;
  7790. }
  7791. /**
  7792. * Function test if type is text
  7793. *
  7794. * @param array $info content informations of field
  7795. * @return bool true if type text
  7796. */
  7797. public function isText($info)
  7798. {
  7799. if (is_array($info)) {
  7800. if (isset($info['type']) && $info['type'] == 'text') {
  7801. return true;
  7802. } else {
  7803. return false;
  7804. }
  7805. }
  7806. return false;
  7807. }
  7808. /**
  7809. * Function test if field can be null
  7810. *
  7811. * @param array $info content informations of field
  7812. * @return bool true if it can be null
  7813. */
  7814. protected function canBeNull($info)
  7815. {
  7816. if (is_array($info)) {
  7817. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7818. return true;
  7819. } else {
  7820. return false;
  7821. }
  7822. }
  7823. return true;
  7824. }
  7825. /**
  7826. * Function test if field is forced to null if zero or empty
  7827. *
  7828. * @param array $info content informations of field
  7829. * @return bool true if forced to null
  7830. */
  7831. protected function isForcedToNullIfZero($info)
  7832. {
  7833. if (is_array($info)) {
  7834. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7835. return true;
  7836. } else {
  7837. return false;
  7838. }
  7839. }
  7840. return false;
  7841. }
  7842. /**
  7843. * Function test if is indexed
  7844. *
  7845. * @param array $info content informations of field
  7846. * @return bool
  7847. */
  7848. protected function isIndex($info)
  7849. {
  7850. if (is_array($info)) {
  7851. if (isset($info['index']) && $info['index'] == true) {
  7852. return true;
  7853. } else {
  7854. return false;
  7855. }
  7856. }
  7857. return false;
  7858. }
  7859. /**
  7860. * Function to prepare a part of the query for insert.
  7861. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7862. * $this->${field} should be a clean value. The page can run
  7863. *
  7864. * @return array
  7865. */
  7866. protected function setSaveQuery()
  7867. {
  7868. global $conf;
  7869. $queryarray = array();
  7870. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7871. // Depending on field type ('datetime', ...)
  7872. if ($this->isDate($info)) {
  7873. if (empty($this->{$field})) {
  7874. $queryarray[$field] = null;
  7875. } else {
  7876. $queryarray[$field] = $this->db->idate($this->{$field});
  7877. }
  7878. } elseif ($this->isDuration($info)) {
  7879. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7880. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7881. if (!isset($this->{$field})) {
  7882. if (!empty($info['default'])) {
  7883. $queryarray[$field] = $info['default'];
  7884. } else {
  7885. $queryarray[$field] = 0;
  7886. }
  7887. } else {
  7888. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7889. }
  7890. } else {
  7891. $queryarray[$field] = null;
  7892. }
  7893. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7894. if ($field == 'entity' && is_null($this->{$field})) {
  7895. $queryarray[$field] = $conf->entity;
  7896. } else {
  7897. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7898. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7899. if (!isset($this->{$field})) {
  7900. $queryarray[$field] = 0;
  7901. } elseif ($this->isInt($info)) {
  7902. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7903. } elseif ($this->isFloat($info)) {
  7904. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7905. }
  7906. } else {
  7907. $queryarray[$field] = null;
  7908. }
  7909. }
  7910. } else {
  7911. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  7912. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  7913. $queryarray[$field] = $this->{$field};
  7914. }
  7915. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7916. unset($queryarray[$field]);
  7917. }
  7918. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7919. $queryarray[$field] = null; // May force 0 to null
  7920. }
  7921. }
  7922. return $queryarray;
  7923. }
  7924. /**
  7925. * Function to load data from a SQL pointer into properties of current object $this
  7926. *
  7927. * @param stdClass $obj Contain data of object from database
  7928. * @return void
  7929. */
  7930. public function setVarsFromFetchObj(&$obj)
  7931. {
  7932. global $db;
  7933. foreach ($this->fields as $field => $info) {
  7934. if ($this->isDate($info)) {
  7935. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7936. $this->{$field} = '';
  7937. } else {
  7938. $this->{$field} = $db->jdate($obj->{$field});
  7939. }
  7940. } elseif ($this->isInt($info)) {
  7941. if ($field == 'rowid') {
  7942. $this->id = (int) $obj->{$field};
  7943. } else {
  7944. if ($this->isForcedToNullIfZero($info)) {
  7945. if (empty($obj->{$field})) {
  7946. $this->{$field} = null;
  7947. } else {
  7948. $this->{$field} = (double) $obj->{$field};
  7949. }
  7950. } else {
  7951. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7952. $this->{$field} = (int) $obj->{$field};
  7953. } else {
  7954. $this->{$field} = null;
  7955. }
  7956. }
  7957. }
  7958. } elseif ($this->isFloat($info)) {
  7959. if ($this->isForcedToNullIfZero($info)) {
  7960. if (empty($obj->{$field})) {
  7961. $this->{$field} = null;
  7962. } else {
  7963. $this->{$field} = (double) $obj->{$field};
  7964. }
  7965. } else {
  7966. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7967. $this->{$field} = (double) $obj->{$field};
  7968. } else {
  7969. $this->{$field} = null;
  7970. }
  7971. }
  7972. } else {
  7973. $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
  7974. }
  7975. }
  7976. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7977. if (!isset($this->fields['ref']) && isset($this->id)) {
  7978. $this->ref = $this->id;
  7979. }
  7980. }
  7981. /**
  7982. * Function to concat keys of fields
  7983. *
  7984. * @param string $alias String of alias of table for fields. For example 't'.
  7985. * @return string list of alias fields
  7986. */
  7987. public function getFieldList($alias = '')
  7988. {
  7989. $keys = array_keys($this->fields);
  7990. if (!empty($alias)) {
  7991. $keys_with_alias = array();
  7992. foreach ($keys as $fieldname) {
  7993. $keys_with_alias[] = $alias . '.' . $fieldname;
  7994. }
  7995. return implode(',', $keys_with_alias);
  7996. } else {
  7997. return implode(',', $keys);
  7998. }
  7999. }
  8000. /**
  8001. * Add quote to field value if necessary
  8002. *
  8003. * @param string|int $value Value to protect
  8004. * @param array $fieldsentry Properties of field
  8005. * @return string
  8006. */
  8007. protected function quote($value, $fieldsentry)
  8008. {
  8009. if (is_null($value)) {
  8010. return 'NULL';
  8011. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  8012. return price2num("$value");
  8013. } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
  8014. return (int) $value;
  8015. } elseif ($fieldsentry['type'] == 'boolean') {
  8016. if ($value) {
  8017. return 'true';
  8018. } else {
  8019. return 'false';
  8020. }
  8021. } else {
  8022. return "'".$this->db->escape($value)."'";
  8023. }
  8024. }
  8025. /**
  8026. * Create object into database
  8027. *
  8028. * @param User $user User that creates
  8029. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8030. * @return int <0 if KO, Id of created object if OK
  8031. */
  8032. public function createCommon(User $user, $notrigger = false)
  8033. {
  8034. global $langs;
  8035. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  8036. $error = 0;
  8037. $now = dol_now();
  8038. $fieldvalues = $this->setSaveQuery();
  8039. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  8040. $fieldvalues['date_creation'] = $this->db->idate($now);
  8041. }
  8042. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  8043. $fieldvalues['fk_user_creat'] = $user->id;
  8044. }
  8045. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  8046. if (array_key_exists('ref', $fieldvalues)) {
  8047. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8048. }
  8049. $keys = array();
  8050. $values = array(); // Array to store string forged for SQL syntax
  8051. foreach ($fieldvalues as $k => $v) {
  8052. $keys[$k] = $k;
  8053. $value = $this->fields[$k];
  8054. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  8055. }
  8056. // Clean and check mandatory
  8057. foreach ($keys as $key) {
  8058. // If field is an implicit foreign key field (so type = 'integer:...')
  8059. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8060. $values[$key] = '';
  8061. }
  8062. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8063. $values[$key] = '';
  8064. }
  8065. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  8066. $error++;
  8067. $langs->load("errors");
  8068. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  8069. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8070. }
  8071. // If value is null and there is a default value for field
  8072. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  8073. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  8074. }
  8075. // If field is an implicit foreign key field (so type = 'integer:...')
  8076. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  8077. if (isset($this->fields[$key]['default'])) {
  8078. $values[$key] = ((int) $this->fields[$key]['default']);
  8079. } else {
  8080. $values[$key] = 'null';
  8081. }
  8082. }
  8083. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  8084. $values[$key] = 'null';
  8085. }
  8086. }
  8087. if ($error) {
  8088. return -1;
  8089. }
  8090. $this->db->begin();
  8091. if (!$error) {
  8092. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  8093. $sql .= " (".implode(", ", $keys).')';
  8094. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  8095. $res = $this->db->query($sql);
  8096. if (!$res) {
  8097. $error++;
  8098. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  8099. $this->errors[] = "ErrorRefAlreadyExists";
  8100. } else {
  8101. $this->errors[] = $this->db->lasterror();
  8102. }
  8103. }
  8104. }
  8105. if (!$error) {
  8106. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  8107. }
  8108. // If we have a field ref with a default value of (PROV)
  8109. if (!$error) {
  8110. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  8111. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  8112. $resqlupdate = $this->db->query($sql);
  8113. if ($resqlupdate === false) {
  8114. $error++;
  8115. $this->errors[] = $this->db->lasterror();
  8116. } else {
  8117. $this->ref = '(PROV'.$this->id.')';
  8118. }
  8119. }
  8120. }
  8121. // Create extrafields
  8122. if (!$error) {
  8123. $result = $this->insertExtraFields();
  8124. if ($result < 0) {
  8125. $error++;
  8126. }
  8127. }
  8128. // Create lines
  8129. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8130. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8131. for ($i = 0; $i < $num; $i++) {
  8132. $line = $this->lines[$i];
  8133. $keyforparent = $this->fk_element;
  8134. $line->$keyforparent = $this->id;
  8135. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8136. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8137. if (!is_object($line)) {
  8138. $line = (object) $line;
  8139. }
  8140. $result = $line->create($user, 1);
  8141. if ($result < 0) {
  8142. $this->error = $line->error;
  8143. $this->db->rollback();
  8144. return -1;
  8145. }
  8146. }
  8147. }
  8148. // Triggers
  8149. if (!$error && !$notrigger) {
  8150. // Call triggers
  8151. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  8152. if ($result < 0) {
  8153. $error++;
  8154. }
  8155. // End call triggers
  8156. }
  8157. // Commit or rollback
  8158. if ($error) {
  8159. $this->db->rollback();
  8160. return -1;
  8161. } else {
  8162. $this->db->commit();
  8163. return $this->id;
  8164. }
  8165. }
  8166. /**
  8167. * Load object in memory from the database
  8168. *
  8169. * @param int $id Id object
  8170. * @param string $ref Ref
  8171. * @param string $morewhere More SQL filters (' AND ...')
  8172. * @return int <0 if KO, 0 if not found, >0 if OK
  8173. */
  8174. public function fetchCommon($id, $ref = null, $morewhere = '')
  8175. {
  8176. if (empty($id) && empty($ref) && empty($morewhere)) {
  8177. return -1;
  8178. }
  8179. $fieldlist = $this->getFieldList('t');
  8180. if (empty($fieldlist)) {
  8181. return 0;
  8182. }
  8183. $sql = "SELECT ".$fieldlist;
  8184. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8185. if (!empty($id)) {
  8186. $sql .= ' WHERE t.rowid = '.((int) $id);
  8187. } elseif (!empty($ref)) {
  8188. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8189. } else {
  8190. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8191. }
  8192. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8193. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  8194. }
  8195. if ($morewhere) {
  8196. $sql .= $morewhere;
  8197. }
  8198. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8199. $res = $this->db->query($sql);
  8200. if ($res) {
  8201. $obj = $this->db->fetch_object($res);
  8202. if ($obj) {
  8203. $this->setVarsFromFetchObj($obj);
  8204. // Retrieve all extrafield
  8205. // fetch optionals attributes and labels
  8206. $this->fetch_optionals();
  8207. return $this->id;
  8208. } else {
  8209. return 0;
  8210. }
  8211. } else {
  8212. $this->error = $this->db->lasterror();
  8213. $this->errors[] = $this->error;
  8214. return -1;
  8215. }
  8216. }
  8217. /**
  8218. * Load object in memory from the database
  8219. *
  8220. * @param string $morewhere More SQL filters (' AND ...')
  8221. * @return int <0 if KO, 0 if not found, >0 if OK
  8222. */
  8223. public function fetchLinesCommon($morewhere = '')
  8224. {
  8225. $objectlineclassname = get_class($this).'Line';
  8226. if (!class_exists($objectlineclassname)) {
  8227. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8228. return -1;
  8229. }
  8230. $objectline = new $objectlineclassname($this->db);
  8231. $sql = "SELECT ".$objectline->getFieldList('l');
  8232. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8233. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8234. if ($morewhere) {
  8235. $sql .= $morewhere;
  8236. }
  8237. if (isset($objectline->fields['position'])) {
  8238. $sql .= $this->db->order('position', 'ASC');
  8239. }
  8240. $resql = $this->db->query($sql);
  8241. if ($resql) {
  8242. $num_rows = $this->db->num_rows($resql);
  8243. $i = 0;
  8244. while ($i < $num_rows) {
  8245. $obj = $this->db->fetch_object($resql);
  8246. if ($obj) {
  8247. $newline = new $objectlineclassname($this->db);
  8248. $newline->setVarsFromFetchObj($obj);
  8249. $this->lines[] = $newline;
  8250. }
  8251. $i++;
  8252. }
  8253. return 1;
  8254. } else {
  8255. $this->error = $this->db->lasterror();
  8256. $this->errors[] = $this->error;
  8257. return -1;
  8258. }
  8259. }
  8260. /**
  8261. * Update object into database
  8262. *
  8263. * @param User $user User that modifies
  8264. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8265. * @return int <0 if KO, >0 if OK
  8266. */
  8267. public function updateCommon(User $user, $notrigger = false)
  8268. {
  8269. global $conf, $langs;
  8270. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8271. $error = 0;
  8272. $now = dol_now();
  8273. $fieldvalues = $this->setSaveQuery();
  8274. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8275. $fieldvalues['date_modification'] = $this->db->idate($now);
  8276. }
  8277. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8278. $fieldvalues['fk_user_modif'] = $user->id;
  8279. }
  8280. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8281. if (array_key_exists('ref', $fieldvalues)) {
  8282. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8283. }
  8284. // Add quotes and escape on fields with type string
  8285. $keys = array();
  8286. $values = array();
  8287. $tmp = array();
  8288. foreach ($fieldvalues as $k => $v) {
  8289. $keys[$k] = $k;
  8290. $value = $this->fields[$k];
  8291. $values[$k] = $this->quote($v, $value);
  8292. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8293. }
  8294. // Clean and check mandatory fields
  8295. foreach ($keys as $key) {
  8296. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8297. $values[$key] = ''; // This is an implicit foreign key field
  8298. }
  8299. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8300. $values[$key] = ''; // This is an explicit foreign key field
  8301. }
  8302. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8303. /*
  8304. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8305. {
  8306. $error++;
  8307. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8308. }*/
  8309. }
  8310. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8311. $this->db->begin();
  8312. if (!$error) {
  8313. $res = $this->db->query($sql);
  8314. if (!$res) {
  8315. $error++;
  8316. $this->errors[] = $this->db->lasterror();
  8317. }
  8318. }
  8319. // Update extrafield
  8320. if (!$error) {
  8321. $result = $this->insertExtraFields();
  8322. if ($result < 0) {
  8323. $error++;
  8324. }
  8325. }
  8326. // Triggers
  8327. if (!$error && !$notrigger) {
  8328. // Call triggers
  8329. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8330. if ($result < 0) {
  8331. $error++;
  8332. } //Do also here what you must do to rollback action if trigger fail
  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. * Delete object in database
  8346. *
  8347. * @param User $user User that deletes
  8348. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8349. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8350. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8351. */
  8352. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8353. {
  8354. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8355. $error = 0;
  8356. $this->db->begin();
  8357. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8358. foreach ($this->childtables as $table) {
  8359. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8360. $resql = $this->db->query($sql);
  8361. if (!$resql) {
  8362. $this->error = $this->db->lasterror();
  8363. $this->errors[] = $this->error;
  8364. $this->db->rollback();
  8365. return -1;
  8366. }
  8367. }
  8368. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8369. $objectisused = $this->isObjectUsed($this->id);
  8370. if (!empty($objectisused)) {
  8371. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8372. $this->error = 'ErrorRecordHasChildren';
  8373. $this->errors[] = $this->error;
  8374. $this->db->rollback();
  8375. return 0;
  8376. }
  8377. }
  8378. // Delete cascade first
  8379. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8380. foreach ($this->childtablesoncascade as $table) {
  8381. $deleteFromObject = explode(':', $table);
  8382. if (count($deleteFromObject) >= 2) {
  8383. $className = str_replace('@', '', $deleteFromObject[0]);
  8384. $filePath = $deleteFromObject[1];
  8385. $columnName = $deleteFromObject[2];
  8386. $TMoreSQL = array();
  8387. $more_sql = $deleteFromObject[3];
  8388. if (!empty($more_sql)) {
  8389. $TMoreSQL['customsql'] = $more_sql;
  8390. }
  8391. if (dol_include_once($filePath)) {
  8392. $childObject = new $className($this->db);
  8393. if (method_exists($childObject, 'deleteByParentField')) {
  8394. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8395. if ($result < 0) {
  8396. $error++;
  8397. $this->errors[] = $childObject->error;
  8398. break;
  8399. }
  8400. } else {
  8401. $error++;
  8402. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8403. break;
  8404. }
  8405. } else {
  8406. $error++;
  8407. $this->errors[] = 'Cannot include child class file '.$filePath;
  8408. break;
  8409. }
  8410. } else {
  8411. // Delete record in child table
  8412. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8413. $resql = $this->db->query($sql);
  8414. if (!$resql) {
  8415. $error++;
  8416. $this->error = $this->db->lasterror();
  8417. $this->errors[] = $this->error;
  8418. break;
  8419. }
  8420. }
  8421. }
  8422. }
  8423. if (!$error) {
  8424. if (!$notrigger) {
  8425. // Call triggers
  8426. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8427. if ($result < 0) {
  8428. $error++;
  8429. } // Do also here what you must do to rollback action if trigger fail
  8430. // End call triggers
  8431. }
  8432. }
  8433. // Delete llx_ecm_files
  8434. if (!$error) {
  8435. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8436. if (!$res) {
  8437. $error++;
  8438. }
  8439. }
  8440. // Delete linked object
  8441. $res = $this->deleteObjectLinked();
  8442. if ($res < 0) {
  8443. $error++;
  8444. }
  8445. if (!$error && !empty($this->isextrafieldmanaged)) {
  8446. $result = $this->deleteExtraFields();
  8447. if ($result < 0) {
  8448. $error++;
  8449. }
  8450. }
  8451. if (!$error) {
  8452. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8453. $resql = $this->db->query($sql);
  8454. if (!$resql) {
  8455. $error++;
  8456. $this->errors[] = $this->db->lasterror();
  8457. }
  8458. }
  8459. // Commit or rollback
  8460. if ($error) {
  8461. $this->db->rollback();
  8462. return -1;
  8463. } else {
  8464. $this->db->commit();
  8465. return 1;
  8466. }
  8467. }
  8468. /**
  8469. * Delete all child object from a parent ID
  8470. *
  8471. * @param int $parentId Parent Id
  8472. * @param string $parentField Name of Foreign key parent column
  8473. * @param array $filter an array filter
  8474. * @param string $filtermode AND or OR
  8475. * @return int <0 if KO, >0 if OK
  8476. * @throws Exception
  8477. */
  8478. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8479. {
  8480. global $user;
  8481. $error = 0;
  8482. $deleted = 0;
  8483. if (!empty($parentId) && !empty($parentField)) {
  8484. $this->db->begin();
  8485. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8486. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8487. // Manage filters
  8488. $sqlwhere = array();
  8489. if (count($filter) > 0) {
  8490. foreach ($filter as $key => $value) {
  8491. if ($key == 'customsql') {
  8492. $sqlwhere[] = $value;
  8493. } elseif (strpos($value, '%') === false) {
  8494. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8495. } else {
  8496. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8497. }
  8498. }
  8499. }
  8500. if (count($sqlwhere) > 0) {
  8501. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8502. }
  8503. $resql = $this->db->query($sql);
  8504. if (!$resql) {
  8505. $this->errors[] = $this->db->lasterror();
  8506. $error++;
  8507. } else {
  8508. while ($obj = $this->db->fetch_object($resql)) {
  8509. $result = $this->fetch($obj->rowid);
  8510. if ($result < 0) {
  8511. $error++;
  8512. $this->errors[] = $this->error;
  8513. } else {
  8514. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8515. $result = $this->delete();
  8516. } else {
  8517. $result = $this->delete($user);
  8518. }
  8519. if ($result < 0) {
  8520. $error++;
  8521. $this->errors[] = $this->error;
  8522. } else {
  8523. $deleted++;
  8524. }
  8525. }
  8526. }
  8527. }
  8528. if (empty($error)) {
  8529. $this->db->commit();
  8530. return $deleted;
  8531. } else {
  8532. $this->error = implode(', ', $this->errors);
  8533. $this->db->rollback();
  8534. return $error * -1;
  8535. }
  8536. }
  8537. return $deleted;
  8538. }
  8539. /**
  8540. * Delete a line of object in database
  8541. *
  8542. * @param User $user User that delete
  8543. * @param int $idline Id of line to delete
  8544. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8545. * @return int >0 if OK, <0 if KO
  8546. */
  8547. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8548. {
  8549. global $conf;
  8550. $error = 0;
  8551. $tmpforobjectclass = get_class($this);
  8552. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8553. // Call trigger
  8554. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8555. if ($result < 0) {
  8556. return -1;
  8557. }
  8558. // End call triggers
  8559. $this->db->begin();
  8560. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8561. $sql .= " WHERE rowid = ".((int) $idline);
  8562. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8563. $resql = $this->db->query($sql);
  8564. if (!$resql) {
  8565. $this->error = "Error ".$this->db->lasterror();
  8566. $error++;
  8567. }
  8568. if (empty($error)) {
  8569. // Remove extrafields
  8570. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8571. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8572. $tmpobjectline->id = $idline;
  8573. $result = $tmpobjectline->deleteExtraFields();
  8574. if ($result < 0) {
  8575. $error++;
  8576. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8577. }
  8578. }
  8579. }
  8580. if (empty($error)) {
  8581. $this->db->commit();
  8582. return 1;
  8583. } else {
  8584. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8585. $this->db->rollback();
  8586. return -1;
  8587. }
  8588. }
  8589. /**
  8590. * Set to a status
  8591. *
  8592. * @param User $user Object user that modify
  8593. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8594. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8595. * @param string $triggercode Trigger code to use
  8596. * @return int <0 if KO, >0 if OK
  8597. */
  8598. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8599. {
  8600. $error = 0;
  8601. $this->db->begin();
  8602. $statusfield = 'status';
  8603. if ($this->element == 'don' || $this->element == 'donation') {
  8604. $statusfield = 'fk_statut';
  8605. }
  8606. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8607. $sql .= " SET ".$statusfield." = ".((int) $status);
  8608. $sql .= " WHERE rowid = ".((int) $this->id);
  8609. if ($this->db->query($sql)) {
  8610. if (!$error) {
  8611. $this->oldcopy = clone $this;
  8612. }
  8613. if (!$error && !$notrigger) {
  8614. // Call trigger
  8615. $result = $this->call_trigger($triggercode, $user);
  8616. if ($result < 0) {
  8617. $error++;
  8618. }
  8619. }
  8620. if (!$error) {
  8621. $this->status = $status;
  8622. $this->db->commit();
  8623. return 1;
  8624. } else {
  8625. $this->db->rollback();
  8626. return -1;
  8627. }
  8628. } else {
  8629. $this->error = $this->db->error();
  8630. $this->db->rollback();
  8631. return -1;
  8632. }
  8633. }
  8634. /**
  8635. * Initialise object with example values
  8636. * Id must be 0 if object instance is a specimen
  8637. *
  8638. * @return int
  8639. */
  8640. public function initAsSpecimenCommon()
  8641. {
  8642. global $user;
  8643. $this->id = 0;
  8644. $this->specimen = 1;
  8645. $fields = array(
  8646. 'label' => 'This is label',
  8647. 'ref' => 'ABCD1234',
  8648. 'description' => 'This is a description',
  8649. 'qty' => 123.12,
  8650. 'note_public' => 'Public note',
  8651. 'note_private' => 'Private note',
  8652. 'date_creation' => (dol_now() - 3600 * 48),
  8653. 'date_modification' => (dol_now() - 3600 * 24),
  8654. 'fk_user_creat' => $user->id,
  8655. 'fk_user_modif' => $user->id,
  8656. 'date' => dol_now(),
  8657. );
  8658. foreach ($fields as $key => $value) {
  8659. if (array_key_exists($key, $this->fields)) {
  8660. $this->{$key} = $value;
  8661. }
  8662. }
  8663. return 1;
  8664. }
  8665. /* Part for comments */
  8666. /**
  8667. * Load comments linked with current task
  8668. * @return boolean 1 if ok
  8669. */
  8670. public function fetchComments()
  8671. {
  8672. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8673. $comment = new Comment($this->db);
  8674. $result = $comment->fetchAllFor($this->element, $this->id);
  8675. if ($result < 0) {
  8676. $this->errors = array_merge($this->errors, $comment->errors);
  8677. return -1;
  8678. } else {
  8679. $this->comments = $comment->comments;
  8680. }
  8681. return count($this->comments);
  8682. }
  8683. /**
  8684. * Return nb comments already posted
  8685. *
  8686. * @return int
  8687. */
  8688. public function getNbComments()
  8689. {
  8690. return count($this->comments);
  8691. }
  8692. /**
  8693. * Trim object parameters
  8694. *
  8695. * @param string[] $parameters array of parameters to trim
  8696. * @return void
  8697. */
  8698. public function trimParameters($parameters)
  8699. {
  8700. if (!is_array($parameters)) {
  8701. return;
  8702. }
  8703. foreach ($parameters as $parameter) {
  8704. if (isset($this->$parameter)) {
  8705. $this->$parameter = trim($this->$parameter);
  8706. }
  8707. }
  8708. }
  8709. /* Part for categories/tags */
  8710. /**
  8711. * Sets object to given categories.
  8712. *
  8713. * Deletes object from existing categories not supplied.
  8714. * Adds it to non existing supplied categories.
  8715. * Existing categories are left untouch.
  8716. *
  8717. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8718. * @return int Array of category objects or < 0 if KO
  8719. */
  8720. public function getCategoriesCommon($type_categ)
  8721. {
  8722. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8723. // Get current categories
  8724. $c = new Categorie($this->db);
  8725. $existing = $c->containing($this->id, $type_categ, 'id');
  8726. return $existing;
  8727. }
  8728. /**
  8729. * Sets object to given categories.
  8730. *
  8731. * Adds it to non existing supplied categories.
  8732. * Deletes object from existing categories not supplied (if remove_existing==true).
  8733. * Existing categories are left untouch.
  8734. *
  8735. * @param int[]|int $categories Category ID or array of Categories IDs
  8736. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8737. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8738. * @return int <0 if KO, >0 if OK
  8739. */
  8740. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8741. {
  8742. // Handle single category
  8743. if (!is_array($categories)) {
  8744. $categories = array($categories);
  8745. }
  8746. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8747. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8748. if (empty($type_categ)) {
  8749. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8750. return -1;
  8751. }
  8752. // Get current categories
  8753. $c = new Categorie($this->db);
  8754. $existing = $c->containing($this->id, $type_categ, 'id');
  8755. if ($remove_existing) {
  8756. // Diff
  8757. if (is_array($existing)) {
  8758. $to_del = array_diff($existing, $categories);
  8759. $to_add = array_diff($categories, $existing);
  8760. } else {
  8761. $to_del = array(); // Nothing to delete
  8762. $to_add = $categories;
  8763. }
  8764. } else {
  8765. $to_del = array(); // Nothing to delete
  8766. $to_add = array_diff($categories, $existing);
  8767. }
  8768. $error = 0;
  8769. $ok = 0;
  8770. // Process
  8771. foreach ($to_del as $del) {
  8772. if ($c->fetch($del) > 0) {
  8773. $result=$c->del_type($this, $type_categ);
  8774. if ($result < 0) {
  8775. $error++;
  8776. $this->error = $c->error;
  8777. $this->errors = $c->errors;
  8778. break;
  8779. } else {
  8780. $ok += $result;
  8781. }
  8782. }
  8783. }
  8784. foreach ($to_add as $add) {
  8785. if ($c->fetch($add) > 0) {
  8786. $result = $c->add_type($this, $type_categ);
  8787. if ($result < 0) {
  8788. $error++;
  8789. $this->error = $c->error;
  8790. $this->errors = $c->errors;
  8791. break;
  8792. } else {
  8793. $ok += $result;
  8794. }
  8795. }
  8796. }
  8797. return $error ? -1 * $error : $ok;
  8798. }
  8799. /**
  8800. * Copy related categories to another object
  8801. *
  8802. * @param int $fromId Id object source
  8803. * @param int $toId Id object cible
  8804. * @param string $type Type of category ('product', ...)
  8805. * @return int < 0 if error, > 0 if ok
  8806. */
  8807. public function cloneCategories($fromId, $toId, $type = '')
  8808. {
  8809. $this->db->begin();
  8810. if (empty($type)) {
  8811. $type = $this->table_element;
  8812. }
  8813. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8814. $categorystatic = new Categorie($this->db);
  8815. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8816. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8817. $sql .= " WHERE fk_product = ".((int) $fromId);
  8818. if (!$this->db->query($sql)) {
  8819. $this->error = $this->db->lasterror();
  8820. $this->db->rollback();
  8821. return -1;
  8822. }
  8823. $this->db->commit();
  8824. return 1;
  8825. }
  8826. /**
  8827. * Delete related files of object in database
  8828. *
  8829. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8830. * @return bool True if OK, False if KO
  8831. */
  8832. public function deleteEcmFiles($mode = 0)
  8833. {
  8834. global $conf;
  8835. $this->db->begin();
  8836. // Delete in database with mode 0
  8837. if ($mode == 0) {
  8838. switch ($this->element) {
  8839. case 'propal':
  8840. $element = 'propale';
  8841. break;
  8842. case 'product':
  8843. $element = 'produit';
  8844. break;
  8845. case 'order_supplier':
  8846. $element = 'fournisseur/commande';
  8847. break;
  8848. case 'invoice_supplier':
  8849. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8850. break;
  8851. case 'shipping':
  8852. $element = 'expedition/sending';
  8853. break;
  8854. default:
  8855. $element = $this->element;
  8856. }
  8857. // Delete ecm_files extrafields
  8858. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  8859. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8860. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8861. $sql .= ")";
  8862. if (!$this->db->query($sql)) {
  8863. $this->error = $this->db->lasterror();
  8864. $this->db->rollback();
  8865. return false;
  8866. }
  8867. // Delete ecm_files
  8868. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  8869. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8870. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8871. if (!$this->db->query($sql)) {
  8872. $this->error = $this->db->lasterror();
  8873. $this->db->rollback();
  8874. return false;
  8875. }
  8876. }
  8877. // Delete in database with mode 1
  8878. if ($mode == 1) {
  8879. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  8880. $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).")";
  8881. $resql = $this->db->query($sql);
  8882. if (!$resql) {
  8883. $this->error = $this->db->lasterror();
  8884. $this->db->rollback();
  8885. return false;
  8886. }
  8887. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  8888. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8889. $resql = $this->db->query($sql);
  8890. if (!$resql) {
  8891. $this->error = $this->db->lasterror();
  8892. $this->db->rollback();
  8893. return false;
  8894. }
  8895. }
  8896. $this->db->commit();
  8897. return true;
  8898. }
  8899. /**
  8900. * Get linked objects ids
  8901. * @author MMI Mathieu Moulin iProspective
  8902. *
  8903. * @return Array
  8904. */
  8905. public function fetchObjectLinkedIDs($object_class=true)
  8906. {
  8907. $classname = strtolower(get_class($this));
  8908. $sql = 'SELECT e.sourcetype object_type, e.fk_source fk_object
  8909. FROM '.MAIN_DB_PREFIX.'element_element e
  8910. WHERE e.targettype="'.$classname.'" AND e.fk_target="'.$this->id.'"
  8911. UNION
  8912. SELECT e.targettype object_type, e.fk_target fk_object
  8913. FROM '.MAIN_DB_PREFIX.'element_element e
  8914. WHERE e.sourcetype="'.$classname.'" AND e.fk_source="'.$this->id.'"';
  8915. //echo $sql;
  8916. $resql = $this->db->query($sql);
  8917. if (!$resql)
  8918. return;
  8919. $l = [];
  8920. while ($obj = $this->db->fetch_object($resql)) {
  8921. //var_dump($obj);
  8922. $l[] = [$obj->object_type, $obj->fk_object];
  8923. }
  8924. return $l;
  8925. }
  8926. /**
  8927. * Get total amount already paid
  8928. * @author MMI Mathieu Moulin iProspective
  8929. *
  8930. * @return []
  8931. */
  8932. public function getPaiements()
  8933. {
  8934. $classname = strtolower(get_class($this));
  8935. $ol = $this->fetchObjectLinkedIDs();
  8936. //var_dump($ol);
  8937. if (!is_array($ol))
  8938. $ol = [];
  8939. $ol[] = [$classname, $this->id];
  8940. $sql_w = [];
  8941. foreach($ol as $o) {
  8942. if ($o[0]=='facture')
  8943. $sql_w[] = "(pf.`fk_facture`='".$o[1]."')";
  8944. $sql_w[] = "(po.`objecttype`='".$o[0]."' AND po.`fk_object`='".$o[1]."')";
  8945. }
  8946. $sql = "SELECT DISTINCT p2.*, p.*
  8947. FROM ".MAIN_DB_PREFIX."paiement p
  8948. LEFT JOIN ".MAIN_DB_PREFIX."paiement_extrafields p2 ON p2.fk_object=p.rowid
  8949. LEFT JOIN ".MAIN_DB_PREFIX."paiement_object po ON po.fk_paiement=p.rowid
  8950. LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture pf ON pf.fk_paiement=p.rowid
  8951. WHERE ".implode(' OR ', $sql_w);
  8952. //echo $sql;
  8953. $resql = $this->db->query($sql);
  8954. if (!$resql)
  8955. return;
  8956. $l = [];
  8957. while ($obj = $this->db->fetch_object($resql)) {
  8958. //var_dump($obj);
  8959. $l[$obj->rowid] = $obj;
  8960. }
  8961. return $l;
  8962. }
  8963. /**
  8964. * Get total amount already paid
  8965. * @author MMI Mathieu Moulin iProspective
  8966. *
  8967. * @return float
  8968. */
  8969. public function getSommePaiement()
  8970. {
  8971. $mt = 0;
  8972. $l = $this->getPaiements();
  8973. foreach($l as $p) {
  8974. $mt += $p->amount;
  8975. }
  8976. //echo $mt;
  8977. return $mt;
  8978. }
  8979. /**
  8980. * Get total amount already paid
  8981. * @author MMI Mathieu Moulin iProspective
  8982. *
  8983. * @return float
  8984. */
  8985. public function paye()
  8986. {
  8987. return $this->getSommePaiement() >= $this->total_ttc;
  8988. }
  8989. }