commonobject.class.php 340 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870
  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 sotre 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
  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. * @var Contact a related contact
  159. * @see fetch_contact()
  160. */
  161. public $contact;
  162. /**
  163. * @var int The related contact ID
  164. * @see fetch_contact()
  165. */
  166. public $contact_id;
  167. /**
  168. * @var Societe A related thirdparty
  169. * @see fetch_thirdparty()
  170. */
  171. public $thirdparty;
  172. /**
  173. * @var User A related user
  174. * @see fetch_user()
  175. */
  176. public $user;
  177. /**
  178. * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type
  179. * @see fetch_origin()
  180. */
  181. public $origin;
  182. /**
  183. * @var int The id of originating object
  184. * @see fetch_origin()
  185. */
  186. public $origin_id;
  187. /**
  188. * @var string The object's reference
  189. */
  190. public $ref;
  191. /**
  192. * @var string An external reference for the object
  193. */
  194. public $ref_ext;
  195. /**
  196. * @var string The object's previous reference
  197. */
  198. public $ref_previous;
  199. /**
  200. * @var string The object's next reference
  201. */
  202. public $ref_next;
  203. /**
  204. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  205. */
  206. public $newref;
  207. /**
  208. * @var int The object's status
  209. * @see setStatut()
  210. */
  211. public $statut;
  212. /**
  213. * @var int The object's status
  214. * @see setStatut()
  215. */
  216. public $status;
  217. /**
  218. * @var string
  219. * @see getFullAddress()
  220. */
  221. public $country;
  222. /**
  223. * @var int
  224. * @see getFullAddress(), country
  225. */
  226. public $country_id;
  227. /**
  228. * @var string
  229. * @see getFullAddress(), isInEEC(), country
  230. */
  231. public $country_code;
  232. /**
  233. * @var string
  234. * @see getFullAddress()
  235. */
  236. public $state;
  237. /**
  238. * @var int
  239. * @see getFullAddress(), state
  240. */
  241. public $state_id;
  242. /**
  243. * @var string
  244. * @see getFullAddress(), $state
  245. */
  246. public $state_code;
  247. /**
  248. * @var int
  249. * @see getFullAddress(), $region_code, $region
  250. */
  251. public $region_id;
  252. /**
  253. * @var string
  254. * @see getFullAddress(), $region_id, $region
  255. */
  256. public $region_code;
  257. /**
  258. * @var string
  259. * @see getFullAddress(), $region_id, $region_code
  260. */
  261. public $region;
  262. /**
  263. * @var int
  264. * @see fetch_barcode()
  265. */
  266. public $barcode_type;
  267. /**
  268. * @var string
  269. * @see fetch_barcode(), barcode_type
  270. */
  271. public $barcode_type_code;
  272. /**
  273. * @var string
  274. * @see fetch_barcode(), barcode_type
  275. */
  276. public $barcode_type_label;
  277. /**
  278. * @var string
  279. * @see fetch_barcode(), barcode_type
  280. */
  281. public $barcode_type_coder;
  282. /**
  283. * @var int Payment method ID (cheque, cash, ...)
  284. * @see setPaymentMethods()
  285. */
  286. public $mode_reglement_id;
  287. /**
  288. * @var int Payment terms ID
  289. * @see setPaymentTerms()
  290. */
  291. public $cond_reglement_id;
  292. /**
  293. * @var int Demand reason ID
  294. */
  295. public $demand_reason_id;
  296. /**
  297. * @var int Transport mode ID (For module intracomm report)
  298. * @see setTransportMode()
  299. */
  300. public $transport_mode_id;
  301. /**
  302. * @var int Payment terms ID
  303. * @deprecated Kept for compatibility
  304. * @see cond_reglement_id;
  305. */
  306. public $cond_reglement;
  307. /**
  308. * @var int Delivery address ID
  309. * @see setDeliveryAddress()
  310. * @deprecated
  311. */
  312. public $fk_delivery_address;
  313. /**
  314. * @var int Shipping method ID
  315. * @see setShippingMethod()
  316. */
  317. public $shipping_method_id;
  318. /**
  319. * @var string
  320. * @see SetDocModel()
  321. */
  322. public $model_pdf;
  323. /**
  324. * @var string
  325. * @deprecated
  326. * @see $model_pdf
  327. */
  328. public $modelpdf;
  329. /**
  330. * @var string
  331. * Contains relative path of last generated main file
  332. */
  333. public $last_main_doc;
  334. /**
  335. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  336. * @deprecated
  337. * @see $fk_account
  338. */
  339. public $fk_bank;
  340. /**
  341. * @var int Bank account ID
  342. * @see SetBankAccount()
  343. */
  344. public $fk_account;
  345. /**
  346. * @var string Open ID
  347. */
  348. public $openid;
  349. /**
  350. * @var string Public note
  351. * @see update_note()
  352. */
  353. public $note_public;
  354. /**
  355. * @var string Private note
  356. * @see update_note()
  357. */
  358. public $note_private;
  359. /**
  360. * @deprecated
  361. * @see $note_private
  362. */
  363. public $note;
  364. /**
  365. * @var float Total amount before taxes
  366. * @see update_price()
  367. */
  368. public $total_ht;
  369. /**
  370. * @var float Total VAT amount
  371. * @see update_price()
  372. */
  373. public $total_tva;
  374. /**
  375. * @var float Total local tax 1 amount
  376. * @see update_price()
  377. */
  378. public $total_localtax1;
  379. /**
  380. * @var float Total local tax 2 amount
  381. * @see update_price()
  382. */
  383. public $total_localtax2;
  384. /**
  385. * @var float Total amount with taxes
  386. * @see update_price()
  387. */
  388. public $total_ttc;
  389. /**
  390. * @var CommonObjectLine[]
  391. */
  392. public $lines;
  393. /**
  394. * @var mixed Contains comments
  395. * @see fetchComments()
  396. */
  397. public $comments = array();
  398. /**
  399. * @var string The name
  400. */
  401. public $name;
  402. /**
  403. * @var string The lastname
  404. */
  405. public $lastname;
  406. /**
  407. * @var string The firstname
  408. */
  409. public $firstname;
  410. /**
  411. * @var string The civility code, not an integer
  412. */
  413. public $civility_id;
  414. // Dates
  415. /**
  416. * @var integer|string date_creation
  417. */
  418. public $date_creation;
  419. /**
  420. * @var integer|string $date_validation;
  421. */
  422. public $date_validation; // Date validation
  423. /**
  424. * @var integer|string $date_modification;
  425. */
  426. public $date_modification; // Date last change (tms field)
  427. public $next_prev_filter;
  428. /**
  429. * @var int 1 if object is specimen
  430. */
  431. public $specimen = 0;
  432. /**
  433. * @var int Id of contact to send object (used by the trigger of module Agenda)
  434. */
  435. public $sendtoid;
  436. /**
  437. * @var float Amount already paid (used to show correct status)
  438. */
  439. public $alreadypaid;
  440. /**
  441. * @var array List of child tables. To test if we can delete object.
  442. */
  443. protected $childtables = array();
  444. /**
  445. * @var array List of child tables. To know object to delete on cascade.
  446. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  447. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  448. */
  449. protected $childtablesoncascade = array();
  450. // No constructor as it is an abstract class
  451. /**
  452. * Check an object id/ref exists
  453. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  454. *
  455. * @param string $element String of element ('product', 'facture', ...)
  456. * @param int $id Id of object
  457. * @param string $ref Ref of object to check
  458. * @param string $ref_ext Ref ext of object to check
  459. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  460. */
  461. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  462. {
  463. global $db, $conf;
  464. $sql = "SELECT rowid, ref, ref_ext";
  465. $sql .= " FROM ".$db->prefix().$element;
  466. $sql .= " WHERE entity IN (".getEntity($element).")";
  467. if ($id > 0) {
  468. $sql .= " AND rowid = ".((int) $id);
  469. } elseif ($ref) {
  470. $sql .= " AND ref = '".$db->escape($ref)."'";
  471. } elseif ($ref_ext) {
  472. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  473. } else {
  474. $error = 'ErrorWrongParameters';
  475. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  476. return -1;
  477. }
  478. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  479. $sql .= " AND entity = ".((int) $conf->entity);
  480. }
  481. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  482. $resql = $db->query($sql);
  483. if ($resql) {
  484. $num = $db->num_rows($resql);
  485. if ($num > 0) {
  486. return 1;
  487. } else {
  488. return 0;
  489. }
  490. }
  491. return -1;
  492. }
  493. /**
  494. * Method to output saved errors
  495. *
  496. * @return string String with errors
  497. */
  498. public function errorsToString()
  499. {
  500. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  501. }
  502. /**
  503. * Return customer ref for screen output.
  504. *
  505. * @param string $objref Customer ref
  506. * @return string Customer ref formated
  507. */
  508. public function getFormatedCustomerRef($objref)
  509. {
  510. global $hookmanager;
  511. $parameters = array('objref'=>$objref);
  512. $action = '';
  513. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  514. if ($reshook > 0) {
  515. return $hookmanager->resArray['objref'];
  516. }
  517. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  518. }
  519. /**
  520. * Return supplier ref for screen output.
  521. *
  522. * @param string $objref Supplier ref
  523. * @return string Supplier ref formated
  524. */
  525. public function getFormatedSupplierRef($objref)
  526. {
  527. global $hookmanager;
  528. $parameters = array('objref'=>$objref);
  529. $action = '';
  530. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  531. if ($reshook > 0) {
  532. return $hookmanager->resArray['objref'];
  533. }
  534. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  535. }
  536. /**
  537. * Return full name (civility+' '+name+' '+lastname)
  538. *
  539. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  540. * @param int $option 0=No option, 1=Add civility
  541. * @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
  542. * @param int $maxlen Maximum length
  543. * @return string String with full name
  544. */
  545. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  546. {
  547. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  548. $lastname = $this->lastname;
  549. $firstname = $this->firstname;
  550. if (empty($lastname)) {
  551. $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 : '')))));
  552. }
  553. $ret = '';
  554. if (!empty($option) && !empty($this->civility_code)) {
  555. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  556. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  557. } else {
  558. $ret .= $this->civility_code.' ';
  559. }
  560. }
  561. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  562. return dol_trunc($ret, $maxlen);
  563. }
  564. /**
  565. * Set to upper or ucwords/lower if needed
  566. *
  567. * @return void;
  568. */
  569. public function setUpperOrLowerCase()
  570. {
  571. global $conf;
  572. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  573. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  574. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  575. $this->name = dol_ucwords(dol_strtolower($this->name));
  576. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  577. }
  578. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  579. $this->lastname = dol_strtoupper($this->lastname);
  580. $this->name = dol_strtoupper($this->name);
  581. $this->name_alias = dol_strtoupper($this->name_alias);
  582. }
  583. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  584. $this->address = dol_strtoupper($this->address);
  585. $this->town = dol_strtoupper($this->town);
  586. }
  587. }
  588. /**
  589. * Return clicable link of object (with eventually picto)
  590. *
  591. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  592. * @return string HTML Code for Kanban thumb.
  593. */
  594. public function getKanbanView($option = '')
  595. {
  596. $return = '<div class="box-flex-item box-flex-grow-zero">';
  597. $return .= '<div class="info-box info-box-sm">';
  598. $return .= '<span class="info-box-icon bg-infobox-action">';
  599. $return .= img_picto('', $this->picto);
  600. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  601. $return .= '</span>';
  602. $return .= '<div class="info-box-content">';
  603. $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  604. if (property_exists($this, 'label')) {
  605. $return .= '<br><span class="info-box-label opacitymedium">'.$this->label.'</span>';
  606. }
  607. if (method_exists($this, 'getLibStatut')) {
  608. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).'</div>';
  609. }
  610. $return .= '</div>';
  611. $return .= '</div>';
  612. $return .= '</div>';
  613. return $return;
  614. }
  615. /**
  616. * Return full address of contact
  617. *
  618. * @param int $withcountry 1=Add country into address string
  619. * @param string $sep Separator to use to build string
  620. * @param int $withregion 1=Add region into address string
  621. * @param string $extralangcode User extralanguages as value
  622. * @return string Full address string
  623. */
  624. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  625. {
  626. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  627. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  628. $tmparray = getCountry($this->country_id, 'all');
  629. $this->country_code = $tmparray['code'];
  630. $this->country = $tmparray['label'];
  631. }
  632. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  633. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  634. $tmparray = getState($this->state_id, 'all', 0, 1);
  635. $this->state_code = $tmparray['code'];
  636. $this->state = $tmparray['label'];
  637. $this->region_code = $tmparray['region_code'];
  638. $this->region = $tmparray['region'];
  639. }
  640. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  641. }
  642. /**
  643. * Return full address for banner
  644. *
  645. * @param string $htmlkey HTML id to make banner content unique
  646. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  647. * @return string Full address string
  648. */
  649. public function getBannerAddress($htmlkey, $object)
  650. {
  651. global $conf, $langs, $form, $extralanguages;
  652. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  653. $contactid = 0;
  654. $thirdpartyid = 0;
  655. $elementforaltlanguage = $this->element;
  656. if ($this->element == 'societe') {
  657. $thirdpartyid = $this->id;
  658. }
  659. if ($this->element == 'contact') {
  660. $contactid = $this->id;
  661. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  662. }
  663. if ($this->element == 'user') {
  664. $contactid = $this->contact_id;
  665. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  666. }
  667. $out = '';
  668. $outdone = 0;
  669. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  670. if ($coords) {
  671. if (!empty($conf->use_javascript_ajax)) {
  672. // Add picto with tooltip on map
  673. $namecoords = '';
  674. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  675. $namecoords .= $object->name.'<br>';
  676. }
  677. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  678. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  679. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  680. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  681. $out .= '</a> ';
  682. }
  683. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  684. $outdone++;
  685. $outdone++;
  686. // List of extra languages
  687. $arrayoflangcode = array();
  688. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  689. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  690. }
  691. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  692. if (!is_object($extralanguages)) {
  693. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  694. $extralanguages = new ExtraLanguages($this->db);
  695. }
  696. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  697. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  698. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  699. $this->fetchValuesForExtraLanguages();
  700. if (!is_object($form)) {
  701. $form = new Form($this->db);
  702. }
  703. $htmltext = '';
  704. // If there is extra languages
  705. foreach ($arrayoflangcode as $extralangcode) {
  706. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  707. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  708. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  709. }
  710. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  711. }
  712. }
  713. }
  714. 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
  715. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  716. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  717. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  718. } else {
  719. $out .= ($outdone ? ' - ' : '').$this->state;
  720. }
  721. $outdone++;
  722. }
  723. 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)) {
  724. $out .= ($outdone ? '<br>' : '');
  725. }
  726. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  727. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  728. $outdone++;
  729. }
  730. if (!empty($this->phone_pro)) {
  731. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  732. $outdone++;
  733. }
  734. if (!empty($this->phone_mobile)) {
  735. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  736. $outdone++;
  737. }
  738. if (!empty($this->phone_perso)) {
  739. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  740. $outdone++;
  741. }
  742. if (!empty($this->office_phone)) {
  743. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  744. $outdone++;
  745. }
  746. if (!empty($this->user_mobile)) {
  747. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  748. $outdone++;
  749. }
  750. if (!empty($this->fax)) {
  751. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  752. $outdone++;
  753. }
  754. if (!empty($this->office_fax)) {
  755. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  756. $outdone++;
  757. }
  758. if ($out) {
  759. $out .= '<div style="clear: both;"></div>';
  760. }
  761. $outdone = 0;
  762. if (!empty($this->email)) {
  763. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  764. $outdone++;
  765. }
  766. if (!empty($this->url)) {
  767. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  768. $out .= dol_print_url($this->url, '_blank', 0, 1);
  769. $outdone++;
  770. }
  771. if (!empty($conf->socialnetworks->enabled)) {
  772. $outsocialnetwork = '';
  773. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  774. $socialnetworksdict = getArrayOfSocialNetworks();
  775. foreach ($this->socialnetworks as $key => $value) {
  776. if ($value) {
  777. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  778. }
  779. $outdone++;
  780. }
  781. } else { // Old code to remove
  782. if (!empty($this->skype)) {
  783. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  784. }
  785. $outdone++;
  786. if (!empty($this->jabberid)) {
  787. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  788. }
  789. $outdone++;
  790. if (!empty($this->twitter)) {
  791. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  792. }
  793. $outdone++;
  794. if (!empty($this->facebook)) {
  795. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  796. }
  797. $outdone++;
  798. if (!empty($this->linkedin)) {
  799. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  800. }
  801. $outdone++;
  802. }
  803. if ($outsocialnetwork) {
  804. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  805. }
  806. }
  807. if ($out) {
  808. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  809. } else {
  810. return '';
  811. }
  812. }
  813. /**
  814. * Return the link of last main doc file for direct public download.
  815. *
  816. * @param string $modulepart Module related to document
  817. * @param int $initsharekey Init the share key if it was not yet defined
  818. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  819. * @return string Link or empty string if there is no download link
  820. */
  821. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  822. {
  823. global $user, $dolibarr_main_url_root;
  824. if (empty($this->last_main_doc)) {
  825. return ''; // No way to known which document name to use
  826. }
  827. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  828. $ecmfile = new EcmFiles($this->db);
  829. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  830. if ($result < 0) {
  831. $this->error = $ecmfile->error;
  832. $this->errors = $ecmfile->errors;
  833. return -1;
  834. }
  835. if (empty($ecmfile->id)) {
  836. // Add entry into index
  837. if ($initsharekey) {
  838. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  839. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  840. /*
  841. $ecmfile->filepath = $rel_dir;
  842. $ecmfile->filename = $filename;
  843. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  844. $ecmfile->fullpath_orig = '';
  845. $ecmfile->gen_or_uploaded = 'generated';
  846. $ecmfile->description = ''; // indexed content
  847. $ecmfile->keywords = ''; // keyword content
  848. $ecmfile->share = getRandomPassword(true);
  849. $result = $ecmfile->create($user);
  850. if ($result < 0)
  851. {
  852. $this->error = $ecmfile->error;
  853. $this->errors = $ecmfile->errors;
  854. }
  855. */
  856. } else {
  857. return '';
  858. }
  859. } elseif (empty($ecmfile->share)) {
  860. // Add entry into index
  861. if ($initsharekey) {
  862. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  863. $ecmfile->share = getRandomPassword(true);
  864. $ecmfile->update($user);
  865. } else {
  866. return '';
  867. }
  868. }
  869. // Define $urlwithroot
  870. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  871. // This is to use external domain name found into config file
  872. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  873. //else
  874. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  875. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  876. $forcedownload = 0;
  877. $paramlink = '';
  878. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  879. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  880. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  881. if (!empty($ecmfile->share)) {
  882. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  883. }
  884. if ($forcedownload) {
  885. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  886. }
  887. if ($relativelink) {
  888. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  889. } else {
  890. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  891. }
  892. // Here $ecmfile->share is defined
  893. return $linktoreturn;
  894. }
  895. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  896. /**
  897. * Add a link between element $this->element and a contact
  898. *
  899. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  900. * @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
  901. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  902. * @param int $notrigger Disable all triggers
  903. * @return int <0 if KO, 0 if already added, >0 if OK
  904. */
  905. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  906. {
  907. // phpcs:enable
  908. global $user, $langs;
  909. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  910. // Check parameters
  911. if ($fk_socpeople <= 0) {
  912. $langs->load("errors");
  913. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  914. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  915. return -1;
  916. }
  917. if (!$type_contact) {
  918. $langs->load("errors");
  919. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  920. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  921. return -2;
  922. }
  923. $id_type_contact = 0;
  924. if (is_numeric($type_contact)) {
  925. $id_type_contact = $type_contact;
  926. } else {
  927. // We look for id type_contact
  928. $sql = "SELECT tc.rowid";
  929. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  930. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  931. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  932. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  933. //print $sql;
  934. $resql = $this->db->query($sql);
  935. if ($resql) {
  936. $obj = $this->db->fetch_object($resql);
  937. if ($obj) {
  938. $id_type_contact = $obj->rowid;
  939. }
  940. }
  941. }
  942. if ($id_type_contact == 0) {
  943. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  944. 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");
  945. return -3;
  946. }
  947. $datecreate = dol_now();
  948. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  949. $TListeContacts = $this->liste_contact(-1, $source);
  950. $already_added = false;
  951. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  952. foreach ($TListeContacts as $array_contact) {
  953. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  954. $already_added = true;
  955. break;
  956. }
  957. }
  958. }
  959. if (!$already_added) {
  960. $this->db->begin();
  961. // Insert into database
  962. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  963. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  964. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  965. $sql .= "'".$this->db->idate($datecreate)."'";
  966. $sql .= ", 4, ".((int) $id_type_contact);
  967. $sql .= ")";
  968. $resql = $this->db->query($sql);
  969. if ($resql) {
  970. if (!$notrigger) {
  971. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  972. if ($result < 0) {
  973. $this->db->rollback();
  974. return -1;
  975. }
  976. }
  977. $this->db->commit();
  978. return 1;
  979. } else {
  980. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  981. $this->error = $this->db->errno();
  982. $this->db->rollback();
  983. return -2;
  984. } else {
  985. $this->error = $this->db->lasterror();
  986. $this->db->rollback();
  987. return -1;
  988. }
  989. }
  990. } else {
  991. return 0;
  992. }
  993. }
  994. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  995. /**
  996. * Copy contact from one element to current
  997. *
  998. * @param CommonObject $objFrom Source element
  999. * @param string $source Nature of contact ('internal' or 'external')
  1000. * @return int >0 if OK, <0 if KO
  1001. */
  1002. public function copy_linked_contact($objFrom, $source = 'internal')
  1003. {
  1004. // phpcs:enable
  1005. $contacts = $objFrom->liste_contact(-1, $source);
  1006. foreach ($contacts as $contact) {
  1007. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  1008. return -1;
  1009. }
  1010. }
  1011. return 1;
  1012. }
  1013. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1014. /**
  1015. * Update a link to contact line
  1016. *
  1017. * @param int $rowid Id of line contact-element
  1018. * @param int $statut New status of link
  1019. * @param int $type_contact_id Id of contact type (not modified if 0)
  1020. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1021. * @return int <0 if KO, >= 0 if OK
  1022. */
  1023. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1024. {
  1025. // phpcs:enable
  1026. // Insert into database
  1027. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  1028. $sql .= " statut = ".$statut;
  1029. if ($type_contact_id) {
  1030. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1031. }
  1032. if ($fk_socpeople) {
  1033. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1034. }
  1035. $sql .= " where rowid = ".((int) $rowid);
  1036. $resql = $this->db->query($sql);
  1037. if ($resql) {
  1038. return 0;
  1039. } else {
  1040. $this->error = $this->db->lasterror();
  1041. return -1;
  1042. }
  1043. }
  1044. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1045. /**
  1046. * Delete a link to contact line
  1047. *
  1048. * @param int $rowid Id of contact link line to delete
  1049. * @param int $notrigger Disable all triggers
  1050. * @return int >0 if OK, <0 if KO
  1051. */
  1052. public function delete_contact($rowid, $notrigger = 0)
  1053. {
  1054. // phpcs:enable
  1055. global $user;
  1056. $this->db->begin();
  1057. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1058. $sql .= " WHERE rowid = ".((int) $rowid);
  1059. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1060. if ($this->db->query($sql)) {
  1061. if (!$notrigger) {
  1062. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1063. if ($result < 0) {
  1064. $this->db->rollback();
  1065. return -1;
  1066. }
  1067. }
  1068. $this->db->commit();
  1069. return 1;
  1070. } else {
  1071. $this->error = $this->db->lasterror();
  1072. $this->db->rollback();
  1073. return -1;
  1074. }
  1075. }
  1076. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1077. /**
  1078. * Delete all links between an object $this and all its contacts
  1079. *
  1080. * @param string $source '' or 'internal' or 'external'
  1081. * @param string $code Type of contact (code or id)
  1082. * @return int >0 if OK, <0 if KO
  1083. */
  1084. public function delete_linked_contact($source = '', $code = '')
  1085. {
  1086. // phpcs:enable
  1087. $listId = '';
  1088. $temp = array();
  1089. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1090. if (!empty($typeContact)) {
  1091. foreach ($typeContact as $key => $value) {
  1092. array_push($temp, $key);
  1093. }
  1094. $listId = implode(",", $temp);
  1095. }
  1096. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1097. $sql .= " WHERE element_id = ".((int) $this->id);
  1098. if (!empty($listId)) {
  1099. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1100. }
  1101. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1102. if ($this->db->query($sql)) {
  1103. return 1;
  1104. } else {
  1105. $this->error = $this->db->lasterror();
  1106. return -1;
  1107. }
  1108. }
  1109. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1110. /**
  1111. * Get array of all contacts for an object
  1112. *
  1113. * @param int $status Status of links to get (-1=all)
  1114. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1115. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1116. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1117. * @return array|int Array of contacts, -1 if error
  1118. */
  1119. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1120. {
  1121. // phpcs:enable
  1122. global $langs;
  1123. $tab = array();
  1124. $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
  1125. if ($source == 'internal') {
  1126. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1127. }
  1128. if ($source == 'external' || $source == 'thirdparty') {
  1129. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1130. }
  1131. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1132. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1133. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
  1134. $sql .= ", ".$this->db->prefix()."element_contact ec";
  1135. if ($source == 'internal') {
  1136. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1137. }
  1138. if ($source == 'external' || $source == 'thirdparty') {
  1139. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1140. }
  1141. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1142. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1143. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1144. if ($code) {
  1145. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1146. }
  1147. if ($source == 'internal') {
  1148. $sql .= " AND tc.source = 'internal'";
  1149. }
  1150. if ($source == 'external' || $source == 'thirdparty') {
  1151. $sql .= " AND tc.source = 'external'";
  1152. }
  1153. $sql .= " AND tc.active=1";
  1154. if ($status >= 0) {
  1155. $sql .= " AND ec.statut = ".((int) $status);
  1156. }
  1157. $sql .= " ORDER BY t.lastname ASC";
  1158. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1159. $resql = $this->db->query($sql);
  1160. if ($resql) {
  1161. $num = $this->db->num_rows($resql);
  1162. $i = 0;
  1163. while ($i < $num) {
  1164. $obj = $this->db->fetch_object($resql);
  1165. if (!$list) {
  1166. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1167. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1168. $tab[$i] = array(
  1169. 'source' => $obj->source,
  1170. 'socid' => $obj->socid,
  1171. 'id' => $obj->id,
  1172. 'nom' => $obj->lastname, // For backward compatibility
  1173. 'civility' => $obj->civility,
  1174. 'lastname' => $obj->lastname,
  1175. 'firstname' => $obj->firstname,
  1176. 'email'=>$obj->email,
  1177. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1178. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1179. 'statuscontact' => $obj->statuscontact,
  1180. 'rowid' => $obj->rowid,
  1181. 'code' => $obj->code,
  1182. 'libelle' => $libelle_type,
  1183. 'status' => $obj->statuslink,
  1184. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1185. );
  1186. } else {
  1187. $tab[$i] = $obj->id;
  1188. }
  1189. $i++;
  1190. }
  1191. return $tab;
  1192. } else {
  1193. $this->error = $this->db->lasterror();
  1194. dol_print_error($this->db);
  1195. return -1;
  1196. }
  1197. }
  1198. /**
  1199. * Update status of a contact linked to object
  1200. *
  1201. * @param int $rowid Id of link between object and contact
  1202. * @return int <0 if KO, >=0 if OK
  1203. */
  1204. public function swapContactStatus($rowid)
  1205. {
  1206. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1207. $sql .= " tc.code, tc.libelle";
  1208. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1209. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1210. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1211. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1212. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1213. $resql = $this->db->query($sql);
  1214. if ($resql) {
  1215. $obj = $this->db->fetch_object($resql);
  1216. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1217. $result = $this->update_contact($rowid, $newstatut);
  1218. $this->db->free($resql);
  1219. return $result;
  1220. } else {
  1221. $this->error = $this->db->error();
  1222. dol_print_error($this->db);
  1223. return -1;
  1224. }
  1225. }
  1226. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1227. /**
  1228. * Return array with list of possible values for type of contacts
  1229. *
  1230. * @param string $source 'internal', 'external' or 'all'
  1231. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1232. * @param int $option 0=Return array id->label, 1=Return array code->label
  1233. * @param int $activeonly 0=all status of contact, 1=only the active
  1234. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1235. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1236. */
  1237. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1238. {
  1239. // phpcs:enable
  1240. global $langs;
  1241. if (empty($order)) {
  1242. $order = 'position';
  1243. }
  1244. if ($order == 'position') {
  1245. $order .= ',code';
  1246. }
  1247. $tab = array();
  1248. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1249. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1250. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1251. if ($activeonly == 1) {
  1252. $sql .= " AND tc.active=1"; // only the active types
  1253. }
  1254. if (!empty($source) && $source != 'all') {
  1255. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1256. }
  1257. if (!empty($code)) {
  1258. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1259. }
  1260. $sql .= $this->db->order($order, 'ASC');
  1261. //print "sql=".$sql;
  1262. $resql = $this->db->query($sql);
  1263. if ($resql) {
  1264. $num = $this->db->num_rows($resql);
  1265. $i = 0;
  1266. while ($i < $num) {
  1267. $obj = $this->db->fetch_object($resql);
  1268. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1269. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1270. if (empty($option)) {
  1271. $tab[$obj->rowid] = $libelle_type;
  1272. } else {
  1273. $tab[$obj->code] = $libelle_type;
  1274. }
  1275. $i++;
  1276. }
  1277. return $tab;
  1278. } else {
  1279. $this->error = $this->db->lasterror();
  1280. //dol_print_error($this->db);
  1281. return null;
  1282. }
  1283. }
  1284. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1285. /**
  1286. * Return array with list of possible values for type of contacts
  1287. *
  1288. * @param string $source 'internal', 'external' or 'all'
  1289. * @param int $option 0=Return array id->label, 1=Return array code->label
  1290. * @param int $activeonly 0=all status of contact, 1=only the active
  1291. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1292. * @param string $element Filter on 1 element type
  1293. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1294. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1295. */
  1296. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1297. {
  1298. // phpcs:enable
  1299. global $langs, $conf;
  1300. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1301. $tab = array();
  1302. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1303. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1304. $sqlWhere = array();
  1305. if (!empty($element)) {
  1306. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1307. }
  1308. if (!empty($excludeelement)) {
  1309. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1310. }
  1311. if ($activeonly == 1) {
  1312. $sqlWhere[] = " tc.active=1"; // only the active types
  1313. }
  1314. if (!empty($source) && $source != 'all') {
  1315. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1316. }
  1317. if (!empty($code)) {
  1318. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1319. }
  1320. if (count($sqlWhere) > 0) {
  1321. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1322. }
  1323. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1324. dol_syslog(__METHOD__, LOG_DEBUG);
  1325. $resql = $this->db->query($sql);
  1326. if ($resql) {
  1327. $num = $this->db->num_rows($resql);
  1328. if ($num > 0) {
  1329. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1330. while ($obj = $this->db->fetch_object($resql)) {
  1331. $modulename = $obj->element;
  1332. if (strpos($obj->element, 'project') !== false) {
  1333. $modulename = 'projet';
  1334. } elseif ($obj->element == 'contrat') {
  1335. $element = 'contract';
  1336. } elseif ($obj->element == 'action') {
  1337. $modulename = 'agenda';
  1338. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1339. $modulename = 'fournisseur';
  1340. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1341. $modulename = 'fournisseur';
  1342. }
  1343. if (!empty($conf->{$modulename}->enabled)) {
  1344. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1345. $tmpelement = $obj->element;
  1346. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1347. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1348. if (empty($option)) {
  1349. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1350. } else {
  1351. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1352. }
  1353. }
  1354. }
  1355. }
  1356. return $tab;
  1357. } else {
  1358. $this->error = $this->db->lasterror();
  1359. return null;
  1360. }
  1361. }
  1362. /**
  1363. * Return id of contacts for a source and a contact code.
  1364. * Example: contact client de facturation ('external', 'BILLING')
  1365. * Example: contact client de livraison ('external', 'SHIPPING')
  1366. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1367. *
  1368. * @param string $source 'external' or 'internal'
  1369. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1370. * @param int $status limited to a certain status
  1371. * @return array List of id for such contacts
  1372. */
  1373. public function getIdContact($source, $code, $status = 0)
  1374. {
  1375. global $conf;
  1376. $result = array();
  1377. $i = 0;
  1378. //cas particulier pour les expeditions
  1379. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1380. $id = $this->origin_id;
  1381. $element = 'commande';
  1382. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1383. $id = $this->origin_id;
  1384. $element = 'order_supplier';
  1385. } else {
  1386. $id = $this->id;
  1387. $element = $this->element;
  1388. }
  1389. $sql = "SELECT ec.fk_socpeople";
  1390. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1391. if ($source == 'internal') {
  1392. $sql .= " ".$this->db->prefix()."user as c,";
  1393. }
  1394. if ($source == 'external') {
  1395. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1396. }
  1397. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1398. $sql .= " WHERE ec.element_id = ".((int) $id);
  1399. $sql .= " AND ec.fk_socpeople = c.rowid";
  1400. if ($source == 'internal') {
  1401. $sql .= " AND c.entity IN (".getEntity('user').")";
  1402. }
  1403. if ($source == 'external') {
  1404. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1405. }
  1406. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1407. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1408. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1409. if ($code) {
  1410. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1411. }
  1412. $sql .= " AND tc.active = 1";
  1413. if ($status) {
  1414. $sql .= " AND ec.statut = ".((int) $status);
  1415. }
  1416. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1417. $resql = $this->db->query($sql);
  1418. if ($resql) {
  1419. while ($obj = $this->db->fetch_object($resql)) {
  1420. $result[$i] = $obj->fk_socpeople;
  1421. $i++;
  1422. }
  1423. } else {
  1424. $this->error = $this->db->error();
  1425. return null;
  1426. }
  1427. return $result;
  1428. }
  1429. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1430. /**
  1431. * Load object contact with id=$this->contact_id into $this->contact
  1432. *
  1433. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1434. * @return int <0 if KO, >0 if OK
  1435. */
  1436. public function fetch_contact($contactid = null)
  1437. {
  1438. // phpcs:enable
  1439. if (empty($contactid)) {
  1440. $contactid = $this->contact_id;
  1441. }
  1442. if (empty($contactid)) {
  1443. return 0;
  1444. }
  1445. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1446. $contact = new Contact($this->db);
  1447. $result = $contact->fetch($contactid);
  1448. $this->contact = $contact;
  1449. return $result;
  1450. }
  1451. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1452. /**
  1453. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1454. *
  1455. * @param int $force_thirdparty_id Force thirdparty id
  1456. * @return int <0 if KO, >0 if OK
  1457. */
  1458. public function fetch_thirdparty($force_thirdparty_id = 0)
  1459. {
  1460. // phpcs:enable
  1461. global $conf;
  1462. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1463. return 0;
  1464. }
  1465. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1466. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1467. if ($force_thirdparty_id) {
  1468. $idtofetch = $force_thirdparty_id;
  1469. }
  1470. if ($idtofetch) {
  1471. $thirdparty = new Societe($this->db);
  1472. $result = $thirdparty->fetch($idtofetch);
  1473. if ($result<0) {
  1474. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1475. }
  1476. $this->thirdparty = $thirdparty;
  1477. // Use first price level if level not defined for third party
  1478. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1479. $this->thirdparty->price_level = 1;
  1480. }
  1481. return $result;
  1482. } else {
  1483. return -1;
  1484. }
  1485. }
  1486. /**
  1487. * Looks for an object with ref matching the wildcard provided
  1488. * It does only work when $this->table_ref_field is set
  1489. *
  1490. * @param string $ref Wildcard
  1491. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1492. */
  1493. public function fetchOneLike($ref)
  1494. {
  1495. if (!$this->table_ref_field) {
  1496. return 0;
  1497. }
  1498. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1499. $query = $this->db->query($sql);
  1500. if (!$this->db->num_rows($query)) {
  1501. return 0;
  1502. }
  1503. $result = $this->db->fetch_object($query);
  1504. return $this->fetch($result->rowid);
  1505. }
  1506. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1507. /**
  1508. * Load data for barcode into properties ->barcode_type*
  1509. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1510. * if it is not defined, ->element must be defined to know default barcode type.
  1511. *
  1512. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1513. */
  1514. public function fetch_barcode()
  1515. {
  1516. // phpcs:enable
  1517. global $conf;
  1518. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1519. $idtype = $this->barcode_type;
  1520. 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
  1521. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1522. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1523. } elseif ($this->element == 'societe') {
  1524. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1525. } else {
  1526. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1527. }
  1528. }
  1529. if ($idtype > 0) {
  1530. 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
  1531. $sql = "SELECT rowid, code, libelle as label, coder";
  1532. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1533. $sql .= " WHERE rowid = ".((int) $idtype);
  1534. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1535. $resql = $this->db->query($sql);
  1536. if ($resql) {
  1537. $obj = $this->db->fetch_object($resql);
  1538. $this->barcode_type = $obj->rowid;
  1539. $this->barcode_type_code = $obj->code;
  1540. $this->barcode_type_label = $obj->label;
  1541. $this->barcode_type_coder = $obj->coder;
  1542. return 1;
  1543. } else {
  1544. dol_print_error($this->db);
  1545. return -1;
  1546. }
  1547. }
  1548. }
  1549. return 0;
  1550. }
  1551. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1552. /**
  1553. * Load the project with id $this->fk_project into this->project
  1554. *
  1555. * @return int <0 if KO, >=0 if OK
  1556. */
  1557. public function fetch_project()
  1558. {
  1559. // phpcs:enable
  1560. return $this->fetch_projet();
  1561. }
  1562. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1563. /**
  1564. * Load the project with id $this->fk_project into this->project
  1565. *
  1566. * @return int <0 if KO, >=0 if OK
  1567. */
  1568. public function fetch_projet()
  1569. {
  1570. // phpcs:enable
  1571. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1572. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1573. $this->fk_project = $this->fk_projet; // For backward compatibility
  1574. }
  1575. if (empty($this->fk_project)) {
  1576. return 0;
  1577. }
  1578. $project = new Project($this->db);
  1579. $result = $project->fetch($this->fk_project);
  1580. $this->projet = $project; // deprecated
  1581. $this->project = $project;
  1582. return $result;
  1583. }
  1584. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1585. /**
  1586. * Load the product with id $this->fk_product into this->product
  1587. *
  1588. * @return int <0 if KO, >=0 if OK
  1589. */
  1590. public function fetch_product()
  1591. {
  1592. // phpcs:enable
  1593. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1594. if (empty($this->fk_product)) {
  1595. return 0;
  1596. }
  1597. $product = new Product($this->db);
  1598. $result = $product->fetch($this->fk_product);
  1599. $this->product = $product;
  1600. return $result;
  1601. }
  1602. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1603. /**
  1604. * Load the user with id $userid into this->user
  1605. *
  1606. * @param int $userid Id du contact
  1607. * @return int <0 if KO, >0 if OK
  1608. */
  1609. public function fetch_user($userid)
  1610. {
  1611. // phpcs:enable
  1612. $user = new User($this->db);
  1613. $result = $user->fetch($userid);
  1614. $this->user = $user;
  1615. return $result;
  1616. }
  1617. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1618. /**
  1619. * Read linked origin object
  1620. *
  1621. * @return void
  1622. */
  1623. public function fetch_origin()
  1624. {
  1625. // phpcs:enable
  1626. if ($this->origin == 'shipping') {
  1627. $this->origin = 'expedition';
  1628. }
  1629. if ($this->origin == 'delivery') {
  1630. $this->origin = 'livraison';
  1631. }
  1632. if ($this->origin == 'order_supplier') {
  1633. $this->origin = 'commandeFournisseur';
  1634. }
  1635. $origin = $this->origin;
  1636. $classname = ucfirst($origin);
  1637. $this->$origin = new $classname($this->db);
  1638. $this->$origin->fetch($this->origin_id);
  1639. }
  1640. /**
  1641. * Load object from specific field
  1642. *
  1643. * @param string $table Table element or element line
  1644. * @param string $field Field selected
  1645. * @param string $key Import key
  1646. * @param string $element Element name
  1647. * @return int <0 if KO, >0 if OK
  1648. */
  1649. public function fetchObjectFrom($table, $field, $key, $element = null)
  1650. {
  1651. global $conf;
  1652. $result = false;
  1653. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1654. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1655. if (!empty($element)) {
  1656. $sql .= " AND entity IN (".getEntity($element).")";
  1657. } else {
  1658. $sql .= " AND entity = ".((int) $conf->entity);
  1659. }
  1660. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1661. $resql = $this->db->query($sql);
  1662. if ($resql) {
  1663. $row = $this->db->fetch_row($resql);
  1664. // Test for avoid error -1
  1665. if ($row[0] > 0) {
  1666. $result = $this->fetch($row[0]);
  1667. }
  1668. }
  1669. return $result;
  1670. }
  1671. /**
  1672. * Getter generic. Load value from a specific field
  1673. *
  1674. * @param string $table Table of element or element line
  1675. * @param int $id Element id
  1676. * @param string $field Field selected
  1677. * @return int <0 if KO, >0 if OK
  1678. */
  1679. public function getValueFrom($table, $id, $field)
  1680. {
  1681. $result = false;
  1682. if (!empty($id) && !empty($field) && !empty($table)) {
  1683. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1684. $sql .= " WHERE rowid = ".((int) $id);
  1685. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1686. $resql = $this->db->query($sql);
  1687. if ($resql) {
  1688. $row = $this->db->fetch_row($resql);
  1689. $result = $row[0];
  1690. }
  1691. }
  1692. return $result;
  1693. }
  1694. /**
  1695. * Setter generic. Update a specific field into database.
  1696. * Warning: Trigger is run only if param trigkey is provided.
  1697. *
  1698. * @param string $field Field to update
  1699. * @param mixed $value New value
  1700. * @param string $table To force other table element or element line (should not be used)
  1701. * @param int $id To force other object id (should not be used)
  1702. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1703. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1704. * @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'
  1705. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1706. * @param string $fk_user_field Name of field to save user id making change
  1707. * @return int <0 if KO, >0 if OK
  1708. * @see updateExtraField()
  1709. */
  1710. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1711. {
  1712. global $user, $langs, $conf;
  1713. if (empty($table)) {
  1714. $table = $this->table_element;
  1715. }
  1716. if (empty($id)) {
  1717. $id = $this->id;
  1718. }
  1719. if (empty($format)) {
  1720. $format = 'text';
  1721. }
  1722. if (empty($id_field)) {
  1723. $id_field = 'rowid';
  1724. }
  1725. $error = 0;
  1726. $this->db->begin();
  1727. // Special case
  1728. if ($table == 'product' && $field == 'note_private') {
  1729. $field = 'note';
  1730. }
  1731. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1732. $fk_user_field = 'fk_user_mod';
  1733. }
  1734. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1735. if ($format == 'text') {
  1736. $sql .= $field." = '".$this->db->escape($value)."'";
  1737. } elseif ($format == 'int') {
  1738. $sql .= $field." = ".((int) $value);
  1739. } elseif ($format == 'date') {
  1740. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1741. }
  1742. if ($fk_user_field) {
  1743. if (!empty($fuser) && is_object($fuser)) {
  1744. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1745. } elseif (empty($fuser) || $fuser != 'none') {
  1746. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1747. }
  1748. }
  1749. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1750. dol_syslog(__METHOD__."", LOG_DEBUG);
  1751. $resql = $this->db->query($sql);
  1752. if ($resql) {
  1753. if ($trigkey) {
  1754. // call trigger with updated object values
  1755. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1756. $result = $this->fetch($id);
  1757. } else {
  1758. $result = $this->fetchCommon($id);
  1759. }
  1760. if ($result >= 0) {
  1761. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1762. }
  1763. if ($result < 0) {
  1764. $error++;
  1765. }
  1766. }
  1767. if (!$error) {
  1768. if (property_exists($this, $field)) {
  1769. $this->$field = $value;
  1770. }
  1771. $this->db->commit();
  1772. return 1;
  1773. } else {
  1774. $this->db->rollback();
  1775. return -2;
  1776. }
  1777. } else {
  1778. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1779. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1780. } else {
  1781. $this->error = $this->db->lasterror();
  1782. }
  1783. $this->db->rollback();
  1784. return -1;
  1785. }
  1786. }
  1787. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1788. /**
  1789. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1790. *
  1791. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1792. * @param string $fieldid Name of field to use for the select MAX and MIN
  1793. * @param int $nodbprefix Do not include DB prefix to forge table name
  1794. * @return int <0 if KO, >0 if OK
  1795. */
  1796. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1797. {
  1798. // phpcs:enable
  1799. global $conf, $user;
  1800. if (!$this->table_element) {
  1801. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1802. return -1;
  1803. }
  1804. if ($fieldid == 'none') {
  1805. return 1;
  1806. }
  1807. // For backward compatibility
  1808. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1809. $fieldid = 'titre';
  1810. }
  1811. // Security on socid
  1812. $socid = 0;
  1813. if ($user->socid > 0) {
  1814. $socid = $user->socid;
  1815. }
  1816. // this->ismultientitymanaged contains
  1817. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1818. $aliastablesociete = 's';
  1819. if ($this->element == 'societe') {
  1820. $aliastablesociete = 'te'; // te as table_element
  1821. }
  1822. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1823. $sql = "SELECT MAX(te.".$fieldid.")";
  1824. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1825. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1826. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1827. }
  1828. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1829. $tmparray = explode('@', $this->ismultientitymanaged);
  1830. $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
  1831. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1832. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1833. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1834. $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
  1835. }
  1836. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1837. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1838. }
  1839. $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)
  1840. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1841. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1842. }
  1843. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1844. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1845. }
  1846. if (!empty($filter)) {
  1847. if (!preg_match('/^\s*AND/i', $filter)) {
  1848. $sql .= " AND "; // For backward compatibility
  1849. }
  1850. $sql .= $filter;
  1851. }
  1852. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1853. $tmparray = explode('@', $this->ismultientitymanaged);
  1854. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1855. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1856. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1857. }
  1858. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1859. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1860. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1861. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1862. } else {
  1863. $sql .= " AND ug.fk_user = te.rowid";
  1864. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1865. }
  1866. } else {
  1867. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1868. }
  1869. }
  1870. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1871. $tmparray = explode('@', $this->ismultientitymanaged);
  1872. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1873. }
  1874. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1875. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1876. }
  1877. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1878. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1879. }
  1880. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1881. $sql .= ' AND te.rowid = '.((int) $socid);
  1882. }
  1883. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1884. $result = $this->db->query($sql);
  1885. if (!$result) {
  1886. $this->error = $this->db->lasterror();
  1887. return -1;
  1888. }
  1889. $row = $this->db->fetch_row($result);
  1890. $this->ref_previous = $row[0];
  1891. $sql = "SELECT MIN(te.".$fieldid.")";
  1892. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1893. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1894. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1895. }
  1896. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1897. $tmparray = explode('@', $this->ismultientitymanaged);
  1898. $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
  1899. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1900. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1901. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1902. $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
  1903. }
  1904. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1905. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1906. }
  1907. $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)
  1908. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1909. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1910. }
  1911. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1912. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1913. }
  1914. if (!empty($filter)) {
  1915. if (!preg_match('/^\s*AND/i', $filter)) {
  1916. $sql .= " AND "; // For backward compatibility
  1917. }
  1918. $sql .= $filter;
  1919. }
  1920. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1921. $tmparray = explode('@', $this->ismultientitymanaged);
  1922. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1923. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1924. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1925. }
  1926. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1927. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1928. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1929. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1930. } else {
  1931. $sql .= " AND ug.fk_user = te.rowid";
  1932. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1933. }
  1934. } else {
  1935. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1936. }
  1937. }
  1938. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1939. $tmparray = explode('@', $this->ismultientitymanaged);
  1940. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1941. }
  1942. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1943. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1944. }
  1945. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1946. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1947. }
  1948. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1949. $sql .= ' AND te.rowid = '.((int) $socid);
  1950. }
  1951. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1952. // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null
  1953. $result = $this->db->query($sql);
  1954. if (!$result) {
  1955. $this->error = $this->db->lasterror();
  1956. return -2;
  1957. }
  1958. $row = $this->db->fetch_row($result);
  1959. $this->ref_next = $row[0];
  1960. return 1;
  1961. }
  1962. /**
  1963. * Return list of id of contacts of object
  1964. *
  1965. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1966. * @return array Array of id of contacts (if source=external or internal)
  1967. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1968. */
  1969. public function getListContactId($source = 'external')
  1970. {
  1971. $contactAlreadySelected = array();
  1972. $tab = $this->liste_contact(-1, $source);
  1973. $num = count($tab);
  1974. $i = 0;
  1975. while ($i < $num) {
  1976. if ($source == 'thirdparty') {
  1977. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1978. } else {
  1979. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1980. }
  1981. $i++;
  1982. }
  1983. return $contactAlreadySelected;
  1984. }
  1985. /**
  1986. * Link element with a project
  1987. *
  1988. * @param int $projectid Project id to link element to
  1989. * @param int $notrigger Disable the trigger
  1990. * @return int <0 if KO, >0 if OK
  1991. */
  1992. public function setProject($projectid, $notrigger = 0)
  1993. {
  1994. global $user;
  1995. $error = 0;
  1996. if (!$this->table_element) {
  1997. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1998. return -1;
  1999. }
  2000. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2001. if (!empty($this->fields['fk_project'])) { // Common case
  2002. if ($projectid) {
  2003. $sql .= " SET fk_project = ".((int) $projectid);
  2004. } else {
  2005. $sql .= " SET fk_project = NULL";
  2006. }
  2007. $sql .= ' WHERE rowid = '.((int) $this->id);
  2008. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  2009. if ($projectid) {
  2010. $sql .= " SET fk_project = ".((int) $projectid);
  2011. } else {
  2012. $sql .= " SET fk_project = NULL";
  2013. }
  2014. $sql .= ' WHERE id = '.((int) $this->id);
  2015. } else // Special case for old architecture objects
  2016. {
  2017. if ($projectid) {
  2018. $sql .= ' SET fk_projet = '.((int) $projectid);
  2019. } else {
  2020. $sql .= ' SET fk_projet = NULL';
  2021. }
  2022. $sql .= " WHERE rowid = ".((int) $this->id);
  2023. }
  2024. $this->db->begin();
  2025. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2026. if ($this->db->query($sql)) {
  2027. $this->fk_project = ((int) $projectid);
  2028. } else {
  2029. dol_print_error($this->db);
  2030. $error++;
  2031. }
  2032. // Triggers
  2033. if (!$error && !$notrigger) {
  2034. // Call triggers
  2035. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2036. if ($result < 0) {
  2037. $error++;
  2038. } //Do also here what you must do to rollback action if trigger fail
  2039. // End call triggers
  2040. }
  2041. // Commit or rollback
  2042. if ($error) {
  2043. $this->db->rollback();
  2044. return -1;
  2045. } else {
  2046. $this->db->commit();
  2047. return 1;
  2048. }
  2049. }
  2050. /**
  2051. * Change the payments methods
  2052. *
  2053. * @param int $id Id of new payment method
  2054. * @return int >0 if OK, <0 if KO
  2055. */
  2056. public function setPaymentMethods($id)
  2057. {
  2058. global $user;
  2059. $error = 0; $notrigger = 0;
  2060. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2061. if ($this->statut >= 0 || $this->element == 'societe') {
  2062. // TODO uniformize field name
  2063. $fieldname = 'fk_mode_reglement';
  2064. if ($this->element == 'societe') {
  2065. $fieldname = 'mode_reglement';
  2066. }
  2067. if (get_class($this) == 'Fournisseur') {
  2068. $fieldname = 'mode_reglement_supplier';
  2069. }
  2070. if (get_class($this) == 'Tva') {
  2071. $fieldname = 'fk_typepayment';
  2072. }
  2073. if (get_class($this) == 'Salary') {
  2074. $fieldname = 'fk_typepayment';
  2075. }
  2076. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2077. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2078. $sql .= ' WHERE rowid='.((int) $this->id);
  2079. if ($this->db->query($sql)) {
  2080. $this->mode_reglement_id = $id;
  2081. // for supplier
  2082. if (get_class($this) == 'Fournisseur') {
  2083. $this->mode_reglement_supplier_id = $id;
  2084. }
  2085. // Triggers
  2086. if (!$error && !$notrigger) {
  2087. // Call triggers
  2088. if (get_class($this) == 'Commande') {
  2089. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2090. } else {
  2091. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2092. }
  2093. if ($result < 0) {
  2094. $error++;
  2095. }
  2096. // End call triggers
  2097. }
  2098. return 1;
  2099. } else {
  2100. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2101. $this->error = $this->db->error();
  2102. return -1;
  2103. }
  2104. } else {
  2105. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2106. $this->error = 'Status of the object is incompatible '.$this->statut;
  2107. return -2;
  2108. }
  2109. }
  2110. /**
  2111. * Change the multicurrency code
  2112. *
  2113. * @param string $code multicurrency code
  2114. * @return int >0 if OK, <0 if KO
  2115. */
  2116. public function setMulticurrencyCode($code)
  2117. {
  2118. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2119. if ($this->statut >= 0 || $this->element == 'societe') {
  2120. $fieldname = 'multicurrency_code';
  2121. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2122. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2123. $sql .= ' WHERE rowid='.((int) $this->id);
  2124. if ($this->db->query($sql)) {
  2125. $this->multicurrency_code = $code;
  2126. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2127. if ($rate) {
  2128. $this->setMulticurrencyRate($rate, 2);
  2129. }
  2130. return 1;
  2131. } else {
  2132. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2133. $this->error = $this->db->error();
  2134. return -1;
  2135. }
  2136. } else {
  2137. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2138. $this->error = 'Status of the object is incompatible '.$this->statut;
  2139. return -2;
  2140. }
  2141. }
  2142. /**
  2143. * Change the multicurrency rate
  2144. *
  2145. * @param double $rate multicurrency rate
  2146. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2147. * @return int >0 if OK, <0 if KO
  2148. */
  2149. public function setMulticurrencyRate($rate, $mode = 1)
  2150. {
  2151. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2152. if ($this->statut >= 0 || $this->element == 'societe') {
  2153. $fieldname = 'multicurrency_tx';
  2154. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2155. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2156. $sql .= ' WHERE rowid='.((int) $this->id);
  2157. if ($this->db->query($sql)) {
  2158. $this->multicurrency_tx = $rate;
  2159. // Update line price
  2160. if (!empty($this->lines)) {
  2161. foreach ($this->lines as &$line) {
  2162. // Amounts in company currency will be recalculated
  2163. if ($mode == 1) {
  2164. $line->subprice = 0;
  2165. }
  2166. // Amounts in foreign currency will be recalculated
  2167. if ($mode == 2) {
  2168. $line->multicurrency_subprice = 0;
  2169. }
  2170. switch ($this->element) {
  2171. case 'propal':
  2172. $this->updateline(
  2173. $line->id,
  2174. $line->subprice,
  2175. $line->qty,
  2176. $line->remise_percent,
  2177. $line->tva_tx,
  2178. $line->localtax1_tx,
  2179. $line->localtax2_tx,
  2180. ($line->description ? $line->description : $line->desc),
  2181. 'HT',
  2182. $line->info_bits,
  2183. $line->special_code,
  2184. $line->fk_parent_line,
  2185. $line->skip_update_total,
  2186. $line->fk_fournprice,
  2187. $line->pa_ht,
  2188. $line->label,
  2189. $line->product_type,
  2190. $line->date_start,
  2191. $line->date_end,
  2192. $line->array_options,
  2193. $line->fk_unit,
  2194. $line->multicurrency_subprice
  2195. );
  2196. break;
  2197. case 'commande':
  2198. $this->updateline(
  2199. $line->id,
  2200. ($line->description ? $line->description : $line->desc),
  2201. $line->subprice,
  2202. $line->qty,
  2203. $line->remise_percent,
  2204. $line->tva_tx,
  2205. $line->localtax1_tx,
  2206. $line->localtax2_tx,
  2207. 'HT',
  2208. $line->info_bits,
  2209. $line->date_start,
  2210. $line->date_end,
  2211. $line->product_type,
  2212. $line->fk_parent_line,
  2213. $line->skip_update_total,
  2214. $line->fk_fournprice,
  2215. $line->pa_ht,
  2216. $line->label,
  2217. $line->special_code,
  2218. $line->array_options,
  2219. $line->fk_unit,
  2220. $line->multicurrency_subprice
  2221. );
  2222. break;
  2223. case 'facture':
  2224. $this->updateline(
  2225. $line->id,
  2226. ($line->description ? $line->description : $line->desc),
  2227. $line->subprice,
  2228. $line->qty,
  2229. $line->remise_percent,
  2230. $line->date_start,
  2231. $line->date_end,
  2232. $line->tva_tx,
  2233. $line->localtax1_tx,
  2234. $line->localtax2_tx,
  2235. 'HT',
  2236. $line->info_bits,
  2237. $line->product_type,
  2238. $line->fk_parent_line,
  2239. $line->skip_update_total,
  2240. $line->fk_fournprice,
  2241. $line->pa_ht,
  2242. $line->label,
  2243. $line->special_code,
  2244. $line->array_options,
  2245. $line->situation_percent,
  2246. $line->fk_unit,
  2247. $line->multicurrency_subprice
  2248. );
  2249. break;
  2250. case 'supplier_proposal':
  2251. $this->updateline(
  2252. $line->id,
  2253. $line->subprice,
  2254. $line->qty,
  2255. $line->remise_percent,
  2256. $line->tva_tx,
  2257. $line->localtax1_tx,
  2258. $line->localtax2_tx,
  2259. ($line->description ? $line->description : $line->desc),
  2260. 'HT',
  2261. $line->info_bits,
  2262. $line->special_code,
  2263. $line->fk_parent_line,
  2264. $line->skip_update_total,
  2265. $line->fk_fournprice,
  2266. $line->pa_ht,
  2267. $line->label,
  2268. $line->product_type,
  2269. $line->array_options,
  2270. $line->ref_fourn,
  2271. $line->multicurrency_subprice
  2272. );
  2273. break;
  2274. case 'order_supplier':
  2275. $this->updateline(
  2276. $line->id,
  2277. ($line->description ? $line->description : $line->desc),
  2278. $line->subprice,
  2279. $line->qty,
  2280. $line->remise_percent,
  2281. $line->tva_tx,
  2282. $line->localtax1_tx,
  2283. $line->localtax2_tx,
  2284. 'HT',
  2285. $line->info_bits,
  2286. $line->product_type,
  2287. false,
  2288. $line->date_start,
  2289. $line->date_end,
  2290. $line->array_options,
  2291. $line->fk_unit,
  2292. $line->multicurrency_subprice,
  2293. $line->ref_supplier
  2294. );
  2295. break;
  2296. case 'invoice_supplier':
  2297. $this->updateline(
  2298. $line->id,
  2299. ($line->description ? $line->description : $line->desc),
  2300. $line->subprice,
  2301. $line->tva_tx,
  2302. $line->localtax1_tx,
  2303. $line->localtax2_tx,
  2304. $line->qty,
  2305. 0,
  2306. 'HT',
  2307. $line->info_bits,
  2308. $line->product_type,
  2309. $line->remise_percent,
  2310. false,
  2311. $line->date_start,
  2312. $line->date_end,
  2313. $line->array_options,
  2314. $line->fk_unit,
  2315. $line->multicurrency_subprice,
  2316. $line->ref_supplier
  2317. );
  2318. break;
  2319. default:
  2320. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2321. break;
  2322. }
  2323. }
  2324. }
  2325. return 1;
  2326. } else {
  2327. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2328. $this->error = $this->db->error();
  2329. return -1;
  2330. }
  2331. } else {
  2332. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2333. $this->error = 'Status of the object is incompatible '.$this->statut;
  2334. return -2;
  2335. }
  2336. }
  2337. /**
  2338. * Change the payments terms
  2339. *
  2340. * @param int $id Id of new payment terms
  2341. * @param string $deposit_percent % of deposit if needed by payment terms
  2342. * @return int >0 if OK, <0 if KO
  2343. */
  2344. public function setPaymentTerms($id, $deposit_percent = null)
  2345. {
  2346. dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
  2347. if ($this->statut >= 0 || $this->element == 'societe') {
  2348. // TODO uniformize field name
  2349. $fieldname = 'fk_cond_reglement';
  2350. if ($this->element == 'societe') {
  2351. $fieldname = 'cond_reglement';
  2352. }
  2353. if (get_class($this) == 'Fournisseur') {
  2354. $fieldname = 'cond_reglement_supplier';
  2355. }
  2356. if (empty($deposit_percent) || $deposit_percent < 0) {
  2357. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2358. }
  2359. if ($deposit_percent > 100) {
  2360. $deposit_percent = 100;
  2361. }
  2362. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2363. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2364. $sql .= " , deposit_percent = " . (! empty($deposit_percent) ? "'".$this->db->escape($deposit_percent)."'" : 'NULL');
  2365. $sql .= ' WHERE rowid='.((int) $this->id);
  2366. if ($this->db->query($sql)) {
  2367. $this->cond_reglement_id = $id;
  2368. // for supplier
  2369. if (get_class($this) == 'Fournisseur') {
  2370. $this->cond_reglement_supplier_id = $id;
  2371. }
  2372. $this->cond_reglement = $id; // for compatibility
  2373. $this->deposit_percent = $deposit_percent;
  2374. return 1;
  2375. } else {
  2376. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2377. $this->error = $this->db->error();
  2378. return -1;
  2379. }
  2380. } else {
  2381. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2382. $this->error = 'Status of the object is incompatible '.$this->statut;
  2383. return -2;
  2384. }
  2385. }
  2386. /**
  2387. * Change the transport mode methods
  2388. *
  2389. * @param int $id Id of transport mode
  2390. * @return int >0 if OK, <0 if KO
  2391. */
  2392. public function setTransportMode($id)
  2393. {
  2394. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2395. if ($this->statut >= 0 || $this->element == 'societe') {
  2396. $fieldname = 'fk_transport_mode';
  2397. if ($this->element == 'societe') {
  2398. $fieldname = 'transport_mode';
  2399. }
  2400. if (get_class($this) == 'Fournisseur') {
  2401. $fieldname = 'transport_mode_supplier';
  2402. }
  2403. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2404. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2405. $sql .= ' WHERE rowid='.((int) $this->id);
  2406. if ($this->db->query($sql)) {
  2407. $this->transport_mode_id = $id;
  2408. // for supplier
  2409. if (get_class($this) == 'Fournisseur') {
  2410. $this->transport_mode_supplier_id = $id;
  2411. }
  2412. return 1;
  2413. } else {
  2414. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2415. $this->error = $this->db->error();
  2416. return -1;
  2417. }
  2418. } else {
  2419. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2420. $this->error = 'Status of the object is incompatible '.$this->statut;
  2421. return -2;
  2422. }
  2423. }
  2424. /**
  2425. * Change the retained warranty payments terms
  2426. *
  2427. * @param int $id Id of new payment terms
  2428. * @return int >0 if OK, <0 if KO
  2429. */
  2430. public function setRetainedWarrantyPaymentTerms($id)
  2431. {
  2432. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2433. if ($this->statut >= 0 || $this->element == 'societe') {
  2434. $fieldname = 'retained_warranty_fk_cond_reglement';
  2435. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2436. $sql .= " SET ".$fieldname." = ".((int) $id);
  2437. $sql .= ' WHERE rowid='.((int) $this->id);
  2438. if ($this->db->query($sql)) {
  2439. $this->retained_warranty_fk_cond_reglement = $id;
  2440. return 1;
  2441. } else {
  2442. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2443. $this->error = $this->db->error();
  2444. return -1;
  2445. }
  2446. } else {
  2447. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2448. $this->error = 'Status of the object is incompatible '.$this->statut;
  2449. return -2;
  2450. }
  2451. }
  2452. /**
  2453. * Define delivery address
  2454. * @deprecated
  2455. *
  2456. * @param int $id Address id
  2457. * @return int <0 si ko, >0 si ok
  2458. */
  2459. public function setDeliveryAddress($id)
  2460. {
  2461. $fieldname = 'fk_delivery_address';
  2462. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2463. $fieldname = 'fk_address';
  2464. }
  2465. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2466. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2467. if ($this->db->query($sql)) {
  2468. $this->fk_delivery_address = $id;
  2469. return 1;
  2470. } else {
  2471. $this->error = $this->db->error();
  2472. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2473. return -1;
  2474. }
  2475. }
  2476. /**
  2477. * Change the shipping method
  2478. *
  2479. * @param int $shipping_method_id Id of shipping method
  2480. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2481. * @param User $userused Object user
  2482. *
  2483. * @return int 1 if OK, 0 if KO
  2484. */
  2485. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2486. {
  2487. global $user;
  2488. if (empty($userused)) {
  2489. $userused = $user;
  2490. }
  2491. $error = 0;
  2492. if (!$this->table_element) {
  2493. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2494. return -1;
  2495. }
  2496. $this->db->begin();
  2497. if ($shipping_method_id < 0) {
  2498. $shipping_method_id = 'NULL';
  2499. }
  2500. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2501. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2502. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2503. $sql .= " WHERE rowid=".((int) $this->id);
  2504. $resql = $this->db->query($sql);
  2505. if (!$resql) {
  2506. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2507. $this->error = $this->db->lasterror();
  2508. $error++;
  2509. } else {
  2510. if (!$notrigger) {
  2511. // Call trigger
  2512. $this->context = array('shippingmethodupdate'=>1);
  2513. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2514. if ($result < 0) {
  2515. $error++;
  2516. }
  2517. // End call trigger
  2518. }
  2519. }
  2520. if ($error) {
  2521. $this->db->rollback();
  2522. return -1;
  2523. } else {
  2524. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2525. $this->db->commit();
  2526. return 1;
  2527. }
  2528. }
  2529. /**
  2530. * Change the warehouse
  2531. *
  2532. * @param int $warehouse_id Id of warehouse
  2533. * @return int 1 if OK, 0 if KO
  2534. */
  2535. public function setWarehouse($warehouse_id)
  2536. {
  2537. if (!$this->table_element) {
  2538. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2539. return -1;
  2540. }
  2541. if ($warehouse_id < 0) {
  2542. $warehouse_id = 'NULL';
  2543. }
  2544. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2545. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2546. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2547. $sql .= " WHERE rowid=".((int) $this->id);
  2548. if ($this->db->query($sql)) {
  2549. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2550. return 1;
  2551. } else {
  2552. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2553. $this->error = $this->db->error();
  2554. return 0;
  2555. }
  2556. }
  2557. /**
  2558. * Set last model used by doc generator
  2559. *
  2560. * @param User $user User object that make change
  2561. * @param string $modelpdf Modele name
  2562. * @return int <0 if KO, >0 if OK
  2563. */
  2564. public function setDocModel($user, $modelpdf)
  2565. {
  2566. if (!$this->table_element) {
  2567. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2568. return -1;
  2569. }
  2570. $newmodelpdf = dol_trunc($modelpdf, 255);
  2571. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2572. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2573. $sql .= " WHERE rowid = ".((int) $this->id);
  2574. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2575. $resql = $this->db->query($sql);
  2576. if ($resql) {
  2577. $this->model_pdf = $modelpdf;
  2578. $this->modelpdf = $modelpdf; // For bakward compatibility
  2579. return 1;
  2580. } else {
  2581. dol_print_error($this->db);
  2582. return 0;
  2583. }
  2584. }
  2585. /**
  2586. * Change the bank account
  2587. *
  2588. * @param int $fk_account Id of bank account
  2589. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2590. * @param User $userused Object user
  2591. * @return int 1 if OK, 0 if KO
  2592. */
  2593. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2594. {
  2595. global $user;
  2596. if (empty($userused)) {
  2597. $userused = $user;
  2598. }
  2599. $error = 0;
  2600. if (!$this->table_element) {
  2601. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2602. return -1;
  2603. }
  2604. $this->db->begin();
  2605. if ($fk_account < 0) {
  2606. $fk_account = 'NULL';
  2607. }
  2608. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2609. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2610. $sql .= " SET fk_account = ".((int) $fk_account);
  2611. $sql .= " WHERE rowid=".((int) $this->id);
  2612. $resql = $this->db->query($sql);
  2613. if (!$resql) {
  2614. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2615. $this->error = $this->db->lasterror();
  2616. $error++;
  2617. } else {
  2618. if (!$notrigger) {
  2619. // Call trigger
  2620. $this->context = array('bankaccountupdate'=>1);
  2621. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2622. if ($result < 0) {
  2623. $error++;
  2624. }
  2625. // End call trigger
  2626. }
  2627. }
  2628. if ($error) {
  2629. $this->db->rollback();
  2630. return -1;
  2631. } else {
  2632. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2633. $this->db->commit();
  2634. return 1;
  2635. }
  2636. }
  2637. // TODO: Move line related operations to CommonObjectLine?
  2638. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2639. /**
  2640. * Save a new position (field rang) for details lines.
  2641. * You can choose to set position for lines with already a position or lines without any position defined.
  2642. *
  2643. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2644. * @param string $rowidorder ASC or DESC
  2645. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2646. * @return int <0 if KO, >0 if OK
  2647. */
  2648. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2649. {
  2650. // phpcs:enable
  2651. if (!$this->table_element_line) {
  2652. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2653. return -1;
  2654. }
  2655. if (!$this->fk_element) {
  2656. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2657. return -1;
  2658. }
  2659. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2660. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2661. $fieldposition = 'position';
  2662. }
  2663. // Count number of lines to reorder (according to choice $renum)
  2664. $nl = 0;
  2665. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2666. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2667. if (!$renum) {
  2668. $sql .= " AND " . $fieldposition . " = 0";
  2669. }
  2670. if ($renum) {
  2671. $sql .= " AND " . $fieldposition . " <> 0";
  2672. }
  2673. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2674. $resql = $this->db->query($sql);
  2675. if ($resql) {
  2676. $row = $this->db->fetch_row($resql);
  2677. $nl = $row[0];
  2678. } else {
  2679. dol_print_error($this->db);
  2680. }
  2681. if ($nl > 0) {
  2682. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2683. $rows = array();
  2684. // We first search all lines that are parent lines (for multilevel details lines)
  2685. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2686. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2687. if ($fk_parent_line) {
  2688. $sql .= ' AND fk_parent_line IS NULL';
  2689. }
  2690. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2691. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2692. $resql = $this->db->query($sql);
  2693. if ($resql) {
  2694. $i = 0;
  2695. $num = $this->db->num_rows($resql);
  2696. while ($i < $num) {
  2697. $row = $this->db->fetch_row($resql);
  2698. $rows[] = $row[0]; // Add parent line into array rows
  2699. $childrens = $this->getChildrenOfLine($row[0]);
  2700. if (!empty($childrens)) {
  2701. foreach ($childrens as $child) {
  2702. array_push($rows, $child);
  2703. }
  2704. }
  2705. $i++;
  2706. }
  2707. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2708. if (!empty($rows)) {
  2709. foreach ($rows as $key => $row) {
  2710. $this->updateRangOfLine($row, ($key + 1));
  2711. }
  2712. }
  2713. } else {
  2714. dol_print_error($this->db);
  2715. }
  2716. }
  2717. return 1;
  2718. }
  2719. /**
  2720. * Get children of line
  2721. *
  2722. * @param int $id Id of parent line
  2723. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2724. * @return array Array with list of children lines id
  2725. */
  2726. public function getChildrenOfLine($id, $includealltree = 0)
  2727. {
  2728. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2729. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2730. $fieldposition = 'position';
  2731. }
  2732. $rows = array();
  2733. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2734. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2735. $sql .= ' AND fk_parent_line = '.((int) $id);
  2736. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2737. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2738. $resql = $this->db->query($sql);
  2739. if ($resql) {
  2740. if ($this->db->num_rows($resql) > 0) {
  2741. while ($row = $this->db->fetch_row($resql)) {
  2742. $rows[] = $row[0];
  2743. if (!empty($includealltree)) {
  2744. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2745. }
  2746. }
  2747. }
  2748. }
  2749. return $rows;
  2750. }
  2751. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2752. /**
  2753. * Update a line to have a lower rank
  2754. *
  2755. * @param int $rowid Id of line
  2756. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2757. * @return void
  2758. */
  2759. public function line_up($rowid, $fk_parent_line = true)
  2760. {
  2761. // phpcs:enable
  2762. $this->line_order(false, 'ASC', $fk_parent_line);
  2763. // Get rang of line
  2764. $rang = $this->getRangOfLine($rowid);
  2765. // Update position of line
  2766. $this->updateLineUp($rowid, $rang);
  2767. }
  2768. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2769. /**
  2770. * Update a line to have a higher rank
  2771. *
  2772. * @param int $rowid Id of line
  2773. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2774. * @return void
  2775. */
  2776. public function line_down($rowid, $fk_parent_line = true)
  2777. {
  2778. // phpcs:enable
  2779. $this->line_order(false, 'ASC', $fk_parent_line);
  2780. // Get rang of line
  2781. $rang = $this->getRangOfLine($rowid);
  2782. // Get max value for rang
  2783. $max = $this->line_max();
  2784. // Update position of line
  2785. $this->updateLineDown($rowid, $rang, $max);
  2786. }
  2787. /**
  2788. * Update position of line (rang)
  2789. *
  2790. * @param int $rowid Id of line
  2791. * @param int $rang Position
  2792. * @return int <0 if KO, >0 if OK
  2793. */
  2794. public function updateRangOfLine($rowid, $rang)
  2795. {
  2796. global $hookmanager;
  2797. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2798. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2799. $fieldposition = 'position';
  2800. }
  2801. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2802. $sql .= ' WHERE rowid = '.((int) $rowid);
  2803. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2804. if (!$this->db->query($sql)) {
  2805. dol_print_error($this->db);
  2806. return -1;
  2807. } else {
  2808. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2809. $action='';
  2810. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2811. return 1;
  2812. }
  2813. }
  2814. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2815. /**
  2816. * Update position of line with ajax (rang)
  2817. *
  2818. * @param array $rows Array of rows
  2819. * @return void
  2820. */
  2821. public function line_ajaxorder($rows)
  2822. {
  2823. // phpcs:enable
  2824. $num = count($rows);
  2825. for ($i = 0; $i < $num; $i++) {
  2826. $this->updateRangOfLine($rows[$i], ($i + 1));
  2827. }
  2828. }
  2829. /**
  2830. * Update position of line up (rang)
  2831. *
  2832. * @param int $rowid Id of line
  2833. * @param int $rang Position
  2834. * @return void
  2835. */
  2836. public function updateLineUp($rowid, $rang)
  2837. {
  2838. if ($rang > 1) {
  2839. $fieldposition = 'rang';
  2840. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2841. $fieldposition = 'position';
  2842. }
  2843. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2844. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2845. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2846. if ($this->db->query($sql)) {
  2847. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2848. $sql .= ' WHERE rowid = '.((int) $rowid);
  2849. if (!$this->db->query($sql)) {
  2850. dol_print_error($this->db);
  2851. }
  2852. } else {
  2853. dol_print_error($this->db);
  2854. }
  2855. }
  2856. }
  2857. /**
  2858. * Update position of line down (rang)
  2859. *
  2860. * @param int $rowid Id of line
  2861. * @param int $rang Position
  2862. * @param int $max Max
  2863. * @return void
  2864. */
  2865. public function updateLineDown($rowid, $rang, $max)
  2866. {
  2867. if ($rang < $max) {
  2868. $fieldposition = 'rang';
  2869. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2870. $fieldposition = 'position';
  2871. }
  2872. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2873. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2874. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2875. if ($this->db->query($sql)) {
  2876. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2877. $sql .= ' WHERE rowid = '.((int) $rowid);
  2878. if (!$this->db->query($sql)) {
  2879. dol_print_error($this->db);
  2880. }
  2881. } else {
  2882. dol_print_error($this->db);
  2883. }
  2884. }
  2885. }
  2886. /**
  2887. * Get position of line (rang)
  2888. *
  2889. * @param int $rowid Id of line
  2890. * @return int Value of rang in table of lines
  2891. */
  2892. public function getRangOfLine($rowid)
  2893. {
  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 = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  2899. $sql .= " WHERE rowid = ".((int) $rowid);
  2900. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2901. $resql = $this->db->query($sql);
  2902. if ($resql) {
  2903. $row = $this->db->fetch_row($resql);
  2904. return $row[0];
  2905. }
  2906. }
  2907. /**
  2908. * Get rowid of the line relative to its position
  2909. *
  2910. * @param int $rang Rang value
  2911. * @return int Rowid of the line
  2912. */
  2913. public function getIdOfLine($rang)
  2914. {
  2915. $fieldposition = 'rang';
  2916. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2917. $fieldposition = 'position';
  2918. }
  2919. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2920. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2921. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  2922. $resql = $this->db->query($sql);
  2923. if ($resql) {
  2924. $row = $this->db->fetch_row($resql);
  2925. return $row[0];
  2926. }
  2927. }
  2928. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2929. /**
  2930. * Get max value used for position of line (rang)
  2931. *
  2932. * @param int $fk_parent_line Parent line id
  2933. * @return int Max value of rang in table of lines
  2934. */
  2935. public function line_max($fk_parent_line = 0)
  2936. {
  2937. // phpcs:enable
  2938. $positionfield = 'rang';
  2939. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  2940. $positionfield = 'position';
  2941. }
  2942. // Search the last rang with fk_parent_line
  2943. if ($fk_parent_line) {
  2944. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2945. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2946. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  2947. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2948. $resql = $this->db->query($sql);
  2949. if ($resql) {
  2950. $row = $this->db->fetch_row($resql);
  2951. if (!empty($row[0])) {
  2952. return $row[0];
  2953. } else {
  2954. return $this->getRangOfLine($fk_parent_line);
  2955. }
  2956. }
  2957. } else {
  2958. // If not, search the last rang of element
  2959. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  2960. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2961. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2962. $resql = $this->db->query($sql);
  2963. if ($resql) {
  2964. $row = $this->db->fetch_row($resql);
  2965. return $row[0];
  2966. }
  2967. }
  2968. }
  2969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2970. /**
  2971. * Update external ref of element
  2972. *
  2973. * @param string $ref_ext Update field ref_ext
  2974. * @return int <0 if KO, >0 if OK
  2975. */
  2976. public function update_ref_ext($ref_ext)
  2977. {
  2978. // phpcs:enable
  2979. if (!$this->table_element) {
  2980. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2981. return -1;
  2982. }
  2983. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2984. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2985. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  2986. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2987. if ($this->db->query($sql)) {
  2988. $this->ref_ext = $ref_ext;
  2989. return 1;
  2990. } else {
  2991. $this->error = $this->db->error();
  2992. return -1;
  2993. }
  2994. }
  2995. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2996. /**
  2997. * Update note of element
  2998. *
  2999. * @param string $note New value for note
  3000. * @param string $suffix '', '_public' or '_private'
  3001. * @return int <0 if KO, >0 if OK
  3002. */
  3003. public function update_note($note, $suffix = '')
  3004. {
  3005. // phpcs:enable
  3006. global $user;
  3007. if (!$this->table_element) {
  3008. $this->error = 'update_note was called on objet with property table_element not defined';
  3009. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  3010. return -1;
  3011. }
  3012. if (!in_array($suffix, array('', '_public', '_private'))) {
  3013. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3014. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3015. return -2;
  3016. }
  3017. $newsuffix = $suffix;
  3018. // Special cas
  3019. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3020. $newsuffix = '';
  3021. }
  3022. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3023. $fieldusermod = "fk_user_mod";
  3024. } elseif ($this->table_element == 'ecm_files') {
  3025. $fieldusermod = "fk_user_m";
  3026. } else {
  3027. $fieldusermod = "fk_user_modif";
  3028. }
  3029. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3030. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  3031. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  3032. $sql .= " WHERE rowid = ".((int) $this->id);
  3033. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  3034. if ($this->db->query($sql)) {
  3035. if ($suffix == '_public') {
  3036. $this->note_public = $note;
  3037. } elseif ($suffix == '_private') {
  3038. $this->note_private = $note;
  3039. } else {
  3040. $this->note = $note; // deprecated
  3041. $this->note_private = $note;
  3042. }
  3043. return 1;
  3044. } else {
  3045. $this->error = $this->db->lasterror();
  3046. return -1;
  3047. }
  3048. }
  3049. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3050. /**
  3051. * Update public note (kept for backward compatibility)
  3052. *
  3053. * @param string $note New value for note
  3054. * @return int <0 if KO, >0 if OK
  3055. * @deprecated
  3056. * @see update_note()
  3057. */
  3058. public function update_note_public($note)
  3059. {
  3060. // phpcs:enable
  3061. return $this->update_note($note, '_public');
  3062. }
  3063. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3064. /**
  3065. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3066. * Must be called at end of methods addline or updateline.
  3067. *
  3068. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3069. * @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
  3070. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  3071. * @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).
  3072. * @return int <0 if KO, >0 if OK
  3073. */
  3074. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3075. {
  3076. // phpcs:enable
  3077. global $conf, $hookmanager, $action;
  3078. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3079. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3080. if ($reshook > 0) {
  3081. return 1; // replacement code
  3082. } elseif ($reshook < 0) {
  3083. return -1; // failure
  3084. } // reshook = 0 => execute normal code
  3085. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3086. $MODULE = "";
  3087. if ($this->element == 'propal') {
  3088. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3089. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3090. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3091. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3092. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3093. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3094. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3095. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3096. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3097. } elseif ($this->element == 'supplier_proposal') {
  3098. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3099. }
  3100. if (!empty($MODULE)) {
  3101. if (!empty($conf->global->$MODULE)) {
  3102. $modsactivated = explode(',', $conf->global->$MODULE);
  3103. foreach ($modsactivated as $mod) {
  3104. if ($conf->$mod->enabled) {
  3105. return 1; // update was disabled by specific setup
  3106. }
  3107. }
  3108. }
  3109. }
  3110. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3111. if ($roundingadjust == '-1') {
  3112. $roundingadjust = 'auto'; // For backward compatibility
  3113. }
  3114. $forcedroundingmode = $roundingadjust;
  3115. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3116. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  3117. } elseif ($forcedroundingmode == 'auto') {
  3118. $forcedroundingmode = '0';
  3119. }
  3120. $error = 0;
  3121. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3122. // Define constants to find lines to sum
  3123. $fieldtva = 'total_tva';
  3124. $fieldlocaltax1 = 'total_localtax1';
  3125. $fieldlocaltax2 = 'total_localtax2';
  3126. $fieldup = 'subprice';
  3127. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3128. $fieldtva = 'tva';
  3129. $fieldup = 'pu_ht';
  3130. }
  3131. if ($this->element == 'invoice_supplier_rec') {
  3132. $fieldup = 'pu_ht';
  3133. }
  3134. if ($this->element == 'expensereport') {
  3135. $fieldup = 'value_unit';
  3136. }
  3137. $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,";
  3138. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3139. if ($this->table_element_line == 'facturedet') {
  3140. $sql .= ', situation_percent';
  3141. }
  3142. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3143. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3144. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3145. if ($exclspec) {
  3146. $product_field = 'product_type';
  3147. if ($this->table_element_line == 'contratdet') {
  3148. $product_field = ''; // contratdet table has no product_type field
  3149. }
  3150. if ($product_field) {
  3151. $sql .= " AND ".$product_field." <> 9";
  3152. }
  3153. }
  3154. $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
  3155. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3156. $resql = $this->db->query($sql);
  3157. if ($resql) {
  3158. $this->total_ht = 0;
  3159. $this->total_tva = 0;
  3160. $this->total_localtax1 = 0;
  3161. $this->total_localtax2 = 0;
  3162. $this->total_ttc = 0;
  3163. $total_ht_by_vats = array();
  3164. $total_tva_by_vats = array();
  3165. $total_ttc_by_vats = array();
  3166. $this->multicurrency_total_ht = 0;
  3167. $this->multicurrency_total_tva = 0;
  3168. $this->multicurrency_total_ttc = 0;
  3169. $num = $this->db->num_rows($resql);
  3170. $i = 0;
  3171. while ($i < $num) {
  3172. $obj = $this->db->fetch_object($resql);
  3173. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3174. $parameters = array('fk_element' => $obj->rowid);
  3175. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3176. 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'
  3177. // This part of code is to fix data. We should not call it too often.
  3178. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3179. $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);
  3180. $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.
  3181. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3182. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3183. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3184. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3185. $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);
  3186. 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);
  3187. $resqlfix = $this->db->query($sqlfix);
  3188. if (!$resqlfix) {
  3189. dol_print_error($this->db, 'Failed to update line');
  3190. }
  3191. $obj->total_tva = $tmpcal[1];
  3192. $obj->total_ttc = $tmpcal[2];
  3193. }
  3194. }
  3195. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3196. $this->total_tva += $obj->total_tva;
  3197. $this->total_localtax1 += $obj->total_localtax1;
  3198. $this->total_localtax2 += $obj->total_localtax2;
  3199. $this->total_ttc += $obj->total_ttc;
  3200. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3201. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3202. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3203. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3204. $total_ht_by_vats[$obj->vatrate] = 0;
  3205. }
  3206. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3207. $total_tva_by_vats[$obj->vatrate] = 0;
  3208. }
  3209. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3210. $total_ttc_by_vats[$obj->vatrate] = 0;
  3211. }
  3212. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3213. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3214. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3215. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3216. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3217. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3218. //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";
  3219. if ($diff) {
  3220. if (abs($diff) > 0.1) {
  3221. $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.';
  3222. dol_syslog($errmsg, LOG_WARNING);
  3223. dol_print_error('', $errmsg);
  3224. exit;
  3225. }
  3226. $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);
  3227. 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);
  3228. $resqlfix = $this->db->query($sqlfix);
  3229. if (!$resqlfix) {
  3230. dol_print_error($this->db, 'Failed to update line');
  3231. }
  3232. $this->total_tva -= $diff;
  3233. $this->total_ttc -= $diff;
  3234. $total_tva_by_vats[$obj->vatrate] -= $diff;
  3235. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  3236. }
  3237. }
  3238. $i++;
  3239. }
  3240. // Add revenue stamp to total
  3241. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3242. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3243. // Situations totals
  3244. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3245. $prev_sits = $this->get_prev_sits();
  3246. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3247. $this->total_ht -= $sit->total_ht;
  3248. $this->total_tva -= $sit->total_tva;
  3249. $this->total_localtax1 -= $sit->total_localtax1;
  3250. $this->total_localtax2 -= $sit->total_localtax2;
  3251. $this->total_ttc -= $sit->total_ttc;
  3252. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3253. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3254. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3255. }
  3256. }
  3257. $this->db->free($resql);
  3258. // Now update global field total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
  3259. $fieldht = 'total_ht';
  3260. $fieldtva = 'tva';
  3261. $fieldlocaltax1 = 'localtax1';
  3262. $fieldlocaltax2 = 'localtax2';
  3263. $fieldttc = 'total_ttc';
  3264. // Specific code for backward compatibility with old field names
  3265. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3266. $fieldtva = 'total_tva';
  3267. }
  3268. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3269. $fieldtva = 'total_tva';
  3270. }
  3271. if ($this->element == 'propal') {
  3272. $fieldtva = 'total_tva';
  3273. }
  3274. if ($this->element == 'expensereport') {
  3275. $fieldtva = 'total_tva';
  3276. }
  3277. if ($this->element == 'supplier_proposal') {
  3278. $fieldtva = 'total_tva';
  3279. }
  3280. if ($this->element == 'commande') {
  3281. $fieldtva = 'total_tva';
  3282. }
  3283. if ($this->element == 'order_supplier') {
  3284. $fieldtva = 'total_tva';
  3285. }
  3286. if (empty($nodatabaseupdate)) {
  3287. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3288. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht)).",";
  3289. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva)).",";
  3290. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1)).",";
  3291. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2)).",";
  3292. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc));
  3293. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3294. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3295. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3296. $sql .= " WHERE rowid = ".((int) $this->id);
  3297. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3298. $resql = $this->db->query($sql);
  3299. if (!$resql) {
  3300. $error++;
  3301. $this->error = $this->db->lasterror();
  3302. $this->errors[] = $this->db->lasterror();
  3303. }
  3304. }
  3305. if (!$error) {
  3306. return 1;
  3307. } else {
  3308. return -1;
  3309. }
  3310. } else {
  3311. dol_print_error($this->db, 'Bad request in update_price');
  3312. return -1;
  3313. }
  3314. }
  3315. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3316. /**
  3317. * Add objects linked in llx_element_element.
  3318. *
  3319. * @param string $origin Linked element type
  3320. * @param int $origin_id Linked element id
  3321. * @param User $f_user User that create
  3322. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3323. * @return int <=0 if KO, >0 if OK
  3324. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3325. */
  3326. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3327. {
  3328. // phpcs:enable
  3329. global $user, $hookmanager, $action;
  3330. $origin = (!empty($origin) ? $origin : $this->origin);
  3331. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3332. $f_user = isset($f_user) ? $f_user : $user;
  3333. // Special case
  3334. if ($origin == 'order') {
  3335. $origin = 'commande';
  3336. }
  3337. if ($origin == 'invoice') {
  3338. $origin = 'facture';
  3339. }
  3340. if ($origin == 'invoice_template') {
  3341. $origin = 'facturerec';
  3342. }
  3343. if ($origin == 'supplierorder') {
  3344. $origin = 'order_supplier';
  3345. }
  3346. // 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.
  3347. // 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.
  3348. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3349. // Add module part to target type if object has $module property and isn't in core modules.
  3350. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3351. $parameters = array('targettype'=>$targettype);
  3352. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3353. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3354. if ($reshook > 0) {
  3355. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3356. }
  3357. $this->db->begin();
  3358. $error = 0;
  3359. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3360. $sql .= "fk_source";
  3361. $sql .= ", sourcetype";
  3362. $sql .= ", fk_target";
  3363. $sql .= ", targettype";
  3364. $sql .= ") VALUES (";
  3365. $sql .= ((int) $origin_id);
  3366. $sql .= ", '" . $this->db->escape($origin) . "'";
  3367. $sql .= ", " . ((int) $this->id);
  3368. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3369. $sql .= ")";
  3370. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3371. if ($this->db->query($sql)) {
  3372. if (!$notrigger) {
  3373. // Call trigger
  3374. $this->context['link_origin'] = $origin;
  3375. $this->context['link_origin_id'] = $origin_id;
  3376. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3377. if ($result < 0) {
  3378. $error++;
  3379. }
  3380. // End call triggers
  3381. }
  3382. } else {
  3383. $this->error = $this->db->lasterror();
  3384. $error++;
  3385. }
  3386. if (!$error) {
  3387. $this->db->commit();
  3388. return 1;
  3389. } else {
  3390. $this->db->rollback();
  3391. return 0;
  3392. }
  3393. }
  3394. /**
  3395. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3396. * this->linkedObjectsIds array +
  3397. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3398. * Possible usage for parameters:
  3399. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3400. * - source id+type -> will get list of targets linked to source
  3401. * - target id+type -> will get list of sources linked to target
  3402. * - source id+type + target type -> will get list of targets of the type linked to source
  3403. * - target id+type + source type -> will get list of sources of the type linked to target
  3404. *
  3405. * @param int $sourceid Object source id (if not defined, id of object)
  3406. * @param string $sourcetype Object source type (if not defined, element name of object)
  3407. * @param int $targetid Object target id (if not defined, id of object)
  3408. * @param string $targettype Object target type (if not defined, element name of object)
  3409. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3410. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3411. * @param string $orderby SQL 'ORDER BY' clause
  3412. * @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.
  3413. * @return int <0 if KO, >0 if OK
  3414. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3415. */
  3416. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3417. {
  3418. global $conf, $hookmanager, $action;
  3419. // Important for pdf generation time reduction
  3420. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3421. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3422. return 1;
  3423. }
  3424. $this->linkedObjectsIds = array();
  3425. $this->linkedObjects = array();
  3426. $justsource = false;
  3427. $justtarget = false;
  3428. $withtargettype = false;
  3429. $withsourcetype = false;
  3430. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3431. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3432. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3433. if ($reshook > 0) {
  3434. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3435. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3436. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3437. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3438. }
  3439. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3440. $justsource = true; // the source (id and type) is a search criteria
  3441. if (!empty($targettype)) {
  3442. $withtargettype = true;
  3443. }
  3444. }
  3445. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3446. $justtarget = true; // the target (id and type) is a search criteria
  3447. if (!empty($sourcetype)) {
  3448. $withsourcetype = true;
  3449. }
  3450. }
  3451. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3452. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3453. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3454. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3455. /*if (empty($sourceid) && empty($targetid))
  3456. {
  3457. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3458. return -1;
  3459. }*/
  3460. // Links between objects are stored in table element_element
  3461. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3462. $sql .= " FROM ".$this->db->prefix()."element_element";
  3463. $sql .= " WHERE ";
  3464. if ($justsource || $justtarget) {
  3465. if ($justsource) {
  3466. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3467. if ($withtargettype) {
  3468. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3469. }
  3470. } elseif ($justtarget) {
  3471. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3472. if ($withsourcetype) {
  3473. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3474. }
  3475. }
  3476. } else {
  3477. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3478. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3479. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3480. $this->linkedObjectsFullLoaded[$this->id] = true;
  3481. }
  3482. }
  3483. $sql .= " ORDER BY ".$orderby;
  3484. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3485. $resql = $this->db->query($sql);
  3486. if ($resql) {
  3487. $num = $this->db->num_rows($resql);
  3488. $i = 0;
  3489. while ($i < $num) {
  3490. $obj = $this->db->fetch_object($resql);
  3491. if ($justsource || $justtarget) {
  3492. if ($justsource) {
  3493. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3494. } elseif ($justtarget) {
  3495. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3496. }
  3497. } else {
  3498. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3499. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3500. }
  3501. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3502. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3503. }
  3504. }
  3505. $i++;
  3506. }
  3507. if (!empty($this->linkedObjectsIds)) {
  3508. $tmparray = $this->linkedObjectsIds;
  3509. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3510. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3511. $module = $element = $subelement = $objecttype;
  3512. $regs = array();
  3513. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3514. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3515. $module = $element = $regs[1];
  3516. $subelement = $regs[2];
  3517. }
  3518. $classpath = $element.'/class';
  3519. // To work with non standard classpath or module name
  3520. if ($objecttype == 'facture') {
  3521. $classpath = 'compta/facture/class';
  3522. } elseif ($objecttype == 'facturerec') {
  3523. $classpath = 'compta/facture/class';
  3524. $module = 'facture';
  3525. } elseif ($objecttype == 'propal') {
  3526. $classpath = 'comm/propal/class';
  3527. } elseif ($objecttype == 'supplier_proposal') {
  3528. $classpath = 'supplier_proposal/class';
  3529. } elseif ($objecttype == 'shipping') {
  3530. $classpath = 'expedition/class';
  3531. $subelement = 'expedition';
  3532. $module = 'expedition_bon';
  3533. } elseif ($objecttype == 'delivery') {
  3534. $classpath = 'delivery/class';
  3535. $subelement = 'delivery';
  3536. $module = 'delivery_note';
  3537. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3538. $classpath = 'fourn/class';
  3539. $module = 'fournisseur';
  3540. } elseif ($objecttype == 'fichinter') {
  3541. $classpath = 'fichinter/class';
  3542. $subelement = 'fichinter';
  3543. $module = 'ficheinter';
  3544. } elseif ($objecttype == 'subscription') {
  3545. $classpath = 'adherents/class';
  3546. $module = 'adherent';
  3547. } elseif ($objecttype == 'contact') {
  3548. $module = 'societe';
  3549. }
  3550. // Set classfile
  3551. $classfile = strtolower($subelement);
  3552. $classname = ucfirst($subelement);
  3553. if ($objecttype == 'order') {
  3554. $classfile = 'commande';
  3555. $classname = 'Commande';
  3556. } elseif ($objecttype == 'invoice_supplier') {
  3557. $classfile = 'fournisseur.facture';
  3558. $classname = 'FactureFournisseur';
  3559. } elseif ($objecttype == 'order_supplier') {
  3560. $classfile = 'fournisseur.commande';
  3561. $classname = 'CommandeFournisseur';
  3562. } elseif ($objecttype == 'supplier_proposal') {
  3563. $classfile = 'supplier_proposal';
  3564. $classname = 'SupplierProposal';
  3565. } elseif ($objecttype == 'facturerec') {
  3566. $classfile = 'facture-rec';
  3567. $classname = 'FactureRec';
  3568. } elseif ($objecttype == 'subscription') {
  3569. $classfile = 'subscription';
  3570. $classname = 'Subscription';
  3571. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3572. $classpath = 'projet/class';
  3573. $classfile = 'project';
  3574. $classname = 'Project';
  3575. } elseif ($objecttype == 'conferenceorboothattendee') {
  3576. $classpath = 'eventorganization/class';
  3577. $classfile = 'conferenceorboothattendee';
  3578. $classname = 'ConferenceOrBoothAttendee';
  3579. $module = 'eventorganization';
  3580. } elseif ($objecttype == 'conferenceorbooth') {
  3581. $classpath = 'eventorganization/class';
  3582. $classfile = 'conferenceorbooth';
  3583. $classname = 'ConferenceOrBooth';
  3584. $module = 'eventorganization';
  3585. } elseif ($objecttype == 'mo') {
  3586. $classpath = 'mrp/class';
  3587. $classfile = 'mo';
  3588. $classname = 'Mo';
  3589. $module = 'mrp';
  3590. }
  3591. // Here $module, $classfile and $classname are set, we can use them.
  3592. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3593. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3594. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3595. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3596. if (class_exists($classname)) {
  3597. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3598. $object = new $classname($this->db);
  3599. $ret = $object->fetch($objectid);
  3600. if ($ret >= 0) {
  3601. $this->linkedObjects[$objecttype][$i] = $object;
  3602. }
  3603. }
  3604. }
  3605. }
  3606. } else {
  3607. unset($this->linkedObjectsIds[$objecttype]);
  3608. }
  3609. }
  3610. }
  3611. return 1;
  3612. } else {
  3613. dol_print_error($this->db);
  3614. return -1;
  3615. }
  3616. }
  3617. /**
  3618. * Update object linked of a current object
  3619. *
  3620. * @param int $sourceid Object source id
  3621. * @param string $sourcetype Object source type
  3622. * @param int $targetid Object target id
  3623. * @param string $targettype Object target type
  3624. * @param User $f_user User that create
  3625. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3626. * @return int >0 if OK, <0 if KO
  3627. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3628. */
  3629. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3630. {
  3631. global $user;
  3632. $updatesource = false;
  3633. $updatetarget = false;
  3634. $f_user = isset($f_user) ? $f_user : $user;
  3635. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3636. $updatesource = true;
  3637. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3638. $updatetarget = true;
  3639. }
  3640. $this->db->begin();
  3641. $error = 0;
  3642. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3643. if ($updatesource) {
  3644. $sql .= "fk_source = " . ((int) $sourceid);
  3645. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3646. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3647. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3648. } elseif ($updatetarget) {
  3649. $sql .= "fk_target = " . ((int) $targetid);
  3650. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3651. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3652. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3653. }
  3654. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3655. if ($this->db->query($sql)) {
  3656. if (!$notrigger) {
  3657. // Call trigger
  3658. $this->context['link_source_id'] = $sourceid;
  3659. $this->context['link_source_type'] = $sourcetype;
  3660. $this->context['link_target_id'] = $targetid;
  3661. $this->context['link_target_type'] = $targettype;
  3662. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3663. if ($result < 0) {
  3664. $error++;
  3665. }
  3666. // End call triggers
  3667. }
  3668. } else {
  3669. $this->error = $this->db->lasterror();
  3670. $error++;
  3671. }
  3672. if (!$error) {
  3673. $this->db->commit();
  3674. return 1;
  3675. } else {
  3676. $this->db->rollback();
  3677. return -1;
  3678. }
  3679. }
  3680. /**
  3681. * Delete all links between an object $this
  3682. *
  3683. * @param int $sourceid Object source id
  3684. * @param string $sourcetype Object source type
  3685. * @param int $targetid Object target id
  3686. * @param string $targettype Object target type
  3687. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3688. * @param User $f_user User that create
  3689. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3690. * @return int >0 if OK, <0 if KO
  3691. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3692. */
  3693. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3694. {
  3695. global $user;
  3696. $deletesource = false;
  3697. $deletetarget = false;
  3698. $f_user = isset($f_user) ? $f_user : $user;
  3699. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3700. $deletesource = true;
  3701. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3702. $deletetarget = true;
  3703. }
  3704. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3705. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3706. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3707. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3708. $this->db->begin();
  3709. $error = 0;
  3710. if (!$notrigger) {
  3711. // Call trigger
  3712. $this->context['link_id'] = $rowid;
  3713. $this->context['link_source_id'] = $sourceid;
  3714. $this->context['link_source_type'] = $sourcetype;
  3715. $this->context['link_target_id'] = $targetid;
  3716. $this->context['link_target_type'] = $targettype;
  3717. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3718. if ($result < 0) {
  3719. $error++;
  3720. }
  3721. // End call triggers
  3722. }
  3723. if (!$error) {
  3724. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3725. $sql .= " WHERE";
  3726. if ($rowid > 0) {
  3727. $sql .= " rowid = " . ((int) $rowid);
  3728. } else {
  3729. if ($deletesource) {
  3730. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3731. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3732. } elseif ($deletetarget) {
  3733. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3734. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3735. } else {
  3736. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3737. $sql .= " OR";
  3738. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3739. }
  3740. }
  3741. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3742. if (!$this->db->query($sql)) {
  3743. $this->error = $this->db->lasterror();
  3744. $this->errors[] = $this->error;
  3745. $error++;
  3746. }
  3747. }
  3748. if (!$error) {
  3749. $this->db->commit();
  3750. return 1;
  3751. } else {
  3752. $this->db->rollback();
  3753. return 0;
  3754. }
  3755. }
  3756. /**
  3757. * Function used to get an array with all items linked to an object id in association table
  3758. *
  3759. * @param int $fk_object_where id of object we need to get linked items
  3760. * @param string $field_select name of field we need to get a list
  3761. * @param string $field_where name of field of object we need to get linked items
  3762. * @param string $table_element name of association table
  3763. * @return array Array of record
  3764. */
  3765. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3766. {
  3767. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3768. return -1;
  3769. }
  3770. global $db;
  3771. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3772. $resql = $db->query($sql);
  3773. $TRes = array();
  3774. if (!empty($resql)) {
  3775. while ($res = $db->fetch_object($resql)) {
  3776. $TRes[] = $res->{$field_select};
  3777. }
  3778. }
  3779. return $TRes;
  3780. }
  3781. /**
  3782. * Function used to remove all items linked to an object id in association table
  3783. *
  3784. * @param int $fk_object_where id of object we need to remove linked items
  3785. * @param string $field_where name of field of object we need to delete linked items
  3786. * @param string $table_element name of association table
  3787. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3788. */
  3789. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3790. {
  3791. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3792. return -1;
  3793. }
  3794. global $db;
  3795. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3796. $resql = $db->query($sql);
  3797. if (empty($resql)) {
  3798. return 0;
  3799. }
  3800. return 1;
  3801. }
  3802. /**
  3803. * Set status of an object
  3804. *
  3805. * @param int $status Status to set
  3806. * @param int $elementId Id of element to force (use this->id by default if null)
  3807. * @param string $elementType Type of element to force (use this->table_element by default)
  3808. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it not recommended and is deprecated.
  3809. * @param string $fieldstatus Name of status field in this->table_element
  3810. * @return int <0 if KO, >0 if OK
  3811. */
  3812. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3813. {
  3814. global $user, $langs, $conf;
  3815. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3816. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3817. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3818. $this->db->begin();
  3819. if ($elementTable == 'facture_rec') {
  3820. $fieldstatus = "suspended";
  3821. }
  3822. if ($elementTable == 'mailing') {
  3823. $fieldstatus = "statut";
  3824. }
  3825. if ($elementTable == 'cronjob') {
  3826. $fieldstatus = "status";
  3827. }
  3828. if ($elementTable == 'user') {
  3829. $fieldstatus = "statut";
  3830. }
  3831. if ($elementTable == 'expensereport') {
  3832. $fieldstatus = "fk_statut";
  3833. }
  3834. if ($elementTable == 'commande_fournisseur_dispatch') {
  3835. $fieldstatus = "status";
  3836. }
  3837. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3838. $fieldstatus = 'status';
  3839. }
  3840. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3841. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3842. // If status = 1 = validated, update also fk_user_valid
  3843. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3844. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3845. $sql .= ", fk_user_valid = ".((int) $user->id);
  3846. }
  3847. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3848. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3849. }
  3850. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3851. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3852. }
  3853. $sql .= " WHERE rowid=".((int) $elementId);
  3854. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3855. if ($this->db->query($sql)) {
  3856. $error = 0;
  3857. // Try autoset of trigkey
  3858. if (empty($trigkey)) {
  3859. if ($this->element == 'supplier_proposal' && $status == 2) {
  3860. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3861. }
  3862. if ($this->element == 'supplier_proposal' && $status == 3) {
  3863. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3864. }
  3865. if ($this->element == 'supplier_proposal' && $status == 4) {
  3866. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3867. }
  3868. if ($this->element == 'fichinter' && $status == 3) {
  3869. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3870. }
  3871. if ($this->element == 'fichinter' && $status == 2) {
  3872. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3873. }
  3874. if ($this->element == 'fichinter' && $status == 1) {
  3875. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3876. }
  3877. }
  3878. if ($trigkey) {
  3879. // Call trigger
  3880. $result = $this->call_trigger($trigkey, $user);
  3881. if ($result < 0) {
  3882. $error++;
  3883. }
  3884. // End call triggers
  3885. }
  3886. if (!$error) {
  3887. $this->db->commit();
  3888. if (empty($savElementId)) {
  3889. // If the element we update is $this (so $elementId was provided as null)
  3890. if ($fieldstatus == 'tosell') {
  3891. $this->status = $status;
  3892. } elseif ($fieldstatus == 'tobuy') {
  3893. $this->status_buy = $status;
  3894. } else {
  3895. $this->statut = $status;
  3896. $this->status = $status;
  3897. }
  3898. }
  3899. return 1;
  3900. } else {
  3901. $this->db->rollback();
  3902. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3903. return -1;
  3904. }
  3905. } else {
  3906. $this->error = $this->db->lasterror();
  3907. $this->db->rollback();
  3908. return -1;
  3909. }
  3910. }
  3911. /**
  3912. * Load type of canvas of an object if it exists
  3913. *
  3914. * @param int $id Record id
  3915. * @param string $ref Record ref
  3916. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3917. */
  3918. public function getCanvas($id = 0, $ref = '')
  3919. {
  3920. global $conf;
  3921. if (empty($id) && empty($ref)) {
  3922. return 0;
  3923. }
  3924. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3925. return 0; // To increase speed. Not enabled by default.
  3926. }
  3927. // Clean parameters
  3928. $ref = trim($ref);
  3929. $sql = "SELECT rowid, canvas";
  3930. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  3931. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3932. if (!empty($id)) {
  3933. $sql .= " AND rowid = ".((int) $id);
  3934. }
  3935. if (!empty($ref)) {
  3936. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3937. }
  3938. $resql = $this->db->query($sql);
  3939. if ($resql) {
  3940. $obj = $this->db->fetch_object($resql);
  3941. if ($obj) {
  3942. $this->canvas = $obj->canvas;
  3943. return 1;
  3944. } else {
  3945. return 0;
  3946. }
  3947. } else {
  3948. dol_print_error($this->db);
  3949. return -1;
  3950. }
  3951. }
  3952. /**
  3953. * Get special code of a line
  3954. *
  3955. * @param int $lineid Id of line
  3956. * @return int Special code
  3957. */
  3958. public function getSpecialCode($lineid)
  3959. {
  3960. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  3961. $sql .= " WHERE rowid = ".((int) $lineid);
  3962. $resql = $this->db->query($sql);
  3963. if ($resql) {
  3964. $row = $this->db->fetch_row($resql);
  3965. return $row[0];
  3966. }
  3967. }
  3968. /**
  3969. * Function to check if an object is used by others.
  3970. * Check is done into this->childtables. There is no check into llx_element_element.
  3971. *
  3972. * @param int $id Force id of object
  3973. * @param int $entity Force entity to check
  3974. * @return int <0 if KO, 0 if not used, >0 if already used
  3975. */
  3976. public function isObjectUsed($id = 0, $entity = 0)
  3977. {
  3978. global $langs;
  3979. if (empty($id)) {
  3980. $id = $this->id;
  3981. }
  3982. // Check parameters
  3983. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3984. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3985. return -1;
  3986. }
  3987. $arraytoscan = $this->childtables;
  3988. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3989. $tmparray = array_keys($this->childtables);
  3990. if (is_numeric($tmparray[0])) {
  3991. $arraytoscan = array_flip($this->childtables);
  3992. }
  3993. // Test if child exists
  3994. $haschild = 0;
  3995. foreach ($arraytoscan as $table => $element) {
  3996. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3997. // Check if element can be deleted
  3998. $sql = "SELECT COUNT(*) as nb";
  3999. $sql.= " FROM ".$this->db->prefix().$table." as c";
  4000. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4001. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  4002. }
  4003. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  4004. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4005. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  4006. }
  4007. if (!empty($entity)) {
  4008. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4009. $sql.= " AND p.entity = ".((int) $entity);
  4010. } else {
  4011. $sql.= " AND c.entity = ".((int) $entity);
  4012. }
  4013. }
  4014. $resql = $this->db->query($sql);
  4015. if ($resql) {
  4016. $obj = $this->db->fetch_object($resql);
  4017. if ($obj->nb > 0) {
  4018. $langs->load("errors");
  4019. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4020. $haschild += $obj->nb;
  4021. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4022. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4023. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4024. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4025. } else { // new usage: $element['name']=Translation key
  4026. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4027. }
  4028. break; // We found at least one, we stop here
  4029. }
  4030. } else {
  4031. $this->errors[] = $this->db->lasterror();
  4032. return -1;
  4033. }
  4034. }
  4035. if ($haschild > 0) {
  4036. $this->errors[] = "ErrorRecordHasChildren";
  4037. return $haschild;
  4038. } else {
  4039. return 0;
  4040. }
  4041. }
  4042. /**
  4043. * Function to say how many lines object contains
  4044. *
  4045. * @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
  4046. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4047. */
  4048. public function hasProductsOrServices($predefined = -1)
  4049. {
  4050. $nb = 0;
  4051. foreach ($this->lines as $key => $val) {
  4052. $qualified = 0;
  4053. if ($predefined == -1) {
  4054. $qualified = 1;
  4055. }
  4056. if ($predefined == 1 && $val->fk_product > 0) {
  4057. $qualified = 1;
  4058. }
  4059. if ($predefined == 0 && $val->fk_product <= 0) {
  4060. $qualified = 1;
  4061. }
  4062. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4063. $qualified = 1;
  4064. }
  4065. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4066. $qualified = 1;
  4067. }
  4068. if ($qualified) {
  4069. $nb++;
  4070. }
  4071. }
  4072. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4073. return $nb;
  4074. }
  4075. /**
  4076. * Function that returns the total amount HT of discounts applied for all lines.
  4077. *
  4078. * @return float|string Total amout of discount
  4079. */
  4080. public function getTotalDiscount()
  4081. {
  4082. if (!empty($this->table_element_line) ) {
  4083. $total_discount = 0.00;
  4084. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4085. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4086. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4087. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4088. $resql = $this->db->query($sql);
  4089. if ($resql) {
  4090. $num = $this->db->num_rows($resql);
  4091. $i = 0;
  4092. while ($i < $num) {
  4093. $obj = $this->db->fetch_object($resql);
  4094. $pu_ht = $obj->pu_ht;
  4095. $qty = $obj->qty;
  4096. $total_ht = $obj->total_ht;
  4097. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4098. $total_discount += $total_discount_line;
  4099. $i++;
  4100. }
  4101. }
  4102. //print $total_discount; exit;
  4103. return price2num($total_discount);
  4104. }
  4105. return null;
  4106. }
  4107. /**
  4108. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4109. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4110. *
  4111. * @return array array('weight'=>...,'volume'=>...)
  4112. */
  4113. public function getTotalWeightVolume()
  4114. {
  4115. $totalWeight = 0;
  4116. $totalVolume = 0;
  4117. // defined for shipment only
  4118. $totalOrdered = '';
  4119. // defined for shipment only
  4120. $totalToShip = '';
  4121. foreach ($this->lines as $line) {
  4122. if (isset($line->qty_asked)) {
  4123. if (empty($totalOrdered)) {
  4124. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4125. }
  4126. $totalOrdered += $line->qty_asked; // defined for shipment only
  4127. }
  4128. if (isset($line->qty_shipped)) {
  4129. if (empty($totalToShip)) {
  4130. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4131. }
  4132. $totalToShip += $line->qty_shipped; // defined for shipment only
  4133. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4134. if (empty($totalToShip)) {
  4135. $totalToShip = 0;
  4136. }
  4137. $totalToShip += $line->qty; // defined for reception only
  4138. }
  4139. // Define qty, weight, volume, weight_units, volume_units
  4140. if ($this->element == 'shipping') {
  4141. // for shipments
  4142. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4143. } else {
  4144. $qty = $line->qty ? $line->qty : 0;
  4145. }
  4146. $weight = !empty($line->weight) ? $line->weight : 0;
  4147. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4148. $volume = !empty($line->volume) ? $line->volume : 0;
  4149. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4150. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4151. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4152. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4153. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4154. $weightUnit = 0;
  4155. $volumeUnit = 0;
  4156. if (!empty($weight_units)) {
  4157. $weightUnit = $weight_units;
  4158. }
  4159. if (!empty($volume_units)) {
  4160. $volumeUnit = $volume_units;
  4161. }
  4162. if (empty($totalWeight)) {
  4163. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4164. }
  4165. if (empty($totalVolume)) {
  4166. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4167. }
  4168. //var_dump($line->volume_units);
  4169. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4170. $trueWeightUnit = pow(10, $weightUnit);
  4171. $totalWeight += $weight * $qty * $trueWeightUnit;
  4172. } else {
  4173. if ($weight_units == 99) {
  4174. // conversion 1 Pound = 0.45359237 KG
  4175. $trueWeightUnit = 0.45359237;
  4176. $totalWeight += $weight * $qty * $trueWeightUnit;
  4177. } elseif ($weight_units == 98) {
  4178. // conversion 1 Ounce = 0.0283495 KG
  4179. $trueWeightUnit = 0.0283495;
  4180. $totalWeight += $weight * $qty * $trueWeightUnit;
  4181. } else {
  4182. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4183. }
  4184. }
  4185. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4186. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4187. $trueVolumeUnit = pow(10, $volumeUnit);
  4188. //print $line->volume;
  4189. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4190. } else {
  4191. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4192. }
  4193. }
  4194. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4195. }
  4196. /**
  4197. * Set extra parameters
  4198. *
  4199. * @return int <0 if KO, >0 if OK
  4200. */
  4201. public function setExtraParameters()
  4202. {
  4203. $this->db->begin();
  4204. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4205. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4206. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4207. $sql .= " WHERE rowid = ".((int) $this->id);
  4208. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4209. $resql = $this->db->query($sql);
  4210. if (!$resql) {
  4211. $this->error = $this->db->lasterror();
  4212. $this->db->rollback();
  4213. return -1;
  4214. } else {
  4215. $this->db->commit();
  4216. return 1;
  4217. }
  4218. }
  4219. // --------------------
  4220. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4221. // --------------------
  4222. /* This is to show add lines */
  4223. /**
  4224. * Show add free and predefined products/services form
  4225. *
  4226. * @param int $dateSelector 1=Show also date range input fields
  4227. * @param Societe $seller Object thirdparty who sell
  4228. * @param Societe $buyer Object thirdparty who buy
  4229. * @param string $defaulttpldir Directory where to find the template
  4230. * @return void
  4231. */
  4232. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4233. {
  4234. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4235. global $form;
  4236. // Line extrafield
  4237. if (!is_object($extrafields)) {
  4238. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4239. $extrafields = new ExtraFields($this->db);
  4240. }
  4241. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4242. // Output template part (modules that overwrite templates must declare this into descriptor)
  4243. // Use global variables + $dateSelector + $seller and $buyer
  4244. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4245. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4246. foreach ($dirtpls as $module => $reldir) {
  4247. if (!empty($module)) {
  4248. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4249. } else {
  4250. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4251. }
  4252. if (empty($conf->file->strict_mode)) {
  4253. $res = @include $tpl;
  4254. } else {
  4255. $res = include $tpl; // for debug
  4256. }
  4257. if ($res) {
  4258. break;
  4259. }
  4260. }
  4261. }
  4262. /* This is to show array of line of details */
  4263. /**
  4264. * Return HTML table for object lines
  4265. * TODO Move this into an output class file (htmlline.class.php)
  4266. * If lines are into a template, title must also be into a template
  4267. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4268. *
  4269. * @param string $action Action code
  4270. * @param string $seller Object of seller third party
  4271. * @param string $buyer Object of buyer third party
  4272. * @param int $selected Object line selected
  4273. * @param int $dateSelector 1=Show also date range input fields
  4274. * @param string $defaulttpldir Directory where to find the template
  4275. * @return void
  4276. */
  4277. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4278. {
  4279. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4280. // TODO We should not use global var for this
  4281. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4282. // Define usemargins
  4283. $usemargins = 0;
  4284. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4285. $usemargins = 1;
  4286. }
  4287. $num = count($this->lines);
  4288. // Line extrafield
  4289. if (!is_object($extrafields)) {
  4290. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4291. $extrafields = new ExtraFields($this->db);
  4292. }
  4293. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4294. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4295. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4296. if (empty($reshook)) {
  4297. // Output template part (modules that overwrite templates must declare this into descriptor)
  4298. // Use global variables + $dateSelector + $seller and $buyer
  4299. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4300. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4301. foreach ($dirtpls as $module => $reldir) {
  4302. if (!empty($module)) {
  4303. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4304. } else {
  4305. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4306. }
  4307. if (empty($conf->file->strict_mode)) {
  4308. $res = @include $tpl;
  4309. } else {
  4310. $res = include $tpl; // for debug
  4311. }
  4312. if ($res) {
  4313. break;
  4314. }
  4315. }
  4316. }
  4317. $i = 0;
  4318. print "<!-- begin printObjectLines() --><tbody>\n";
  4319. foreach ($this->lines as $line) {
  4320. //Line extrafield
  4321. $line->fetch_optionals();
  4322. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4323. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4324. if (empty($line->fk_parent_line)) {
  4325. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4326. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4327. } else {
  4328. $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);
  4329. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4330. }
  4331. }
  4332. if (empty($reshook)) {
  4333. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4334. }
  4335. $i++;
  4336. }
  4337. print "</tbody><!-- end printObjectLines() -->\n";
  4338. }
  4339. /**
  4340. * Return HTML content of a detail line
  4341. * TODO Move this into an output class file (htmlline.class.php)
  4342. *
  4343. * @param string $action GET/POST action
  4344. * @param CommonObjectLine $line Selected object line to output
  4345. * @param string $var Is it a an odd line (true)
  4346. * @param int $num Number of line (0)
  4347. * @param int $i I
  4348. * @param int $dateSelector 1=Show also date range input fields
  4349. * @param string $seller Object of seller third party
  4350. * @param string $buyer Object of buyer third party
  4351. * @param int $selected Object line selected
  4352. * @param Extrafields $extrafields Object of extrafields
  4353. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4354. * @return void
  4355. */
  4356. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4357. {
  4358. global $conf, $langs, $user, $object, $hookmanager;
  4359. global $form;
  4360. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4361. $object_rights = $this->getRights();
  4362. $element = $this->element;
  4363. $text = '';
  4364. $description = '';
  4365. // Line in view mode
  4366. if ($action != 'editline' || $selected != $line->id) {
  4367. // Product
  4368. if ($line->fk_product > 0) {
  4369. $product_static = new Product($this->db);
  4370. $product_static->fetch($line->fk_product);
  4371. $product_static->ref = $line->ref; //can change ref in hook
  4372. $product_static->label = $line->label; //can change label in hook
  4373. $text = $product_static->getNomUrl(1);
  4374. // Define output language and label
  4375. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4376. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4377. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4378. return;
  4379. }
  4380. $prod = new Product($this->db);
  4381. $prod->fetch($line->fk_product);
  4382. $outputlangs = $langs;
  4383. $newlang = '';
  4384. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4385. $newlang = GETPOST('lang_id', 'aZ09');
  4386. }
  4387. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4388. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4389. }
  4390. if (!empty($newlang)) {
  4391. $outputlangs = new Translate("", $conf);
  4392. $outputlangs->setDefaultLang($newlang);
  4393. }
  4394. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4395. } else {
  4396. $label = $line->product_label;
  4397. }
  4398. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4399. $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc.
  4400. }
  4401. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4402. // Output template part (modules that overwrite templates must declare this into descriptor)
  4403. // Use global variables + $dateSelector + $seller and $buyer
  4404. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4405. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4406. foreach ($dirtpls as $module => $reldir) {
  4407. if (!empty($module)) {
  4408. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4409. } else {
  4410. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4411. }
  4412. if (empty($conf->file->strict_mode)) {
  4413. $res = @include $tpl;
  4414. } else {
  4415. $res = include $tpl; // for debug
  4416. }
  4417. if ($res) {
  4418. break;
  4419. }
  4420. }
  4421. }
  4422. // Line in update mode
  4423. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4424. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4425. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4426. // Output template part (modules that overwrite templates must declare this into descriptor)
  4427. // Use global variables + $dateSelector + $seller and $buyer
  4428. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4429. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4430. foreach ($dirtpls as $module => $reldir) {
  4431. if (!empty($module)) {
  4432. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4433. } else {
  4434. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4435. }
  4436. if (empty($conf->file->strict_mode)) {
  4437. $res = @include $tpl;
  4438. } else {
  4439. $res = include $tpl; // for debug
  4440. }
  4441. if ($res) {
  4442. break;
  4443. }
  4444. }
  4445. }
  4446. }
  4447. /* This is to show array of line of details of source object */
  4448. /**
  4449. * Return HTML table table of source object lines
  4450. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4451. * If lines are into a template, title must also be into a template
  4452. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4453. *
  4454. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4455. * @param array $selectedLines Array of lines id for selected lines
  4456. * @return void
  4457. */
  4458. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4459. {
  4460. global $langs, $hookmanager, $conf, $form, $action;
  4461. print '<tr class="liste_titre">';
  4462. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4463. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4464. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4465. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4466. if (!empty($conf->multicurrency->enabled)) {
  4467. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4468. }
  4469. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4470. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4471. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4472. }
  4473. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4474. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4475. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4476. print '</tr>';
  4477. $i = 0;
  4478. if (!empty($this->lines)) {
  4479. foreach ($this->lines as $line) {
  4480. $reshook = 0;
  4481. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4482. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4483. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4484. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4485. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4486. }
  4487. if (empty($reshook)) {
  4488. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4489. }
  4490. $i++;
  4491. }
  4492. }
  4493. }
  4494. /**
  4495. * Return HTML with a line of table array of source object lines
  4496. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4497. * If lines are into a template, title must also be into a template
  4498. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4499. *
  4500. * @param CommonObjectLine $line Line
  4501. * @param string $var Var
  4502. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4503. * @param string $defaulttpldir Directory where to find the template
  4504. * @param array $selectedLines Array of lines id for selected lines
  4505. * @return void
  4506. */
  4507. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4508. {
  4509. global $langs, $conf;
  4510. //var_dump($line);
  4511. if (!empty($line->date_start)) {
  4512. $date_start = $line->date_start;
  4513. } else {
  4514. $date_start = $line->date_debut_prevue;
  4515. if ($line->date_debut_reel) {
  4516. $date_start = $line->date_debut_reel;
  4517. }
  4518. }
  4519. if (!empty($line->date_end)) {
  4520. $date_end = $line->date_end;
  4521. } else {
  4522. $date_end = $line->date_fin_prevue;
  4523. if ($line->date_fin_reel) {
  4524. $date_end = $line->date_fin_reel;
  4525. }
  4526. }
  4527. $this->tpl['id'] = $line->id;
  4528. $this->tpl['label'] = '';
  4529. if (!empty($line->fk_parent_line)) {
  4530. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4531. }
  4532. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4533. $discount = new DiscountAbsolute($this->db);
  4534. $discount->fk_soc = $this->socid;
  4535. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4536. } elseif (!empty($line->fk_product)) {
  4537. $productstatic = new Product($this->db);
  4538. $productstatic->id = $line->fk_product;
  4539. $productstatic->ref = $line->ref;
  4540. $productstatic->type = $line->fk_product_type;
  4541. if (empty($productstatic->ref)) {
  4542. $line->fetch_product();
  4543. $productstatic = $line->product;
  4544. }
  4545. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4546. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4547. // Dates
  4548. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4549. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4550. }
  4551. } else {
  4552. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4553. if (!empty($line->desc)) {
  4554. $this->tpl['label'] .= $line->desc;
  4555. } else {
  4556. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4557. }
  4558. // Dates
  4559. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4560. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4561. }
  4562. }
  4563. if (!empty($line->desc)) {
  4564. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4565. $discount = new DiscountAbsolute($this->db);
  4566. $discount->fetch($line->fk_remise_except);
  4567. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4568. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4569. $discount = new DiscountAbsolute($this->db);
  4570. $discount->fetch($line->fk_remise_except);
  4571. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4572. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4573. $discount = new DiscountAbsolute($this->db);
  4574. $discount->fetch($line->fk_remise_except);
  4575. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4576. } elseif ($line->desc == '(EXCESS PAID)') {
  4577. $discount = new DiscountAbsolute($this->db);
  4578. $discount->fetch($line->fk_remise_except);
  4579. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4580. } else {
  4581. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4582. }
  4583. } else {
  4584. $this->tpl['description'] = '&nbsp;';
  4585. }
  4586. // VAT Rate
  4587. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4588. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4589. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4590. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4591. }
  4592. $this->tpl['price'] = price($line->subprice);
  4593. $this->tpl['total_ht'] = price($line->total_ht);
  4594. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4595. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4596. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4597. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4598. }
  4599. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4600. // Is the line strike or not
  4601. $this->tpl['strike'] = 0;
  4602. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4603. $this->tpl['strike'] = 1;
  4604. }
  4605. // Output template part (modules that overwrite templates must declare this into descriptor)
  4606. // Use global variables + $dateSelector + $seller and $buyer
  4607. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4608. foreach ($dirtpls as $module => $reldir) {
  4609. if (!empty($module)) {
  4610. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4611. } else {
  4612. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4613. }
  4614. if (empty($conf->file->strict_mode)) {
  4615. $res = @include $tpl;
  4616. } else {
  4617. $res = include $tpl; // for debug
  4618. }
  4619. if ($res) {
  4620. break;
  4621. }
  4622. }
  4623. }
  4624. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4625. /**
  4626. * Add resources to the current object : add entry into llx_element_resources
  4627. * Need $this->element & $this->id
  4628. *
  4629. * @param int $resource_id Resource id
  4630. * @param string $resource_type 'resource'
  4631. * @param int $busy Busy or not
  4632. * @param int $mandatory Mandatory or not
  4633. * @return int <=0 if KO, >0 if OK
  4634. */
  4635. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4636. {
  4637. // phpcs:enable
  4638. $this->db->begin();
  4639. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4640. $sql .= "resource_id";
  4641. $sql .= ", resource_type";
  4642. $sql .= ", element_id";
  4643. $sql .= ", element_type";
  4644. $sql .= ", busy";
  4645. $sql .= ", mandatory";
  4646. $sql .= ") VALUES (";
  4647. $sql .= $resource_id;
  4648. $sql .= ", '".$this->db->escape($resource_type)."'";
  4649. $sql .= ", '".$this->db->escape($this->id)."'";
  4650. $sql .= ", '".$this->db->escape($this->element)."'";
  4651. $sql .= ", '".$this->db->escape($busy)."'";
  4652. $sql .= ", '".$this->db->escape($mandatory)."'";
  4653. $sql .= ")";
  4654. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4655. if ($this->db->query($sql)) {
  4656. $this->db->commit();
  4657. return 1;
  4658. } else {
  4659. $this->error = $this->db->lasterror();
  4660. $this->db->rollback();
  4661. return 0;
  4662. }
  4663. }
  4664. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4665. /**
  4666. * Delete a link to resource line
  4667. *
  4668. * @param int $rowid Id of resource line to delete
  4669. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4670. * @param int $notrigger Disable all triggers
  4671. * @return int >0 if OK, <0 if KO
  4672. */
  4673. public function delete_resource($rowid, $element, $notrigger = 0)
  4674. {
  4675. // phpcs:enable
  4676. global $user;
  4677. $this->db->begin();
  4678. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4679. $sql .= " WHERE rowid = ".((int) $rowid);
  4680. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4681. $resql = $this->db->query($sql);
  4682. if (!$resql) {
  4683. $this->error = $this->db->lasterror();
  4684. $this->db->rollback();
  4685. return -1;
  4686. } else {
  4687. if (!$notrigger) {
  4688. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4689. if ($result < 0) {
  4690. $this->db->rollback();
  4691. return -1;
  4692. }
  4693. }
  4694. $this->db->commit();
  4695. return 1;
  4696. }
  4697. }
  4698. /**
  4699. * Overwrite magic function to solve problem of cloning object that are kept as references
  4700. *
  4701. * @return void
  4702. */
  4703. public function __clone()
  4704. {
  4705. // Force a copy of this->lines, otherwise it will point to same object.
  4706. if (isset($this->lines) && is_array($this->lines)) {
  4707. $nboflines = count($this->lines);
  4708. for ($i = 0; $i < $nboflines; $i++) {
  4709. $this->lines[$i] = clone $this->lines[$i];
  4710. }
  4711. }
  4712. }
  4713. /**
  4714. * Common function for all objects extending CommonObject for generating documents
  4715. *
  4716. * @param string $modelspath Relative folder where generators are placed
  4717. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4718. * @param Translate $outputlangs Output language to use
  4719. * @param int $hidedetails 1 to hide details. 0 by default
  4720. * @param int $hidedesc 1 to hide product description. 0 by default
  4721. * @param int $hideref 1 to hide product reference. 0 by default
  4722. * @param null|array $moreparams Array to provide more information
  4723. * @return int >0 if OK, <0 if KO
  4724. * @see addFileIntoDatabaseIndex()
  4725. */
  4726. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4727. {
  4728. global $conf, $langs, $user, $hookmanager, $action;
  4729. $srctemplatepath = '';
  4730. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4731. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4732. if (empty($reshook)) {
  4733. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4734. if (empty($modele)) {
  4735. $this->error = 'BadValueForParameterModele';
  4736. return -1;
  4737. }
  4738. // Increase limit for PDF build
  4739. $err = error_reporting();
  4740. error_reporting(0);
  4741. @set_time_limit(120);
  4742. error_reporting($err);
  4743. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4744. $tmp = explode(':', $modele, 2);
  4745. if (!empty($tmp[1])) {
  4746. $modele = $tmp[0];
  4747. $srctemplatepath = $tmp[1];
  4748. }
  4749. // Search template files
  4750. $file = '';
  4751. $classname = '';
  4752. $filefound = '';
  4753. $dirmodels = array('/');
  4754. if (is_array($conf->modules_parts['models'])) {
  4755. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4756. }
  4757. foreach ($dirmodels as $reldir) {
  4758. foreach (array('doc', 'pdf') as $prefix) {
  4759. if (in_array(get_class($this), array('Adherent'))) {
  4760. // Member module use prefix_modele.class.php
  4761. $file = $prefix."_".$modele.".class.php";
  4762. } else {
  4763. // Other module use prefix_modele.modules.php
  4764. $file = $prefix."_".$modele.".modules.php";
  4765. }
  4766. // On verifie l'emplacement du modele
  4767. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4768. if (file_exists($file)) {
  4769. $filefound = $file;
  4770. $classname = $prefix.'_'.$modele;
  4771. break;
  4772. }
  4773. }
  4774. if ($filefound) {
  4775. break;
  4776. }
  4777. }
  4778. // If generator was found
  4779. if ($filefound) {
  4780. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4781. require_once $file;
  4782. $obj = new $classname($this->db);
  4783. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4784. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4785. $varfortemplatedir = $obj->scandir;
  4786. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4787. $dirtoscan = $conf->global->$varfortemplatedir;
  4788. $listoffiles = array();
  4789. // Now we add first model found in directories scanned
  4790. $listofdir = explode(',', $dirtoscan);
  4791. foreach ($listofdir as $key => $tmpdir) {
  4792. $tmpdir = trim($tmpdir);
  4793. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4794. if (!$tmpdir) {
  4795. unset($listofdir[$key]);
  4796. continue;
  4797. }
  4798. if (is_dir($tmpdir)) {
  4799. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4800. if (count($tmpfiles)) {
  4801. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4802. }
  4803. }
  4804. }
  4805. if (count($listoffiles)) {
  4806. foreach ($listoffiles as $record) {
  4807. $srctemplatepath = $record['fullname'];
  4808. break;
  4809. }
  4810. }
  4811. }
  4812. if (empty($srctemplatepath)) {
  4813. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4814. return -1;
  4815. }
  4816. }
  4817. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4818. if (!dol_is_file($srctemplatepath)) {
  4819. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4820. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4821. return -1;
  4822. }
  4823. }
  4824. // We save charset_output to restore it because write_file can change it if needed for
  4825. // output format that does not support UTF8.
  4826. $sav_charset_output = $outputlangs->charset_output;
  4827. if (in_array(get_class($this), array('Adherent'))) {
  4828. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4829. } else {
  4830. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4831. }
  4832. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4833. if ($resultwritefile > 0) {
  4834. $outputlangs->charset_output = $sav_charset_output;
  4835. // We delete old preview
  4836. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4837. dol_delete_preview($this);
  4838. // Index file in database
  4839. if (!empty($obj->result['fullpath'])) {
  4840. $destfull = $obj->result['fullpath'];
  4841. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4842. $update_main_doc_field = 0;
  4843. if (!empty($obj->update_main_doc_field)) {
  4844. $update_main_doc_field = 1;
  4845. }
  4846. $this->indexFile($destfull, $update_main_doc_field);
  4847. } else {
  4848. 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);
  4849. }
  4850. // Success in building document. We build meta file.
  4851. dol_meta_create($this);
  4852. return 1;
  4853. } else {
  4854. $outputlangs->charset_output = $sav_charset_output;
  4855. $this->error = $obj->error;
  4856. $this->errors = $obj->errors;
  4857. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  4858. return -1;
  4859. }
  4860. } else {
  4861. if (!$filefound) {
  4862. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4863. $this->errors[] = $this->error;
  4864. dol_syslog($this->error, LOG_ERR);
  4865. } else {
  4866. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4867. $this->errors[] = $this->error;
  4868. dol_syslog($this->error, LOG_ERR);
  4869. }
  4870. return -1;
  4871. }
  4872. } else {
  4873. return $reshook;
  4874. }
  4875. }
  4876. /**
  4877. * Index a file into the ECM database
  4878. *
  4879. * @param string $destfull Full path of file to index
  4880. * @param int $update_main_doc_field Update field main_doc file into table of object
  4881. * @return int <0 if KO, >0 if OK
  4882. */
  4883. public function indexFile($destfull, $update_main_doc_field)
  4884. {
  4885. global $conf, $user;
  4886. $upload_dir = dirname($destfull);
  4887. $destfile = basename($destfull);
  4888. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4889. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4890. $filename = basename($destfile);
  4891. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4892. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4893. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4894. $ecmfile = new EcmFiles($this->db);
  4895. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4896. // Set the public "share" key
  4897. $setsharekey = false;
  4898. if ($this->element == 'propal' || $this->element == 'proposal') {
  4899. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  4900. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  4901. }
  4902. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4903. $setsharekey = true;
  4904. }
  4905. }
  4906. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4907. $setsharekey = true;
  4908. }
  4909. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4910. $setsharekey = true;
  4911. }
  4912. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4913. $setsharekey = true;
  4914. }
  4915. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4916. $setsharekey = true;
  4917. }
  4918. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4919. $setsharekey = true;
  4920. }
  4921. if ($setsharekey) {
  4922. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4923. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4924. $ecmfile->share = getRandomPassword(true);
  4925. }
  4926. }
  4927. if ($result > 0) {
  4928. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4929. $ecmfile->fullpath_orig = '';
  4930. $ecmfile->gen_or_uploaded = 'generated';
  4931. $ecmfile->description = ''; // indexed content
  4932. $ecmfile->keywords = ''; // keyword content
  4933. $result = $ecmfile->update($user);
  4934. if ($result < 0) {
  4935. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4936. return -1;
  4937. }
  4938. } else {
  4939. $ecmfile->entity = $conf->entity;
  4940. $ecmfile->filepath = $rel_dir;
  4941. $ecmfile->filename = $filename;
  4942. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4943. $ecmfile->fullpath_orig = '';
  4944. $ecmfile->gen_or_uploaded = 'generated';
  4945. $ecmfile->description = ''; // indexed content
  4946. $ecmfile->keywords = ''; // keyword content
  4947. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  4948. $ecmfile->src_object_id = $this->id;
  4949. $result = $ecmfile->create($user);
  4950. if ($result < 0) {
  4951. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4952. return -1;
  4953. }
  4954. }
  4955. /*$this->result['fullname']=$destfull;
  4956. $this->result['filepath']=$ecmfile->filepath;
  4957. $this->result['filename']=$ecmfile->filename;*/
  4958. //var_dump($obj->update_main_doc_field);exit;
  4959. if ($update_main_doc_field && !empty($this->table_element)) {
  4960. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  4961. $sql .= " WHERE rowid = ".((int) $this->id);
  4962. $resql = $this->db->query($sql);
  4963. if (!$resql) {
  4964. dol_print_error($this->db);
  4965. return -1;
  4966. } else {
  4967. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4968. }
  4969. }
  4970. }
  4971. return 1;
  4972. }
  4973. /**
  4974. * Build thumb
  4975. * @todo Move this into files.lib.php
  4976. *
  4977. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4978. * @return void
  4979. */
  4980. public function addThumbs($file)
  4981. {
  4982. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4983. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4984. $file_osencoded = dol_osencode($file);
  4985. if (file_exists($file_osencoded)) {
  4986. // Create small thumbs for company (Ratio is near 16/9)
  4987. // Used on logon for example
  4988. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4989. // Create mini thumbs for company (Ratio is near 16/9)
  4990. // Used on menu or for setup page for example
  4991. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4992. }
  4993. }
  4994. /* Functions common to commonobject and commonobjectline */
  4995. /* For default values */
  4996. /**
  4997. * Return the default value to use for a field when showing the create form of object.
  4998. * Return values in this order:
  4999. * 1) If parameter is available into POST, we return it first.
  5000. * 2) If not but an alternate value was provided as parameter of function, we return it.
  5001. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  5002. * 4) Return value found into database (TODO No yet implemented)
  5003. *
  5004. * @param string $fieldname Name of field
  5005. * @param string $alternatevalue Alternate value to use
  5006. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  5007. **/
  5008. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  5009. {
  5010. global $conf, $_POST;
  5011. // If param here has been posted, we use this value first.
  5012. if (GETPOSTISSET($fieldname)) {
  5013. return GETPOST($fieldname, 'alphanohtml', 3);
  5014. }
  5015. if (isset($alternatevalue)) {
  5016. return $alternatevalue;
  5017. }
  5018. $newelement = $this->element;
  5019. if ($newelement == 'facture') {
  5020. $newelement = 'invoice';
  5021. }
  5022. if ($newelement == 'commande') {
  5023. $newelement = 'order';
  5024. }
  5025. if (empty($newelement)) {
  5026. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5027. return '';
  5028. }
  5029. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  5030. //var_dump($keyforfieldname);
  5031. if (isset($conf->global->$keyforfieldname)) {
  5032. return $conf->global->$keyforfieldname;
  5033. }
  5034. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5035. }
  5036. /* For triggers */
  5037. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5038. /**
  5039. * Call trigger based on this instance.
  5040. * Some context information may also be provided into array property this->context.
  5041. * NB: Error from trigger are stacked in interface->errors
  5042. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5043. *
  5044. * @param string $triggerName trigger's name to execute
  5045. * @param User $user Object user
  5046. * @return int Result of run_triggers
  5047. */
  5048. public function call_trigger($triggerName, $user)
  5049. {
  5050. // phpcs:enable
  5051. global $langs, $conf;
  5052. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5053. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5054. exit;
  5055. }
  5056. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5057. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5058. $langs = new Translate('', $conf);
  5059. }
  5060. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5061. $interface = new Interfaces($this->db);
  5062. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5063. if ($result < 0) {
  5064. if (!empty($this->errors)) {
  5065. $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.
  5066. } else {
  5067. $this->errors = $interface->errors;
  5068. }
  5069. }
  5070. return $result;
  5071. }
  5072. /* Functions for data in other language */
  5073. /**
  5074. * Function to get alternative languages of a data into $this->array_languages
  5075. * This method is NOT called by method fetch of objects but must be called separately.
  5076. *
  5077. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5078. * @see fetch_optionnals()
  5079. */
  5080. public function fetchValuesForExtraLanguages()
  5081. {
  5082. // To avoid SQL errors. Probably not the better solution though
  5083. if (!$this->element) {
  5084. return 0;
  5085. }
  5086. if (!($this->id > 0)) {
  5087. return 0;
  5088. }
  5089. if (is_array($this->array_languages)) {
  5090. return 1;
  5091. }
  5092. $this->array_languages = array();
  5093. $element = $this->element;
  5094. if ($element == 'categorie') {
  5095. $element = 'categories'; // For compatibility
  5096. }
  5097. // Request to get translation values for object
  5098. $sql = "SELECT rowid, property, lang , value";
  5099. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5100. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5101. $sql .= " AND fk_object = ".((int) $this->id);
  5102. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5103. $resql = $this->db->query($sql);
  5104. if ($resql) {
  5105. $numrows = $this->db->num_rows($resql);
  5106. if ($numrows) {
  5107. $i = 0;
  5108. while ($i < $numrows) {
  5109. $obj = $this->db->fetch_object($resql);
  5110. $key = $obj->property;
  5111. $value = $obj->value;
  5112. $codelang = $obj->lang;
  5113. $type = $this->fields[$key]['type'];
  5114. // we can add this attribute to object
  5115. if (preg_match('/date/', $type)) {
  5116. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5117. } else {
  5118. $this->array_languages[$key][$codelang] = $value;
  5119. }
  5120. $i++;
  5121. }
  5122. }
  5123. $this->db->free($resql);
  5124. if ($numrows) {
  5125. return $numrows;
  5126. } else {
  5127. return 0;
  5128. }
  5129. } else {
  5130. dol_print_error($this->db);
  5131. return -1;
  5132. }
  5133. }
  5134. /**
  5135. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5136. *
  5137. * @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.
  5138. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5139. */
  5140. public function setValuesForExtraLanguages($onlykey = '')
  5141. {
  5142. global $_POST, $langs;
  5143. // Get extra fields
  5144. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5145. $tmparray = explode('-', $postfieldkey);
  5146. if ($tmparray[0] != 'field') {
  5147. continue;
  5148. }
  5149. $element = $tmparray[1];
  5150. $key = $tmparray[2];
  5151. $codelang = $tmparray[3];
  5152. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5153. if (!empty($onlykey) && $key != $onlykey) {
  5154. continue;
  5155. }
  5156. if ($element != $this->element) {
  5157. continue;
  5158. }
  5159. $key_type = $this->fields[$key]['type'];
  5160. $enabled = 1;
  5161. if (isset($this->fields[$key]['enabled'])) {
  5162. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5163. }
  5164. /*$perms = 1;
  5165. if (isset($this->fields[$key]['perms']))
  5166. {
  5167. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5168. }*/
  5169. if (empty($enabled)) {
  5170. continue;
  5171. }
  5172. //if (empty($perms)) continue;
  5173. if (in_array($key_type, array('date'))) {
  5174. // Clean parameters
  5175. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5176. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5177. } elseif (in_array($key_type, array('datetime'))) {
  5178. // Clean parameters
  5179. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5180. $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'));
  5181. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5182. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5183. if (!empty($value_arr)) {
  5184. $value_key = implode(',', $value_arr);
  5185. } else {
  5186. $value_key = '';
  5187. }
  5188. } elseif (in_array($key_type, array('price', 'double'))) {
  5189. $value_arr = GETPOST($postfieldkey, 'alpha');
  5190. $value_key = price2num($value_arr);
  5191. } else {
  5192. $value_key = GETPOST($postfieldkey);
  5193. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5194. $value_key = '';
  5195. }
  5196. }
  5197. $this->array_languages[$key][$codelang] = $value_key;
  5198. /*if ($nofillrequired) {
  5199. $langs->load('errors');
  5200. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5201. return -1;
  5202. }*/
  5203. }
  5204. return 1;
  5205. }
  5206. /* Functions for extrafields */
  5207. /**
  5208. * Function to make a fetch but set environment to avoid to load computed values before.
  5209. *
  5210. * @param int $id ID of object
  5211. * @return int >0 if OK, 0 if not found, <0 if KO
  5212. */
  5213. public function fetchNoCompute($id)
  5214. {
  5215. global $conf;
  5216. $savDisableCompute = $conf->disable_compute;
  5217. $conf->disable_compute = 1;
  5218. $ret = $this->fetch($id);
  5219. $conf->disable_compute = $savDisableCompute;
  5220. return $ret;
  5221. }
  5222. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5223. /**
  5224. * Function to get extra fields of an object into $this->array_options
  5225. * This method is in most cases called by method fetch of objects but you can call it separately.
  5226. *
  5227. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5228. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5229. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5230. * @see fetchValuesForExtraLanguages()
  5231. */
  5232. public function fetch_optionals($rowid = null, $optionsArray = null)
  5233. {
  5234. // phpcs:enable
  5235. global $conf, $extrafields;
  5236. if (empty($rowid)) {
  5237. $rowid = $this->id;
  5238. }
  5239. if (empty($rowid) && isset($this->rowid)) {
  5240. $rowid = $this->rowid; // deprecated
  5241. }
  5242. // To avoid SQL errors. Probably not the better solution though
  5243. if (!$this->table_element) {
  5244. return 0;
  5245. }
  5246. $this->array_options = array();
  5247. if (!is_array($optionsArray)) {
  5248. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5249. if (!isset($extrafields) || !is_object($extrafields)) {
  5250. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5251. $extrafields = new ExtraFields($this->db);
  5252. }
  5253. // Load array of extrafields for elementype = $this->table_element
  5254. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5255. $extrafields->fetch_name_optionals_label($this->table_element);
  5256. }
  5257. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5258. } else {
  5259. global $extrafields;
  5260. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5261. }
  5262. $table_element = $this->table_element;
  5263. if ($table_element == 'categorie') {
  5264. $table_element = 'categories'; // For compatibility
  5265. }
  5266. // Request to get complementary values
  5267. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5268. $sql = "SELECT rowid";
  5269. foreach ($optionsArray as $name => $label) {
  5270. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5271. $sql .= ", ".$name;
  5272. }
  5273. }
  5274. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5275. $sql .= " WHERE fk_object = ".((int) $rowid);
  5276. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5277. $resql = $this->db->query($sql);
  5278. if ($resql) {
  5279. $numrows = $this->db->num_rows($resql);
  5280. if ($numrows) {
  5281. $tab = $this->db->fetch_array($resql);
  5282. foreach ($tab as $key => $value) {
  5283. // 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)
  5284. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5285. // we can add this attribute to object
  5286. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5287. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5288. $this->array_options["options_".$key] = $this->db->jdate($value);
  5289. } else {
  5290. $this->array_options["options_".$key] = $value;
  5291. }
  5292. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5293. }
  5294. }
  5295. // If field is a computed field, value must become result of compute
  5296. foreach ($tab as $key => $value) {
  5297. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5298. //var_dump($conf->disable_compute);
  5299. if (empty($conf->disable_compute)) {
  5300. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5301. }
  5302. }
  5303. }
  5304. }
  5305. $this->db->free($resql);
  5306. if ($numrows) {
  5307. return $numrows;
  5308. } else {
  5309. return 0;
  5310. }
  5311. } else {
  5312. $this->errors[]=$this->db->lasterror;
  5313. return -1;
  5314. }
  5315. }
  5316. return 0;
  5317. }
  5318. /**
  5319. * Delete all extra fields values for the current object.
  5320. *
  5321. * @return int <0 if KO, >0 if OK
  5322. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5323. */
  5324. public function deleteExtraFields()
  5325. {
  5326. global $conf;
  5327. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5328. return 0;
  5329. }
  5330. $this->db->begin();
  5331. $table_element = $this->table_element;
  5332. if ($table_element == 'categorie') {
  5333. $table_element = 'categories'; // For compatibility
  5334. }
  5335. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5336. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5337. $resql = $this->db->query($sql_del);
  5338. if (!$resql) {
  5339. $this->error = $this->db->lasterror();
  5340. $this->db->rollback();
  5341. return -1;
  5342. } else {
  5343. $this->db->commit();
  5344. return 1;
  5345. }
  5346. }
  5347. /**
  5348. * Add/Update all extra fields values for the current object.
  5349. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5350. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5351. *
  5352. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5353. * @param User $userused Object user
  5354. * @return int -1=error, O=did nothing, 1=OK
  5355. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5356. */
  5357. public function insertExtraFields($trigger = '', $userused = null)
  5358. {
  5359. global $conf, $langs, $user;
  5360. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5361. return 0;
  5362. }
  5363. if (empty($userused)) {
  5364. $userused = $user;
  5365. }
  5366. $error = 0;
  5367. if (!empty($this->array_options)) {
  5368. // Check parameters
  5369. $langs->load('admin');
  5370. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5371. $extrafields = new ExtraFields($this->db);
  5372. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5373. // Eliminate copied source object extra fields that do not exist in target object
  5374. $new_array_options = array();
  5375. foreach ($this->array_options as $key => $value) {
  5376. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5377. $new_array_options[$key] = $value;
  5378. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5379. $new_array_options['options_'.$key] = $value;
  5380. }
  5381. }
  5382. foreach ($new_array_options as $key => $value) {
  5383. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5384. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5385. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5386. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5387. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5388. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5389. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5390. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5391. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5392. if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
  5393. $new_array_options[$key] = null;
  5394. }
  5395. // Similar code than into insertExtraFields
  5396. if ($attributeRequired) {
  5397. $mandatorypb = false;
  5398. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5399. $mandatorypb = true;
  5400. }
  5401. if ($this->array_options[$key] === '') {
  5402. $mandatorypb = true;
  5403. }
  5404. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5405. $mandatorypb = true;
  5406. }
  5407. if ($mandatorypb) {
  5408. $langs->load("errors");
  5409. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5410. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5411. return -1;
  5412. }
  5413. }
  5414. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5415. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5416. if (!empty($attrfieldcomputed)) {
  5417. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5418. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5419. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5420. $new_array_options[$key] = $value;
  5421. } else {
  5422. $new_array_options[$key] = null;
  5423. }
  5424. }
  5425. switch ($attributeType) {
  5426. case 'int':
  5427. if (!is_numeric($value) && $value != '') {
  5428. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5429. return -1;
  5430. } elseif ($value == '') {
  5431. $new_array_options[$key] = null;
  5432. }
  5433. break;
  5434. case 'price':
  5435. case 'double':
  5436. $value = price2num($value);
  5437. if (!is_numeric($value) && $value != '') {
  5438. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5439. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5440. return -1;
  5441. } elseif ($value == '') {
  5442. $value = null;
  5443. }
  5444. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5445. $new_array_options[$key] = $value;
  5446. break;
  5447. /*case 'select': // Not required, we chosed value='0' for undefined values
  5448. if ($value=='-1')
  5449. {
  5450. $this->array_options[$key] = null;
  5451. }
  5452. break;*/
  5453. case 'password':
  5454. $algo = '';
  5455. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5456. // If there is an encryption choice, we use it to crypt data before insert
  5457. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5458. $algo = reset($tmparrays);
  5459. if ($algo != '') {
  5460. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5461. //var_dump($action);
  5462. //var_dump($this->oldcopy);exit;
  5463. 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
  5464. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5465. if ($this->array_options[$key] == $this->oldcopy->array_options[$key]) { // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
  5466. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5467. } else {
  5468. // var_dump($algo);
  5469. $newvalue = dol_hash($this->array_options[$key], $algo);
  5470. $new_array_options[$key] = $newvalue;
  5471. }
  5472. } else {
  5473. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5474. }
  5475. }
  5476. } else // Common usage
  5477. {
  5478. $new_array_options[$key] = $this->array_options[$key];
  5479. }
  5480. break;
  5481. case 'date':
  5482. case 'datetime':
  5483. // If data is a string instead of a timestamp, we convert it
  5484. if (!is_int($this->array_options[$key])) {
  5485. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5486. }
  5487. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5488. break;
  5489. case 'link':
  5490. $param_list = array_keys($attributeParam['options']);
  5491. // 0 : ObjectName
  5492. // 1 : classPath
  5493. $InfoFieldList = explode(":", $param_list[0]);
  5494. dol_include_once($InfoFieldList[1]);
  5495. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5496. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5497. $new_array_options[$key] = '';
  5498. } elseif ($value) {
  5499. $object = new $InfoFieldList[0]($this->db);
  5500. if (is_numeric($value)) {
  5501. $res = $object->fetch($value); // Common case
  5502. } else {
  5503. $res = $object->fetch('', $value); // For compatibility
  5504. }
  5505. if ($res > 0) {
  5506. $new_array_options[$key] = $object->id;
  5507. } else {
  5508. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5509. $this->db->rollback();
  5510. return -1;
  5511. }
  5512. }
  5513. } else {
  5514. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5515. }
  5516. break;
  5517. }
  5518. }
  5519. $this->db->begin();
  5520. $table_element = $this->table_element;
  5521. if ($table_element == 'categorie') {
  5522. $table_element = 'categories'; // For compatibility
  5523. }
  5524. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5525. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5526. $this->db->query($sql_del);
  5527. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5528. foreach ($new_array_options as $key => $value) {
  5529. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5530. // Add field of attribut
  5531. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5532. $sql .= ",".$attributeKey;
  5533. }
  5534. }
  5535. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5536. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5537. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5538. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5539. $sql .= ",".$tmpkey;
  5540. }
  5541. }
  5542. }
  5543. $sql .= ") VALUES (".$this->id;
  5544. foreach ($new_array_options as $key => $value) {
  5545. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5546. // Add field of attribute
  5547. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5548. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5549. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5550. } else {
  5551. $sql .= ",null";
  5552. }
  5553. }
  5554. }
  5555. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5556. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5557. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5558. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5559. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5560. $sql .= ", 0";
  5561. } else {
  5562. $sql .= ", ''";
  5563. }
  5564. }
  5565. }
  5566. }
  5567. $sql .= ")";
  5568. $resql = $this->db->query($sql);
  5569. if (!$resql) {
  5570. $this->error = $this->db->lasterror();
  5571. $error++;
  5572. }
  5573. if (!$error && $trigger) {
  5574. // Call trigger
  5575. $this->context = array('extrafieldaddupdate'=>1);
  5576. $result = $this->call_trigger($trigger, $userused);
  5577. if ($result < 0) {
  5578. $error++;
  5579. }
  5580. // End call trigger
  5581. }
  5582. if ($error) {
  5583. $this->db->rollback();
  5584. return -1;
  5585. } else {
  5586. $this->db->commit();
  5587. return 1;
  5588. }
  5589. } else {
  5590. return 0;
  5591. }
  5592. }
  5593. /**
  5594. * Add/Update all extra fields values for the current object.
  5595. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5596. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5597. *
  5598. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5599. * @param User $userused Object user
  5600. * @return int -1=error, O=did nothing, 1=OK
  5601. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5602. */
  5603. public function insertExtraLanguages($trigger = '', $userused = null)
  5604. {
  5605. global $conf, $langs, $user;
  5606. if (empty($userused)) {
  5607. $userused = $user;
  5608. }
  5609. $error = 0;
  5610. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5611. return 0; // For avoid conflicts if trigger used
  5612. }
  5613. if (is_array($this->array_languages)) {
  5614. $new_array_languages = $this->array_languages;
  5615. foreach ($new_array_languages as $key => $value) {
  5616. $attributeKey = $key;
  5617. $attributeType = $this->fields[$attributeKey]['type'];
  5618. $attributeLabel = $this->fields[$attributeKey]['label'];
  5619. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5620. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5621. switch ($attributeType) {
  5622. case 'int':
  5623. if (!is_numeric($value) && $value != '') {
  5624. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5625. return -1;
  5626. } elseif ($value == '') {
  5627. $new_array_languages[$key] = null;
  5628. }
  5629. break;
  5630. case 'double':
  5631. $value = price2num($value);
  5632. if (!is_numeric($value) && $value != '') {
  5633. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5634. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5635. return -1;
  5636. } elseif ($value == '') {
  5637. $new_array_languages[$key] = null;
  5638. }
  5639. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5640. $new_array_languages[$key] = $value;
  5641. break;
  5642. /*case 'select': // Not required, we chosed value='0' for undefined values
  5643. if ($value=='-1')
  5644. {
  5645. $this->array_options[$key] = null;
  5646. }
  5647. break;*/
  5648. }
  5649. }
  5650. $this->db->begin();
  5651. $table_element = $this->table_element;
  5652. if ($table_element == 'categorie') {
  5653. $table_element = 'categories'; // For compatibility
  5654. }
  5655. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5656. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5657. foreach ($langcodearray as $langcode => $value) {
  5658. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5659. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5660. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5661. $this->db->query($sql_del);
  5662. if ($value !== '') {
  5663. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5664. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5665. $sql .= ")";
  5666. $resql = $this->db->query($sql);
  5667. if (!$resql) {
  5668. $this->error = $this->db->lasterror();
  5669. $error++;
  5670. break;
  5671. }
  5672. }
  5673. }
  5674. }
  5675. if (!$error && $trigger) {
  5676. // Call trigger
  5677. $this->context = array('extralanguagesaddupdate'=>1);
  5678. $result = $this->call_trigger($trigger, $userused);
  5679. if ($result < 0) {
  5680. $error++;
  5681. }
  5682. // End call trigger
  5683. }
  5684. if ($error) {
  5685. $this->db->rollback();
  5686. return -1;
  5687. } else {
  5688. $this->db->commit();
  5689. return 1;
  5690. }
  5691. } else {
  5692. return 0;
  5693. }
  5694. }
  5695. /**
  5696. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5697. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5698. *
  5699. * @param string $key Key of the extrafield to update (without starting 'options_')
  5700. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5701. * @param User $userused Object user
  5702. * @return int -1=error, O=did nothing, 1=OK
  5703. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5704. */
  5705. public function updateExtraField($key, $trigger = null, $userused = null)
  5706. {
  5707. global $conf, $langs, $user;
  5708. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5709. return 0;
  5710. }
  5711. if (empty($userused)) {
  5712. $userused = $user;
  5713. }
  5714. $error = 0;
  5715. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5716. // Check parameters
  5717. $langs->load('admin');
  5718. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5719. $extrafields = new ExtraFields($this->db);
  5720. $extrafields->fetch_name_optionals_label($this->table_element);
  5721. $value = $this->array_options["options_".$key];
  5722. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5723. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5724. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5725. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5726. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5727. // Similar code than into insertExtraFields
  5728. if ($attributeRequired) {
  5729. $mandatorypb = false;
  5730. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5731. $mandatorypb = true;
  5732. }
  5733. if ($this->array_options["options_".$key] === '') {
  5734. $mandatorypb = true;
  5735. }
  5736. if ($mandatorypb) {
  5737. $langs->load("errors");
  5738. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5739. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5740. return -1;
  5741. }
  5742. }
  5743. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5744. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5745. if (!empty($attrfieldcomputed)) {
  5746. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5747. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5748. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5749. $this->array_options["options_".$key] = $value;
  5750. } else {
  5751. $this->array_options["options_".$key] = null;
  5752. }
  5753. }
  5754. switch ($attributeType) {
  5755. case 'int':
  5756. if (!is_numeric($value) && $value != '') {
  5757. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5758. return -1;
  5759. } elseif ($value === '') {
  5760. $this->array_options["options_".$key] = null;
  5761. }
  5762. break;
  5763. case 'double':
  5764. $value = price2num($value);
  5765. if (!is_numeric($value) && $value != '') {
  5766. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5767. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5768. return -1;
  5769. } elseif ($value === '') {
  5770. $value = null;
  5771. }
  5772. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5773. $this->array_options["options_".$key] = $value;
  5774. break;
  5775. /*case 'select': // Not required, we chosed value='0' for undefined values
  5776. if ($value=='-1')
  5777. {
  5778. $this->array_options[$key] = null;
  5779. }
  5780. break;*/
  5781. case 'price':
  5782. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5783. break;
  5784. case 'date':
  5785. case 'datetime':
  5786. if (empty($this->array_options["options_".$key])) {
  5787. $this->array_options["options_".$key] = null;
  5788. } else {
  5789. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5790. }
  5791. break;
  5792. case 'boolean':
  5793. if (empty($this->array_options["options_".$key])) {
  5794. $this->array_options["options_".$key] = null;
  5795. }
  5796. break;
  5797. /*
  5798. case 'link':
  5799. $param_list = array_keys($attributeParam['options']);
  5800. // 0 : ObjectName
  5801. // 1 : classPath
  5802. $InfoFieldList = explode(":", $param_list[0]);
  5803. dol_include_once($InfoFieldList[1]);
  5804. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5805. {
  5806. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5807. {
  5808. $new_array_options[$key] = '';
  5809. } elseif ($value) {
  5810. $object = new $InfoFieldList[0]($this->db);
  5811. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5812. else $res = $object->fetch('', $value); // For compatibility
  5813. if ($res > 0) $new_array_options[$key] = $object->id;
  5814. else {
  5815. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5816. $this->db->rollback();
  5817. return -1;
  5818. }
  5819. }
  5820. } else {
  5821. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5822. }
  5823. break;
  5824. */
  5825. }
  5826. $this->db->begin();
  5827. $linealreadyfound = 0;
  5828. // 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)
  5829. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5830. $resql = $this->db->query($sql);
  5831. if ($resql) {
  5832. $tmpobj = $this->db->fetch_object($resql);
  5833. if ($tmpobj) {
  5834. $linealreadyfound = $tmpobj->nb;
  5835. }
  5836. }
  5837. if ($linealreadyfound) {
  5838. if ($this->array_options["options_".$key] === null) {
  5839. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5840. } else {
  5841. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5842. }
  5843. $sql .= " WHERE fk_object = ".((int) $this->id);
  5844. } else {
  5845. $result = $this->insertExtraFields('', $user);
  5846. if ($result < 0) {
  5847. $error++;
  5848. }
  5849. }
  5850. $resql = $this->db->query($sql);
  5851. if (!$resql) {
  5852. $error++;
  5853. $this->error = $this->db->lasterror();
  5854. }
  5855. if (!$error && $trigger) {
  5856. // Call trigger
  5857. $this->context = array('extrafieldupdate'=>1);
  5858. $result = $this->call_trigger($trigger, $userused);
  5859. if ($result < 0) {
  5860. $error++;
  5861. }
  5862. // End call trigger
  5863. }
  5864. if ($error) {
  5865. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5866. $this->db->rollback();
  5867. return -1;
  5868. } else {
  5869. $this->db->commit();
  5870. return 1;
  5871. }
  5872. } else {
  5873. return 0;
  5874. }
  5875. }
  5876. /**
  5877. * Update an extra language value for the current object.
  5878. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5879. *
  5880. * @param string $key Key of the extrafield (without starting 'options_')
  5881. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5882. * @param User $userused Object user
  5883. * @return int -1=error, O=did nothing, 1=OK
  5884. * @see updateExtraFields(), insertExtraLanguages()
  5885. */
  5886. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5887. {
  5888. global $conf, $langs, $user;
  5889. if (empty($userused)) {
  5890. $userused = $user;
  5891. }
  5892. $error = 0;
  5893. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5894. return 0; // For avoid conflicts if trigger used
  5895. }
  5896. return 0;
  5897. }
  5898. /**
  5899. * Return HTML string to put an input field into a page
  5900. * Code very similar with showInputField of extra fields
  5901. *
  5902. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5903. * @param string $key Key of attribute
  5904. * @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)
  5905. * @param string $moreparam To add more parameters on html input tag
  5906. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5907. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5908. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5909. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5910. * @return string
  5911. */
  5912. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5913. {
  5914. global $conf, $langs, $form;
  5915. if (!is_object($form)) {
  5916. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5917. $form = new Form($this->db);
  5918. }
  5919. if (!empty($this->fields)) {
  5920. $val = $this->fields[$key];
  5921. }
  5922. // Validation tests and output
  5923. $fieldValidationErrorMsg = '';
  5924. $validationClass = '';
  5925. $fieldValidationErrorMsg = $this->getFieldError($key);
  5926. if (!empty($fieldValidationErrorMsg)) {
  5927. $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
  5928. } else {
  5929. $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
  5930. }
  5931. $out = '';
  5932. $type = '';
  5933. $isDependList = 0;
  5934. $param = array();
  5935. $param['options'] = array();
  5936. $reg = array();
  5937. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5938. // Because we work on extrafields
  5939. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5940. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5941. $type = 'link';
  5942. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5943. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5944. $type = 'link';
  5945. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5946. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5947. $type = 'link';
  5948. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5949. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5950. $type = 'sellist';
  5951. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5952. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5953. $type = 'sellist';
  5954. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5955. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5956. $type = 'sellist';
  5957. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5958. $param['options'] = array();
  5959. $type = 'varchar';
  5960. $size = $reg[1];
  5961. } elseif (preg_match('/varchar/', $val['type'])) {
  5962. $param['options'] = array();
  5963. $type = 'varchar';
  5964. } else {
  5965. $param['options'] = array();
  5966. $type = $this->fields[$key]['type'];
  5967. }
  5968. // Special case that force options and type ($type can be integer, varchar, ...)
  5969. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5970. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5971. $type = 'select';
  5972. }
  5973. $label = $this->fields[$key]['label'];
  5974. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5975. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5976. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5977. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5978. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5979. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5980. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5981. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5982. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5983. $objectid = $this->id;
  5984. if ($computed) {
  5985. if (!preg_match('/^search_/', $keyprefix)) {
  5986. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5987. } else {
  5988. return '';
  5989. }
  5990. }
  5991. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5992. if (empty($morecss) && !empty($val['css'])) {
  5993. $morecss = $val['css'];
  5994. } elseif (empty($morecss)) {
  5995. if ($type == 'date') {
  5996. $morecss = 'minwidth100imp';
  5997. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5998. $morecss = 'minwidth200imp';
  5999. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6000. $morecss = 'maxwidth75';
  6001. } elseif ($type == 'url') {
  6002. $morecss = 'minwidth400';
  6003. } elseif ($type == 'boolean') {
  6004. $morecss = '';
  6005. } else {
  6006. if (round($size) < 12) {
  6007. $morecss = 'minwidth100';
  6008. } elseif (round($size) <= 48) {
  6009. $morecss = 'minwidth200';
  6010. } else {
  6011. $morecss = 'minwidth400';
  6012. }
  6013. }
  6014. }
  6015. // Add validation state class
  6016. if (!empty($validationClass)) {
  6017. $morecss.= $validationClass;
  6018. }
  6019. if (in_array($type, array('date'))) {
  6020. $tmp = explode(',', $size);
  6021. $newsize = $tmp[0];
  6022. $showtime = 0;
  6023. // Do not show current date when field not required (see selectDate() method)
  6024. if (!$required && $value == '') {
  6025. $value = '-1';
  6026. }
  6027. // TODO Must also support $moreparam
  6028. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6029. } elseif (in_array($type, array('datetime'))) {
  6030. $tmp = explode(',', $size);
  6031. $newsize = $tmp[0];
  6032. $showtime = 1;
  6033. // Do not show current date when field not required (see selectDate() method)
  6034. if (!$required && $value == '') $value = '-1';
  6035. // TODO Must also support $moreparam
  6036. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6037. } elseif (in_array($type, array('duration'))) {
  6038. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6039. } elseif (in_array($type, array('int', 'integer'))) {
  6040. $tmp = explode(',', $size);
  6041. $newsize = $tmp[0];
  6042. $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' : '').'>';
  6043. } elseif (in_array($type, array('real'))) {
  6044. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6045. } elseif (preg_match('/varchar/', $type)) {
  6046. $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' : '').'>';
  6047. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  6048. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6049. } elseif (preg_match('/^text/', $type)) {
  6050. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6051. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6052. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6053. $out = $doleditor->Create(1);
  6054. } else {
  6055. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6056. }
  6057. } elseif (preg_match('/^html/', $type)) {
  6058. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6059. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6060. $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%');
  6061. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6062. } else {
  6063. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6064. }
  6065. } elseif ($type == 'boolean') {
  6066. $checked = '';
  6067. if (!empty($value)) {
  6068. $checked = ' checked value="1" ';
  6069. } else {
  6070. $checked = ' value="1" ';
  6071. }
  6072. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6073. } elseif ($type == 'price') {
  6074. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6075. $value = price($value);
  6076. }
  6077. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6078. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6079. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6080. $value = price($value);
  6081. }
  6082. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6083. } elseif ($type == 'select') {
  6084. $out = '';
  6085. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6086. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6087. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6088. }
  6089. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6090. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6091. $out .= '<option value="0">&nbsp;</option>';
  6092. }
  6093. foreach ($param['options'] as $key => $val) {
  6094. if ((string) $key == '') {
  6095. continue;
  6096. }
  6097. list($val, $parent) = explode('|', $val);
  6098. $out .= '<option value="'.$key.'"';
  6099. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  6100. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6101. $out .= '>'.$val.'</option>';
  6102. }
  6103. $out .= '</select>';
  6104. } elseif ($type == 'sellist') {
  6105. $out = '';
  6106. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6107. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6108. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6109. }
  6110. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6111. if (is_array($param['options'])) {
  6112. $param_list = array_keys($param['options']);
  6113. $InfoFieldList = explode(":", $param_list[0]);
  6114. $parentName = '';
  6115. $parentField = '';
  6116. // 0 : tableName
  6117. // 1 : label field name
  6118. // 2 : key fields name (if differ of rowid)
  6119. // 3 : key field parent (for dependent lists)
  6120. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6121. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6122. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6123. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6124. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6125. } else {
  6126. $keyList = $InfoFieldList[2].' as rowid';
  6127. }
  6128. }
  6129. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6130. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6131. $keyList .= ', '.$parentField;
  6132. }
  6133. $fields_label = explode('|', $InfoFieldList[1]);
  6134. if (is_array($fields_label)) {
  6135. $keyList .= ', ';
  6136. $keyList .= implode(', ', $fields_label);
  6137. }
  6138. $sqlwhere = '';
  6139. $sql = "SELECT ".$keyList;
  6140. $sql .= " FROM ".$this->db->prefix().$InfoFieldList[0];
  6141. if (!empty($InfoFieldList[4])) {
  6142. // can use SELECT request
  6143. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6144. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6145. }
  6146. // current object id can be use into filter
  6147. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6148. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6149. } else {
  6150. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6151. }
  6152. //We have to join on extrafield table
  6153. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6154. $sql .= " as main, ".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra";
  6155. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6156. } else {
  6157. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6158. }
  6159. } else {
  6160. $sqlwhere .= ' WHERE 1=1';
  6161. }
  6162. // Some tables may have field, some other not. For the moment we disable it.
  6163. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6164. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6165. }
  6166. $sql .= $sqlwhere;
  6167. //print $sql;
  6168. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  6169. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  6170. $resql = $this->db->query($sql);
  6171. if ($resql) {
  6172. $out .= '<option value="0">&nbsp;</option>';
  6173. $num = $this->db->num_rows($resql);
  6174. $i = 0;
  6175. while ($i < $num) {
  6176. $labeltoshow = '';
  6177. $obj = $this->db->fetch_object($resql);
  6178. // Several field into label (eq table:code|libelle:rowid)
  6179. $notrans = false;
  6180. $fields_label = explode('|', $InfoFieldList[1]);
  6181. if (count($fields_label) > 1) {
  6182. $notrans = true;
  6183. foreach ($fields_label as $field_toshow) {
  6184. $labeltoshow .= $obj->$field_toshow.' ';
  6185. }
  6186. } else {
  6187. $labeltoshow = $obj->{$InfoFieldList[1]};
  6188. }
  6189. $labeltoshow = dol_trunc($labeltoshow, 45);
  6190. if ($value == $obj->rowid) {
  6191. foreach ($fields_label as $field_toshow) {
  6192. $translabel = $langs->trans($obj->$field_toshow);
  6193. if ($translabel != $obj->$field_toshow) {
  6194. $labeltoshow = dol_trunc($translabel).' ';
  6195. } else {
  6196. $labeltoshow = dol_trunc($obj->$field_toshow).' ';
  6197. }
  6198. }
  6199. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6200. } else {
  6201. if (!$notrans) {
  6202. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6203. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6204. $labeltoshow = dol_trunc($translabel, 18);
  6205. } else {
  6206. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6207. }
  6208. }
  6209. if (empty($labeltoshow)) {
  6210. $labeltoshow = '(not defined)';
  6211. }
  6212. if ($value == $obj->rowid) {
  6213. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  6214. }
  6215. if (!empty($InfoFieldList[3]) && $parentField) {
  6216. $parent = $parentName.':'.$obj->{$parentField};
  6217. $isDependList = 1;
  6218. }
  6219. $out .= '<option value="'.$obj->rowid.'"';
  6220. $out .= ($value == $obj->rowid ? ' selected' : '');
  6221. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6222. $out .= '>'.$labeltoshow.'</option>';
  6223. }
  6224. $i++;
  6225. }
  6226. $this->db->free($resql);
  6227. } else {
  6228. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6229. }
  6230. }
  6231. $out .= '</select>';
  6232. } elseif ($type == 'checkbox') {
  6233. $value_arr = explode(',', $value);
  6234. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  6235. } elseif ($type == 'radio') {
  6236. $out = '';
  6237. foreach ($param['options'] as $keyopt => $val) {
  6238. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6239. $out .= ' value="'.$keyopt.'"';
  6240. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6241. $out .= ($value == $keyopt ? 'checked' : '');
  6242. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  6243. }
  6244. } elseif ($type == 'chkbxlst') {
  6245. if (is_array($value)) {
  6246. $value_arr = $value;
  6247. } else {
  6248. $value_arr = explode(',', $value);
  6249. }
  6250. if (is_array($param['options'])) {
  6251. $param_list = array_keys($param['options']);
  6252. $InfoFieldList = explode(":", $param_list[0]);
  6253. $parentName = '';
  6254. $parentField = '';
  6255. // 0 : tableName
  6256. // 1 : label field name
  6257. // 2 : key fields name (if differ of rowid)
  6258. // 3 : key field parent (for dependent lists)
  6259. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6260. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6261. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6262. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6263. $keyList .= ', '.$parentField;
  6264. }
  6265. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6266. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6267. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6268. } else {
  6269. $keyList = $InfoFieldList[2].' as rowid';
  6270. }
  6271. }
  6272. $fields_label = explode('|', $InfoFieldList[1]);
  6273. if (is_array($fields_label)) {
  6274. $keyList .= ', ';
  6275. $keyList .= implode(', ', $fields_label);
  6276. }
  6277. $sqlwhere = '';
  6278. $sql = "SELECT ".$keyList;
  6279. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6280. if (!empty($InfoFieldList[4])) {
  6281. // can use SELECT request
  6282. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6283. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6284. }
  6285. // current object id can be use into filter
  6286. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6287. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6288. } else {
  6289. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6290. }
  6291. // We have to join on extrafield table
  6292. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6293. $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
  6294. $sqlwhere .= " WHERE extra.fk_object=main.".$InfoFieldList[2]." AND ".$InfoFieldList[4];
  6295. } else {
  6296. $sqlwhere .= " WHERE ".$InfoFieldList[4];
  6297. }
  6298. } else {
  6299. $sqlwhere .= ' WHERE 1=1';
  6300. }
  6301. // Some tables may have field, some other not. For the moment we disable it.
  6302. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6303. $sqlwhere .= " AND entity = ".((int) $conf->entity);
  6304. }
  6305. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6306. // print $sql;
  6307. $sql .= $sqlwhere;
  6308. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6309. $resql = $this->db->query($sql);
  6310. if ($resql) {
  6311. $num = $this->db->num_rows($resql);
  6312. $i = 0;
  6313. $data = array();
  6314. while ($i < $num) {
  6315. $labeltoshow = '';
  6316. $obj = $this->db->fetch_object($resql);
  6317. $notrans = false;
  6318. // Several field into label (eq table:code|libelle:rowid)
  6319. $fields_label = explode('|', $InfoFieldList[1]);
  6320. if (count($fields_label) > 1) {
  6321. $notrans = true;
  6322. foreach ($fields_label as $field_toshow) {
  6323. $labeltoshow .= $obj->$field_toshow.' ';
  6324. }
  6325. } else {
  6326. $labeltoshow = $obj->{$InfoFieldList[1]};
  6327. }
  6328. $labeltoshow = dol_trunc($labeltoshow, 45);
  6329. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6330. foreach ($fields_label as $field_toshow) {
  6331. $translabel = $langs->trans($obj->$field_toshow);
  6332. if ($translabel != $obj->$field_toshow) {
  6333. $labeltoshow = dol_trunc($translabel, 18).' ';
  6334. } else {
  6335. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6336. }
  6337. }
  6338. $data[$obj->rowid] = $labeltoshow;
  6339. } else {
  6340. if (!$notrans) {
  6341. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6342. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6343. $labeltoshow = dol_trunc($translabel, 18);
  6344. } else {
  6345. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6346. }
  6347. }
  6348. if (empty($labeltoshow)) {
  6349. $labeltoshow = '(not defined)';
  6350. }
  6351. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6352. $data[$obj->rowid] = $labeltoshow;
  6353. }
  6354. if (!empty($InfoFieldList[3]) && $parentField) {
  6355. $parent = $parentName.':'.$obj->{$parentField};
  6356. $isDependList = 1;
  6357. }
  6358. $data[$obj->rowid] = $labeltoshow;
  6359. }
  6360. $i++;
  6361. }
  6362. $this->db->free($resql);
  6363. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6364. } else {
  6365. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6366. }
  6367. }
  6368. } elseif ($type == 'link') {
  6369. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6370. $param_list_array = explode(':', $param_list[0]);
  6371. $showempty = (($required && $default != '') ? 0 : 1);
  6372. if (!preg_match('/search_/', $keyprefix)) {
  6373. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6374. if (!empty($this->fields[$key]['picto'])) {
  6375. $morecss .= ' widthcentpercentminusxx';
  6376. } else {
  6377. $morecss .= ' widthcentpercentminusx';
  6378. }
  6379. } else {
  6380. if (!empty($this->fields[$key]['picto'])) {
  6381. $morecss .= ' widthcentpercentminusx';
  6382. }
  6383. }
  6384. }
  6385. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6386. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6387. 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".
  6388. list($class, $classfile) = explode(':', $param_list[0]);
  6389. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6390. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6391. } else {
  6392. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6393. }
  6394. $paramforthenewlink = '';
  6395. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6396. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6397. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6398. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6399. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6400. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6401. $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>';
  6402. }
  6403. }
  6404. } elseif ($type == 'password') {
  6405. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6406. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6407. } elseif ($type == 'array') {
  6408. $newval = $val;
  6409. $newval['type'] = 'varchar(256)';
  6410. $out = '';
  6411. if (!empty($value)) {
  6412. foreach ($value as $option) {
  6413. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6414. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6415. }
  6416. }
  6417. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6418. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6419. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6420. if (!empty($conf->use_javascript_ajax)) {
  6421. $out .= '
  6422. <script>
  6423. $(document).ready(function() {
  6424. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6425. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6426. });
  6427. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6428. $(this).parent().remove();
  6429. });
  6430. });
  6431. </script>';
  6432. }
  6433. }
  6434. if (!empty($hidden)) {
  6435. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6436. }
  6437. if ($isDependList==1) {
  6438. $out .= $this->getJSListDependancies('_common');
  6439. }
  6440. /* Add comments
  6441. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6442. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6443. */
  6444. // Display error message for field
  6445. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6446. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6447. }
  6448. return $out;
  6449. }
  6450. /**
  6451. * Return HTML string to show a field into a page
  6452. * Code very similar with showOutputField of extra fields
  6453. *
  6454. * @param array $val Array of properties of field to show
  6455. * @param string $key Key of attribute
  6456. * @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)
  6457. * @param string $moreparam To add more parametes on html input tag
  6458. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6459. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6460. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6461. * @return string
  6462. */
  6463. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6464. {
  6465. global $conf, $langs, $form;
  6466. if (!is_object($form)) {
  6467. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6468. $form = new Form($this->db);
  6469. }
  6470. $objectid = $this->id; // Not used ???
  6471. $label = empty($val['label']) ? '' : $val['label'];
  6472. $type = empty($val['type']) ? '' : $val['type'];
  6473. $size = empty($val['css']) ? '' : $val['css'];
  6474. $reg = array();
  6475. // Convert var to be able to share same code than showOutputField of extrafields
  6476. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6477. $type = 'varchar'; // convert varchar(xx) int varchar
  6478. $size = $reg[1];
  6479. } elseif (preg_match('/varchar/', $type)) {
  6480. $type = 'varchar'; // convert varchar(xx) int varchar
  6481. }
  6482. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6483. $type = 'select';
  6484. }
  6485. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6486. $type = 'link';
  6487. }
  6488. $default = empty($val['default']) ? '' : $val['default'];
  6489. $computed = empty($val['computed']) ? '' : $val['computed'];
  6490. $unique = empty($val['unique']) ? '' : $val['unique'];
  6491. $required = empty($val['required']) ? '' : $val['required'];
  6492. $param = array();
  6493. $param['options'] = array();
  6494. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6495. $param['options'] = $val['arrayofkeyval'];
  6496. }
  6497. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6498. $type = 'link';
  6499. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6500. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6501. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6502. $type = 'sellist';
  6503. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6504. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6505. $type = 'sellist';
  6506. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6507. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6508. $type = 'sellist';
  6509. }
  6510. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6511. $list = (empty($val['list']) ? '' : $val['list']);
  6512. $help = (empty($val['help']) ? '' : $val['help']);
  6513. $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)
  6514. if ($hidden) {
  6515. return '';
  6516. }
  6517. // If field is a computed field, value must become result of compute
  6518. if ($computed) {
  6519. // Make the eval of compute string
  6520. //var_dump($computed);
  6521. $value = dol_eval($computed, 1, 0, '');
  6522. }
  6523. if (empty($morecss)) {
  6524. if ($type == 'date') {
  6525. $morecss = 'minwidth100imp';
  6526. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6527. $morecss = 'minwidth200imp';
  6528. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6529. $morecss = 'maxwidth75';
  6530. } elseif ($type == 'url') {
  6531. $morecss = 'minwidth400';
  6532. } elseif ($type == 'boolean') {
  6533. $morecss = '';
  6534. } else {
  6535. if (is_numeric($size) && round($size) < 12) {
  6536. $morecss = 'minwidth100';
  6537. } elseif (is_numeric($size) && round($size) <= 48) {
  6538. $morecss = 'minwidth200';
  6539. } else {
  6540. $morecss = 'minwidth400';
  6541. }
  6542. }
  6543. }
  6544. // Format output value differently according to properties of field
  6545. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6546. $value = $this->getNomUrl(1, '', 0, '', 1);
  6547. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6548. $value = $this->getLibStatut(3);
  6549. } elseif ($type == 'date') {
  6550. if (!empty($value)) {
  6551. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6552. } else {
  6553. $value = '';
  6554. }
  6555. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6556. if (!empty($value)) {
  6557. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6558. } else {
  6559. $value = '';
  6560. }
  6561. } elseif ($type == 'duration') {
  6562. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6563. if (!is_null($value) && $value !== '') {
  6564. $value = convertSecondToTime($value, 'allhourmin');
  6565. }
  6566. } elseif ($type == 'double' || $type == 'real') {
  6567. if (!is_null($value) && $value !== '') {
  6568. $value = price($value);
  6569. }
  6570. } elseif ($type == 'boolean') {
  6571. $checked = '';
  6572. if (!empty($value)) {
  6573. $checked = ' checked ';
  6574. }
  6575. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6576. } elseif ($type == 'mail') {
  6577. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6578. } elseif ($type == 'url') {
  6579. $value = dol_print_url($value, '_blank', 32, 1);
  6580. } elseif ($type == 'phone') {
  6581. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6582. } elseif ($type == 'price') {
  6583. if (!is_null($value) && $value !== '') {
  6584. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6585. }
  6586. } elseif ($type == 'select') {
  6587. $value = $param['options'][$value];
  6588. } elseif ($type == 'sellist') {
  6589. $param_list = array_keys($param['options']);
  6590. $InfoFieldList = explode(":", $param_list[0]);
  6591. $selectkey = "rowid";
  6592. $keyList = 'rowid';
  6593. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6594. $selectkey = $InfoFieldList[2];
  6595. $keyList = $InfoFieldList[2].' as rowid';
  6596. }
  6597. $fields_label = explode('|', $InfoFieldList[1]);
  6598. if (is_array($fields_label)) {
  6599. $keyList .= ', ';
  6600. $keyList .= implode(', ', $fields_label);
  6601. }
  6602. $sql = "SELECT ".$keyList;
  6603. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6604. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6605. $sql .= ' as main';
  6606. }
  6607. if ($selectkey == 'rowid' && empty($value)) {
  6608. $sql .= " WHERE ".$selectkey." = 0";
  6609. } elseif ($selectkey == 'rowid') {
  6610. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6611. } else {
  6612. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6613. }
  6614. //$sql.= ' AND entity = '.$conf->entity;
  6615. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6616. $resql = $this->db->query($sql);
  6617. if ($resql) {
  6618. $value = ''; // value was used, so now we reste it to use it to build final output
  6619. $obj = $this->db->fetch_object($resql);
  6620. // Several field into label (eq table:code|libelle:rowid)
  6621. $fields_label = explode('|', $InfoFieldList[1]);
  6622. if (is_array($fields_label) && count($fields_label) > 1) {
  6623. foreach ($fields_label as $field_toshow) {
  6624. $translabel = '';
  6625. if (!empty($obj->$field_toshow)) {
  6626. $translabel = $langs->trans($obj->$field_toshow);
  6627. }
  6628. if ($translabel != $field_toshow) {
  6629. $value .= dol_trunc($translabel, 18).' ';
  6630. } else {
  6631. $value .= $obj->$field_toshow.' ';
  6632. }
  6633. }
  6634. } else {
  6635. $translabel = '';
  6636. if (!empty($obj->{$InfoFieldList[1]})) {
  6637. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6638. }
  6639. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6640. $value = dol_trunc($translabel, 18);
  6641. } else {
  6642. $value = $obj->{$InfoFieldList[1]};
  6643. }
  6644. }
  6645. } else {
  6646. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6647. }
  6648. } elseif ($type == 'radio') {
  6649. $value = $param['options'][$value];
  6650. } elseif ($type == 'checkbox') {
  6651. $value_arr = explode(',', $value);
  6652. $value = '';
  6653. if (is_array($value_arr) && count($value_arr) > 0) {
  6654. $toprint = array();
  6655. foreach ($value_arr as $keyval => $valueval) {
  6656. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6657. }
  6658. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6659. }
  6660. } elseif ($type == 'chkbxlst') {
  6661. $value_arr = explode(',', $value);
  6662. $param_list = array_keys($param['options']);
  6663. $InfoFieldList = explode(":", $param_list[0]);
  6664. $selectkey = "rowid";
  6665. $keyList = 'rowid';
  6666. if (count($InfoFieldList) >= 3) {
  6667. $selectkey = $InfoFieldList[2];
  6668. $keyList = $InfoFieldList[2].' as rowid';
  6669. }
  6670. $fields_label = explode('|', $InfoFieldList[1]);
  6671. if (is_array($fields_label)) {
  6672. $keyList .= ', ';
  6673. $keyList .= implode(', ', $fields_label);
  6674. }
  6675. $sql = "SELECT ".$keyList;
  6676. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6677. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6678. $sql .= ' as main';
  6679. }
  6680. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6681. // $sql.= ' AND entity = '.$conf->entity;
  6682. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6683. $resql = $this->db->query($sql);
  6684. if ($resql) {
  6685. $value = ''; // value was used, so now we reste it to use it to build final output
  6686. $toprint = array();
  6687. while ($obj = $this->db->fetch_object($resql)) {
  6688. // Several field into label (eq table:code|libelle:rowid)
  6689. $fields_label = explode('|', $InfoFieldList[1]);
  6690. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6691. if (is_array($fields_label) && count($fields_label) > 1) {
  6692. foreach ($fields_label as $field_toshow) {
  6693. $translabel = '';
  6694. if (!empty($obj->$field_toshow)) {
  6695. $translabel = $langs->trans($obj->$field_toshow);
  6696. }
  6697. if ($translabel != $field_toshow) {
  6698. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6699. } else {
  6700. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6701. }
  6702. }
  6703. } else {
  6704. $translabel = '';
  6705. if (!empty($obj->{$InfoFieldList[1]})) {
  6706. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6707. }
  6708. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6709. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6710. } else {
  6711. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6712. }
  6713. }
  6714. }
  6715. }
  6716. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6717. } else {
  6718. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6719. }
  6720. } elseif ($type == 'link') {
  6721. $out = '';
  6722. // only if something to display (perf)
  6723. if ($value) {
  6724. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6725. $InfoFieldList = explode(":", $param_list[0]);
  6726. $classname = $InfoFieldList[0];
  6727. $classpath = $InfoFieldList[1];
  6728. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6729. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6730. if (!empty($classpath)) {
  6731. dol_include_once($InfoFieldList[1]);
  6732. if ($classname && class_exists($classname)) {
  6733. $object = new $classname($this->db);
  6734. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6735. $object->fetch($value, '', '', '', 0, 1, 1);
  6736. } else {
  6737. $object->fetch($value);
  6738. }
  6739. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6740. }
  6741. } else {
  6742. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6743. return 'Error bad setup of extrafield';
  6744. }
  6745. } else {
  6746. $value = '';
  6747. }
  6748. } elseif (preg_match('/^(text|html)/', $type)) {
  6749. $value = dol_htmlentitiesbr($value);
  6750. } elseif ($type == 'password') {
  6751. $value = preg_replace('/./i', '*', $value);
  6752. } elseif ($type == 'array') {
  6753. $value = implode('<br>', $value);
  6754. }
  6755. //print $type.'-'.$size.'-'.$value;
  6756. $out = $value;
  6757. return $out;
  6758. }
  6759. /**
  6760. * clear validation message result for a field
  6761. *
  6762. * @param string $fieldKey Key of attribute to clear
  6763. * @return null
  6764. */
  6765. public function clearFieldError($fieldKey)
  6766. {
  6767. $this->error = '';
  6768. unset($this->validateFieldsErrors[$fieldKey]);
  6769. }
  6770. /**
  6771. * set validation error message a field
  6772. *
  6773. * @param string $fieldKey Key of attribute
  6774. * @param string $msg the field error message
  6775. * @return null
  6776. */
  6777. public function setFieldError($fieldKey, $msg = '')
  6778. {
  6779. global $langs;
  6780. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  6781. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  6782. }
  6783. /**
  6784. * get field error message
  6785. *
  6786. * @param string $fieldKey Key of attribute
  6787. * @return string
  6788. */
  6789. public function getFieldError($fieldKey)
  6790. {
  6791. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  6792. return $this->validateFieldsErrors[$fieldKey];
  6793. }
  6794. return '';
  6795. }
  6796. /**
  6797. * Return validation test result for a field
  6798. *
  6799. * @param array $val Array of properties of field to show
  6800. * @param string $fieldKey Key of attribute
  6801. * @param string $fieldValue value of attribute
  6802. * @return bool return false if fail true on success, see $this->error for error message
  6803. */
  6804. public function validateField($val, $fieldKey, $fieldValue)
  6805. {
  6806. global $langs;
  6807. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  6808. $this->clearFieldError($fieldKey);
  6809. if (!isset($val[$fieldKey])) {
  6810. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  6811. return false;
  6812. }
  6813. $param = array();
  6814. $param['options'] = array();
  6815. $type = $val[$fieldKey]['type'];
  6816. $required = false;
  6817. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  6818. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  6819. $required = true;
  6820. }
  6821. $maxSize = 0;
  6822. $minSize = 0;
  6823. //
  6824. // PREPARE Elements
  6825. //
  6826. // Convert var to be able to share same code than showOutputField of extrafields
  6827. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6828. $type = 'varchar'; // convert varchar(xx) int varchar
  6829. $maxSize = $reg[1];
  6830. } elseif (preg_match('/varchar/', $type)) {
  6831. $type = 'varchar'; // convert varchar(xx) int varchar
  6832. }
  6833. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6834. $type = 'select';
  6835. }
  6836. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6837. $type = 'link';
  6838. }
  6839. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6840. $param['options'] = $val['arrayofkeyval'];
  6841. }
  6842. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6843. $type = 'link';
  6844. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6845. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6846. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6847. $type = 'sellist';
  6848. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6849. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6850. $type = 'sellist';
  6851. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6852. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6853. $type = 'sellist';
  6854. }
  6855. //
  6856. // TEST Value
  6857. //
  6858. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  6859. $validate = new Validate($this->db, $langs);
  6860. // little trick : to perform tests with good performances sort tests by quick to low
  6861. //
  6862. // COMMON TESTS
  6863. //
  6864. // Required test and empty value
  6865. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  6866. $this->setFieldError($fieldKey, $validate->error);
  6867. return false;
  6868. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  6869. // if no value sent and the field is not mandatory, no need to perform tests
  6870. return true;
  6871. }
  6872. // MAX Size test
  6873. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  6874. $this->setFieldError($fieldKey, $validate->error);
  6875. return false;
  6876. }
  6877. // MIN Size test
  6878. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  6879. $this->setFieldError($fieldKey, $validate->error);
  6880. return false;
  6881. }
  6882. //
  6883. // TESTS for TYPE
  6884. //
  6885. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  6886. if (!$validate->isTimestamp($fieldValue)) {
  6887. $this->setFieldError($fieldKey, $validate->error);
  6888. return false;
  6889. } else { return true; }
  6890. } elseif ($type == 'duration') {
  6891. if (!$validate->isDuration($fieldValue)) {
  6892. $this->setFieldError($fieldKey, $validate->error);
  6893. return false;
  6894. } else { return true; }
  6895. } elseif (in_array($type, array('double', 'real', 'price'))) {
  6896. // is numeric
  6897. if (!$validate->isNumeric($fieldValue)) {
  6898. $this->setFieldError($fieldKey, $validate->error);
  6899. return false;
  6900. } else { return true; }
  6901. } elseif ($type == 'boolean') {
  6902. if (!$validate->isBool($fieldValue)) {
  6903. $this->setFieldError($fieldKey, $validate->error);
  6904. return false;
  6905. } else { return true; }
  6906. } elseif ($type == 'mail') {
  6907. if (!$validate->isEmail($fieldValue)) {
  6908. $this->setFieldError($fieldKey, $validate->error);
  6909. return false;
  6910. }
  6911. } elseif ($type == 'url') {
  6912. if (!$validate->isUrl($fieldValue)) {
  6913. $this->setFieldError($fieldKey, $validate->error);
  6914. return false;
  6915. } else { return true; }
  6916. } elseif ($type == 'phone') {
  6917. if (!$validate->isPhone($fieldValue)) {
  6918. $this->setFieldError($fieldKey, $validate->error);
  6919. return false;
  6920. } else { return true; }
  6921. } elseif ($type == 'select' || $type == 'radio') {
  6922. if (!isset($param['options'][$fieldValue])) {
  6923. $this->error = $langs->trans('RequireValidValue');
  6924. return false;
  6925. } else { return true; }
  6926. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  6927. $param_list = array_keys($param['options']);
  6928. $InfoFieldList = explode(":", $param_list[0]);
  6929. $value_arr = explode(',', $fieldValue);
  6930. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  6931. $selectkey = "rowid";
  6932. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6933. $selectkey = $InfoFieldList[2];
  6934. }
  6935. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  6936. $this->setFieldError($fieldKey, $validate->error);
  6937. return false;
  6938. } else { return true; }
  6939. } elseif ($type == 'link') {
  6940. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6941. $InfoFieldList = explode(":", $param_list[0]);
  6942. $classname = $InfoFieldList[0];
  6943. $classpath = $InfoFieldList[1];
  6944. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  6945. $this->setFieldError($fieldKey, $validate->error);
  6946. return false;
  6947. } else { return true; }
  6948. }
  6949. // if no test failled all is ok
  6950. return true;
  6951. }
  6952. /**
  6953. * Function to show lines of extrafields with output datas.
  6954. * 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
  6955. *
  6956. * @param Extrafields $extrafields Extrafield Object
  6957. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6958. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6959. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6960. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6961. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6962. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6963. * @return string String with html content to show
  6964. */
  6965. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6966. {
  6967. global $db, $conf, $langs, $action, $form, $hookmanager;
  6968. if (!is_object($form)) {
  6969. $form = new Form($db);
  6970. }
  6971. if (!is_object($extrafields)) {
  6972. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  6973. return 'Bad parameter extrafields for showOptionals';
  6974. }
  6975. if (!is_array($extrafields->attributes[$this->table_element])) {
  6976. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  6977. }
  6978. $out = '';
  6979. $parameters = array();
  6980. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6981. if (empty($reshook)) {
  6982. 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) {
  6983. $out .= "\n";
  6984. $out .= '<!-- commonobject:showOptionals --> ';
  6985. $out .= "\n";
  6986. $extrafields_collapse_num = '';
  6987. $e = 0;
  6988. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6989. // Show only the key field in params
  6990. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6991. continue;
  6992. }
  6993. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6994. $enabled = 1;
  6995. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6996. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
  6997. }
  6998. if (empty($enabled)) {
  6999. continue;
  7000. }
  7001. $visibility = 1;
  7002. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  7003. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
  7004. }
  7005. $perms = 1;
  7006. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  7007. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
  7008. }
  7009. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7010. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7011. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7012. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7013. } elseif ($mode == 'view' && empty($visibility)) {
  7014. continue;
  7015. }
  7016. if (empty($perms)) {
  7017. continue;
  7018. }
  7019. // Load language if required
  7020. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7021. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7022. }
  7023. $colspan = 0;
  7024. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  7025. if (array_key_exists('cols', $params)) {
  7026. $colspan = $params['cols'];
  7027. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7028. $reg = array();
  7029. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7030. $colspan = $reg[1];
  7031. } else {
  7032. $colspan = $params['colspan'];
  7033. }
  7034. }
  7035. }
  7036. $colspan = intval($colspan);
  7037. switch ($mode) {
  7038. case "view":
  7039. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  7040. break;
  7041. case "create":
  7042. case "edit":
  7043. // We get the value of property found with GETPOST so it takes into account:
  7044. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7045. $check = 'alphanohtml';
  7046. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7047. $check = 'restricthtml';
  7048. }
  7049. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7050. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7051. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7052. if (is_array($getposttemp)) {
  7053. // $getposttemp is an array but following code expects a comma separated string
  7054. $value = implode(",", $getposttemp);
  7055. } else {
  7056. $value = $getposttemp;
  7057. }
  7058. } else {
  7059. $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.
  7060. }
  7061. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7062. break;
  7063. }
  7064. // Output value of the current field
  7065. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7066. $extrafields_collapse_num = '';
  7067. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7068. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7069. $extrafield_param_list = array_keys($extrafield_param['options']);
  7070. if (count($extrafield_param_list) > 0) {
  7071. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7072. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7073. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7074. }
  7075. }
  7076. }
  7077. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7078. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7079. } else {
  7080. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7081. $csstyle = '';
  7082. if (is_array($params) && count($params) > 0) {
  7083. if (array_key_exists('class', $params)) {
  7084. $class .= $params['class'].' ';
  7085. }
  7086. if (array_key_exists('style', $params)) {
  7087. $csstyle = $params['style'];
  7088. }
  7089. }
  7090. // add html5 elements
  7091. $domData = ' data-element="extrafield"';
  7092. $domData .= ' data-targetelement="'.$this->element.'"';
  7093. $domData .= ' data-targetid="'.$this->id.'"';
  7094. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7095. if ($display_type=='card') {
  7096. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7097. $colspan = 0;
  7098. }
  7099. if ($action == 'selectlines') {
  7100. $colspan++;
  7101. }
  7102. }
  7103. // Convert date into timestamp format (value in memory must be a timestamp)
  7104. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7105. $datenotinstring = null;
  7106. if (array_key_exists('options_'.$key, $this->array_options)) {
  7107. $datenotinstring = $this->array_options['options_'.$key];
  7108. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7109. $datenotinstring = $this->db->jdate($datenotinstring);
  7110. }
  7111. }
  7112. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(12, 0, 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3)) : $datenotinstring;
  7113. }
  7114. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7115. $datenotinstring = null;
  7116. if (array_key_exists('options_'.$key, $this->array_options)) {
  7117. $datenotinstring = $this->array_options['options_'.$key];
  7118. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7119. $datenotinstring = $this->db->jdate($datenotinstring);
  7120. }
  7121. }
  7122. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) ? dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."sec", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3), 'tzuserrel') : $datenotinstring;
  7123. }
  7124. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7125. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7126. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  7127. }
  7128. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7129. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  7130. if ($action == 'create') {
  7131. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7132. }
  7133. }
  7134. $labeltoshow = $langs->trans($label);
  7135. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7136. if ($display_type == 'card') {
  7137. $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.' >';
  7138. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
  7139. $out .= '<td></td>';
  7140. }
  7141. $out .= '<td class="titlefieldcreate wordbreak';
  7142. } elseif ($display_type == 'line') {
  7143. $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.' >';
  7144. $out .= '<div style="display: inline-block; padding-right:4px" class="titlefieldcreate wordbreak';
  7145. }
  7146. //$out .= "titlefield";
  7147. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7148. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7149. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7150. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7151. $out .= '">';
  7152. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7153. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7154. } else {
  7155. $out .= $labeltoshow;
  7156. }
  7157. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7158. $out .= '&nbsp;<span style="color: red">*</span>';
  7159. }
  7160. } else {
  7161. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7162. $out .= ' fieldrequired';
  7163. }
  7164. $out .= '">';
  7165. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7166. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7167. } else {
  7168. $out .= $labeltoshow;
  7169. }
  7170. }
  7171. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7172. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7173. if ($display_type == 'card') {
  7174. // 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
  7175. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7176. } elseif ($display_type == 'line') {
  7177. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="valuefieldcreate '.$this->element.'_extras_'.$key.'">';
  7178. }
  7179. switch ($mode) {
  7180. case "view":
  7181. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7182. break;
  7183. case "create":
  7184. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7185. break;
  7186. case "edit":
  7187. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7188. break;
  7189. }
  7190. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7191. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7192. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7193. } else {
  7194. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7195. }
  7196. $e++;
  7197. }
  7198. }
  7199. $out .= "\n";
  7200. // Add code to manage list depending on others
  7201. if (!empty($conf->use_javascript_ajax)) {
  7202. $out .= $this->getJSListDependancies();
  7203. }
  7204. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7205. }
  7206. }
  7207. $out .= $hookmanager->resPrint;
  7208. return $out;
  7209. }
  7210. /**
  7211. * @param string $type Type for prefix
  7212. * @return string Javacript code to manage dependency
  7213. */
  7214. public function getJSListDependancies($type = '_extra')
  7215. {
  7216. $out = '
  7217. <script>
  7218. jQuery(document).ready(function() {
  7219. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7220. {
  7221. var val = $("select[name=\""+parent_list+"\"]").val();
  7222. var parentVal = parent_list + ":" + val;
  7223. if(typeof val == "string"){
  7224. if(val != "") {
  7225. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7226. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7227. $("select[name=\""+child_list+"\"]").append(options);
  7228. } else {
  7229. var options = orig_select.find("option[parent]").clone();
  7230. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7231. $("select[name=\""+child_list+"\"]").append(options);
  7232. }
  7233. } else if(val > 0) {
  7234. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7235. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7236. $("select[name=\""+child_list+"\"]").append(options);
  7237. } else {
  7238. var options = orig_select.find("option[parent]").clone();
  7239. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7240. $("select[name=\""+child_list+"\"]").append(options);
  7241. }
  7242. }
  7243. function setListDependencies'.$type.'() {
  7244. jQuery("select option[parent]").parent().each(function() {
  7245. var orig_select = {};
  7246. var child_list = $(this).attr("name");
  7247. orig_select[child_list] = $(this).clone();
  7248. var parent = $(this).find("option[parent]:first").attr("parent");
  7249. var infos = parent.split(":");
  7250. var parent_list = infos[0];
  7251. //Hide daughters lists
  7252. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7253. $("#"+child_list).hide();
  7254. //Show mother lists
  7255. } else if ($("#"+parent_list).val() != 0){
  7256. $("#"+parent_list).show();
  7257. }
  7258. //Show the child list if the parent list value is selected
  7259. $("select[name=\""+parent_list+"\"]").click(function() {
  7260. if ($(this).val() != 0){
  7261. $("#"+child_list).show()
  7262. }
  7263. });
  7264. //When we change parent list
  7265. $("select[name=\""+parent_list+"\"]").change(function() {
  7266. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7267. //Select the value 0 on child list after a change on the parent list
  7268. $("#"+child_list).val(0).trigger("change");
  7269. //Hide child lists if the parent value is set to 0
  7270. if ($(this).val() == 0){
  7271. $("#"+child_list).hide();
  7272. }
  7273. });
  7274. });
  7275. }
  7276. setListDependencies'.$type.'();
  7277. });
  7278. </script>'."\n";
  7279. return $out;
  7280. }
  7281. /**
  7282. * Returns the rights used for this class
  7283. * @return stdClass
  7284. */
  7285. public function getRights()
  7286. {
  7287. global $user;
  7288. $element = $this->element;
  7289. if ($element == 'facturerec') {
  7290. $element = 'facture';
  7291. } elseif ($element == 'invoice_supplier_rec') {
  7292. return $user->rights->fournisseur->facture;
  7293. }
  7294. return $user->rights->{$element};
  7295. }
  7296. /**
  7297. * Function used to replace a thirdparty id with another one.
  7298. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7299. * Column name fk_soc MUST be used to identify thirdparties
  7300. *
  7301. * @param DoliDB $db Database handler
  7302. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7303. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7304. * @param string[] $tables Tables that need to be changed
  7305. * @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)
  7306. * @return bool True if success, False if error
  7307. */
  7308. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7309. {
  7310. foreach ($tables as $table) {
  7311. $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7312. if (!$db->query($sql)) {
  7313. if ($ignoreerrors) {
  7314. 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.
  7315. }
  7316. //$this->errors = $db->lasterror();
  7317. return false;
  7318. }
  7319. }
  7320. return true;
  7321. }
  7322. /**
  7323. * Function used to replace a product id with another one.
  7324. * This function is meant to be called from replaceProduct with the appropriate tables
  7325. * Column name fk_product MUST be used to identify products
  7326. *
  7327. * @param DoliDB $db Database handler
  7328. * @param int $origin_id Old product id (the product to delete)
  7329. * @param int $dest_id New product id (the product that will received element of the other)
  7330. * @param string[] $tables Tables that need to be changed
  7331. * @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)
  7332. * @return bool True if success, False if error
  7333. */
  7334. public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7335. {
  7336. foreach ($tables as $table) {
  7337. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7338. if (!$db->query($sql)) {
  7339. if ($ignoreerrors) {
  7340. 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.
  7341. }
  7342. //$this->errors = $db->lasterror();
  7343. return false;
  7344. }
  7345. }
  7346. return true;
  7347. }
  7348. /**
  7349. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7350. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7351. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7352. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7353. * else set min buy price as buy price
  7354. *
  7355. * @param float $unitPrice Product unit price
  7356. * @param float $discountPercent Line discount percent
  7357. * @param int $fk_product Product id
  7358. * @return float <0 if KO, buyprice if OK
  7359. */
  7360. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7361. {
  7362. global $conf;
  7363. $buyPrice = 0;
  7364. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7365. // When ForceBuyingPriceIfNull is set
  7366. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7367. } else {
  7368. // Get cost price for margin calculation
  7369. if (!empty($fk_product) && $fk_product > 0) {
  7370. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7371. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7372. $product = new Product($this->db);
  7373. $result = $product->fetch($fk_product);
  7374. if ($result <= 0) {
  7375. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7376. return -1;
  7377. }
  7378. if ($product->cost_price > 0) {
  7379. $buyPrice = $product->cost_price;
  7380. } elseif ($product->pmp > 0) {
  7381. $buyPrice = $product->pmp;
  7382. }
  7383. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7384. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7385. $product = new Product($this->db);
  7386. $result = $product->fetch($fk_product);
  7387. if ($result <= 0) {
  7388. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7389. return -1;
  7390. }
  7391. if ($product->pmp > 0) {
  7392. $buyPrice = $product->pmp;
  7393. }
  7394. }
  7395. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7396. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7397. $productFournisseur = new ProductFournisseur($this->db);
  7398. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7399. $buyPrice = $productFournisseur->fourn_unitprice;
  7400. } elseif ($result < 0) {
  7401. $this->errors[] = $productFournisseur->error;
  7402. return -2;
  7403. }
  7404. }
  7405. }
  7406. }
  7407. return $buyPrice;
  7408. }
  7409. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7410. /**
  7411. * Show photos of an object (nbmax maximum), into several columns
  7412. *
  7413. * @param string $modulepart 'product', 'ticket', ...
  7414. * @param string $sdir Directory to scan (full absolute path)
  7415. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7416. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7417. * @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'.
  7418. * @param int $showfilename 1=Show filename
  7419. * @param int $showaction 1=Show icon with action links (resize, delete)
  7420. * @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.
  7421. * @param int $maxWidth Max width of original image when size='small'
  7422. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7423. * @param int $notitle Do not add title tag on image
  7424. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7425. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7426. */
  7427. 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)
  7428. {
  7429. // phpcs:enable
  7430. global $conf, $user, $langs;
  7431. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7432. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7433. $sortfield = 'position_name';
  7434. $sortorder = 'asc';
  7435. $dir = $sdir.'/';
  7436. $pdir = '/';
  7437. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7438. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7439. // For backward compatibility
  7440. if ($modulepart == 'product') {
  7441. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  7442. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7443. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7444. }
  7445. }
  7446. // Defined relative dir to DOL_DATA_ROOT
  7447. $relativedir = '';
  7448. if ($dir) {
  7449. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7450. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7451. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7452. }
  7453. $dirthumb = $dir.'thumbs/';
  7454. $pdirthumb = $pdir.'thumbs/';
  7455. $return = '<!-- Photo -->'."\n";
  7456. $nbphoto = 0;
  7457. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7458. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  7459. {
  7460. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7461. $filearray=array_merge($filearray, $filearrayold);
  7462. }*/
  7463. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7464. if (count($filearray)) {
  7465. if ($sortfield && $sortorder) {
  7466. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7467. }
  7468. foreach ($filearray as $key => $val) {
  7469. $photo = '';
  7470. $file = $val['name'];
  7471. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  7472. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7473. if (image_format_supported($file) >= 0) {
  7474. $nbphoto++;
  7475. $photo = $file;
  7476. $viewfilename = $file;
  7477. if ($size == 1 || $size == 'small') { // Format vignette
  7478. // Find name of thumb file
  7479. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7480. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7481. $photo_vignette = '';
  7482. }
  7483. // Get filesize of original file
  7484. $imgarray = dol_getImageSize($dir.$photo);
  7485. if ($nbbyrow > 0) {
  7486. if ($nbphoto == 1) {
  7487. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7488. }
  7489. if ($nbphoto % $nbbyrow == 1) {
  7490. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7491. }
  7492. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7493. } elseif ($nbbyrow < 0) {
  7494. $return .= '<div class="inline-block">';
  7495. }
  7496. $return .= "\n";
  7497. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7498. if (empty($nolink)) {
  7499. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7500. if ($urladvanced) {
  7501. $return .= '<a href="'.$urladvanced.'">';
  7502. } else {
  7503. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7504. }
  7505. }
  7506. // Show image (width height=$maxHeight)
  7507. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7508. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7509. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7510. if ($notitle) {
  7511. $alt = '';
  7512. }
  7513. $addphotorefcss = 1;
  7514. if ($usesharelink) {
  7515. if ($val['share']) {
  7516. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7517. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7518. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7519. } else {
  7520. $return .= '<!-- Show original file -->';
  7521. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7522. }
  7523. } else {
  7524. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7525. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7526. }
  7527. } else {
  7528. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7529. $return .= '<!-- Show thumb -->';
  7530. $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).'">';
  7531. } else {
  7532. $return .= '<!-- Show original file -->';
  7533. $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).'">';
  7534. }
  7535. }
  7536. if (empty($nolink)) {
  7537. $return .= '</a>';
  7538. }
  7539. $return .= "\n";
  7540. if ($showfilename) {
  7541. $return .= '<br>'.$viewfilename;
  7542. }
  7543. if ($showaction) {
  7544. $return .= '<br>';
  7545. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7546. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7547. $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>';
  7548. }
  7549. // Special cas for product
  7550. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7551. // Link to resize
  7552. $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; ';
  7553. // Link to delete
  7554. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7555. $return .= img_delete().'</a>';
  7556. }
  7557. }
  7558. $return .= "\n";
  7559. if ($nbbyrow > 0) {
  7560. $return .= '</td>';
  7561. if (($nbphoto % $nbbyrow) == 0) {
  7562. $return .= '</tr>';
  7563. }
  7564. } elseif ($nbbyrow < 0) {
  7565. $return .= '</div>';
  7566. }
  7567. }
  7568. if (empty($size)) { // Format origine
  7569. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7570. if ($showfilename) {
  7571. $return .= '<br>'.$viewfilename;
  7572. }
  7573. if ($showaction) {
  7574. // Special case for product
  7575. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7576. // Link to resize
  7577. $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; ';
  7578. // Link to delete
  7579. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7580. $return .= img_delete().'</a>';
  7581. }
  7582. }
  7583. }
  7584. // On continue ou on arrete de boucler ?
  7585. if ($nbmax && $nbphoto >= $nbmax) {
  7586. break;
  7587. }
  7588. }
  7589. }
  7590. if ($size == 1 || $size == 'small') {
  7591. if ($nbbyrow > 0) {
  7592. // Ferme tableau
  7593. while ($nbphoto % $nbbyrow) {
  7594. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7595. $nbphoto++;
  7596. }
  7597. if ($nbphoto) {
  7598. $return .= '</table>';
  7599. }
  7600. }
  7601. }
  7602. }
  7603. $this->nbphoto = $nbphoto;
  7604. return $return;
  7605. }
  7606. /**
  7607. * Function test if type is array
  7608. *
  7609. * @param array $info content informations of field
  7610. * @return bool true if array
  7611. */
  7612. protected function isArray($info)
  7613. {
  7614. if (is_array($info)) {
  7615. if (isset($info['type']) && $info['type'] == 'array') {
  7616. return true;
  7617. } else {
  7618. return false;
  7619. }
  7620. }
  7621. return false;
  7622. }
  7623. /**
  7624. * Function test if type is date
  7625. *
  7626. * @param array $info content informations of field
  7627. * @return bool true if date
  7628. */
  7629. public function isDate($info)
  7630. {
  7631. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7632. return true;
  7633. }
  7634. return false;
  7635. }
  7636. /**
  7637. * Function test if type is duration
  7638. *
  7639. * @param array $info content informations of field
  7640. * @return bool true if field of type duration
  7641. */
  7642. public function isDuration($info)
  7643. {
  7644. if (is_array($info)) {
  7645. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7646. return true;
  7647. } else {
  7648. return false;
  7649. }
  7650. } else {
  7651. return false;
  7652. }
  7653. }
  7654. /**
  7655. * Function test if type is integer
  7656. *
  7657. * @param array $info content informations of field
  7658. * @return bool true if integer
  7659. */
  7660. public function isInt($info)
  7661. {
  7662. if (is_array($info)) {
  7663. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7664. return true;
  7665. } else {
  7666. return false;
  7667. }
  7668. } else {
  7669. return false;
  7670. }
  7671. }
  7672. /**
  7673. * Function test if type is float
  7674. *
  7675. * @param array $info content informations of field
  7676. * @return bool true if float
  7677. */
  7678. public function isFloat($info)
  7679. {
  7680. if (is_array($info)) {
  7681. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7682. return true;
  7683. } else {
  7684. return false;
  7685. }
  7686. }
  7687. return false;
  7688. }
  7689. /**
  7690. * Function test if type is text
  7691. *
  7692. * @param array $info content informations of field
  7693. * @return bool true if type text
  7694. */
  7695. public function isText($info)
  7696. {
  7697. if (is_array($info)) {
  7698. if (isset($info['type']) && $info['type'] == 'text') {
  7699. return true;
  7700. } else {
  7701. return false;
  7702. }
  7703. }
  7704. return false;
  7705. }
  7706. /**
  7707. * Function test if field can be null
  7708. *
  7709. * @param array $info content informations of field
  7710. * @return bool true if it can be null
  7711. */
  7712. protected function canBeNull($info)
  7713. {
  7714. if (is_array($info)) {
  7715. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7716. return true;
  7717. } else {
  7718. return false;
  7719. }
  7720. }
  7721. return true;
  7722. }
  7723. /**
  7724. * Function test if field is forced to null if zero or empty
  7725. *
  7726. * @param array $info content informations of field
  7727. * @return bool true if forced to null
  7728. */
  7729. protected function isForcedToNullIfZero($info)
  7730. {
  7731. if (is_array($info)) {
  7732. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7733. return true;
  7734. } else {
  7735. return false;
  7736. }
  7737. }
  7738. return false;
  7739. }
  7740. /**
  7741. * Function test if is indexed
  7742. *
  7743. * @param array $info content informations of field
  7744. * @return bool
  7745. */
  7746. protected function isIndex($info)
  7747. {
  7748. if (is_array($info)) {
  7749. if (isset($info['index']) && $info['index'] == true) {
  7750. return true;
  7751. } else {
  7752. return false;
  7753. }
  7754. }
  7755. return false;
  7756. }
  7757. /**
  7758. * Function to prepare a part of the query for insert.
  7759. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7760. * $this->${field} should be a clean value. The page can run
  7761. *
  7762. * @return array
  7763. */
  7764. protected function setSaveQuery()
  7765. {
  7766. global $conf;
  7767. $queryarray = array();
  7768. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7769. // Depending on field type ('datetime', ...)
  7770. if ($this->isDate($info)) {
  7771. if (empty($this->{$field})) {
  7772. $queryarray[$field] = null;
  7773. } else {
  7774. $queryarray[$field] = $this->db->idate($this->{$field});
  7775. }
  7776. } elseif ($this->isDuration($info)) {
  7777. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7778. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7779. if (!isset($this->{$field})) {
  7780. $queryarray[$field] = 0;
  7781. } else {
  7782. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7783. }
  7784. } else {
  7785. $queryarray[$field] = null;
  7786. }
  7787. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7788. if ($field == 'entity' && is_null($this->{$field})) {
  7789. $queryarray[$field] = $conf->entity;
  7790. } else {
  7791. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7792. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7793. if (!isset($this->{$field})) {
  7794. $queryarray[$field] = 0;
  7795. } elseif ($this->isInt($info)) {
  7796. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7797. } elseif ($this->isFloat($info)) {
  7798. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7799. }
  7800. } else {
  7801. $queryarray[$field] = null;
  7802. }
  7803. }
  7804. } else {
  7805. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  7806. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  7807. $queryarray[$field] = $this->{$field};
  7808. }
  7809. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7810. unset($queryarray[$field]);
  7811. }
  7812. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7813. $queryarray[$field] = null; // May force 0 to null
  7814. }
  7815. }
  7816. return $queryarray;
  7817. }
  7818. /**
  7819. * Function to load data from a SQL pointer into properties of current object $this
  7820. *
  7821. * @param stdClass $obj Contain data of object from database
  7822. * @return void
  7823. */
  7824. public function setVarsFromFetchObj(&$obj)
  7825. {
  7826. global $db;
  7827. foreach ($this->fields as $field => $info) {
  7828. if ($this->isDate($info)) {
  7829. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7830. $this->{$field} = '';
  7831. } else {
  7832. $this->{$field} = $db->jdate($obj->{$field});
  7833. }
  7834. } elseif ($this->isInt($info)) {
  7835. if ($field == 'rowid') {
  7836. $this->id = (int) $obj->{$field};
  7837. } else {
  7838. if ($this->isForcedToNullIfZero($info)) {
  7839. if (empty($obj->{$field})) {
  7840. $this->{$field} = null;
  7841. } else {
  7842. $this->{$field} = (double) $obj->{$field};
  7843. }
  7844. } else {
  7845. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7846. $this->{$field} = (int) $obj->{$field};
  7847. } else {
  7848. $this->{$field} = null;
  7849. }
  7850. }
  7851. }
  7852. } elseif ($this->isFloat($info)) {
  7853. if ($this->isForcedToNullIfZero($info)) {
  7854. if (empty($obj->{$field})) {
  7855. $this->{$field} = null;
  7856. } else {
  7857. $this->{$field} = (double) $obj->{$field};
  7858. }
  7859. } else {
  7860. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7861. $this->{$field} = (double) $obj->{$field};
  7862. } else {
  7863. $this->{$field} = null;
  7864. }
  7865. }
  7866. } else {
  7867. $this->{$field} = $obj->{$field};
  7868. }
  7869. }
  7870. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7871. if (!isset($this->fields['ref']) && isset($this->id)) {
  7872. $this->ref = $this->id;
  7873. }
  7874. }
  7875. /**
  7876. * Function to concat keys of fields
  7877. *
  7878. * @param string $alias String of alias of table for fields. For example 't'.
  7879. * @return string list of alias fields
  7880. */
  7881. public function getFieldList($alias = '')
  7882. {
  7883. $keys = array_keys($this->fields);
  7884. if (!empty($alias)) {
  7885. $keys_with_alias = array();
  7886. foreach ($keys as $fieldname) {
  7887. $keys_with_alias[] = $alias . '.' . $fieldname;
  7888. }
  7889. return implode(',', $keys_with_alias);
  7890. } else {
  7891. return implode(',', $keys);
  7892. }
  7893. }
  7894. /**
  7895. * Add quote to field value if necessary
  7896. *
  7897. * @param string|int $value Value to protect
  7898. * @param array $fieldsentry Properties of field
  7899. * @return string
  7900. */
  7901. protected function quote($value, $fieldsentry)
  7902. {
  7903. if (is_null($value)) {
  7904. return 'NULL';
  7905. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7906. return price2num("$value");
  7907. } elseif ($fieldsentry['type'] == 'boolean') {
  7908. if ($value) {
  7909. return 'true';
  7910. } else {
  7911. return 'false';
  7912. }
  7913. } else {
  7914. return "'".$this->db->escape($value)."'";
  7915. }
  7916. }
  7917. /**
  7918. * Create object into database
  7919. *
  7920. * @param User $user User that creates
  7921. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7922. * @return int <0 if KO, Id of created object if OK
  7923. */
  7924. public function createCommon(User $user, $notrigger = false)
  7925. {
  7926. global $langs;
  7927. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7928. $error = 0;
  7929. $now = dol_now();
  7930. $fieldvalues = $this->setSaveQuery();
  7931. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7932. $fieldvalues['date_creation'] = $this->db->idate($now);
  7933. }
  7934. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7935. $fieldvalues['fk_user_creat'] = $user->id;
  7936. }
  7937. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7938. if (array_key_exists('ref', $fieldvalues)) {
  7939. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7940. }
  7941. $keys = array();
  7942. $values = array(); // Array to store string forged for SQL syntax
  7943. foreach ($fieldvalues as $k => $v) {
  7944. $keys[$k] = $k;
  7945. $value = $this->fields[$k];
  7946. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7947. }
  7948. // Clean and check mandatory
  7949. foreach ($keys as $key) {
  7950. // If field is an implicit foreign key field
  7951. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7952. $values[$key] = '';
  7953. }
  7954. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7955. $values[$key] = '';
  7956. }
  7957. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7958. $error++;
  7959. $langs->load("errors");
  7960. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7961. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7962. }
  7963. // If value is null and there is a default value for field
  7964. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7965. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7966. }
  7967. // If field is an implicit foreign key field
  7968. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7969. if (isset($this->fields[$key]['default'])) {
  7970. $values[$key] = ((int) $this->fields[$key]['default']);
  7971. } else {
  7972. $values[$key] = 'null';
  7973. }
  7974. }
  7975. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7976. $values[$key] = 'null';
  7977. }
  7978. }
  7979. if ($error) {
  7980. return -1;
  7981. }
  7982. $this->db->begin();
  7983. if (!$error) {
  7984. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  7985. $sql .= " (".implode(", ", $keys).')';
  7986. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  7987. $res = $this->db->query($sql);
  7988. if (!$res) {
  7989. $error++;
  7990. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  7991. $this->errors[] = "ErrorRefAlreadyExists";
  7992. } else {
  7993. $this->errors[] = $this->db->lasterror();
  7994. }
  7995. }
  7996. }
  7997. if (!$error) {
  7998. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  7999. }
  8000. // If we have a field ref with a default value of (PROV)
  8001. if (!$error) {
  8002. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  8003. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  8004. $resqlupdate = $this->db->query($sql);
  8005. if ($resqlupdate === false) {
  8006. $error++;
  8007. $this->errors[] = $this->db->lasterror();
  8008. } else {
  8009. $this->ref = '(PROV'.$this->id.')';
  8010. }
  8011. }
  8012. }
  8013. // Create extrafields
  8014. if (!$error) {
  8015. $result = $this->insertExtraFields();
  8016. if ($result < 0) {
  8017. $error++;
  8018. }
  8019. }
  8020. // Create lines
  8021. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8022. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8023. for ($i = 0; $i < $num; $i++) {
  8024. $line = $this->lines[$i];
  8025. $keyforparent = $this->fk_element;
  8026. $line->$keyforparent = $this->id;
  8027. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8028. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8029. if (!is_object($line)) {
  8030. $line = (object) $line;
  8031. }
  8032. $result = $line->create($user, 1);
  8033. if ($result < 0) {
  8034. $this->error = $line->error;
  8035. $this->db->rollback();
  8036. return -1;
  8037. }
  8038. }
  8039. }
  8040. // Triggers
  8041. if (!$error && !$notrigger) {
  8042. // Call triggers
  8043. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  8044. if ($result < 0) {
  8045. $error++;
  8046. }
  8047. // End call triggers
  8048. }
  8049. // Commit or rollback
  8050. if ($error) {
  8051. $this->db->rollback();
  8052. return -1;
  8053. } else {
  8054. $this->db->commit();
  8055. return $this->id;
  8056. }
  8057. }
  8058. /**
  8059. * Load object in memory from the database
  8060. *
  8061. * @param int $id Id object
  8062. * @param string $ref Ref
  8063. * @param string $morewhere More SQL filters (' AND ...')
  8064. * @return int <0 if KO, 0 if not found, >0 if OK
  8065. */
  8066. public function fetchCommon($id, $ref = null, $morewhere = '')
  8067. {
  8068. if (empty($id) && empty($ref) && empty($morewhere)) {
  8069. return -1;
  8070. }
  8071. $fieldlist = $this->getFieldList('t');
  8072. if (empty($fieldlist)) {
  8073. return 0;
  8074. }
  8075. $sql = "SELECT ".$fieldlist;
  8076. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8077. if (!empty($id)) {
  8078. $sql .= ' WHERE t.rowid = '.((int) $id);
  8079. } elseif (!empty($ref)) {
  8080. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8081. } else {
  8082. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8083. }
  8084. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8085. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  8086. }
  8087. if ($morewhere) {
  8088. $sql .= $morewhere;
  8089. }
  8090. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8091. $res = $this->db->query($sql);
  8092. if ($res) {
  8093. $obj = $this->db->fetch_object($res);
  8094. if ($obj) {
  8095. $this->setVarsFromFetchObj($obj);
  8096. // Retrieve all extrafield
  8097. // fetch optionals attributes and labels
  8098. $this->fetch_optionals();
  8099. return $this->id;
  8100. } else {
  8101. return 0;
  8102. }
  8103. } else {
  8104. $this->error = $this->db->lasterror();
  8105. $this->errors[] = $this->error;
  8106. return -1;
  8107. }
  8108. }
  8109. /**
  8110. * Load object in memory from the database
  8111. *
  8112. * @param string $morewhere More SQL filters (' AND ...')
  8113. * @return int <0 if KO, 0 if not found, >0 if OK
  8114. */
  8115. public function fetchLinesCommon($morewhere = '')
  8116. {
  8117. $objectlineclassname = get_class($this).'Line';
  8118. if (!class_exists($objectlineclassname)) {
  8119. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8120. return -1;
  8121. }
  8122. $objectline = new $objectlineclassname($this->db);
  8123. $sql = "SELECT ".$objectline->getFieldList('l');
  8124. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8125. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8126. if ($morewhere) {
  8127. $sql .= $morewhere;
  8128. }
  8129. if (isset($objectline->fields['position'])) {
  8130. $sql .= $this->db->order('position', 'ASC');
  8131. }
  8132. $resql = $this->db->query($sql);
  8133. if ($resql) {
  8134. $num_rows = $this->db->num_rows($resql);
  8135. $i = 0;
  8136. while ($i < $num_rows) {
  8137. $obj = $this->db->fetch_object($resql);
  8138. if ($obj) {
  8139. $newline = new $objectlineclassname($this->db);
  8140. $newline->setVarsFromFetchObj($obj);
  8141. $this->lines[] = $newline;
  8142. }
  8143. $i++;
  8144. }
  8145. return 1;
  8146. } else {
  8147. $this->error = $this->db->lasterror();
  8148. $this->errors[] = $this->error;
  8149. return -1;
  8150. }
  8151. }
  8152. /**
  8153. * Update object into database
  8154. *
  8155. * @param User $user User that modifies
  8156. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8157. * @return int <0 if KO, >0 if OK
  8158. */
  8159. public function updateCommon(User $user, $notrigger = false)
  8160. {
  8161. global $conf, $langs;
  8162. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8163. $error = 0;
  8164. $now = dol_now();
  8165. $fieldvalues = $this->setSaveQuery();
  8166. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8167. $fieldvalues['date_modification'] = $this->db->idate($now);
  8168. }
  8169. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8170. $fieldvalues['fk_user_modif'] = $user->id;
  8171. }
  8172. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8173. if (array_key_exists('ref', $fieldvalues)) {
  8174. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8175. }
  8176. // Add quotes and escape on fields with type string
  8177. $keys = array();
  8178. $values = array();
  8179. $tmp = array();
  8180. foreach ($fieldvalues as $k => $v) {
  8181. $keys[$k] = $k;
  8182. $value = $this->fields[$k];
  8183. $values[$k] = $this->quote($v, $value);
  8184. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8185. }
  8186. // Clean and check mandatory fields
  8187. foreach ($keys as $key) {
  8188. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8189. $values[$key] = ''; // This is an implicit foreign key field
  8190. }
  8191. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8192. $values[$key] = ''; // This is an explicit foreign key field
  8193. }
  8194. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8195. /*
  8196. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8197. {
  8198. $error++;
  8199. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8200. }*/
  8201. }
  8202. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8203. $this->db->begin();
  8204. if (!$error) {
  8205. $res = $this->db->query($sql);
  8206. if (!$res) {
  8207. $error++;
  8208. $this->errors[] = $this->db->lasterror();
  8209. }
  8210. }
  8211. // Update extrafield
  8212. if (!$error) {
  8213. $result = $this->insertExtraFields();
  8214. if ($result < 0) {
  8215. $error++;
  8216. }
  8217. }
  8218. // Triggers
  8219. if (!$error && !$notrigger) {
  8220. // Call triggers
  8221. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8222. if ($result < 0) {
  8223. $error++;
  8224. } //Do also here what you must do to rollback action if trigger fail
  8225. // End call triggers
  8226. }
  8227. // Commit or rollback
  8228. if ($error) {
  8229. $this->db->rollback();
  8230. return -1;
  8231. } else {
  8232. $this->db->commit();
  8233. return $this->id;
  8234. }
  8235. }
  8236. /**
  8237. * Delete object in database
  8238. *
  8239. * @param User $user User that deletes
  8240. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8241. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8242. * @return int <=0 if KO, 0=Nothing done because object has child, >0 if OK
  8243. */
  8244. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8245. {
  8246. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8247. $error = 0;
  8248. $this->db->begin();
  8249. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8250. foreach ($this->childtables as $table) {
  8251. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8252. $resql = $this->db->query($sql);
  8253. if (!$resql) {
  8254. $this->error = $this->db->lasterror();
  8255. $this->errors[] = $this->error;
  8256. $this->db->rollback();
  8257. return -1;
  8258. }
  8259. }
  8260. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8261. $objectisused = $this->isObjectUsed($this->id);
  8262. if (!empty($objectisused)) {
  8263. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8264. $this->error = 'ErrorRecordHasChildren';
  8265. $this->errors[] = $this->error;
  8266. $this->db->rollback();
  8267. return 0;
  8268. }
  8269. }
  8270. // Delete cascade first
  8271. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8272. foreach ($this->childtablesoncascade as $table) {
  8273. $deleteFromObject = explode(':', $table);
  8274. if (count($deleteFromObject) >= 2) {
  8275. $className = str_replace('@', '', $deleteFromObject[0]);
  8276. $filePath = $deleteFromObject[1];
  8277. $columnName = $deleteFromObject[2];
  8278. $TMoreSQL = array();
  8279. $more_sql = $deleteFromObject[3];
  8280. if (!empty($more_sql)) {
  8281. $TMoreSQL['customsql'] = $more_sql;
  8282. }
  8283. if (dol_include_once($filePath)) {
  8284. $childObject = new $className($this->db);
  8285. if (method_exists($childObject, 'deleteByParentField')) {
  8286. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8287. if ($result < 0) {
  8288. $error++;
  8289. $this->errors[] = $childObject->error;
  8290. break;
  8291. }
  8292. } else {
  8293. $error++;
  8294. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8295. break;
  8296. }
  8297. } else {
  8298. $error++;
  8299. $this->errors[] = 'Cannot include child class file '.$filePath;
  8300. break;
  8301. }
  8302. } else {
  8303. // Delete record in child table
  8304. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8305. $resql = $this->db->query($sql);
  8306. if (!$resql) {
  8307. $error++;
  8308. $this->error = $this->db->lasterror();
  8309. $this->errors[] = $this->error;
  8310. break;
  8311. }
  8312. }
  8313. }
  8314. }
  8315. if (!$error) {
  8316. if (!$notrigger) {
  8317. // Call triggers
  8318. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8319. if ($result < 0) {
  8320. $error++;
  8321. } // Do also here what you must do to rollback action if trigger fail
  8322. // End call triggers
  8323. }
  8324. }
  8325. // Delete llx_ecm_files
  8326. if (!$error) {
  8327. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8328. if (!$res) {
  8329. $error++;
  8330. }
  8331. }
  8332. if (!$error && !empty($this->isextrafieldmanaged)) {
  8333. $result = $this->deleteExtraFields();
  8334. if ($result < 0) {
  8335. $error++;
  8336. }
  8337. }
  8338. if (!$error) {
  8339. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8340. $resql = $this->db->query($sql);
  8341. if (!$resql) {
  8342. $error++;
  8343. $this->errors[] = $this->db->lasterror();
  8344. }
  8345. }
  8346. // Commit or rollback
  8347. if ($error) {
  8348. $this->db->rollback();
  8349. return -1;
  8350. } else {
  8351. $this->db->commit();
  8352. return 1;
  8353. }
  8354. }
  8355. /**
  8356. * Delete all child object from a parent ID
  8357. *
  8358. * @param int $parentId Parent Id
  8359. * @param string $parentField Name of Foreign key parent column
  8360. * @param array $filter an array filter
  8361. * @param string $filtermode AND or OR
  8362. * @return int <0 if KO, >0 if OK
  8363. * @throws Exception
  8364. */
  8365. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8366. {
  8367. global $user;
  8368. $error = 0;
  8369. $deleted = 0;
  8370. if (!empty($parentId) && !empty($parentField)) {
  8371. $this->db->begin();
  8372. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8373. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8374. // Manage filters
  8375. $sqlwhere = array();
  8376. if (count($filter) > 0) {
  8377. foreach ($filter as $key => $value) {
  8378. if ($key == 'customsql') {
  8379. $sqlwhere[] = $value;
  8380. } elseif (strpos($value, '%') === false) {
  8381. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8382. } else {
  8383. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8384. }
  8385. }
  8386. }
  8387. if (count($sqlwhere) > 0) {
  8388. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8389. }
  8390. $resql = $this->db->query($sql);
  8391. if (!$resql) {
  8392. $this->errors[] = $this->db->lasterror();
  8393. $error++;
  8394. } else {
  8395. while ($obj = $this->db->fetch_object($resql)) {
  8396. $result = $this->fetch($obj->rowid);
  8397. if ($result < 0) {
  8398. $error++;
  8399. $this->errors[] = $this->error;
  8400. } else {
  8401. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8402. $result = $this->delete();
  8403. } else {
  8404. $result = $this->delete($user);
  8405. }
  8406. if ($result < 0) {
  8407. $error++;
  8408. $this->errors[] = $this->error;
  8409. } else {
  8410. $deleted++;
  8411. }
  8412. }
  8413. }
  8414. }
  8415. if (empty($error)) {
  8416. $this->db->commit();
  8417. return $deleted;
  8418. } else {
  8419. $this->error = implode(', ', $this->errors);
  8420. $this->db->rollback();
  8421. return $error * -1;
  8422. }
  8423. }
  8424. return $deleted;
  8425. }
  8426. /**
  8427. * Delete a line of object in database
  8428. *
  8429. * @param User $user User that delete
  8430. * @param int $idline Id of line to delete
  8431. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8432. * @return int >0 if OK, <0 if KO
  8433. */
  8434. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8435. {
  8436. global $conf;
  8437. $error = 0;
  8438. $tmpforobjectclass = get_class($this);
  8439. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8440. // Call trigger
  8441. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8442. if ($result < 0) {
  8443. return -1;
  8444. }
  8445. // End call triggers
  8446. $this->db->begin();
  8447. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8448. $sql .= " WHERE rowid = ".((int) $idline);
  8449. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  8450. $resql = $this->db->query($sql);
  8451. if (!$resql) {
  8452. $this->error = "Error ".$this->db->lasterror();
  8453. $error++;
  8454. }
  8455. if (empty($error)) {
  8456. // Remove extrafields
  8457. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8458. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8459. $tmpobjectline->id = $idline;
  8460. $result = $tmpobjectline->deleteExtraFields();
  8461. if ($result < 0) {
  8462. $error++;
  8463. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8464. }
  8465. }
  8466. }
  8467. if (empty($error)) {
  8468. $this->db->commit();
  8469. return 1;
  8470. } else {
  8471. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8472. $this->db->rollback();
  8473. return -1;
  8474. }
  8475. }
  8476. /**
  8477. * Set to a status
  8478. *
  8479. * @param User $user Object user that modify
  8480. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8481. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8482. * @param string $triggercode Trigger code to use
  8483. * @return int <0 if KO, >0 if OK
  8484. */
  8485. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8486. {
  8487. $error = 0;
  8488. $this->db->begin();
  8489. $statusfield = 'status';
  8490. if ($this->element == 'don' || $this->element == 'donation') {
  8491. $statusfield = 'fk_statut';
  8492. }
  8493. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8494. $sql .= " SET ".$statusfield." = ".((int) $status);
  8495. $sql .= " WHERE rowid = ".((int) $this->id);
  8496. if ($this->db->query($sql)) {
  8497. if (!$error) {
  8498. $this->oldcopy = clone $this;
  8499. }
  8500. if (!$error && !$notrigger) {
  8501. // Call trigger
  8502. $result = $this->call_trigger($triggercode, $user);
  8503. if ($result < 0) {
  8504. $error++;
  8505. }
  8506. }
  8507. if (!$error) {
  8508. $this->status = $status;
  8509. $this->db->commit();
  8510. return 1;
  8511. } else {
  8512. $this->db->rollback();
  8513. return -1;
  8514. }
  8515. } else {
  8516. $this->error = $this->db->error();
  8517. $this->db->rollback();
  8518. return -1;
  8519. }
  8520. }
  8521. /**
  8522. * Initialise object with example values
  8523. * Id must be 0 if object instance is a specimen
  8524. *
  8525. * @return int
  8526. */
  8527. public function initAsSpecimenCommon()
  8528. {
  8529. global $user;
  8530. $this->id = 0;
  8531. $this->specimen = 1;
  8532. $fields = array(
  8533. 'label' => 'This is label',
  8534. 'ref' => 'ABCD1234',
  8535. 'description' => 'This is a description',
  8536. 'qty' => 123.12,
  8537. 'note_public' => 'Public note',
  8538. 'note_private' => 'Private note',
  8539. 'date_creation' => (dol_now() - 3600 * 48),
  8540. 'date_modification' => (dol_now() - 3600 * 24),
  8541. 'fk_user_creat' => $user->id,
  8542. 'fk_user_modif' => $user->id,
  8543. 'date' => dol_now(),
  8544. );
  8545. foreach ($fields as $key => $value) {
  8546. if (array_key_exists($key, $this->fields)) {
  8547. $this->{$key} = $value;
  8548. }
  8549. }
  8550. return 1;
  8551. }
  8552. /* Part for comments */
  8553. /**
  8554. * Load comments linked with current task
  8555. * @return boolean 1 if ok
  8556. */
  8557. public function fetchComments()
  8558. {
  8559. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8560. $comment = new Comment($this->db);
  8561. $result = $comment->fetchAllFor($this->element, $this->id);
  8562. if ($result < 0) {
  8563. $this->errors = array_merge($this->errors, $comment->errors);
  8564. return -1;
  8565. } else {
  8566. $this->comments = $comment->comments;
  8567. }
  8568. return count($this->comments);
  8569. }
  8570. /**
  8571. * Return nb comments already posted
  8572. *
  8573. * @return int
  8574. */
  8575. public function getNbComments()
  8576. {
  8577. return count($this->comments);
  8578. }
  8579. /**
  8580. * Trim object parameters
  8581. *
  8582. * @param string[] $parameters array of parameters to trim
  8583. * @return void
  8584. */
  8585. public function trimParameters($parameters)
  8586. {
  8587. if (!is_array($parameters)) {
  8588. return;
  8589. }
  8590. foreach ($parameters as $parameter) {
  8591. if (isset($this->$parameter)) {
  8592. $this->$parameter = trim($this->$parameter);
  8593. }
  8594. }
  8595. }
  8596. /* Part for categories/tags */
  8597. /**
  8598. * Sets object to given categories.
  8599. *
  8600. * Deletes object from existing categories not supplied.
  8601. * Adds it to non existing supplied categories.
  8602. * Existing categories are left untouch.
  8603. *
  8604. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8605. * @return int Array of category objects or < 0 if KO
  8606. */
  8607. public function getCategoriesCommon($type_categ)
  8608. {
  8609. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8610. // Get current categories
  8611. $c = new Categorie($this->db);
  8612. $existing = $c->containing($this->id, $type_categ, 'id');
  8613. return $existing;
  8614. }
  8615. /**
  8616. * Sets object to given categories.
  8617. *
  8618. * Adds it to non existing supplied categories.
  8619. * Deletes object from existing categories not supplied (if remove_existing==true).
  8620. * Existing categories are left untouch.
  8621. *
  8622. * @param int[]|int $categories Category ID or array of Categories IDs
  8623. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8624. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8625. * @return int <0 if KO, >0 if OK
  8626. */
  8627. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8628. {
  8629. // Handle single category
  8630. if (!is_array($categories)) {
  8631. $categories = array($categories);
  8632. }
  8633. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8634. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8635. if (empty($type_categ)) {
  8636. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8637. return -1;
  8638. }
  8639. // Get current categories
  8640. $c = new Categorie($this->db);
  8641. $existing = $c->containing($this->id, $type_categ, 'id');
  8642. if ($remove_existing) {
  8643. // Diff
  8644. if (is_array($existing)) {
  8645. $to_del = array_diff($existing, $categories);
  8646. $to_add = array_diff($categories, $existing);
  8647. } else {
  8648. $to_del = array(); // Nothing to delete
  8649. $to_add = $categories;
  8650. }
  8651. } else {
  8652. $to_del = array(); // Nothing to delete
  8653. $to_add = array_diff($categories, $existing);
  8654. }
  8655. $error = 0;
  8656. $ok = 0;
  8657. // Process
  8658. foreach ($to_del as $del) {
  8659. if ($c->fetch($del) > 0) {
  8660. $result=$c->del_type($this, $type_categ);
  8661. if ($result < 0) {
  8662. $error++;
  8663. $this->error = $c->error;
  8664. $this->errors = $c->errors;
  8665. break;
  8666. } else {
  8667. $ok += $result;
  8668. }
  8669. }
  8670. }
  8671. foreach ($to_add as $add) {
  8672. if ($c->fetch($add) > 0) {
  8673. $result = $c->add_type($this, $type_categ);
  8674. if ($result < 0) {
  8675. $error++;
  8676. $this->error = $c->error;
  8677. $this->errors = $c->errors;
  8678. break;
  8679. } else {
  8680. $ok += $result;
  8681. }
  8682. }
  8683. }
  8684. return $error ? -1 * $error : $ok;
  8685. }
  8686. /**
  8687. * Copy related categories to another object
  8688. *
  8689. * @param int $fromId Id object source
  8690. * @param int $toId Id object cible
  8691. * @param string $type Type of category ('product', ...)
  8692. * @return int < 0 if error, > 0 if ok
  8693. */
  8694. public function cloneCategories($fromId, $toId, $type = '')
  8695. {
  8696. $this->db->begin();
  8697. if (empty($type)) {
  8698. $type = $this->table_element;
  8699. }
  8700. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8701. $categorystatic = new Categorie($this->db);
  8702. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8703. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8704. $sql .= " WHERE fk_product = ".((int) $fromId);
  8705. if (!$this->db->query($sql)) {
  8706. $this->error = $this->db->lasterror();
  8707. $this->db->rollback();
  8708. return -1;
  8709. }
  8710. $this->db->commit();
  8711. return 1;
  8712. }
  8713. /**
  8714. * Delete related files of object in database
  8715. *
  8716. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8717. * @return bool True if OK, False if KO
  8718. */
  8719. public function deleteEcmFiles($mode = 0)
  8720. {
  8721. global $conf;
  8722. $this->db->begin();
  8723. // Delete in database with mode 0
  8724. if ($mode == 0) {
  8725. switch ($this->element) {
  8726. case 'propal':
  8727. $element = 'propale';
  8728. break;
  8729. case 'product':
  8730. $element = 'produit';
  8731. break;
  8732. case 'order_supplier':
  8733. $element = 'fournisseur/commande';
  8734. break;
  8735. case 'invoice_supplier':
  8736. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8737. break;
  8738. case 'shipping':
  8739. $element = 'expedition/sending';
  8740. break;
  8741. default:
  8742. $element = $this->element;
  8743. }
  8744. // Delete ecm_files extrafields
  8745. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  8746. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8747. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8748. $sql .= ")";
  8749. if (!$this->db->query($sql)) {
  8750. $this->error = $this->db->lasterror();
  8751. $this->db->rollback();
  8752. return false;
  8753. }
  8754. // Delete ecm_files
  8755. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  8756. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8757. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  8758. if (!$this->db->query($sql)) {
  8759. $this->error = $this->db->lasterror();
  8760. $this->db->rollback();
  8761. return false;
  8762. }
  8763. }
  8764. // Delete in database with mode 1
  8765. if ($mode == 1) {
  8766. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  8767. $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).")";
  8768. $resql = $this->db->query($sql);
  8769. if (!$resql) {
  8770. $this->error = $this->db->lasterror();
  8771. $this->db->rollback();
  8772. return false;
  8773. }
  8774. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  8775. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  8776. $resql = $this->db->query($sql);
  8777. if (!$resql) {
  8778. $this->error = $this->db->lasterror();
  8779. $this->db->rollback();
  8780. return false;
  8781. }
  8782. }
  8783. $this->db->commit();
  8784. return true;
  8785. }
  8786. }