commonobject.class.php 315 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2019 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/core/class/commonobject.class.php
  34. * \ingroup core
  35. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  36. */
  37. /**
  38. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  39. */
  40. abstract class CommonObject
  41. {
  42. /**
  43. * @var DoliDb Database handler (result of a new DoliDB)
  44. */
  45. public $db;
  46. /**
  47. * @var int The object identifier
  48. */
  49. public $id;
  50. /**
  51. * @var int The environment ID when using a multicompany module
  52. */
  53. public $entity;
  54. /**
  55. * @var string Error string
  56. * @see $errors
  57. */
  58. public $error;
  59. /**
  60. * @var string Error string that is hidden but can be used to store complementatry technical code.
  61. */
  62. public $errorhidden;
  63. /**
  64. * @var string[] Array of error strings
  65. */
  66. public $errors = array();
  67. /**
  68. * @var string ID to identify managed object
  69. */
  70. public $element;
  71. /**
  72. * @var string Name of table without prefix where object is stored
  73. */
  74. public $table_element;
  75. /**
  76. * @var string Name of subtable line
  77. */
  78. public $table_element_line = '';
  79. /**
  80. * @var string Key value used to track if data is coming from import wizard
  81. */
  82. public $import_key;
  83. /**
  84. * @var mixed Contains data to manage extrafields
  85. */
  86. public $array_options = array();
  87. /**
  88. * @var mixed Array to store alternative languages values of object
  89. */
  90. public $array_languages = null; // Value is array() when load already tried
  91. /**
  92. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  93. */
  94. public $linkedObjectsIds;
  95. /**
  96. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  97. */
  98. public $linkedObjects;
  99. /**
  100. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  101. */
  102. public $oldcopy;
  103. /**
  104. * @var string Column name of the ref field.
  105. */
  106. protected $table_ref_field = '';
  107. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  108. /**
  109. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  110. */
  111. public $context = array();
  112. /**
  113. * @var string Contains canvas name if record is an alternative canvas record
  114. */
  115. public $canvas;
  116. /**
  117. * @var Project The related project
  118. * @see fetch_projet()
  119. */
  120. public $project;
  121. /**
  122. * @var int The related project ID
  123. * @see setProject(), project
  124. */
  125. public $fk_project;
  126. /**
  127. * @deprecated
  128. * @see project
  129. */
  130. public $projet;
  131. /**
  132. * @var Contact a related contact
  133. * @see fetch_contact()
  134. */
  135. public $contact;
  136. /**
  137. * @var int The related contact ID
  138. * @see fetch_contact()
  139. */
  140. public $contact_id;
  141. /**
  142. * @var Societe A related thirdparty
  143. * @see fetch_thirdparty()
  144. */
  145. public $thirdparty;
  146. /**
  147. * @var User A related user
  148. * @see fetch_user()
  149. */
  150. public $user;
  151. /**
  152. * @var string The type of originating object ('commande', 'facture', ...)
  153. * @see fetch_origin()
  154. */
  155. public $origin;
  156. /**
  157. * @var int The id of originating object
  158. * @see fetch_origin()
  159. */
  160. public $origin_id;
  161. /**
  162. * @var string The object's reference
  163. */
  164. public $ref;
  165. /**
  166. * @var string An external reference for the object
  167. */
  168. public $ref_ext;
  169. /**
  170. * @var string The object's previous reference
  171. */
  172. public $ref_previous;
  173. /**
  174. * @var string The object's next reference
  175. */
  176. public $ref_next;
  177. /**
  178. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  179. */
  180. public $newref;
  181. /**
  182. * @var int The object's status
  183. * @see setStatut()
  184. */
  185. public $statut;
  186. /**
  187. * @var int The object's status
  188. * @see setStatut()
  189. */
  190. public $status;
  191. /**
  192. * @var string
  193. * @see getFullAddress()
  194. */
  195. public $country;
  196. /**
  197. * @var int
  198. * @see getFullAddress(), country
  199. */
  200. public $country_id;
  201. /**
  202. * @var string
  203. * @see getFullAddress(), isInEEC(), country
  204. */
  205. public $country_code;
  206. /**
  207. * @var string
  208. * @see getFullAddress()
  209. */
  210. public $state;
  211. /**
  212. * @var int
  213. * @see getFullAddress(), state
  214. */
  215. public $state_id;
  216. /**
  217. * @var string
  218. * @see getFullAddress(), $state
  219. */
  220. public $state_code;
  221. /**
  222. * @var int
  223. * @see getFullAddress(), $region_code, $region
  224. */
  225. public $region_id;
  226. /**
  227. * @var string
  228. * @see getFullAddress(), $region_id, $region
  229. */
  230. public $region_code;
  231. /**
  232. * @var string
  233. * @see getFullAddress(), $region_id, $region_code
  234. */
  235. public $region;
  236. /**
  237. * @var int
  238. * @see fetch_barcode()
  239. */
  240. public $barcode_type;
  241. /**
  242. * @var string
  243. * @see fetch_barcode(), barcode_type
  244. */
  245. public $barcode_type_code;
  246. /**
  247. * @var string
  248. * @see fetch_barcode(), barcode_type
  249. */
  250. public $barcode_type_label;
  251. /**
  252. * @var string
  253. * @see fetch_barcode(), barcode_type
  254. */
  255. public $barcode_type_coder;
  256. /**
  257. * @var int Payment method ID (cheque, cash, ...)
  258. * @see setPaymentMethods()
  259. */
  260. public $mode_reglement_id;
  261. /**
  262. * @var int Payment terms ID
  263. * @see setPaymentTerms()
  264. */
  265. public $cond_reglement_id;
  266. /**
  267. * @var int Demand reason ID
  268. */
  269. public $demand_reason_id;
  270. /**
  271. * @var int Transport mode ID (For module intracomm report)
  272. * @see setTransportMode()
  273. */
  274. public $transport_mode_id;
  275. /**
  276. * @var int Payment terms ID
  277. * @deprecated Kept for compatibility
  278. * @see cond_reglement_id;
  279. */
  280. public $cond_reglement;
  281. /**
  282. * @var int Delivery address ID
  283. * @see setDeliveryAddress()
  284. * @deprecated
  285. */
  286. public $fk_delivery_address;
  287. /**
  288. * @var int Shipping method ID
  289. * @see setShippingMethod()
  290. */
  291. public $shipping_method_id;
  292. /**
  293. * @var string
  294. * @see SetDocModel()
  295. */
  296. public $model_pdf;
  297. /**
  298. * @var string
  299. * @deprecated
  300. * @see $model_pdf
  301. */
  302. public $modelpdf;
  303. /**
  304. * @var string
  305. * Contains relative path of last generated main file
  306. */
  307. public $last_main_doc;
  308. /**
  309. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  310. * @deprecated
  311. * @see $fk_account
  312. */
  313. public $fk_bank;
  314. /**
  315. * @var int Bank account ID
  316. * @see SetBankAccount()
  317. */
  318. public $fk_account;
  319. /**
  320. * @var string Open ID
  321. */
  322. public $openid;
  323. /**
  324. * @var string Public note
  325. * @see update_note()
  326. */
  327. public $note_public;
  328. /**
  329. * @var string Private note
  330. * @see update_note()
  331. */
  332. public $note_private;
  333. /**
  334. * @deprecated
  335. * @see $note_private
  336. */
  337. public $note;
  338. /**
  339. * @var float Total amount before taxes
  340. * @see update_price()
  341. */
  342. public $total_ht;
  343. /**
  344. * @var float Total VAT amount
  345. * @see update_price()
  346. */
  347. public $total_tva;
  348. /**
  349. * @var float Total local tax 1 amount
  350. * @see update_price()
  351. */
  352. public $total_localtax1;
  353. /**
  354. * @var float Total local tax 2 amount
  355. * @see update_price()
  356. */
  357. public $total_localtax2;
  358. /**
  359. * @var float Total amount with taxes
  360. * @see update_price()
  361. */
  362. public $total_ttc;
  363. /**
  364. * @var CommonObjectLine[]
  365. */
  366. public $lines;
  367. /**
  368. * @var mixed Contains comments
  369. * @see fetchComments()
  370. */
  371. public $comments = array();
  372. /**
  373. * @var string The name
  374. */
  375. public $name;
  376. /**
  377. * @var string The lastname
  378. */
  379. public $lastname;
  380. /**
  381. * @var string The firstname
  382. */
  383. public $firstname;
  384. /**
  385. * @var string The civility code, not an integer
  386. */
  387. public $civility_id;
  388. // Dates
  389. /**
  390. * @var integer|string date_creation
  391. */
  392. public $date_creation;
  393. /**
  394. * @var integer|string $date_validation;
  395. */
  396. public $date_validation; // Date validation
  397. /**
  398. * @var integer|string $date_modification;
  399. */
  400. public $date_modification; // Date last change (tms field)
  401. public $next_prev_filter;
  402. /**
  403. * @var int 1 if object is specimen
  404. */
  405. public $specimen = 0;
  406. /**
  407. * @var int Id of contact to send object (used by the trigger of module Agenda)
  408. */
  409. public $sendtoid;
  410. /**
  411. * @var float Amount already paid (used to show correct status)
  412. */
  413. public $alreadypaid;
  414. /**
  415. * @var array List of child tables. To test if we can delete object.
  416. */
  417. protected $childtables = array();
  418. /**
  419. * @var array List of child tables. To know object to delete on cascade.
  420. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  421. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  422. */
  423. protected $childtablesoncascade = array();
  424. // No constructor as it is an abstract class
  425. /**
  426. * Check an object id/ref exists
  427. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  428. *
  429. * @param string $element String of element ('product', 'facture', ...)
  430. * @param int $id Id of object
  431. * @param string $ref Ref of object to check
  432. * @param string $ref_ext Ref ext of object to check
  433. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  434. */
  435. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  436. {
  437. global $db, $conf;
  438. $sql = "SELECT rowid, ref, ref_ext";
  439. $sql .= " FROM ".MAIN_DB_PREFIX.$element;
  440. $sql .= " WHERE entity IN (".getEntity($element).")";
  441. if ($id > 0) {
  442. $sql .= " AND rowid = ".((int) $id);
  443. } elseif ($ref) {
  444. $sql .= " AND ref = '".$db->escape($ref)."'";
  445. } elseif ($ref_ext) {
  446. $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
  447. } else {
  448. $error = 'ErrorWrongParameters';
  449. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  450. return -1;
  451. }
  452. if ($ref || $ref_ext) {
  453. $sql .= " AND entity = ".((int) $conf->entity);
  454. }
  455. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  456. $resql = $db->query($sql);
  457. if ($resql) {
  458. $num = $db->num_rows($resql);
  459. if ($num > 0) {
  460. return 1;
  461. } else {
  462. return 0;
  463. }
  464. }
  465. return -1;
  466. }
  467. /**
  468. * Method to output saved errors
  469. *
  470. * @return string String with errors
  471. */
  472. public function errorsToString()
  473. {
  474. return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
  475. }
  476. /**
  477. * Return customer ref for screen output.
  478. *
  479. * @param string $objref Customer ref
  480. * @return string Customer ref formated
  481. */
  482. public function getFormatedCustomerRef($objref)
  483. {
  484. global $hookmanager;
  485. $parameters = array('objref'=>$objref);
  486. $action = '';
  487. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  488. if ($reshook > 0) {
  489. return $hookmanager->resArray['objref'];
  490. }
  491. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  492. }
  493. /**
  494. * Return supplier ref for screen output.
  495. *
  496. * @param string $objref Supplier ref
  497. * @return string Supplier ref formated
  498. */
  499. public function getFormatedSupplierRef($objref)
  500. {
  501. global $hookmanager;
  502. $parameters = array('objref'=>$objref);
  503. $action = '';
  504. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  505. if ($reshook > 0) {
  506. return $hookmanager->resArray['objref'];
  507. }
  508. return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  509. }
  510. /**
  511. * Return full name (civility+' '+name+' '+lastname)
  512. *
  513. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  514. * @param int $option 0=No option, 1=Add civility
  515. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  516. * @param int $maxlen Maximum length
  517. * @return string String with full name
  518. */
  519. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  520. {
  521. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  522. $lastname = $this->lastname;
  523. $firstname = $this->firstname;
  524. if (empty($lastname)) {
  525. $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
  526. }
  527. $ret = '';
  528. if (!empty($option) && !empty($this->civility_code)) {
  529. if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) {
  530. $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' ';
  531. } else {
  532. $ret .= $this->civility_code.' ';
  533. }
  534. }
  535. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  536. return dol_trunc($ret, $maxlen);
  537. }
  538. /**
  539. * Set to upper or ucwords/lower if needed
  540. *
  541. * @return void;
  542. */
  543. public function setUpperOrLowerCase()
  544. {
  545. global $conf;
  546. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  547. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  548. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  549. $this->name = dol_ucwords(dol_strtolower($this->name));
  550. $this->name_alias = dol_ucwords(dol_strtolower($this->name_alias));
  551. }
  552. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  553. $this->lastname = dol_strtoupper($this->lastname);
  554. $this->name = dol_strtoupper($this->name);
  555. $this->name_alias = dol_strtoupper($this->name_alias);
  556. }
  557. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  558. $this->address = dol_strtoupper($this->address);
  559. $this->town = dol_strtoupper($this->town);
  560. }
  561. }
  562. /**
  563. * Return clicable link of object (with eventually picto)
  564. *
  565. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  566. * @return string HTML Code for Kanban thumb.
  567. */
  568. public function getKanbanView($option = '')
  569. {
  570. $return = '<div class="box-flex-item">';
  571. $return .= '<div class="info-box info-box-sm">';
  572. $return .= '<span class="info-box-icon bg-infobox-action">';
  573. $return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  574. $return .= '</span>';
  575. $return .= '<div class="info-box-content">';
  576. $return .= '<span class="info-box-title">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  577. $return .= '</div>';
  578. $return .= '</div>';
  579. $return .= '</div>';
  580. return $return;
  581. }
  582. /**
  583. * Return full address of contact
  584. *
  585. * @param int $withcountry 1=Add country into address string
  586. * @param string $sep Separator to use to build string
  587. * @param int $withregion 1=Add region into address string
  588. * @param string $extralangcode User extralanguages as value
  589. * @return string Full address string
  590. */
  591. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  592. {
  593. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  594. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  595. $tmparray = getCountry($this->country_id, 'all');
  596. $this->country_code = $tmparray['code'];
  597. $this->country = $tmparray['label'];
  598. }
  599. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  600. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  601. $tmparray = getState($this->state_id, 'all', 0, 1);
  602. $this->state_code = $tmparray['code'];
  603. $this->state = $tmparray['label'];
  604. $this->region_code = $tmparray['region_code'];
  605. $this->region = $tmparray['region'];
  606. }
  607. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  608. }
  609. /**
  610. * Return full address for banner
  611. *
  612. * @param string $htmlkey HTML id to make banner content unique
  613. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  614. * @return string Full address string
  615. */
  616. public function getBannerAddress($htmlkey, $object)
  617. {
  618. global $conf, $langs, $form, $extralanguages;
  619. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  620. $contactid = 0;
  621. $thirdpartyid = 0;
  622. $elementforaltlanguage = $this->element;
  623. if ($this->element == 'societe') {
  624. $thirdpartyid = $this->id;
  625. }
  626. if ($this->element == 'contact') {
  627. $contactid = $this->id;
  628. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  629. }
  630. if ($this->element == 'user') {
  631. $contactid = $this->contact_id;
  632. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  633. }
  634. $out = '';
  635. $outdone = 0;
  636. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  637. if ($coords) {
  638. if (!empty($conf->use_javascript_ajax)) {
  639. // Add picto with tooltip on map
  640. $namecoords = '';
  641. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  642. $namecoords .= $object->name.'<br>';
  643. }
  644. $namecoords .= $this->getFullName($langs, 1).'<br>'.$coords;
  645. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  646. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  647. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  648. $out .= '</a> ';
  649. }
  650. $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  651. $outdone++;
  652. $outdone++;
  653. // List of extra languages
  654. $arrayoflangcode = array();
  655. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  656. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  657. }
  658. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  659. if (!is_object($extralanguages)) {
  660. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  661. $extralanguages = new ExtraLanguages($this->db);
  662. }
  663. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  664. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  665. $out .= "<!-- alternatelanguage for '".$elementforaltlanguage."' set to fields '".join(',', $extralanguages->attributes[$elementforaltlanguage])."' -->\n";
  666. $this->fetchValuesForExtraLanguages();
  667. if (!is_object($form)) {
  668. $form = new Form($this->db);
  669. }
  670. $htmltext = '';
  671. // If there is extra languages
  672. foreach ($arrayoflangcode as $extralangcode) {
  673. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  674. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  675. $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
  676. }
  677. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  678. }
  679. }
  680. }
  681. if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
  682. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  683. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  684. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  685. } else {
  686. $out .= ($outdone ? ' - ' : '').$this->state;
  687. }
  688. $outdone++;
  689. }
  690. if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) {
  691. $out .= ($outdone ? '<br>' : '');
  692. }
  693. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  694. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  695. $outdone++;
  696. }
  697. if (!empty($this->phone_pro)) {
  698. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  699. $outdone++;
  700. }
  701. if (!empty($this->phone_mobile)) {
  702. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  703. $outdone++;
  704. }
  705. if (!empty($this->phone_perso)) {
  706. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  707. $outdone++;
  708. }
  709. if (!empty($this->office_phone)) {
  710. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  711. $outdone++;
  712. }
  713. if (!empty($this->user_mobile)) {
  714. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  715. $outdone++;
  716. }
  717. if (!empty($this->fax)) {
  718. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  719. $outdone++;
  720. }
  721. if (!empty($this->office_fax)) {
  722. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  723. $outdone++;
  724. }
  725. if ($out) {
  726. $out .= '<div style="clear: both;"></div>';
  727. }
  728. $outdone = 0;
  729. if (!empty($this->email)) {
  730. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  731. $outdone++;
  732. }
  733. if (!empty($this->url)) {
  734. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  735. $out .= dol_print_url($this->url, '_blank', 0, 1);
  736. $outdone++;
  737. }
  738. if (!empty($conf->socialnetworks->enabled)) {
  739. $outsocialnetwork = '';
  740. if (!empty($this->socialnetworks) && is_countable($this->socialnetworks) && count($this->socialnetworks) > 0) {
  741. $socialnetworksdict = getArrayOfSocialNetworks();
  742. foreach ($this->socialnetworks as $key => $value) {
  743. if ($value) {
  744. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  745. }
  746. $outdone++;
  747. }
  748. } else { // Old code to remove
  749. if (!empty($this->skype)) {
  750. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  751. }
  752. $outdone++;
  753. if (!empty($this->jabberid)) {
  754. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  755. }
  756. $outdone++;
  757. if (!empty($this->twitter)) {
  758. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  759. }
  760. $outdone++;
  761. if (!empty($this->facebook)) {
  762. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  763. }
  764. $outdone++;
  765. if (!empty($this->linkedin)) {
  766. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  767. }
  768. $outdone++;
  769. }
  770. if ($outsocialnetwork) {
  771. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  772. }
  773. }
  774. if ($out) {
  775. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  776. } else {
  777. return '';
  778. }
  779. }
  780. /**
  781. * Return the link of last main doc file for direct public download.
  782. *
  783. * @param string $modulepart Module related to document
  784. * @param int $initsharekey Init the share key if it was not yet defined
  785. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  786. * @return string Link or empty string if there is no download link
  787. */
  788. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  789. {
  790. global $user, $dolibarr_main_url_root;
  791. if (empty($this->last_main_doc)) {
  792. return ''; // No way to known which document name to use
  793. }
  794. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  795. $ecmfile = new EcmFiles($this->db);
  796. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  797. if ($result < 0) {
  798. $this->error = $ecmfile->error;
  799. $this->errors = $ecmfile->errors;
  800. return -1;
  801. }
  802. if (empty($ecmfile->id)) {
  803. // Add entry into index
  804. if ($initsharekey) {
  805. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  806. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  807. /*
  808. $ecmfile->filepath = $rel_dir;
  809. $ecmfile->filename = $filename;
  810. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  811. $ecmfile->fullpath_orig = '';
  812. $ecmfile->gen_or_uploaded = 'generated';
  813. $ecmfile->description = ''; // indexed content
  814. $ecmfile->keywords = ''; // keyword content
  815. $ecmfile->share = getRandomPassword(true);
  816. $result = $ecmfile->create($user);
  817. if ($result < 0)
  818. {
  819. $this->error = $ecmfile->error;
  820. $this->errors = $ecmfile->errors;
  821. }
  822. */
  823. } else {
  824. return '';
  825. }
  826. } elseif (empty($ecmfile->share)) {
  827. // Add entry into index
  828. if ($initsharekey) {
  829. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  830. $ecmfile->share = getRandomPassword(true);
  831. $ecmfile->update($user);
  832. } else {
  833. return '';
  834. }
  835. }
  836. // Define $urlwithroot
  837. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  838. // This is to use external domain name found into config file
  839. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  840. //else
  841. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  842. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  843. $forcedownload = 0;
  844. $paramlink = '';
  845. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  846. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  847. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  848. if (!empty($ecmfile->share)) {
  849. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  850. }
  851. if ($forcedownload) {
  852. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  853. }
  854. if ($relativelink) {
  855. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  856. } else {
  857. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  858. }
  859. // Here $ecmfile->share is defined
  860. return $linktoreturn;
  861. }
  862. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  863. /**
  864. * Add a link between element $this->element and a contact
  865. *
  866. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  867. * @param int|string $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
  868. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  869. * @param int $notrigger Disable all triggers
  870. * @return int <0 if KO, 0 if already added, >0 if OK
  871. */
  872. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  873. {
  874. // phpcs:enable
  875. global $user, $langs;
  876. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  877. // Check parameters
  878. if ($fk_socpeople <= 0) {
  879. $langs->load("errors");
  880. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  881. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  882. return -1;
  883. }
  884. if (!$type_contact) {
  885. $langs->load("errors");
  886. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  887. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  888. return -2;
  889. }
  890. $id_type_contact = 0;
  891. if (is_numeric($type_contact)) {
  892. $id_type_contact = $type_contact;
  893. } else {
  894. // We look for id type_contact
  895. $sql = "SELECT tc.rowid";
  896. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  897. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  898. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  899. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  900. //print $sql;
  901. $resql = $this->db->query($sql);
  902. if ($resql) {
  903. $obj = $this->db->fetch_object($resql);
  904. if ($obj) {
  905. $id_type_contact = $obj->rowid;
  906. }
  907. }
  908. }
  909. if ($id_type_contact == 0) {
  910. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  911. dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
  912. return -3;
  913. }
  914. $datecreate = dol_now();
  915. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  916. $TListeContacts = $this->liste_contact(-1, $source);
  917. $already_added = false;
  918. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  919. foreach ($TListeContacts as $array_contact) {
  920. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  921. $already_added = true;
  922. break;
  923. }
  924. }
  925. }
  926. if (!$already_added) {
  927. $this->db->begin();
  928. // Insert into database
  929. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  930. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  931. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  932. $sql .= "'".$this->db->idate($datecreate)."'";
  933. $sql .= ", 4, ".((int) $id_type_contact);
  934. $sql .= ")";
  935. $resql = $this->db->query($sql);
  936. if ($resql) {
  937. if (!$notrigger) {
  938. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  939. if ($result < 0) {
  940. $this->db->rollback();
  941. return -1;
  942. }
  943. }
  944. $this->db->commit();
  945. return 1;
  946. } else {
  947. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  948. $this->error = $this->db->errno();
  949. $this->db->rollback();
  950. return -2;
  951. } else {
  952. $this->error = $this->db->lasterror();
  953. $this->db->rollback();
  954. return -1;
  955. }
  956. }
  957. } else {
  958. return 0;
  959. }
  960. }
  961. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  962. /**
  963. * Copy contact from one element to current
  964. *
  965. * @param CommonObject $objFrom Source element
  966. * @param string $source Nature of contact ('internal' or 'external')
  967. * @return int >0 if OK, <0 if KO
  968. */
  969. public function copy_linked_contact($objFrom, $source = 'internal')
  970. {
  971. // phpcs:enable
  972. $contacts = $objFrom->liste_contact(-1, $source);
  973. foreach ($contacts as $contact) {
  974. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  975. return -1;
  976. }
  977. }
  978. return 1;
  979. }
  980. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  981. /**
  982. * Update a link to contact line
  983. *
  984. * @param int $rowid Id of line contact-element
  985. * @param int $statut New status of link
  986. * @param int $type_contact_id Id of contact type (not modified if 0)
  987. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  988. * @return int <0 if KO, >= 0 if OK
  989. */
  990. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  991. {
  992. // phpcs:enable
  993. // Insert into database
  994. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  995. $sql .= " statut = ".$statut;
  996. if ($type_contact_id) {
  997. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  998. }
  999. if ($fk_socpeople) {
  1000. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1001. }
  1002. $sql .= " where rowid = ".((int) $rowid);
  1003. $resql = $this->db->query($sql);
  1004. if ($resql) {
  1005. return 0;
  1006. } else {
  1007. $this->error = $this->db->lasterror();
  1008. return -1;
  1009. }
  1010. }
  1011. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1012. /**
  1013. * Delete a link to contact line
  1014. *
  1015. * @param int $rowid Id of contact link line to delete
  1016. * @param int $notrigger Disable all triggers
  1017. * @return int >0 if OK, <0 if KO
  1018. */
  1019. public function delete_contact($rowid, $notrigger = 0)
  1020. {
  1021. // phpcs:enable
  1022. global $user;
  1023. $this->db->begin();
  1024. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1025. $sql .= " WHERE rowid = ".((int) $rowid);
  1026. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1027. if ($this->db->query($sql)) {
  1028. if (!$notrigger) {
  1029. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1030. if ($result < 0) {
  1031. $this->db->rollback();
  1032. return -1;
  1033. }
  1034. }
  1035. $this->db->commit();
  1036. return 1;
  1037. } else {
  1038. $this->error = $this->db->lasterror();
  1039. $this->db->rollback();
  1040. return -1;
  1041. }
  1042. }
  1043. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1044. /**
  1045. * Delete all links between an object $this and all its contacts
  1046. *
  1047. * @param string $source '' or 'internal' or 'external'
  1048. * @param string $code Type of contact (code or id)
  1049. * @return int >0 if OK, <0 if KO
  1050. */
  1051. public function delete_linked_contact($source = '', $code = '')
  1052. {
  1053. // phpcs:enable
  1054. $temp = array();
  1055. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1056. foreach ($typeContact as $key => $value) {
  1057. array_push($temp, $key);
  1058. }
  1059. $listId = implode(",", $temp);
  1060. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1061. $sql .= " WHERE element_id = ".$this->id;
  1062. if ($listId) {
  1063. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1064. }
  1065. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1066. if ($this->db->query($sql)) {
  1067. return 1;
  1068. } else {
  1069. $this->error = $this->db->lasterror();
  1070. return -1;
  1071. }
  1072. }
  1073. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1074. /**
  1075. * Get array of all contacts for an object
  1076. *
  1077. * @param int $status Status of links to get (-1=all)
  1078. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1079. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  1080. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1081. * @return array|int Array of contacts, -1 if error
  1082. */
  1083. public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
  1084. {
  1085. // phpcs:enable
  1086. global $langs;
  1087. $tab = array();
  1088. $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
  1089. if ($source == 'internal') {
  1090. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1091. }
  1092. if ($source == 'external' || $source == 'thirdparty') {
  1093. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1094. }
  1095. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1096. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1097. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1098. $sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
  1099. if ($source == 'internal') {
  1100. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  1101. }
  1102. if ($source == 'external' || $source == 'thirdparty') {
  1103. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  1104. }
  1105. $sql .= " WHERE ec.element_id =".$this->id;
  1106. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1107. $sql .= " AND tc.element='".$this->db->escape($this->element)."'";
  1108. if ($code) {
  1109. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1110. }
  1111. if ($source == 'internal') {
  1112. $sql .= " AND tc.source = 'internal'";
  1113. }
  1114. if ($source == 'external' || $source == 'thirdparty') {
  1115. $sql .= " AND tc.source = 'external'";
  1116. }
  1117. $sql .= " AND tc.active=1";
  1118. if ($status >= 0) {
  1119. $sql .= " AND ec.statut = ".((int) $status);
  1120. }
  1121. $sql .= " ORDER BY t.lastname ASC";
  1122. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1123. $resql = $this->db->query($sql);
  1124. if ($resql) {
  1125. $num = $this->db->num_rows($resql);
  1126. $i = 0;
  1127. while ($i < $num) {
  1128. $obj = $this->db->fetch_object($resql);
  1129. if (!$list) {
  1130. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1131. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1132. $tab[$i] = array(
  1133. 'source' => $obj->source,
  1134. 'socid' => $obj->socid,
  1135. 'id' => $obj->id,
  1136. 'nom' => $obj->lastname, // For backward compatibility
  1137. 'civility' => $obj->civility,
  1138. 'lastname' => $obj->lastname,
  1139. 'firstname' => $obj->firstname,
  1140. 'email'=>$obj->email,
  1141. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1142. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1143. 'statuscontact' => $obj->statuscontact,
  1144. 'rowid' => $obj->rowid,
  1145. 'code' => $obj->code,
  1146. 'libelle' => $libelle_type,
  1147. 'status' => $obj->statuslink,
  1148. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1149. );
  1150. } else {
  1151. $tab[$i] = $obj->id;
  1152. }
  1153. $i++;
  1154. }
  1155. return $tab;
  1156. } else {
  1157. $this->error = $this->db->lasterror();
  1158. dol_print_error($this->db);
  1159. return -1;
  1160. }
  1161. }
  1162. /**
  1163. * Update status of a contact linked to object
  1164. *
  1165. * @param int $rowid Id of link between object and contact
  1166. * @return int <0 if KO, >=0 if OK
  1167. */
  1168. public function swapContactStatus($rowid)
  1169. {
  1170. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1171. $sql .= " tc.code, tc.libelle";
  1172. $sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  1173. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1174. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1175. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1176. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1177. $resql = $this->db->query($sql);
  1178. if ($resql) {
  1179. $obj = $this->db->fetch_object($resql);
  1180. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1181. $result = $this->update_contact($rowid, $newstatut);
  1182. $this->db->free($resql);
  1183. return $result;
  1184. } else {
  1185. $this->error = $this->db->error();
  1186. dol_print_error($this->db);
  1187. return -1;
  1188. }
  1189. }
  1190. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1191. /**
  1192. * Return array with list of possible values for type of contacts
  1193. *
  1194. * @param string $source 'internal', 'external' or 'all'
  1195. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1196. * @param int $option 0=Return array id->label, 1=Return array code->label
  1197. * @param int $activeonly 0=all status of contact, 1=only the active
  1198. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1199. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1200. */
  1201. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1202. {
  1203. // phpcs:enable
  1204. global $langs;
  1205. if (empty($order)) {
  1206. $order = 'position';
  1207. }
  1208. if ($order == 'position') {
  1209. $order .= ',code';
  1210. }
  1211. $tab = array();
  1212. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1213. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1214. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1215. if ($activeonly == 1) {
  1216. $sql .= " AND tc.active=1"; // only the active types
  1217. }
  1218. if (!empty($source) && $source != 'all') {
  1219. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1220. }
  1221. if (!empty($code)) {
  1222. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1223. }
  1224. $sql .= $this->db->order($order, 'ASC');
  1225. //print "sql=".$sql;
  1226. $resql = $this->db->query($sql);
  1227. if ($resql) {
  1228. $num = $this->db->num_rows($resql);
  1229. $i = 0;
  1230. while ($i < $num) {
  1231. $obj = $this->db->fetch_object($resql);
  1232. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1233. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1234. if (empty($option)) {
  1235. $tab[$obj->rowid] = $libelle_type;
  1236. } else {
  1237. $tab[$obj->code] = $libelle_type;
  1238. }
  1239. $i++;
  1240. }
  1241. return $tab;
  1242. } else {
  1243. $this->error = $this->db->lasterror();
  1244. //dol_print_error($this->db);
  1245. return null;
  1246. }
  1247. }
  1248. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1249. /**
  1250. * Return array with list of possible values for type of contacts
  1251. *
  1252. * @param string $source 'internal', 'external' or 'all'
  1253. * @param int $option 0=Return array id->label, 1=Return array code->label
  1254. * @param int $activeonly 0=all status of contact, 1=only the active
  1255. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1256. * @param string $element Filter on 1 element type
  1257. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1258. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1259. */
  1260. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1261. {
  1262. // phpcs:enable
  1263. global $langs, $conf;
  1264. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1265. $tab = array();
  1266. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1267. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  1268. $sqlWhere = array();
  1269. if (!empty($element)) {
  1270. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1271. }
  1272. if (!empty($excludeelement)) {
  1273. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1274. }
  1275. if ($activeonly == 1) {
  1276. $sqlWhere[] = " tc.active=1"; // only the active types
  1277. }
  1278. if (!empty($source) && $source != 'all') {
  1279. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1280. }
  1281. if (!empty($code)) {
  1282. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1283. }
  1284. if (count($sqlWhere) > 0) {
  1285. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1286. }
  1287. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1288. dol_syslog(__METHOD__, LOG_DEBUG);
  1289. $resql = $this->db->query($sql);
  1290. if ($resql) {
  1291. $num = $this->db->num_rows($resql);
  1292. if ($num > 0) {
  1293. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1294. while ($obj = $this->db->fetch_object($resql)) {
  1295. $modulename = $obj->element;
  1296. if (strpos($obj->element, 'project') !== false) {
  1297. $modulename = 'projet';
  1298. } elseif ($obj->element == 'contrat') {
  1299. $element = 'contract';
  1300. } elseif ($obj->element == 'action') {
  1301. $modulename = 'agenda';
  1302. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1303. $modulename = 'fournisseur';
  1304. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1305. $modulename = 'fournisseur';
  1306. }
  1307. if (!empty($conf->{$modulename}->enabled)) {
  1308. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1309. $tmpelement = $obj->element;
  1310. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1311. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1312. if (empty($option)) {
  1313. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1314. } else {
  1315. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1316. }
  1317. }
  1318. }
  1319. }
  1320. return $tab;
  1321. } else {
  1322. $this->error = $this->db->lasterror();
  1323. return null;
  1324. }
  1325. }
  1326. /**
  1327. * Return id of contacts for a source and a contact code.
  1328. * Example: contact client de facturation ('external', 'BILLING')
  1329. * Example: contact client de livraison ('external', 'SHIPPING')
  1330. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1331. *
  1332. * @param string $source 'external' or 'internal'
  1333. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1334. * @param int $status limited to a certain status
  1335. * @return array List of id for such contacts
  1336. */
  1337. public function getIdContact($source, $code, $status = 0)
  1338. {
  1339. global $conf;
  1340. $result = array();
  1341. $i = 0;
  1342. //cas particulier pour les expeditions
  1343. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1344. $id = $this->origin_id;
  1345. $element = 'commande';
  1346. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1347. $id = $this->origin_id;
  1348. $element = 'order_supplier';
  1349. } else {
  1350. $id = $this->id;
  1351. $element = $this->element;
  1352. }
  1353. $sql = "SELECT ec.fk_socpeople";
  1354. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1355. if ($source == 'internal') {
  1356. $sql .= " ".MAIN_DB_PREFIX."user as c,";
  1357. }
  1358. if ($source == 'external') {
  1359. $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
  1360. }
  1361. $sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1362. $sql .= " WHERE ec.element_id = ".((int) $id);
  1363. $sql .= " AND ec.fk_socpeople = c.rowid";
  1364. if ($source == 'internal') {
  1365. $sql .= " AND c.entity IN (".getEntity('user').")";
  1366. }
  1367. if ($source == 'external') {
  1368. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1369. }
  1370. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1371. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1372. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1373. if ($code) {
  1374. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1375. }
  1376. $sql .= " AND tc.active = 1";
  1377. if ($status) {
  1378. $sql .= " AND ec.statut = ".((int) $status);
  1379. }
  1380. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1381. $resql = $this->db->query($sql);
  1382. if ($resql) {
  1383. while ($obj = $this->db->fetch_object($resql)) {
  1384. $result[$i] = $obj->fk_socpeople;
  1385. $i++;
  1386. }
  1387. } else {
  1388. $this->error = $this->db->error();
  1389. return null;
  1390. }
  1391. return $result;
  1392. }
  1393. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1394. /**
  1395. * Load object contact with id=$this->contact_id into $this->contact
  1396. *
  1397. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1398. * @return int <0 if KO, >0 if OK
  1399. */
  1400. public function fetch_contact($contactid = null)
  1401. {
  1402. // phpcs:enable
  1403. if (empty($contactid)) {
  1404. $contactid = $this->contact_id;
  1405. }
  1406. if (empty($contactid)) {
  1407. return 0;
  1408. }
  1409. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1410. $contact = new Contact($this->db);
  1411. $result = $contact->fetch($contactid);
  1412. $this->contact = $contact;
  1413. return $result;
  1414. }
  1415. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1416. /**
  1417. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1418. *
  1419. * @param int $force_thirdparty_id Force thirdparty id
  1420. * @return int <0 if KO, >0 if OK
  1421. */
  1422. public function fetch_thirdparty($force_thirdparty_id = 0)
  1423. {
  1424. // phpcs:enable
  1425. global $conf;
  1426. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
  1427. return 0;
  1428. }
  1429. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1430. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1431. if ($force_thirdparty_id) {
  1432. $idtofetch = $force_thirdparty_id;
  1433. }
  1434. if ($idtofetch) {
  1435. $thirdparty = new Societe($this->db);
  1436. $result = $thirdparty->fetch($idtofetch);
  1437. if ($result<0) {
  1438. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1439. }
  1440. $this->thirdparty = $thirdparty;
  1441. // Use first price level if level not defined for third party
  1442. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1443. $this->thirdparty->price_level = 1;
  1444. }
  1445. return $result;
  1446. } else {
  1447. return -1;
  1448. }
  1449. }
  1450. /**
  1451. * Looks for an object with ref matching the wildcard provided
  1452. * It does only work when $this->table_ref_field is set
  1453. *
  1454. * @param string $ref Wildcard
  1455. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1456. */
  1457. public function fetchOneLike($ref)
  1458. {
  1459. if (!$this->table_ref_field) {
  1460. return 0;
  1461. }
  1462. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
  1463. $query = $this->db->query($sql);
  1464. if (!$this->db->num_rows($query)) {
  1465. return 0;
  1466. }
  1467. $result = $this->db->fetch_object($query);
  1468. return $this->fetch($result->rowid);
  1469. }
  1470. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1471. /**
  1472. * Load data for barcode into properties ->barcode_type*
  1473. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1474. * if it is not defined, ->element must be defined to know default barcode type.
  1475. *
  1476. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1477. */
  1478. public function fetch_barcode()
  1479. {
  1480. // phpcs:enable
  1481. global $conf;
  1482. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1483. $idtype = $this->barcode_type;
  1484. 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
  1485. if ($this->element == 'product') {
  1486. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1487. } elseif ($this->element == 'societe') {
  1488. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1489. } else {
  1490. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1491. }
  1492. }
  1493. if ($idtype > 0) {
  1494. 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
  1495. $sql = "SELECT rowid, code, libelle as label, coder";
  1496. $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1497. $sql .= " WHERE rowid = ".((int) $idtype);
  1498. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1499. $resql = $this->db->query($sql);
  1500. if ($resql) {
  1501. $obj = $this->db->fetch_object($resql);
  1502. $this->barcode_type = $obj->rowid;
  1503. $this->barcode_type_code = $obj->code;
  1504. $this->barcode_type_label = $obj->label;
  1505. $this->barcode_type_coder = $obj->coder;
  1506. return 1;
  1507. } else {
  1508. dol_print_error($this->db);
  1509. return -1;
  1510. }
  1511. }
  1512. }
  1513. return 0;
  1514. }
  1515. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1516. /**
  1517. * Load the project with id $this->fk_project into this->project
  1518. *
  1519. * @return int <0 if KO, >=0 if OK
  1520. */
  1521. public function fetch_projet()
  1522. {
  1523. // phpcs:enable
  1524. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1525. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1526. $this->fk_project = $this->fk_projet; // For backward compatibility
  1527. }
  1528. if (empty($this->fk_project)) {
  1529. return 0;
  1530. }
  1531. $project = new Project($this->db);
  1532. $result = $project->fetch($this->fk_project);
  1533. $this->projet = $project; // deprecated
  1534. $this->project = $project;
  1535. return $result;
  1536. }
  1537. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1538. /**
  1539. * Load the product with id $this->fk_product into this->product
  1540. *
  1541. * @return int <0 if KO, >=0 if OK
  1542. */
  1543. public function fetch_product()
  1544. {
  1545. // phpcs:enable
  1546. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1547. if (empty($this->fk_product)) {
  1548. return 0;
  1549. }
  1550. $product = new Product($this->db);
  1551. $result = $product->fetch($this->fk_product);
  1552. $this->product = $product;
  1553. return $result;
  1554. }
  1555. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1556. /**
  1557. * Load the user with id $userid into this->user
  1558. *
  1559. * @param int $userid Id du contact
  1560. * @return int <0 if KO, >0 if OK
  1561. */
  1562. public function fetch_user($userid)
  1563. {
  1564. // phpcs:enable
  1565. $user = new User($this->db);
  1566. $result = $user->fetch($userid);
  1567. $this->user = $user;
  1568. return $result;
  1569. }
  1570. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1571. /**
  1572. * Read linked origin object
  1573. *
  1574. * @return void
  1575. */
  1576. public function fetch_origin()
  1577. {
  1578. // phpcs:enable
  1579. if ($this->origin == 'shipping') {
  1580. $this->origin = 'expedition';
  1581. }
  1582. if ($this->origin == 'delivery') {
  1583. $this->origin = 'livraison';
  1584. }
  1585. if ($this->origin == 'order_supplier') {
  1586. $this->origin = 'commandeFournisseur';
  1587. }
  1588. $origin = $this->origin;
  1589. $classname = ucfirst($origin);
  1590. $this->$origin = new $classname($this->db);
  1591. $this->$origin->fetch($this->origin_id);
  1592. }
  1593. /**
  1594. * Load object from specific field
  1595. *
  1596. * @param string $table Table element or element line
  1597. * @param string $field Field selected
  1598. * @param string $key Import key
  1599. * @param string $element Element name
  1600. * @return int <0 if KO, >0 if OK
  1601. */
  1602. public function fetchObjectFrom($table, $field, $key, $element = null)
  1603. {
  1604. global $conf;
  1605. $result = false;
  1606. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1607. $sql .= " WHERE ".$field." = '".$key."'";
  1608. if (!empty($element)) {
  1609. $sql .= " AND entity IN (".getEntity($element).")";
  1610. } else {
  1611. $sql .= " AND entity = ".$conf->entity;
  1612. }
  1613. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1614. $resql = $this->db->query($sql);
  1615. if ($resql) {
  1616. $row = $this->db->fetch_row($resql);
  1617. // Test for avoid error -1
  1618. if ($row[0] > 0) {
  1619. $result = $this->fetch($row[0]);
  1620. }
  1621. }
  1622. return $result;
  1623. }
  1624. /**
  1625. * Getter generic. Load value from a specific field
  1626. *
  1627. * @param string $table Table of element or element line
  1628. * @param int $id Element id
  1629. * @param string $field Field selected
  1630. * @return int <0 if KO, >0 if OK
  1631. */
  1632. public function getValueFrom($table, $id, $field)
  1633. {
  1634. $result = false;
  1635. if (!empty($id) && !empty($field) && !empty($table)) {
  1636. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1637. $sql .= " WHERE rowid = ".((int) $id);
  1638. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1639. $resql = $this->db->query($sql);
  1640. if ($resql) {
  1641. $row = $this->db->fetch_row($resql);
  1642. $result = $row[0];
  1643. }
  1644. }
  1645. return $result;
  1646. }
  1647. /**
  1648. * Setter generic. Update a specific field into database.
  1649. * Warning: Trigger is run only if param trigkey is provided.
  1650. *
  1651. * @param string $field Field to update
  1652. * @param mixed $value New value
  1653. * @param string $table To force other table element or element line (should not be used)
  1654. * @param int $id To force other object id (should not be used)
  1655. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1656. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1657. * @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'
  1658. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1659. * @param string $fk_user_field Name of field to save user id making change
  1660. * @return int <0 if KO, >0 if OK
  1661. * @see updateExtraField()
  1662. */
  1663. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1664. {
  1665. global $user, $langs, $conf;
  1666. if (empty($table)) {
  1667. $table = $this->table_element;
  1668. }
  1669. if (empty($id)) {
  1670. $id = $this->id;
  1671. }
  1672. if (empty($format)) {
  1673. $format = 'text';
  1674. }
  1675. if (empty($id_field)) {
  1676. $id_field = 'rowid';
  1677. }
  1678. $error = 0;
  1679. $this->db->begin();
  1680. // Special case
  1681. if ($table == 'product' && $field == 'note_private') {
  1682. $field = 'note';
  1683. }
  1684. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1685. $fk_user_field = 'fk_user_mod';
  1686. }
  1687. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1688. if ($format == 'text') {
  1689. $sql .= $field." = '".$this->db->escape($value)."'";
  1690. } elseif ($format == 'int') {
  1691. $sql .= $field." = ".((int) $value);
  1692. } elseif ($format == 'date') {
  1693. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1694. }
  1695. if ($fk_user_field) {
  1696. if (!empty($fuser) && is_object($fuser)) {
  1697. $sql .= ", ".$fk_user_field." = ".$fuser->id;
  1698. } elseif (empty($fuser) || $fuser != 'none') {
  1699. $sql .= ", ".$fk_user_field." = ".$user->id;
  1700. }
  1701. }
  1702. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1703. dol_syslog(__METHOD__."", LOG_DEBUG);
  1704. $resql = $this->db->query($sql);
  1705. if ($resql) {
  1706. if ($trigkey) {
  1707. // call trigger with updated object values
  1708. if (empty($this->fields) && method_exists($this, 'fetch')) {
  1709. $result = $this->fetch($id);
  1710. } else {
  1711. $result = $this->fetchCommon($id);
  1712. }
  1713. if ($result >= 0) {
  1714. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1715. }
  1716. if ($result < 0) {
  1717. $error++;
  1718. }
  1719. }
  1720. if (!$error) {
  1721. if (property_exists($this, $field)) {
  1722. $this->$field = $value;
  1723. }
  1724. $this->db->commit();
  1725. return 1;
  1726. } else {
  1727. $this->db->rollback();
  1728. return -2;
  1729. }
  1730. } else {
  1731. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1732. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1733. } else {
  1734. $this->error = $this->db->lasterror();
  1735. }
  1736. $this->db->rollback();
  1737. return -1;
  1738. }
  1739. }
  1740. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1741. /**
  1742. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1743. *
  1744. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
  1745. * @param string $fieldid Name of field to use for the select MAX and MIN
  1746. * @param int $nodbprefix Do not include DB prefix to forge table name
  1747. * @return int <0 if KO, >0 if OK
  1748. */
  1749. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1750. {
  1751. // phpcs:enable
  1752. global $conf, $user;
  1753. if (!$this->table_element) {
  1754. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1755. return -1;
  1756. }
  1757. if ($fieldid == 'none') {
  1758. return 1;
  1759. }
  1760. // Security on socid
  1761. $socid = 0;
  1762. if ($user->socid > 0) {
  1763. $socid = $user->socid;
  1764. }
  1765. // this->ismultientitymanaged contains
  1766. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1767. $aliastablesociete = 's';
  1768. if ($this->element == 'societe') {
  1769. $aliastablesociete = 'te'; // te as table_element
  1770. }
  1771. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1772. $sql = "SELECT MAX(te.".$fieldid.")";
  1773. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1774. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1775. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1776. }
  1777. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1778. $tmparray = explode('@', $this->ismultientitymanaged);
  1779. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1780. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1781. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1782. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1783. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1784. }
  1785. if ($restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
  1786. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1787. }
  1788. $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)
  1789. if ($restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
  1790. $sql .= " AND sc.fk_user = ".$user->id;
  1791. }
  1792. if ($restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
  1793. $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1794. }
  1795. if (!empty($filter)) {
  1796. if (!preg_match('/^\s*AND/i', $filter)) {
  1797. $sql .= " AND "; // For backward compatibility
  1798. }
  1799. $sql .= $filter;
  1800. }
  1801. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1802. $tmparray = explode('@', $this->ismultientitymanaged);
  1803. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1804. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1805. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1806. }
  1807. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1808. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1809. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1810. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1811. } else {
  1812. $sql .= " AND ug.fk_user = te.rowid";
  1813. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1814. }
  1815. } else {
  1816. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1817. }
  1818. }
  1819. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1820. $tmparray = explode('@', $this->ismultientitymanaged);
  1821. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1822. }
  1823. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1824. $sql .= ' AND te.fk_soc = '.$socid;
  1825. }
  1826. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1827. $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1828. }
  1829. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1830. $sql .= ' AND te.rowid = '.$socid;
  1831. }
  1832. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1833. $result = $this->db->query($sql);
  1834. if (!$result) {
  1835. $this->error = $this->db->lasterror();
  1836. return -1;
  1837. }
  1838. $row = $this->db->fetch_row($result);
  1839. $this->ref_previous = $row[0];
  1840. $sql = "SELECT MIN(te.".$fieldid.")";
  1841. $sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1842. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1843. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1844. }
  1845. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1846. $tmparray = explode('@', $this->ismultientitymanaged);
  1847. $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1848. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1849. $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1850. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1851. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1852. }
  1853. if ($restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
  1854. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1855. }
  1856. $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)
  1857. if ($restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
  1858. $sql .= " AND sc.fk_user = ".$user->id;
  1859. }
  1860. if ($restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
  1861. $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
  1862. }
  1863. if (!empty($filter)) {
  1864. if (!preg_match('/^\s*AND/i', $filter)) {
  1865. $sql .= " AND "; // For backward compatibility
  1866. }
  1867. $sql .= $filter;
  1868. }
  1869. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1870. $tmparray = explode('@', $this->ismultientitymanaged);
  1871. $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity
  1872. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
  1873. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1874. }
  1875. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1876. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1877. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1878. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1879. } else {
  1880. $sql .= " AND ug.fk_user = te.rowid";
  1881. $sql .= " AND ug.entity IN (".getEntity($this->element).")";
  1882. }
  1883. } else {
  1884. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1885. }
  1886. }
  1887. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1888. $tmparray = explode('@', $this->ismultientitymanaged);
  1889. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1890. }
  1891. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1892. $sql .= ' AND te.fk_soc = '.$socid;
  1893. }
  1894. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1895. $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
  1896. }
  1897. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1898. $sql .= ' AND te.rowid = '.$socid;
  1899. }
  1900. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1901. // 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
  1902. $result = $this->db->query($sql);
  1903. if (!$result) {
  1904. $this->error = $this->db->lasterror();
  1905. return -2;
  1906. }
  1907. $row = $this->db->fetch_row($result);
  1908. $this->ref_next = $row[0];
  1909. return 1;
  1910. }
  1911. /**
  1912. * Return list of id of contacts of object
  1913. *
  1914. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1915. * @return array Array of id of contacts (if source=external or internal)
  1916. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1917. */
  1918. public function getListContactId($source = 'external')
  1919. {
  1920. $contactAlreadySelected = array();
  1921. $tab = $this->liste_contact(-1, $source);
  1922. $num = count($tab);
  1923. $i = 0;
  1924. while ($i < $num) {
  1925. if ($source == 'thirdparty') {
  1926. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1927. } else {
  1928. $contactAlreadySelected[$i] = $tab[$i]['id'];
  1929. }
  1930. $i++;
  1931. }
  1932. return $contactAlreadySelected;
  1933. }
  1934. /**
  1935. * Link element with a project
  1936. *
  1937. * @param int $projectid Project id to link element to
  1938. * @return int <0 if KO, >0 if OK
  1939. */
  1940. public function setProject($projectid)
  1941. {
  1942. if (!$this->table_element) {
  1943. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  1944. return -1;
  1945. }
  1946. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1947. if (!empty($this->fields['fk_project'])) { // Common case
  1948. if ($projectid) {
  1949. $sql .= ' SET fk_project = '.((int) $projectid);
  1950. } else {
  1951. $sql .= ' SET fk_project = NULL';
  1952. }
  1953. $sql .= ' WHERE rowid = '.((int) $this->id);
  1954. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  1955. if ($projectid) {
  1956. $sql .= ' SET fk_project = '.((int) $projectid);
  1957. } else {
  1958. $sql .= ' SET fk_project = NULL';
  1959. }
  1960. $sql .= ' WHERE id = '.((int) $this->id);
  1961. } else // Special case for old architecture objects
  1962. {
  1963. if ($projectid) {
  1964. $sql .= ' SET fk_projet = '.((int) $projectid);
  1965. } else {
  1966. $sql .= ' SET fk_projet = NULL';
  1967. }
  1968. $sql .= ' WHERE rowid = '.$this->id;
  1969. }
  1970. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1971. if ($this->db->query($sql)) {
  1972. $this->fk_project = ((int) $projectid);
  1973. return 1;
  1974. } else {
  1975. dol_print_error($this->db);
  1976. return -1;
  1977. }
  1978. }
  1979. /**
  1980. * Change the payments methods
  1981. *
  1982. * @param int $id Id of new payment method
  1983. * @return int >0 if OK, <0 if KO
  1984. */
  1985. public function setPaymentMethods($id)
  1986. {
  1987. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1988. if ($this->statut >= 0 || $this->element == 'societe') {
  1989. // TODO uniformize field name
  1990. $fieldname = 'fk_mode_reglement';
  1991. if ($this->element == 'societe') {
  1992. $fieldname = 'mode_reglement';
  1993. }
  1994. if (get_class($this) == 'Fournisseur') {
  1995. $fieldname = 'mode_reglement_supplier';
  1996. }
  1997. if (get_class($this) == 'Tva') {
  1998. $fieldname = 'fk_typepayment';
  1999. }
  2000. if (get_class($this) == 'Salary') {
  2001. $fieldname = 'fk_typepayment';
  2002. }
  2003. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2004. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2005. $sql .= ' WHERE rowid='.((int) $this->id);
  2006. if ($this->db->query($sql)) {
  2007. $this->mode_reglement_id = $id;
  2008. // for supplier
  2009. if (get_class($this) == 'Fournisseur') {
  2010. $this->mode_reglement_supplier_id = $id;
  2011. }
  2012. return 1;
  2013. } else {
  2014. dol_syslog(get_class($this).'::setPaymentMethods Error '.$sql.' - '.$this->db->error());
  2015. $this->error = $this->db->error();
  2016. return -1;
  2017. }
  2018. } else {
  2019. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2020. $this->error = 'Status of the object is incompatible '.$this->statut;
  2021. return -2;
  2022. }
  2023. }
  2024. /**
  2025. * Change the multicurrency code
  2026. *
  2027. * @param string $code multicurrency code
  2028. * @return int >0 if OK, <0 if KO
  2029. */
  2030. public function setMulticurrencyCode($code)
  2031. {
  2032. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2033. if ($this->statut >= 0 || $this->element == 'societe') {
  2034. $fieldname = 'multicurrency_code';
  2035. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2036. $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
  2037. $sql .= ' WHERE rowid='.((int) $this->id);
  2038. if ($this->db->query($sql)) {
  2039. $this->multicurrency_code = $code;
  2040. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2041. if ($rate) {
  2042. $this->setMulticurrencyRate($rate, 2);
  2043. }
  2044. return 1;
  2045. } else {
  2046. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2047. $this->error = $this->db->error();
  2048. return -1;
  2049. }
  2050. } else {
  2051. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2052. $this->error = 'Status of the object is incompatible '.$this->statut;
  2053. return -2;
  2054. }
  2055. }
  2056. /**
  2057. * Change the multicurrency rate
  2058. *
  2059. * @param double $rate multicurrency rate
  2060. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2061. * @return int >0 if OK, <0 if KO
  2062. */
  2063. public function setMulticurrencyRate($rate, $mode = 1)
  2064. {
  2065. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2066. if ($this->statut >= 0 || $this->element == 'societe') {
  2067. $fieldname = 'multicurrency_tx';
  2068. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2069. $sql .= ' SET '.$fieldname.' = '.((float) $rate);
  2070. $sql .= ' WHERE rowid='.((int) $this->id);
  2071. if ($this->db->query($sql)) {
  2072. $this->multicurrency_tx = $rate;
  2073. // Update line price
  2074. if (!empty($this->lines)) {
  2075. foreach ($this->lines as &$line) {
  2076. // Amounts in company currency will be recalculated
  2077. if ($mode == 1) {
  2078. $line->subprice = 0;
  2079. }
  2080. // Amounts in foreign currency will be recalculated
  2081. if ($mode == 2) {
  2082. $line->multicurrency_subprice = 0;
  2083. }
  2084. switch ($this->element) {
  2085. case 'propal':
  2086. $this->updateline(
  2087. $line->id,
  2088. $line->subprice,
  2089. $line->qty,
  2090. $line->remise_percent,
  2091. $line->tva_tx,
  2092. $line->localtax1_tx,
  2093. $line->localtax2_tx,
  2094. ($line->description ? $line->description : $line->desc),
  2095. 'HT',
  2096. $line->info_bits,
  2097. $line->special_code,
  2098. $line->fk_parent_line,
  2099. $line->skip_update_total,
  2100. $line->fk_fournprice,
  2101. $line->pa_ht,
  2102. $line->label,
  2103. $line->product_type,
  2104. $line->date_start,
  2105. $line->date_end,
  2106. $line->array_options,
  2107. $line->fk_unit,
  2108. $line->multicurrency_subprice
  2109. );
  2110. break;
  2111. case 'commande':
  2112. $this->updateline(
  2113. $line->id,
  2114. ($line->description ? $line->description : $line->desc),
  2115. $line->subprice,
  2116. $line->qty,
  2117. $line->remise_percent,
  2118. $line->tva_tx,
  2119. $line->localtax1_tx,
  2120. $line->localtax2_tx,
  2121. 'HT',
  2122. $line->info_bits,
  2123. $line->date_start,
  2124. $line->date_end,
  2125. $line->product_type,
  2126. $line->fk_parent_line,
  2127. $line->skip_update_total,
  2128. $line->fk_fournprice,
  2129. $line->pa_ht,
  2130. $line->label,
  2131. $line->special_code,
  2132. $line->array_options,
  2133. $line->fk_unit,
  2134. $line->multicurrency_subprice
  2135. );
  2136. break;
  2137. case 'facture':
  2138. $this->updateline(
  2139. $line->id,
  2140. ($line->description ? $line->description : $line->desc),
  2141. $line->subprice,
  2142. $line->qty,
  2143. $line->remise_percent,
  2144. $line->date_start,
  2145. $line->date_end,
  2146. $line->tva_tx,
  2147. $line->localtax1_tx,
  2148. $line->localtax2_tx,
  2149. 'HT',
  2150. $line->info_bits,
  2151. $line->product_type,
  2152. $line->fk_parent_line,
  2153. $line->skip_update_total,
  2154. $line->fk_fournprice,
  2155. $line->pa_ht,
  2156. $line->label,
  2157. $line->special_code,
  2158. $line->array_options,
  2159. $line->situation_percent,
  2160. $line->fk_unit,
  2161. $line->multicurrency_subprice
  2162. );
  2163. break;
  2164. case 'supplier_proposal':
  2165. $this->updateline(
  2166. $line->id,
  2167. $line->subprice,
  2168. $line->qty,
  2169. $line->remise_percent,
  2170. $line->tva_tx,
  2171. $line->localtax1_tx,
  2172. $line->localtax2_tx,
  2173. ($line->description ? $line->description : $line->desc),
  2174. 'HT',
  2175. $line->info_bits,
  2176. $line->special_code,
  2177. $line->fk_parent_line,
  2178. $line->skip_update_total,
  2179. $line->fk_fournprice,
  2180. $line->pa_ht,
  2181. $line->label,
  2182. $line->product_type,
  2183. $line->array_options,
  2184. $line->ref_fourn,
  2185. $line->multicurrency_subprice
  2186. );
  2187. break;
  2188. case 'order_supplier':
  2189. $this->updateline(
  2190. $line->id,
  2191. ($line->description ? $line->description : $line->desc),
  2192. $line->subprice,
  2193. $line->qty,
  2194. $line->remise_percent,
  2195. $line->tva_tx,
  2196. $line->localtax1_tx,
  2197. $line->localtax2_tx,
  2198. 'HT',
  2199. $line->info_bits,
  2200. $line->product_type,
  2201. false,
  2202. $line->date_start,
  2203. $line->date_end,
  2204. $line->array_options,
  2205. $line->fk_unit,
  2206. $line->multicurrency_subprice,
  2207. $line->ref_supplier
  2208. );
  2209. break;
  2210. case 'invoice_supplier':
  2211. $this->updateline(
  2212. $line->id,
  2213. ($line->description ? $line->description : $line->desc),
  2214. $line->subprice,
  2215. $line->tva_tx,
  2216. $line->localtax1_tx,
  2217. $line->localtax2_tx,
  2218. $line->qty,
  2219. 0,
  2220. 'HT',
  2221. $line->info_bits,
  2222. $line->product_type,
  2223. $line->remise_percent,
  2224. false,
  2225. $line->date_start,
  2226. $line->date_end,
  2227. $line->array_options,
  2228. $line->fk_unit,
  2229. $line->multicurrency_subprice,
  2230. $line->ref_supplier
  2231. );
  2232. break;
  2233. default:
  2234. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2235. break;
  2236. }
  2237. }
  2238. }
  2239. return 1;
  2240. } else {
  2241. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2242. $this->error = $this->db->error();
  2243. return -1;
  2244. }
  2245. } else {
  2246. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2247. $this->error = 'Status of the object is incompatible '.$this->statut;
  2248. return -2;
  2249. }
  2250. }
  2251. /**
  2252. * Change the payments terms
  2253. *
  2254. * @param int $id Id of new payment terms
  2255. * @return int >0 if OK, <0 if KO
  2256. */
  2257. public function setPaymentTerms($id)
  2258. {
  2259. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  2260. if ($this->statut >= 0 || $this->element == 'societe') {
  2261. // TODO uniformize field name
  2262. $fieldname = 'fk_cond_reglement';
  2263. if ($this->element == 'societe') {
  2264. $fieldname = 'cond_reglement';
  2265. }
  2266. if (get_class($this) == 'Fournisseur') {
  2267. $fieldname = 'cond_reglement_supplier';
  2268. }
  2269. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2270. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2271. $sql .= ' WHERE rowid='.((int) $this->id);
  2272. if ($this->db->query($sql)) {
  2273. $this->cond_reglement_id = $id;
  2274. // for supplier
  2275. if (get_class($this) == 'Fournisseur') {
  2276. $this->cond_reglement_supplier_id = $id;
  2277. }
  2278. $this->cond_reglement = $id; // for compatibility
  2279. return 1;
  2280. } else {
  2281. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2282. $this->error = $this->db->error();
  2283. return -1;
  2284. }
  2285. } else {
  2286. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2287. $this->error = 'Status of the object is incompatible '.$this->statut;
  2288. return -2;
  2289. }
  2290. }
  2291. /**
  2292. * Change the transport mode methods
  2293. *
  2294. * @param int $id Id of transport mode
  2295. * @return int >0 if OK, <0 if KO
  2296. */
  2297. public function setTransportMode($id)
  2298. {
  2299. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2300. if ($this->statut >= 0 || $this->element == 'societe') {
  2301. $fieldname = 'fk_transport_mode';
  2302. if ($this->element == 'societe') {
  2303. $fieldname = 'transport_mode';
  2304. }
  2305. if (get_class($this) == 'Fournisseur') {
  2306. $fieldname = 'transport_mode_supplier';
  2307. }
  2308. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2309. $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL');
  2310. $sql .= ' WHERE rowid='.((int) $this->id);
  2311. if ($this->db->query($sql)) {
  2312. $this->transport_mode_id = $id;
  2313. // for supplier
  2314. if (get_class($this) == 'Fournisseur') {
  2315. $this->transport_mode_supplier_id = $id;
  2316. }
  2317. return 1;
  2318. } else {
  2319. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2320. $this->error = $this->db->error();
  2321. return -1;
  2322. }
  2323. } else {
  2324. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2325. $this->error = 'Status of the object is incompatible '.$this->statut;
  2326. return -2;
  2327. }
  2328. }
  2329. /**
  2330. * Change the retained warranty payments terms
  2331. *
  2332. * @param int $id Id of new payment terms
  2333. * @return int >0 if OK, <0 if KO
  2334. */
  2335. public function setRetainedWarrantyPaymentTerms($id)
  2336. {
  2337. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2338. if ($this->statut >= 0 || $this->element == 'societe') {
  2339. $fieldname = 'retained_warranty_fk_cond_reglement';
  2340. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2341. $sql .= ' SET '.$fieldname.' = '.((int) $id);
  2342. $sql .= ' WHERE rowid='.((int) $this->id);
  2343. if ($this->db->query($sql)) {
  2344. $this->retained_warranty_fk_cond_reglement = $id;
  2345. return 1;
  2346. } else {
  2347. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2348. $this->error = $this->db->error();
  2349. return -1;
  2350. }
  2351. } else {
  2352. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2353. $this->error = 'Status of the object is incompatible '.$this->statut;
  2354. return -2;
  2355. }
  2356. }
  2357. /**
  2358. * Define delivery address
  2359. * @deprecated
  2360. *
  2361. * @param int $id Address id
  2362. * @return int <0 si ko, >0 si ok
  2363. */
  2364. public function setDeliveryAddress($id)
  2365. {
  2366. $fieldname = 'fk_delivery_address';
  2367. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2368. $fieldname = 'fk_address';
  2369. }
  2370. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".((int) $id);
  2371. $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  2372. if ($this->db->query($sql)) {
  2373. $this->fk_delivery_address = $id;
  2374. return 1;
  2375. } else {
  2376. $this->error = $this->db->error();
  2377. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$sql.' - '.$this->error);
  2378. return -1;
  2379. }
  2380. }
  2381. /**
  2382. * Change the shipping method
  2383. *
  2384. * @param int $shipping_method_id Id of shipping method
  2385. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2386. * @param User $userused Object user
  2387. *
  2388. * @return int 1 if OK, 0 if KO
  2389. */
  2390. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2391. {
  2392. global $user;
  2393. if (empty($userused)) {
  2394. $userused = $user;
  2395. }
  2396. $error = 0;
  2397. if (!$this->table_element) {
  2398. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2399. return -1;
  2400. }
  2401. $this->db->begin();
  2402. if ($shipping_method_id < 0) {
  2403. $shipping_method_id = 'NULL';
  2404. }
  2405. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2406. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2407. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2408. $sql .= " WHERE rowid=".((int) $this->id);
  2409. $resql = $this->db->query($sql);
  2410. if (!$resql) {
  2411. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2412. $this->error = $this->db->lasterror();
  2413. $error++;
  2414. } else {
  2415. if (!$notrigger) {
  2416. // Call trigger
  2417. $this->context = array('shippingmethodupdate'=>1);
  2418. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2419. if ($result < 0) {
  2420. $error++;
  2421. }
  2422. // End call trigger
  2423. }
  2424. }
  2425. if ($error) {
  2426. $this->db->rollback();
  2427. return -1;
  2428. } else {
  2429. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2430. $this->db->commit();
  2431. return 1;
  2432. }
  2433. }
  2434. /**
  2435. * Change the warehouse
  2436. *
  2437. * @param int $warehouse_id Id of warehouse
  2438. * @return int 1 if OK, 0 if KO
  2439. */
  2440. public function setWarehouse($warehouse_id)
  2441. {
  2442. if (!$this->table_element) {
  2443. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2444. return -1;
  2445. }
  2446. if ($warehouse_id < 0) {
  2447. $warehouse_id = 'NULL';
  2448. }
  2449. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2450. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2451. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2452. $sql .= " WHERE rowid=".((int) $this->id);
  2453. if ($this->db->query($sql)) {
  2454. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2455. return 1;
  2456. } else {
  2457. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2458. $this->error = $this->db->error();
  2459. return 0;
  2460. }
  2461. }
  2462. /**
  2463. * Set last model used by doc generator
  2464. *
  2465. * @param User $user User object that make change
  2466. * @param string $modelpdf Modele name
  2467. * @return int <0 if KO, >0 if OK
  2468. */
  2469. public function setDocModel($user, $modelpdf)
  2470. {
  2471. if (!$this->table_element) {
  2472. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2473. return -1;
  2474. }
  2475. $newmodelpdf = dol_trunc($modelpdf, 255);
  2476. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2477. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2478. $sql .= " WHERE rowid = ".$this->id;
  2479. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2480. $resql = $this->db->query($sql);
  2481. if ($resql) {
  2482. $this->model_pdf = $modelpdf;
  2483. $this->modelpdf = $modelpdf; // For bakward compatibility
  2484. return 1;
  2485. } else {
  2486. dol_print_error($this->db);
  2487. return 0;
  2488. }
  2489. }
  2490. /**
  2491. * Change the bank account
  2492. *
  2493. * @param int $fk_account Id of bank account
  2494. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2495. * @param User $userused Object user
  2496. * @return int 1 if OK, 0 if KO
  2497. */
  2498. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2499. {
  2500. global $user;
  2501. if (empty($userused)) {
  2502. $userused = $user;
  2503. }
  2504. $error = 0;
  2505. if (!$this->table_element) {
  2506. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2507. return -1;
  2508. }
  2509. $this->db->begin();
  2510. if ($fk_account < 0) {
  2511. $fk_account = 'NULL';
  2512. }
  2513. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2514. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2515. $sql .= " SET fk_account = ".((int) $fk_account);
  2516. $sql .= " WHERE rowid=".((int) $this->id);
  2517. $resql = $this->db->query($sql);
  2518. if (!$resql) {
  2519. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2520. $this->error = $this->db->lasterror();
  2521. $error++;
  2522. } else {
  2523. if (!$notrigger) {
  2524. // Call trigger
  2525. $this->context = array('bankaccountupdate'=>1);
  2526. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2527. if ($result < 0) {
  2528. $error++;
  2529. }
  2530. // End call trigger
  2531. }
  2532. }
  2533. if ($error) {
  2534. $this->db->rollback();
  2535. return -1;
  2536. } else {
  2537. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2538. $this->db->commit();
  2539. return 1;
  2540. }
  2541. }
  2542. // TODO: Move line related operations to CommonObjectLine?
  2543. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2544. /**
  2545. * Save a new position (field rang) for details lines.
  2546. * You can choose to set position for lines with already a position or lines without any position defined.
  2547. *
  2548. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2549. * @param string $rowidorder ASC or DESC
  2550. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2551. * @return int <0 if KO, >0 if OK
  2552. */
  2553. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2554. {
  2555. // phpcs:enable
  2556. if (!$this->table_element_line) {
  2557. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2558. return -1;
  2559. }
  2560. if (!$this->fk_element) {
  2561. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2562. return -1;
  2563. }
  2564. // Count number of lines to reorder (according to choice $renum)
  2565. $nl = 0;
  2566. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2567. $sql .= ' WHERE '.$this->fk_element.'='.$this->id;
  2568. if (!$renum) {
  2569. $sql .= ' AND rang = 0';
  2570. }
  2571. if ($renum) {
  2572. $sql .= ' AND rang <> 0';
  2573. }
  2574. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2575. $resql = $this->db->query($sql);
  2576. if ($resql) {
  2577. $row = $this->db->fetch_row($resql);
  2578. $nl = $row[0];
  2579. } else {
  2580. dol_print_error($this->db);
  2581. }
  2582. if ($nl > 0) {
  2583. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2584. $rows = array();
  2585. // We first search all lines that are parent lines (for multilevel details lines)
  2586. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2587. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2588. if ($fk_parent_line) {
  2589. $sql .= ' AND fk_parent_line IS NULL';
  2590. }
  2591. $sql .= ' ORDER BY rang ASC, rowid '.$rowidorder;
  2592. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2593. $resql = $this->db->query($sql);
  2594. if ($resql) {
  2595. $i = 0;
  2596. $num = $this->db->num_rows($resql);
  2597. while ($i < $num) {
  2598. $row = $this->db->fetch_row($resql);
  2599. $rows[] = $row[0]; // Add parent line into array rows
  2600. $childrens = $this->getChildrenOfLine($row[0]);
  2601. if (!empty($childrens)) {
  2602. foreach ($childrens as $child) {
  2603. array_push($rows, $child);
  2604. }
  2605. }
  2606. $i++;
  2607. }
  2608. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2609. if (!empty($rows)) {
  2610. foreach ($rows as $key => $row) {
  2611. $this->updateRangOfLine($row, ($key + 1));
  2612. }
  2613. }
  2614. } else {
  2615. dol_print_error($this->db);
  2616. }
  2617. }
  2618. return 1;
  2619. }
  2620. /**
  2621. * Get children of line
  2622. *
  2623. * @param int $id Id of parent line
  2624. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2625. * @return array Array with list of children lines id
  2626. */
  2627. public function getChildrenOfLine($id, $includealltree = 0)
  2628. {
  2629. $rows = array();
  2630. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2631. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2632. $sql .= ' AND fk_parent_line = '.$id;
  2633. $sql .= ' ORDER BY rang ASC';
  2634. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  2635. $resql = $this->db->query($sql);
  2636. if ($resql) {
  2637. if ($this->db->num_rows($resql) > 0) {
  2638. while ($row = $this->db->fetch_row($resql)) {
  2639. $rows[] = $row[0];
  2640. if (!empty($includealltree)) {
  2641. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2642. }
  2643. }
  2644. }
  2645. }
  2646. return $rows;
  2647. }
  2648. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2649. /**
  2650. * Update a line to have a lower rank
  2651. *
  2652. * @param int $rowid Id of line
  2653. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2654. * @return void
  2655. */
  2656. public function line_up($rowid, $fk_parent_line = true)
  2657. {
  2658. // phpcs:enable
  2659. $this->line_order(false, 'ASC', $fk_parent_line);
  2660. // Get rang of line
  2661. $rang = $this->getRangOfLine($rowid);
  2662. // Update position of line
  2663. $this->updateLineUp($rowid, $rang);
  2664. }
  2665. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2666. /**
  2667. * Update a line to have a higher rank
  2668. *
  2669. * @param int $rowid Id of line
  2670. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2671. * @return void
  2672. */
  2673. public function line_down($rowid, $fk_parent_line = true)
  2674. {
  2675. // phpcs:enable
  2676. $this->line_order(false, 'ASC', $fk_parent_line);
  2677. // Get rang of line
  2678. $rang = $this->getRangOfLine($rowid);
  2679. // Get max value for rang
  2680. $max = $this->line_max();
  2681. // Update position of line
  2682. $this->updateLineDown($rowid, $rang, $max);
  2683. }
  2684. /**
  2685. * Update position of line (rang)
  2686. *
  2687. * @param int $rowid Id of line
  2688. * @param int $rang Position
  2689. * @return void
  2690. */
  2691. public function updateRangOfLine($rowid, $rang)
  2692. {
  2693. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2694. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) {
  2695. $fieldposition = 'position';
  2696. }
  2697. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2698. $sql .= ' WHERE rowid = '.((int) $rowid);
  2699. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2700. if (!$this->db->query($sql)) {
  2701. dol_print_error($this->db);
  2702. }
  2703. }
  2704. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2705. /**
  2706. * Update position of line with ajax (rang)
  2707. *
  2708. * @param array $rows Array of rows
  2709. * @return void
  2710. */
  2711. public function line_ajaxorder($rows)
  2712. {
  2713. // phpcs:enable
  2714. $num = count($rows);
  2715. for ($i = 0; $i < $num; $i++) {
  2716. $this->updateRangOfLine($rows[$i], ($i + 1));
  2717. }
  2718. }
  2719. /**
  2720. * Update position of line up (rang)
  2721. *
  2722. * @param int $rowid Id of line
  2723. * @param int $rang Position
  2724. * @return void
  2725. */
  2726. public function updateLineUp($rowid, $rang)
  2727. {
  2728. if ($rang > 1) {
  2729. $fieldposition = 'rang';
  2730. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2731. $fieldposition = 'position';
  2732. }
  2733. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2734. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2735. $sql .= ' AND rang = '.($rang - 1);
  2736. if ($this->db->query($sql)) {
  2737. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) ($rang - 1));
  2738. $sql .= ' WHERE rowid = '.((int) $rowid);
  2739. if (!$this->db->query($sql)) {
  2740. dol_print_error($this->db);
  2741. }
  2742. } else {
  2743. dol_print_error($this->db);
  2744. }
  2745. }
  2746. }
  2747. /**
  2748. * Update position of line down (rang)
  2749. *
  2750. * @param int $rowid Id of line
  2751. * @param int $rang Position
  2752. * @param int $max Max
  2753. * @return void
  2754. */
  2755. public function updateLineDown($rowid, $rang, $max)
  2756. {
  2757. if ($rang < $max) {
  2758. $fieldposition = 'rang';
  2759. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
  2760. $fieldposition = 'position';
  2761. }
  2762. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) $rang);
  2763. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2764. $sql .= ' AND rang = '.((int) ($rang + 1));
  2765. if ($this->db->query($sql)) {
  2766. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.((int) ($rang + 1));
  2767. $sql .= ' WHERE rowid = '.((int) $rowid);
  2768. if (!$this->db->query($sql)) {
  2769. dol_print_error($this->db);
  2770. }
  2771. } else {
  2772. dol_print_error($this->db);
  2773. }
  2774. }
  2775. }
  2776. /**
  2777. * Get position of line (rang)
  2778. *
  2779. * @param int $rowid Id of line
  2780. * @return int Value of rang in table of lines
  2781. */
  2782. public function getRangOfLine($rowid)
  2783. {
  2784. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2785. $sql .= ' WHERE rowid ='.((int) $rowid);
  2786. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2787. $resql = $this->db->query($sql);
  2788. if ($resql) {
  2789. $row = $this->db->fetch_row($resql);
  2790. return $row[0];
  2791. }
  2792. }
  2793. /**
  2794. * Get rowid of the line relative to its position
  2795. *
  2796. * @param int $rang Rang value
  2797. * @return int Rowid of the line
  2798. */
  2799. public function getIdOfLine($rang)
  2800. {
  2801. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2802. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2803. $sql .= ' AND rang = '.((int) $rang);
  2804. $resql = $this->db->query($sql);
  2805. if ($resql) {
  2806. $row = $this->db->fetch_row($resql);
  2807. return $row[0];
  2808. }
  2809. }
  2810. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2811. /**
  2812. * Get max value used for position of line (rang)
  2813. *
  2814. * @param int $fk_parent_line Parent line id
  2815. * @return int Max value of rang in table of lines
  2816. */
  2817. public function line_max($fk_parent_line = 0)
  2818. {
  2819. // phpcs:enable
  2820. $positionfield = 'rang';
  2821. if ($this->table_element == 'bom_bom') {
  2822. $positionfield = 'position';
  2823. }
  2824. // Search the last rang with fk_parent_line
  2825. if ($fk_parent_line) {
  2826. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2827. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2828. $sql .= ' AND fk_parent_line = '.$fk_parent_line;
  2829. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2830. $resql = $this->db->query($sql);
  2831. if ($resql) {
  2832. $row = $this->db->fetch_row($resql);
  2833. if (!empty($row[0])) {
  2834. return $row[0];
  2835. } else {
  2836. return $this->getRangOfLine($fk_parent_line);
  2837. }
  2838. }
  2839. } else {
  2840. // If not, search the last rang of element
  2841. $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2842. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  2843. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2844. $resql = $this->db->query($sql);
  2845. if ($resql) {
  2846. $row = $this->db->fetch_row($resql);
  2847. return $row[0];
  2848. }
  2849. }
  2850. }
  2851. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2852. /**
  2853. * Update external ref of element
  2854. *
  2855. * @param string $ref_ext Update field ref_ext
  2856. * @return int <0 if KO, >0 if OK
  2857. */
  2858. public function update_ref_ext($ref_ext)
  2859. {
  2860. // phpcs:enable
  2861. if (!$this->table_element) {
  2862. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2863. return -1;
  2864. }
  2865. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2866. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2867. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id;
  2868. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2869. if ($this->db->query($sql)) {
  2870. $this->ref_ext = $ref_ext;
  2871. return 1;
  2872. } else {
  2873. $this->error = $this->db->error();
  2874. return -1;
  2875. }
  2876. }
  2877. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2878. /**
  2879. * Update note of element
  2880. *
  2881. * @param string $note New value for note
  2882. * @param string $suffix '', '_public' or '_private'
  2883. * @return int <0 if KO, >0 if OK
  2884. */
  2885. public function update_note($note, $suffix = '')
  2886. {
  2887. // phpcs:enable
  2888. global $user;
  2889. if (!$this->table_element) {
  2890. $this->error = 'update_note was called on objet with property table_element not defined';
  2891. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2892. return -1;
  2893. }
  2894. if (!in_array($suffix, array('', '_public', '_private'))) {
  2895. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2896. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2897. return -2;
  2898. }
  2899. $newsuffix = $suffix;
  2900. // Special cas
  2901. if ($this->table_element == 'product' && $newsuffix == '_private') {
  2902. $newsuffix = '';
  2903. }
  2904. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  2905. $fieldusermod = "fk_user_mod";
  2906. } elseif ($this->table_element == 'ecm_files') {
  2907. $fieldusermod = "fk_user_m";
  2908. } else {
  2909. $fieldusermod = "fk_user_modif";
  2910. }
  2911. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2912. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  2913. $sql .= " ,".$fieldusermod." = ".$user->id;
  2914. $sql .= " WHERE rowid =".$this->id;
  2915. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2916. if ($this->db->query($sql)) {
  2917. if ($suffix == '_public') {
  2918. $this->note_public = $note;
  2919. } elseif ($suffix == '_private') {
  2920. $this->note_private = $note;
  2921. } else {
  2922. $this->note = $note; // deprecated
  2923. $this->note_private = $note;
  2924. }
  2925. return 1;
  2926. } else {
  2927. $this->error = $this->db->lasterror();
  2928. return -1;
  2929. }
  2930. }
  2931. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2932. /**
  2933. * Update public note (kept for backward compatibility)
  2934. *
  2935. * @param string $note New value for note
  2936. * @return int <0 if KO, >0 if OK
  2937. * @deprecated
  2938. * @see update_note()
  2939. */
  2940. public function update_note_public($note)
  2941. {
  2942. // phpcs:enable
  2943. return $this->update_note($note, '_public');
  2944. }
  2945. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2946. /**
  2947. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2948. * Must be called at end of methods addline or updateline.
  2949. *
  2950. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2951. * @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
  2952. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2953. * @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.
  2954. * @return int <0 if KO, >0 if OK
  2955. */
  2956. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  2957. {
  2958. // phpcs:enable
  2959. global $conf, $hookmanager, $action;
  2960. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  2961. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2962. if ($reshook > 0) {
  2963. return 1; // replacement code
  2964. } elseif ($reshook < 0) {
  2965. return -1; // failure
  2966. } // reshook = 0 => execute normal code
  2967. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  2968. $MODULE = "";
  2969. if ($this->element == 'propal') {
  2970. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  2971. } elseif ($this->element == 'commande' || $this->element == 'order') {
  2972. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  2973. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  2974. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  2975. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier') {
  2976. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  2977. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  2978. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  2979. } elseif ($this->element == 'supplier_proposal') {
  2980. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  2981. }
  2982. if (!empty($MODULE)) {
  2983. if (!empty($conf->global->$MODULE)) {
  2984. $modsactivated = explode(',', $conf->global->$MODULE);
  2985. foreach ($modsactivated as $mod) {
  2986. if ($conf->$mod->enabled) {
  2987. return 1; // update was disabled by specific setup
  2988. }
  2989. }
  2990. }
  2991. }
  2992. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2993. if ($roundingadjust == '-1') {
  2994. $roundingadjust = 'auto'; // For backward compatibility
  2995. }
  2996. $forcedroundingmode = $roundingadjust;
  2997. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  2998. $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  2999. } elseif ($forcedroundingmode == 'auto') {
  3000. $forcedroundingmode = '0';
  3001. }
  3002. $error = 0;
  3003. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3004. // Define constants to find lines to sum
  3005. $fieldtva = 'total_tva';
  3006. $fieldlocaltax1 = 'total_localtax1';
  3007. $fieldlocaltax2 = 'total_localtax2';
  3008. $fieldup = 'subprice';
  3009. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3010. $fieldtva = 'tva';
  3011. $fieldup = 'pu_ht';
  3012. }
  3013. if ($this->element == 'expensereport') {
  3014. $fieldup = 'value_unit';
  3015. }
  3016. $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,';
  3017. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3018. if ($this->table_element_line == 'facturedet') {
  3019. $sql .= ', situation_percent';
  3020. }
  3021. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3022. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3023. $sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
  3024. if ($exclspec) {
  3025. $product_field = 'product_type';
  3026. if ($this->table_element_line == 'contratdet') {
  3027. $product_field = ''; // contratdet table has no product_type field
  3028. }
  3029. if ($product_field) {
  3030. $sql .= ' AND '.$product_field.' <> 9';
  3031. }
  3032. }
  3033. $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
  3034. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3035. $resql = $this->db->query($sql);
  3036. if ($resql) {
  3037. $this->total_ht = 0;
  3038. $this->total_tva = 0;
  3039. $this->total_localtax1 = 0;
  3040. $this->total_localtax2 = 0;
  3041. $this->total_ttc = 0;
  3042. $total_ht_by_vats = array();
  3043. $total_tva_by_vats = array();
  3044. $total_ttc_by_vats = array();
  3045. $this->multicurrency_total_ht = 0;
  3046. $this->multicurrency_total_tva = 0;
  3047. $this->multicurrency_total_ttc = 0;
  3048. $num = $this->db->num_rows($resql);
  3049. $i = 0;
  3050. while ($i < $num) {
  3051. $obj = $this->db->fetch_object($resql);
  3052. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3053. $parameters = array('fk_element' => $obj->rowid);
  3054. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3055. 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'
  3056. // This part of code is to fix data. We should not call it too often.
  3057. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3058. $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);
  3059. $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.
  3060. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3061. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
  3062. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3063. if ($diff_when_using_price_ht && $diff_on_current_total) {
  3064. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  3065. 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);
  3066. $resqlfix = $this->db->query($sqlfix);
  3067. if (!$resqlfix) {
  3068. dol_print_error($this->db, 'Failed to update line');
  3069. }
  3070. $obj->total_tva = $tmpcal[1];
  3071. $obj->total_ttc = $tmpcal[2];
  3072. }
  3073. }
  3074. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3075. $this->total_tva += $obj->total_tva;
  3076. $this->total_localtax1 += $obj->total_localtax1;
  3077. $this->total_localtax2 += $obj->total_localtax2;
  3078. $this->total_ttc += $obj->total_ttc;
  3079. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3080. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3081. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3082. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3083. $total_ht_by_vats[$obj->vatrate] = 0;
  3084. }
  3085. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3086. $total_tva_by_vats[$obj->vatrate] = 0;
  3087. }
  3088. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3089. $total_ttc_by_vats[$obj->vatrate] = 0;
  3090. }
  3091. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3092. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3093. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3094. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3095. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3096. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3097. //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";
  3098. if ($diff) {
  3099. if (abs($diff) > 0.1) {
  3100. $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.';
  3101. dol_syslog($errmsg, LOG_WARNING);
  3102. dol_print_error('', $errmsg);
  3103. exit;
  3104. }
  3105. $sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid;
  3106. 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);
  3107. $resqlfix = $this->db->query($sqlfix);
  3108. if (!$resqlfix) {
  3109. dol_print_error($this->db, 'Failed to update line');
  3110. }
  3111. $this->total_tva -= $diff;
  3112. $this->total_ttc -= $diff;
  3113. $total_tva_by_vats[$obj->vatrate] -= $diff;
  3114. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  3115. }
  3116. }
  3117. $i++;
  3118. }
  3119. // Add revenue stamp to total
  3120. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3121. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3122. // Situations totals
  3123. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3124. $prev_sits = $this->get_prev_sits();
  3125. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3126. $this->total_ht -= $sit->total_ht;
  3127. $this->total_tva -= $sit->total_tva;
  3128. $this->total_localtax1 -= $sit->total_localtax1;
  3129. $this->total_localtax2 -= $sit->total_localtax2;
  3130. $this->total_ttc -= $sit->total_ttc;
  3131. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3132. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3133. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3134. }
  3135. }
  3136. $this->db->free($resql);
  3137. // Now update global field total_ht, total_ttc and tva
  3138. $fieldht = 'total_ht';
  3139. $fieldtva = 'tva';
  3140. $fieldlocaltax1 = 'localtax1';
  3141. $fieldlocaltax2 = 'localtax2';
  3142. $fieldttc = 'total_ttc';
  3143. // Specific code for backward compatibility with old field names
  3144. if ($this->element == 'facture' || $this->element == 'facturerec') {
  3145. $fieldtva = 'total_tva';
  3146. }
  3147. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3148. $fieldtva = 'total_tva';
  3149. }
  3150. if ($this->element == 'propal') {
  3151. $fieldtva = 'total_tva';
  3152. }
  3153. if ($this->element == 'expensereport') {
  3154. $fieldtva = 'total_tva';
  3155. }
  3156. if ($this->element == 'supplier_proposal') {
  3157. $fieldtva = 'total_tva';
  3158. }
  3159. if ($this->element == 'commande') {
  3160. $fieldtva = 'total_tva';
  3161. }
  3162. if ($this->element == 'order_supplier') {
  3163. $fieldtva = 'total_tva';
  3164. }
  3165. if (empty($nodatabaseupdate)) {
  3166. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  3167. $sql .= " ".$fieldht." = ".price2num($this->total_ht).",";
  3168. $sql .= " ".$fieldtva." = ".price2num($this->total_tva).",";
  3169. $sql .= " ".$fieldlocaltax1." = ".price2num($this->total_localtax1).",";
  3170. $sql .= " ".$fieldlocaltax2." = ".price2num($this->total_localtax2).",";
  3171. $sql .= " ".$fieldttc." = ".price2num($this->total_ttc);
  3172. $sql .= ", multicurrency_total_ht = ".price2num($this->multicurrency_total_ht, 'MT', 1);
  3173. $sql .= ", multicurrency_total_tva = ".price2num($this->multicurrency_total_tva, 'MT', 1);
  3174. $sql .= ", multicurrency_total_ttc = ".price2num($this->multicurrency_total_ttc, 'MT', 1);
  3175. $sql .= ' WHERE rowid = '.$this->id;
  3176. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3177. $resql = $this->db->query($sql);
  3178. if (!$resql) {
  3179. $error++;
  3180. $this->error = $this->db->lasterror();
  3181. $this->errors[] = $this->db->lasterror();
  3182. }
  3183. }
  3184. if (!$error) {
  3185. return 1;
  3186. } else {
  3187. return -1;
  3188. }
  3189. } else {
  3190. dol_print_error($this->db, 'Bad request in update_price');
  3191. return -1;
  3192. }
  3193. }
  3194. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3195. /**
  3196. * Add objects linked in llx_element_element.
  3197. *
  3198. * @param string $origin Linked element type
  3199. * @param int $origin_id Linked element id
  3200. * @param User $f_user User that create
  3201. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3202. * @return int <=0 if KO, >0 if OK
  3203. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3204. */
  3205. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3206. {
  3207. // phpcs:enable
  3208. global $user;
  3209. $origin = (!empty($origin) ? $origin : $this->origin);
  3210. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3211. $f_user = isset($f_user) ? $f_user : $user;
  3212. // Special case
  3213. if ($origin == 'order') {
  3214. $origin = 'commande';
  3215. }
  3216. if ($origin == 'invoice') {
  3217. $origin = 'facture';
  3218. }
  3219. if ($origin == 'invoice_template') {
  3220. $origin = 'facturerec';
  3221. }
  3222. if ($origin == 'supplierorder') {
  3223. $origin = 'order_supplier';
  3224. }
  3225. $this->db->begin();
  3226. $error = 0;
  3227. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "element_element (";
  3228. $sql .= "fk_source";
  3229. $sql .= ", sourcetype";
  3230. $sql .= ", fk_target";
  3231. $sql .= ", targettype";
  3232. $sql .= ") VALUES (";
  3233. $sql .= $origin_id;
  3234. $sql .= ", '" . $this->db->escape($origin) . "'";
  3235. $sql .= ", " . $this->id;
  3236. $sql .= ", '" . $this->db->escape($this->element) . "'";
  3237. $sql .= ")";
  3238. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3239. if ($this->db->query($sql)) {
  3240. if (!$notrigger) {
  3241. // Call trigger
  3242. $this->context['link_origin'] = $origin;
  3243. $this->context['link_origin_id'] = $origin_id;
  3244. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3245. if ($result < 0) {
  3246. $error++;
  3247. }
  3248. // End call triggers
  3249. }
  3250. } else {
  3251. $this->error = $this->db->lasterror();
  3252. $error++;
  3253. }
  3254. if (!$error) {
  3255. $this->db->commit();
  3256. return 1;
  3257. } else {
  3258. $this->db->rollback();
  3259. return 0;
  3260. }
  3261. }
  3262. /**
  3263. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3264. * this->linkedObjectsIds array +
  3265. * this->linkedObjects array if $loadalsoobjects = 1
  3266. * Possible usage for parameters:
  3267. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3268. * - source id+type -> will get target list linked to source
  3269. * - target id+type -> will get source list linked to target
  3270. * - source id+type + target type -> will get target list of the type
  3271. * - target id+type + target source -> will get source list of the type
  3272. *
  3273. * @param int $sourceid Object source id (if not defined, id of object)
  3274. * @param string $sourcetype Object source type (if not defined, element name of object)
  3275. * @param int $targetid Object target id (if not defined, id of object)
  3276. * @param string $targettype Object target type (if not defined, elemennt name of object)
  3277. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3278. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3279. * @param string $orderby SQL 'ORDER BY' clause
  3280. * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances)
  3281. * @return int <0 if KO, >0 if OK
  3282. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3283. */
  3284. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3285. {
  3286. global $conf;
  3287. $this->linkedObjectsIds = array();
  3288. $this->linkedObjects = array();
  3289. $justsource = false;
  3290. $justtarget = false;
  3291. $withtargettype = false;
  3292. $withsourcetype = false;
  3293. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3294. $justsource = true; // the source (id and type) is a search criteria
  3295. if (!empty($targettype)) {
  3296. $withtargettype = true;
  3297. }
  3298. }
  3299. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3300. $justtarget = true; // the target (id and type) is a search criteria
  3301. if (!empty($sourcetype)) {
  3302. $withsourcetype = true;
  3303. }
  3304. }
  3305. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3306. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3307. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3308. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3309. /*if (empty($sourceid) && empty($targetid))
  3310. {
  3311. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3312. return -1;
  3313. }*/
  3314. // Links between objects are stored in table element_element
  3315. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  3316. $sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
  3317. $sql .= " WHERE ";
  3318. if ($justsource || $justtarget) {
  3319. if ($justsource) {
  3320. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3321. if ($withtargettype) {
  3322. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3323. }
  3324. } elseif ($justtarget) {
  3325. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3326. if ($withsourcetype) {
  3327. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3328. }
  3329. }
  3330. } else {
  3331. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3332. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3333. }
  3334. $sql .= ' ORDER BY '.$orderby;
  3335. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3336. $resql = $this->db->query($sql);
  3337. if ($resql) {
  3338. $num = $this->db->num_rows($resql);
  3339. $i = 0;
  3340. while ($i < $num) {
  3341. $obj = $this->db->fetch_object($resql);
  3342. if ($justsource || $justtarget) {
  3343. if ($justsource) {
  3344. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3345. } elseif ($justtarget) {
  3346. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3347. }
  3348. } else {
  3349. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3350. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3351. }
  3352. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3353. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3354. }
  3355. }
  3356. $i++;
  3357. }
  3358. if (!empty($this->linkedObjectsIds)) {
  3359. $tmparray = $this->linkedObjectsIds;
  3360. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3361. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3362. $module = $element = $subelement = $objecttype;
  3363. $regs = array();
  3364. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3365. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3366. $module = $element = $regs[1];
  3367. $subelement = $regs[2];
  3368. }
  3369. $classpath = $element.'/class';
  3370. // To work with non standard classpath or module name
  3371. if ($objecttype == 'facture') {
  3372. $classpath = 'compta/facture/class';
  3373. } elseif ($objecttype == 'facturerec') {
  3374. $classpath = 'compta/facture/class';
  3375. $module = 'facture';
  3376. } elseif ($objecttype == 'propal') {
  3377. $classpath = 'comm/propal/class';
  3378. } elseif ($objecttype == 'supplier_proposal') {
  3379. $classpath = 'supplier_proposal/class';
  3380. } elseif ($objecttype == 'shipping') {
  3381. $classpath = 'expedition/class';
  3382. $subelement = 'expedition';
  3383. $module = 'expedition_bon';
  3384. } elseif ($objecttype == 'delivery') {
  3385. $classpath = 'delivery/class';
  3386. $subelement = 'delivery';
  3387. $module = 'delivery_note';
  3388. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3389. $classpath = 'fourn/class';
  3390. $module = 'fournisseur';
  3391. } elseif ($objecttype == 'fichinter') {
  3392. $classpath = 'fichinter/class';
  3393. $subelement = 'fichinter';
  3394. $module = 'ficheinter';
  3395. } elseif ($objecttype == 'subscription') {
  3396. $classpath = 'adherents/class';
  3397. $module = 'adherent';
  3398. } elseif ($objecttype == 'contact') {
  3399. $module = 'societe';
  3400. }
  3401. // Set classfile
  3402. $classfile = strtolower($subelement);
  3403. $classname = ucfirst($subelement);
  3404. if ($objecttype == 'order') {
  3405. $classfile = 'commande';
  3406. $classname = 'Commande';
  3407. } elseif ($objecttype == 'invoice_supplier') {
  3408. $classfile = 'fournisseur.facture';
  3409. $classname = 'FactureFournisseur';
  3410. } elseif ($objecttype == 'order_supplier') {
  3411. $classfile = 'fournisseur.commande';
  3412. $classname = 'CommandeFournisseur';
  3413. } elseif ($objecttype == 'supplier_proposal') {
  3414. $classfile = 'supplier_proposal';
  3415. $classname = 'SupplierProposal';
  3416. } elseif ($objecttype == 'facturerec') {
  3417. $classfile = 'facture-rec';
  3418. $classname = 'FactureRec';
  3419. } elseif ($objecttype == 'subscription') {
  3420. $classfile = 'subscription';
  3421. $classname = 'Subscription';
  3422. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3423. $classpath = 'projet/class';
  3424. $classfile = 'project';
  3425. $classname = 'Project';
  3426. } elseif ($objecttype == 'conferenceorboothattendee') {
  3427. $classpath = 'eventorganization/class';
  3428. $classfile = 'conferenceorboothattendee';
  3429. $classname = 'ConferenceOrBoothAttendee';
  3430. $module = 'eventorganization';
  3431. }
  3432. // Here $module, $classfile and $classname are set
  3433. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
  3434. if ($loadalsoobjects) {
  3435. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3436. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3437. if (class_exists($classname)) {
  3438. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3439. $object = new $classname($this->db);
  3440. $ret = $object->fetch($objectid);
  3441. if ($ret >= 0) {
  3442. $this->linkedObjects[$objecttype][$i] = $object;
  3443. }
  3444. }
  3445. }
  3446. }
  3447. } else {
  3448. unset($this->linkedObjectsIds[$objecttype]);
  3449. }
  3450. }
  3451. }
  3452. return 1;
  3453. } else {
  3454. dol_print_error($this->db);
  3455. return -1;
  3456. }
  3457. }
  3458. /**
  3459. * Update object linked of a current object
  3460. *
  3461. * @param int $sourceid Object source id
  3462. * @param string $sourcetype Object source type
  3463. * @param int $targetid Object target id
  3464. * @param string $targettype Object target type
  3465. * @param User $f_user User that create
  3466. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3467. * @return int >0 if OK, <0 if KO
  3468. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3469. */
  3470. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3471. {
  3472. global $user;
  3473. $updatesource = false;
  3474. $updatetarget = false;
  3475. $f_user = isset($f_user) ? $f_user : $user;
  3476. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3477. $updatesource = true;
  3478. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3479. $updatetarget = true;
  3480. }
  3481. $this->db->begin();
  3482. $error = 0;
  3483. $sql = "UPDATE " . MAIN_DB_PREFIX . "element_element SET ";
  3484. if ($updatesource) {
  3485. $sql .= "fk_source = " . $sourceid;
  3486. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3487. $sql .= " WHERE fk_target = " . $this->id;
  3488. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3489. } elseif ($updatetarget) {
  3490. $sql .= "fk_target = " . $targetid;
  3491. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3492. $sql .= " WHERE fk_source = " . $this->id;
  3493. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3494. }
  3495. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3496. if ($this->db->query($sql)) {
  3497. if (!$notrigger) {
  3498. // Call trigger
  3499. $this->context['link_source_id'] = $sourceid;
  3500. $this->context['link_source_type'] = $sourcetype;
  3501. $this->context['link_target_id'] = $targetid;
  3502. $this->context['link_target_type'] = $targettype;
  3503. $result = $this->call_trigger('OBJECT_LINK_UPDATE', $f_user);
  3504. if ($result < 0) {
  3505. $error++;
  3506. }
  3507. // End call triggers
  3508. }
  3509. } else {
  3510. $this->error = $this->db->lasterror();
  3511. $error++;
  3512. }
  3513. if (!$error) {
  3514. $this->db->commit();
  3515. return 1;
  3516. } else {
  3517. $this->db->rollback();
  3518. return -1;
  3519. }
  3520. }
  3521. /**
  3522. * Delete all links between an object $this
  3523. *
  3524. * @param int $sourceid Object source id
  3525. * @param string $sourcetype Object source type
  3526. * @param int $targetid Object target id
  3527. * @param string $targettype Object target type
  3528. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3529. * @param User $f_user User that create
  3530. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3531. * @return int >0 if OK, <0 if KO
  3532. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3533. */
  3534. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3535. {
  3536. global $user;
  3537. $deletesource = false;
  3538. $deletetarget = false;
  3539. $f_user = isset($f_user) ? $f_user : $user;
  3540. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3541. $deletesource = true;
  3542. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3543. $deletetarget = true;
  3544. }
  3545. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3546. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3547. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3548. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3549. $this->db->begin();
  3550. $error = 0;
  3551. if (!$notrigger) {
  3552. // Call trigger
  3553. $this->context['link_id'] = $rowid;
  3554. $this->context['link_source_id'] = $sourceid;
  3555. $this->context['link_source_type'] = $sourcetype;
  3556. $this->context['link_target_id'] = $targetid;
  3557. $this->context['link_target_type'] = $targettype;
  3558. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3559. if ($result < 0) {
  3560. $error++;
  3561. }
  3562. // End call triggers
  3563. }
  3564. if (!$error) {
  3565. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "element_element";
  3566. $sql .= " WHERE";
  3567. if ($rowid > 0) {
  3568. $sql .= " rowid = " . ((int) $rowid);
  3569. } else {
  3570. if ($deletesource) {
  3571. $sql .= " fk_source = " . $sourceid . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3572. $sql .= " AND fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3573. } elseif ($deletetarget) {
  3574. $sql .= " fk_target = " . $targetid . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3575. $sql .= " AND fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3576. } else {
  3577. $sql .= " (fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3578. $sql .= " OR";
  3579. $sql .= " (fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3580. }
  3581. }
  3582. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3583. if (!$this->db->query($sql)) {
  3584. $this->error = $this->db->lasterror();
  3585. $this->errors[] = $this->error;
  3586. $error++;
  3587. }
  3588. }
  3589. if (!$error) {
  3590. $this->db->commit();
  3591. return 1;
  3592. } else {
  3593. $this->db->rollback();
  3594. return 0;
  3595. }
  3596. }
  3597. /**
  3598. * Function used to get an array with all items linked to an object id in association table
  3599. *
  3600. * @param int $fk_object_where id of object we need to get linked items
  3601. * @param string $field_select name of field we need to get a list
  3602. * @param string $field_where name of field of object we need to get linked items
  3603. * @param string $table_element name of association table
  3604. * @return array Array of record
  3605. */
  3606. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3607. {
  3608. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3609. return -1;
  3610. }
  3611. global $db;
  3612. $sql = 'SELECT '.$field_select.' FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.((int) $fk_object_where);
  3613. $resql = $db->query($sql);
  3614. $TRes = array();
  3615. if (!empty($resql)) {
  3616. while ($res = $db->fetch_object($resql)) {
  3617. $TRes[] = $res->{$field_select};
  3618. }
  3619. }
  3620. return $TRes;
  3621. }
  3622. /**
  3623. * Function used to remove all items linked to an object id in association table
  3624. *
  3625. * @param int $fk_object_where id of object we need to remove linked items
  3626. * @param string $field_where name of field of object we need to delete linked items
  3627. * @param string $table_element name of association table
  3628. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3629. */
  3630. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3631. {
  3632. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3633. return -1;
  3634. }
  3635. global $db;
  3636. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.((int) $fk_object_where);
  3637. $resql = $db->query($sql);
  3638. if (empty($resql)) {
  3639. return 0;
  3640. }
  3641. return 1;
  3642. }
  3643. /**
  3644. * Set status of an object
  3645. *
  3646. * @param int $status Status to set
  3647. * @param int $elementId Id of element to force (use this->id by default)
  3648. * @param string $elementType Type of element to force (use this->table_element by default)
  3649. * @param string $trigkey Trigger key to use for trigger
  3650. * @return int <0 if KO, >0 if OK
  3651. */
  3652. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '')
  3653. {
  3654. global $user, $langs, $conf;
  3655. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3656. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3657. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3658. $this->db->begin();
  3659. $fieldstatus = "fk_statut";
  3660. if ($elementTable == 'facture_rec') {
  3661. $fieldstatus = "suspended";
  3662. }
  3663. if ($elementTable == 'mailing') {
  3664. $fieldstatus = "statut";
  3665. }
  3666. if ($elementTable == 'cronjob') {
  3667. $fieldstatus = "status";
  3668. }
  3669. if ($elementTable == 'user') {
  3670. $fieldstatus = "statut";
  3671. }
  3672. if ($elementTable == 'expensereport') {
  3673. $fieldstatus = "fk_statut";
  3674. }
  3675. if ($elementTable == 'commande_fournisseur_dispatch') {
  3676. $fieldstatus = "status";
  3677. }
  3678. if (is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3679. $fieldstatus = 'status';
  3680. }
  3681. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  3682. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3683. // If status = 1 = validated, update also fk_user_valid
  3684. if ($status == 1 && $elementTable == 'expensereport') {
  3685. $sql .= ", fk_user_valid = ".$user->id;
  3686. }
  3687. $sql .= " WHERE rowid=".((int) $elementId);
  3688. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3689. if ($this->db->query($sql)) {
  3690. $error = 0;
  3691. // Try autoset of trigkey
  3692. if (empty($trigkey)) {
  3693. if ($this->element == 'supplier_proposal' && $status == 2) {
  3694. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3695. }
  3696. if ($this->element == 'supplier_proposal' && $status == 3) {
  3697. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3698. }
  3699. if ($this->element == 'supplier_proposal' && $status == 4) {
  3700. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3701. }
  3702. if ($this->element == 'fichinter' && $status == 3) {
  3703. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3704. }
  3705. if ($this->element == 'fichinter' && $status == 2) {
  3706. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3707. }
  3708. if ($this->element == 'fichinter' && $status == 1) {
  3709. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3710. }
  3711. }
  3712. if ($trigkey) {
  3713. // Call trigger
  3714. $result = $this->call_trigger($trigkey, $user);
  3715. if ($result < 0) {
  3716. $error++;
  3717. }
  3718. // End call triggers
  3719. }
  3720. if (!$error) {
  3721. $this->db->commit();
  3722. if (empty($savElementId)) { // If the element we update was $this (so $elementId is null)
  3723. $this->statut = $status;
  3724. $this->status = $status;
  3725. }
  3726. return 1;
  3727. } else {
  3728. $this->db->rollback();
  3729. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3730. return -1;
  3731. }
  3732. } else {
  3733. $this->error = $this->db->lasterror();
  3734. $this->db->rollback();
  3735. return -1;
  3736. }
  3737. }
  3738. /**
  3739. * Load type of canvas of an object if it exists
  3740. *
  3741. * @param int $id Record id
  3742. * @param string $ref Record ref
  3743. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3744. */
  3745. public function getCanvas($id = 0, $ref = '')
  3746. {
  3747. global $conf;
  3748. if (empty($id) && empty($ref)) {
  3749. return 0;
  3750. }
  3751. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  3752. return 0; // To increase speed. Not enabled by default.
  3753. }
  3754. // Clean parameters
  3755. $ref = trim($ref);
  3756. $sql = "SELECT rowid, canvas";
  3757. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3758. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  3759. if (!empty($id)) {
  3760. $sql .= " AND rowid = ".((int) $id);
  3761. }
  3762. if (!empty($ref)) {
  3763. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  3764. }
  3765. $resql = $this->db->query($sql);
  3766. if ($resql) {
  3767. $obj = $this->db->fetch_object($resql);
  3768. if ($obj) {
  3769. $this->canvas = $obj->canvas;
  3770. return 1;
  3771. } else {
  3772. return 0;
  3773. }
  3774. } else {
  3775. dol_print_error($this->db);
  3776. return -1;
  3777. }
  3778. }
  3779. /**
  3780. * Get special code of a line
  3781. *
  3782. * @param int $lineid Id of line
  3783. * @return int Special code
  3784. */
  3785. public function getSpecialCode($lineid)
  3786. {
  3787. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3788. $sql .= ' WHERE rowid = '.((int) $lineid);
  3789. $resql = $this->db->query($sql);
  3790. if ($resql) {
  3791. $row = $this->db->fetch_row($resql);
  3792. return $row[0];
  3793. }
  3794. }
  3795. /**
  3796. * Function to check if an object is used by others.
  3797. * Check is done into this->childtables. There is no check into llx_element_element.
  3798. *
  3799. * @param int $id Force id of object
  3800. * @return int <0 if KO, 0 if not used, >0 if already used
  3801. */
  3802. public function isObjectUsed($id = 0)
  3803. {
  3804. global $langs;
  3805. if (empty($id)) {
  3806. $id = $this->id;
  3807. }
  3808. // Check parameters
  3809. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  3810. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3811. return -1;
  3812. }
  3813. $arraytoscan = $this->childtables;
  3814. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3815. $tmparray = array_keys($this->childtables);
  3816. if (is_numeric($tmparray[0])) {
  3817. $arraytoscan = array_flip($this->childtables);
  3818. }
  3819. // Test if child exists
  3820. $haschild = 0;
  3821. foreach ($arraytoscan as $table => $elementname) {
  3822. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3823. // Check if third party can be deleted
  3824. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3825. $sql .= " WHERE ".$this->fk_element." = ".((int) $id);
  3826. $resql = $this->db->query($sql);
  3827. if ($resql) {
  3828. $obj = $this->db->fetch_object($resql);
  3829. if ($obj->nb > 0) {
  3830. $langs->load("errors");
  3831. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3832. $haschild += $obj->nb;
  3833. if (is_numeric($elementname)) { // old usage
  3834. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
  3835. } else // new usage: $elementname=Translation key
  3836. {
  3837. $this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
  3838. }
  3839. break; // We found at least one, we stop here
  3840. }
  3841. } else {
  3842. $this->errors[] = $this->db->lasterror();
  3843. return -1;
  3844. }
  3845. }
  3846. if ($haschild > 0) {
  3847. $this->errors[] = "ErrorRecordHasChildren";
  3848. return $haschild;
  3849. } else {
  3850. return 0;
  3851. }
  3852. }
  3853. /**
  3854. * Function to say how many lines object contains
  3855. *
  3856. * @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
  3857. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3858. */
  3859. public function hasProductsOrServices($predefined = -1)
  3860. {
  3861. $nb = 0;
  3862. foreach ($this->lines as $key => $val) {
  3863. $qualified = 0;
  3864. if ($predefined == -1) {
  3865. $qualified = 1;
  3866. }
  3867. if ($predefined == 1 && $val->fk_product > 0) {
  3868. $qualified = 1;
  3869. }
  3870. if ($predefined == 0 && $val->fk_product <= 0) {
  3871. $qualified = 1;
  3872. }
  3873. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  3874. $qualified = 1;
  3875. }
  3876. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  3877. $qualified = 1;
  3878. }
  3879. if ($qualified) {
  3880. $nb++;
  3881. }
  3882. }
  3883. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3884. return $nb;
  3885. }
  3886. /**
  3887. * Function that returns the total amount HT of discounts applied for all lines.
  3888. *
  3889. * @return float|string Total amout of discount
  3890. */
  3891. public function getTotalDiscount()
  3892. {
  3893. if (!empty($this->table_element_line) ) {
  3894. $total_discount = 0.00;
  3895. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3896. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  3897. $sql .= " WHERE ".$this->fk_element." = ".$this->id;
  3898. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3899. $resql = $this->db->query($sql);
  3900. if ($resql) {
  3901. $num = $this->db->num_rows($resql);
  3902. $i = 0;
  3903. while ($i < $num) {
  3904. $obj = $this->db->fetch_object($resql);
  3905. $pu_ht = $obj->pu_ht;
  3906. $qty = $obj->qty;
  3907. $total_ht = $obj->total_ht;
  3908. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3909. $total_discount += $total_discount_line;
  3910. $i++;
  3911. }
  3912. }
  3913. //print $total_discount; exit;
  3914. return price2num($total_discount);
  3915. }
  3916. return null;
  3917. }
  3918. /**
  3919. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3920. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3921. *
  3922. * @return array array('weight'=>...,'volume'=>...)
  3923. */
  3924. public function getTotalWeightVolume()
  3925. {
  3926. $totalWeight = 0;
  3927. $totalVolume = 0;
  3928. // defined for shipment only
  3929. $totalOrdered = '';
  3930. // defined for shipment only
  3931. $totalToShip = '';
  3932. foreach ($this->lines as $line) {
  3933. if (isset($line->qty_asked)) {
  3934. if (empty($totalOrdered)) {
  3935. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  3936. }
  3937. $totalOrdered += $line->qty_asked; // defined for shipment only
  3938. }
  3939. if (isset($line->qty_shipped)) {
  3940. if (empty($totalToShip)) {
  3941. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  3942. }
  3943. $totalToShip += $line->qty_shipped; // defined for shipment only
  3944. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  3945. if (empty($totalToShip)) {
  3946. $totalToShip = 0;
  3947. }
  3948. $totalToShip += $line->qty; // defined for reception only
  3949. }
  3950. // Define qty, weight, volume, weight_units, volume_units
  3951. if ($this->element == 'shipping') {
  3952. // for shipments
  3953. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  3954. } else {
  3955. $qty = $line->qty ? $line->qty : 0;
  3956. }
  3957. $weight = $line->weight ? $line->weight : 0;
  3958. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  3959. $volume = $line->volume ? $line->volume : 0;
  3960. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  3961. $weight_units = $line->weight_units;
  3962. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  3963. $volume_units = $line->volume_units;
  3964. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  3965. $weightUnit = 0;
  3966. $volumeUnit = 0;
  3967. if (!empty($weight_units)) {
  3968. $weightUnit = $weight_units;
  3969. }
  3970. if (!empty($volume_units)) {
  3971. $volumeUnit = $volume_units;
  3972. }
  3973. if (empty($totalWeight)) {
  3974. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  3975. }
  3976. if (empty($totalVolume)) {
  3977. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  3978. }
  3979. //var_dump($line->volume_units);
  3980. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3981. $trueWeightUnit = pow(10, $weightUnit);
  3982. $totalWeight += $weight * $qty * $trueWeightUnit;
  3983. } else {
  3984. if ($weight_units == 99) {
  3985. // conversion 1 Pound = 0.45359237 KG
  3986. $trueWeightUnit = 0.45359237;
  3987. $totalWeight += $weight * $qty * $trueWeightUnit;
  3988. } elseif ($weight_units == 98) {
  3989. // conversion 1 Ounce = 0.0283495 KG
  3990. $trueWeightUnit = 0.0283495;
  3991. $totalWeight += $weight * $qty * $trueWeightUnit;
  3992. } else {
  3993. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  3994. }
  3995. }
  3996. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3997. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  3998. $trueVolumeUnit = pow(10, $volumeUnit);
  3999. //print $line->volume;
  4000. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4001. } else {
  4002. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4003. }
  4004. }
  4005. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4006. }
  4007. /**
  4008. * Set extra parameters
  4009. *
  4010. * @return int <0 if KO, >0 if OK
  4011. */
  4012. public function setExtraParameters()
  4013. {
  4014. $this->db->begin();
  4015. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4016. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  4017. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4018. $sql .= " WHERE rowid = ".$this->id;
  4019. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4020. $resql = $this->db->query($sql);
  4021. if (!$resql) {
  4022. $this->error = $this->db->lasterror();
  4023. $this->db->rollback();
  4024. return -1;
  4025. } else {
  4026. $this->db->commit();
  4027. return 1;
  4028. }
  4029. }
  4030. // --------------------
  4031. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4032. // --------------------
  4033. /* This is to show add lines */
  4034. /**
  4035. * Show add free and predefined products/services form
  4036. *
  4037. * @param int $dateSelector 1=Show also date range input fields
  4038. * @param Societe $seller Object thirdparty who sell
  4039. * @param Societe $buyer Object thirdparty who buy
  4040. * @param string $defaulttpldir Directory where to find the template
  4041. * @return void
  4042. */
  4043. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4044. {
  4045. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4046. global $form;
  4047. // Line extrafield
  4048. if (!is_object($extrafields)) {
  4049. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4050. $extrafields = new ExtraFields($this->db);
  4051. }
  4052. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4053. // Output template part (modules that overwrite templates must declare this into descriptor)
  4054. // Use global variables + $dateSelector + $seller and $buyer
  4055. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4056. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4057. foreach ($dirtpls as $module => $reldir) {
  4058. if (!empty($module)) {
  4059. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4060. } else {
  4061. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4062. }
  4063. if (empty($conf->file->strict_mode)) {
  4064. $res = @include $tpl;
  4065. } else {
  4066. $res = include $tpl; // for debug
  4067. }
  4068. if ($res) {
  4069. break;
  4070. }
  4071. }
  4072. }
  4073. /* This is to show array of line of details */
  4074. /**
  4075. * Return HTML table for object lines
  4076. * TODO Move this into an output class file (htmlline.class.php)
  4077. * If lines are into a template, title must also be into a template
  4078. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4079. *
  4080. * @param string $action Action code
  4081. * @param string $seller Object of seller third party
  4082. * @param string $buyer Object of buyer third party
  4083. * @param int $selected Object line selected
  4084. * @param int $dateSelector 1=Show also date range input fields
  4085. * @param string $defaulttpldir Directory where to find the template
  4086. * @return void
  4087. */
  4088. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4089. {
  4090. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4091. // TODO We should not use global var for this
  4092. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4093. // Define usemargins
  4094. $usemargins = 0;
  4095. if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4096. $usemargins = 1;
  4097. }
  4098. $num = count($this->lines);
  4099. // Line extrafield
  4100. if (!is_object($extrafields)) {
  4101. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4102. $extrafields = new ExtraFields($this->db);
  4103. }
  4104. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4105. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4106. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4107. if (empty($reshook)) {
  4108. // Output template part (modules that overwrite templates must declare this into descriptor)
  4109. // Use global variables + $dateSelector + $seller and $buyer
  4110. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4111. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4112. foreach ($dirtpls as $module => $reldir) {
  4113. if (!empty($module)) {
  4114. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4115. } else {
  4116. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4117. }
  4118. if (empty($conf->file->strict_mode)) {
  4119. $res = @include $tpl;
  4120. } else {
  4121. $res = include $tpl; // for debug
  4122. }
  4123. if ($res) {
  4124. break;
  4125. }
  4126. }
  4127. }
  4128. $i = 0;
  4129. print "<!-- begin printObjectLines() --><tbody>\n";
  4130. foreach ($this->lines as $line) {
  4131. //Line extrafield
  4132. $line->fetch_optionals();
  4133. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  4134. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4135. if (empty($line->fk_parent_line)) {
  4136. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4137. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4138. } else {
  4139. $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);
  4140. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4141. }
  4142. }
  4143. if (empty($reshook)) {
  4144. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4145. }
  4146. $i++;
  4147. }
  4148. print "</tbody><!-- end printObjectLines() -->\n";
  4149. }
  4150. /**
  4151. * Return HTML content of a detail line
  4152. * TODO Move this into an output class file (htmlline.class.php)
  4153. *
  4154. * @param string $action GET/POST action
  4155. * @param CommonObjectLine $line Selected object line to output
  4156. * @param string $var Is it a an odd line (true)
  4157. * @param int $num Number of line (0)
  4158. * @param int $i I
  4159. * @param int $dateSelector 1=Show also date range input fields
  4160. * @param string $seller Object of seller third party
  4161. * @param string $buyer Object of buyer third party
  4162. * @param int $selected Object line selected
  4163. * @param Extrafields $extrafields Object of extrafields
  4164. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4165. * @return void
  4166. */
  4167. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4168. {
  4169. global $conf, $langs, $user, $object, $hookmanager;
  4170. global $form;
  4171. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4172. $object_rights = $this->getRights();
  4173. $element = $this->element;
  4174. $text = '';
  4175. $description = '';
  4176. // Line in view mode
  4177. if ($action != 'editline' || $selected != $line->id) {
  4178. // Product
  4179. if ($line->fk_product > 0) {
  4180. $product_static = new Product($this->db);
  4181. $product_static->fetch($line->fk_product);
  4182. $product_static->ref = $line->ref; //can change ref in hook
  4183. $product_static->label = $line->label; //can change label in hook
  4184. $text = $product_static->getNomUrl(1);
  4185. // Define output language and label
  4186. if (!empty($conf->global->MAIN_MULTILANGS)) {
  4187. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4188. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4189. return;
  4190. }
  4191. $prod = new Product($this->db);
  4192. $prod->fetch($line->fk_product);
  4193. $outputlangs = $langs;
  4194. $newlang = '';
  4195. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4196. $newlang = GETPOST('lang_id', 'aZ09');
  4197. }
  4198. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4199. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4200. }
  4201. if (!empty($newlang)) {
  4202. $outputlangs = new Translate("", $conf);
  4203. $outputlangs->setDefaultLang($newlang);
  4204. }
  4205. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4206. } else {
  4207. $label = $line->product_label;
  4208. }
  4209. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4210. $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.
  4211. }
  4212. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4213. // Output template part (modules that overwrite templates must declare this into descriptor)
  4214. // Use global variables + $dateSelector + $seller and $buyer
  4215. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4216. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4217. foreach ($dirtpls as $module => $reldir) {
  4218. if (!empty($module)) {
  4219. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4220. } else {
  4221. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4222. }
  4223. if (empty($conf->file->strict_mode)) {
  4224. $res = @include $tpl;
  4225. } else {
  4226. $res = include $tpl; // for debug
  4227. }
  4228. if ($res) {
  4229. break;
  4230. }
  4231. }
  4232. }
  4233. // Line in update mode
  4234. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4235. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4236. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4237. // Output template part (modules that overwrite templates must declare this into descriptor)
  4238. // Use global variables + $dateSelector + $seller and $buyer
  4239. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4240. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4241. foreach ($dirtpls as $module => $reldir) {
  4242. if (!empty($module)) {
  4243. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4244. } else {
  4245. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4246. }
  4247. if (empty($conf->file->strict_mode)) {
  4248. $res = @include $tpl;
  4249. } else {
  4250. $res = include $tpl; // for debug
  4251. }
  4252. if ($res) {
  4253. break;
  4254. }
  4255. }
  4256. }
  4257. }
  4258. /* This is to show array of line of details of source object */
  4259. /**
  4260. * Return HTML table table of source object lines
  4261. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4262. * If lines are into a template, title must also be into a template
  4263. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4264. *
  4265. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4266. * @param array $selectedLines Array of lines id for selected lines
  4267. * @return void
  4268. */
  4269. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4270. {
  4271. global $langs, $hookmanager, $conf, $form;
  4272. print '<tr class="liste_titre">';
  4273. print '<td>'.$langs->trans('Ref').'</td>';
  4274. print '<td>'.$langs->trans('Description').'</td>';
  4275. print '<td class="right">'.$langs->trans('VATRate').'</td>';
  4276. print '<td class="right">'.$langs->trans('PriceUHT').'</td>';
  4277. if (!empty($conf->multicurrency->enabled)) {
  4278. print '<td class="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4279. }
  4280. print '<td class="right">'.$langs->trans('Qty').'</td>';
  4281. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4282. print '<td class="left">'.$langs->trans('Unit').'</td>';
  4283. }
  4284. print '<td class="right">'.$langs->trans('ReductionShort').'</td>';
  4285. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4286. print '</tr>';
  4287. $i = 0;
  4288. if (!empty($this->lines)) {
  4289. foreach ($this->lines as $line) {
  4290. if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4291. if (empty($line->fk_parent_line)) {
  4292. $parameters = array('line'=>$line, 'i'=>$i);
  4293. $action = '';
  4294. $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4295. }
  4296. } else {
  4297. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4298. }
  4299. $i++;
  4300. }
  4301. }
  4302. }
  4303. /**
  4304. * Return HTML with a line of table array of source object lines
  4305. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4306. * If lines are into a template, title must also be into a template
  4307. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4308. *
  4309. * @param CommonObjectLine $line Line
  4310. * @param string $var Var
  4311. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4312. * @param string $defaulttpldir Directory where to find the template
  4313. * @param array $selectedLines Array of lines id for selected lines
  4314. * @return void
  4315. */
  4316. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4317. {
  4318. global $langs, $conf;
  4319. //var_dump($line);
  4320. if (!empty($line->date_start)) {
  4321. $date_start = $line->date_start;
  4322. } else {
  4323. $date_start = $line->date_debut_prevue;
  4324. if ($line->date_debut_reel) {
  4325. $date_start = $line->date_debut_reel;
  4326. }
  4327. }
  4328. if (!empty($line->date_end)) {
  4329. $date_end = $line->date_end;
  4330. } else {
  4331. $date_end = $line->date_fin_prevue;
  4332. if ($line->date_fin_reel) {
  4333. $date_end = $line->date_fin_reel;
  4334. }
  4335. }
  4336. $this->tpl['id'] = $line->id;
  4337. $this->tpl['label'] = '';
  4338. if (!empty($line->fk_parent_line)) {
  4339. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4340. }
  4341. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4342. $discount = new DiscountAbsolute($this->db);
  4343. $discount->fk_soc = $this->socid;
  4344. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4345. } elseif (!empty($line->fk_product)) {
  4346. $productstatic = new Product($this->db);
  4347. $productstatic->id = $line->fk_product;
  4348. $productstatic->ref = $line->ref;
  4349. $productstatic->type = $line->fk_product_type;
  4350. if (empty($productstatic->ref)) {
  4351. $line->fetch_product();
  4352. $productstatic = $line->product;
  4353. }
  4354. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4355. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4356. // Dates
  4357. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4358. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4359. }
  4360. } else {
  4361. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4362. if (!empty($line->desc)) {
  4363. $this->tpl['label'] .= $line->desc;
  4364. } else {
  4365. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4366. }
  4367. // Dates
  4368. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4369. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4370. }
  4371. }
  4372. if (!empty($line->desc)) {
  4373. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4374. $discount = new DiscountAbsolute($this->db);
  4375. $discount->fetch($line->fk_remise_except);
  4376. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4377. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4378. $discount = new DiscountAbsolute($this->db);
  4379. $discount->fetch($line->fk_remise_except);
  4380. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4381. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4382. $discount = new DiscountAbsolute($this->db);
  4383. $discount->fetch($line->fk_remise_except);
  4384. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4385. } elseif ($line->desc == '(EXCESS PAID)') {
  4386. $discount = new DiscountAbsolute($this->db);
  4387. $discount->fetch($line->fk_remise_except);
  4388. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4389. } else {
  4390. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4391. }
  4392. } else {
  4393. $this->tpl['description'] = '&nbsp;';
  4394. }
  4395. // VAT Rate
  4396. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4397. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4398. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4399. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4400. }
  4401. $this->tpl['price'] = price($line->subprice);
  4402. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4403. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4404. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4405. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4406. }
  4407. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4408. // Is the line strike or not
  4409. $this->tpl['strike'] = 0;
  4410. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4411. $this->tpl['strike'] = 1;
  4412. }
  4413. // Output template part (modules that overwrite templates must declare this into descriptor)
  4414. // Use global variables + $dateSelector + $seller and $buyer
  4415. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4416. foreach ($dirtpls as $module => $reldir) {
  4417. if (!empty($module)) {
  4418. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4419. } else {
  4420. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4421. }
  4422. if (empty($conf->file->strict_mode)) {
  4423. $res = @include $tpl;
  4424. } else {
  4425. $res = include $tpl; // for debug
  4426. }
  4427. if ($res) {
  4428. break;
  4429. }
  4430. }
  4431. }
  4432. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4433. /**
  4434. * Add resources to the current object : add entry into llx_element_resources
  4435. * Need $this->element & $this->id
  4436. *
  4437. * @param int $resource_id Resource id
  4438. * @param string $resource_type 'resource'
  4439. * @param int $busy Busy or not
  4440. * @param int $mandatory Mandatory or not
  4441. * @return int <=0 if KO, >0 if OK
  4442. */
  4443. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4444. {
  4445. // phpcs:enable
  4446. $this->db->begin();
  4447. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  4448. $sql .= "resource_id";
  4449. $sql .= ", resource_type";
  4450. $sql .= ", element_id";
  4451. $sql .= ", element_type";
  4452. $sql .= ", busy";
  4453. $sql .= ", mandatory";
  4454. $sql .= ") VALUES (";
  4455. $sql .= $resource_id;
  4456. $sql .= ", '".$this->db->escape($resource_type)."'";
  4457. $sql .= ", '".$this->db->escape($this->id)."'";
  4458. $sql .= ", '".$this->db->escape($this->element)."'";
  4459. $sql .= ", '".$this->db->escape($busy)."'";
  4460. $sql .= ", '".$this->db->escape($mandatory)."'";
  4461. $sql .= ")";
  4462. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4463. if ($this->db->query($sql)) {
  4464. $this->db->commit();
  4465. return 1;
  4466. } else {
  4467. $this->error = $this->db->lasterror();
  4468. $this->db->rollback();
  4469. return 0;
  4470. }
  4471. }
  4472. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4473. /**
  4474. * Delete a link to resource line
  4475. *
  4476. * @param int $rowid Id of resource line to delete
  4477. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4478. * @param int $notrigger Disable all triggers
  4479. * @return int >0 if OK, <0 if KO
  4480. */
  4481. public function delete_resource($rowid, $element, $notrigger = 0)
  4482. {
  4483. // phpcs:enable
  4484. global $user;
  4485. $this->db->begin();
  4486. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  4487. $sql .= " WHERE rowid = ".((int) $rowid);
  4488. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4489. $resql = $this->db->query($sql);
  4490. if (!$resql) {
  4491. $this->error = $this->db->lasterror();
  4492. $this->db->rollback();
  4493. return -1;
  4494. } else {
  4495. if (!$notrigger) {
  4496. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4497. if ($result < 0) {
  4498. $this->db->rollback();
  4499. return -1;
  4500. }
  4501. }
  4502. $this->db->commit();
  4503. return 1;
  4504. }
  4505. }
  4506. /**
  4507. * Overwrite magic function to solve problem of cloning object that are kept as references
  4508. *
  4509. * @return void
  4510. */
  4511. public function __clone()
  4512. {
  4513. // Force a copy of this->lines, otherwise it will point to same object.
  4514. if (isset($this->lines) && is_array($this->lines)) {
  4515. $nboflines = count($this->lines);
  4516. for ($i = 0; $i < $nboflines; $i++) {
  4517. $this->lines[$i] = clone $this->lines[$i];
  4518. }
  4519. }
  4520. }
  4521. /**
  4522. * Common function for all objects extending CommonObject for generating documents
  4523. *
  4524. * @param string $modelspath Relative folder where generators are placed
  4525. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4526. * @param Translate $outputlangs Output language to use
  4527. * @param int $hidedetails 1 to hide details. 0 by default
  4528. * @param int $hidedesc 1 to hide product description. 0 by default
  4529. * @param int $hideref 1 to hide product reference. 0 by default
  4530. * @param null|array $moreparams Array to provide more information
  4531. * @return int >0 if OK, <0 if KO
  4532. * @see addFileIntoDatabaseIndex()
  4533. */
  4534. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4535. {
  4536. global $conf, $langs, $user, $hookmanager, $action;
  4537. $srctemplatepath = '';
  4538. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4539. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4540. if (empty($reshook)) {
  4541. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4542. if (empty($modele)) {
  4543. $this->error = 'BadValueForParameterModele';
  4544. return -1;
  4545. }
  4546. // Increase limit for PDF build
  4547. $err = error_reporting();
  4548. error_reporting(0);
  4549. @set_time_limit(120);
  4550. error_reporting($err);
  4551. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4552. $tmp = explode(':', $modele, 2);
  4553. if (!empty($tmp[1])) {
  4554. $modele = $tmp[0];
  4555. $srctemplatepath = $tmp[1];
  4556. }
  4557. // Search template files
  4558. $file = '';
  4559. $classname = '';
  4560. $filefound = '';
  4561. $dirmodels = array('/');
  4562. if (is_array($conf->modules_parts['models'])) {
  4563. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4564. }
  4565. foreach ($dirmodels as $reldir) {
  4566. foreach (array('doc', 'pdf') as $prefix) {
  4567. if (in_array(get_class($this), array('Adherent'))) {
  4568. // Member module use prefix_modele.class.php
  4569. $file = $prefix."_".$modele.".class.php";
  4570. } else {
  4571. // Other module use prefix_modele.modules.php
  4572. $file = $prefix."_".$modele.".modules.php";
  4573. }
  4574. // On verifie l'emplacement du modele
  4575. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4576. if (file_exists($file)) {
  4577. $filefound = $file;
  4578. $classname = $prefix.'_'.$modele;
  4579. break;
  4580. }
  4581. }
  4582. if ($filefound) {
  4583. break;
  4584. }
  4585. }
  4586. // If generator was found
  4587. if ($filefound) {
  4588. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4589. require_once $file;
  4590. $obj = new $classname($this->db);
  4591. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4592. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4593. $varfortemplatedir = $obj->scandir;
  4594. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4595. $dirtoscan = $conf->global->$varfortemplatedir;
  4596. $listoffiles = array();
  4597. // Now we add first model found in directories scanned
  4598. $listofdir = explode(',', $dirtoscan);
  4599. foreach ($listofdir as $key => $tmpdir) {
  4600. $tmpdir = trim($tmpdir);
  4601. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4602. if (!$tmpdir) {
  4603. unset($listofdir[$key]);
  4604. continue;
  4605. }
  4606. if (is_dir($tmpdir)) {
  4607. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4608. if (count($tmpfiles)) {
  4609. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4610. }
  4611. }
  4612. }
  4613. if (count($listoffiles)) {
  4614. foreach ($listoffiles as $record) {
  4615. $srctemplatepath = $record['fullname'];
  4616. break;
  4617. }
  4618. }
  4619. }
  4620. if (empty($srctemplatepath)) {
  4621. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4622. return -1;
  4623. }
  4624. }
  4625. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4626. if (!dol_is_file($srctemplatepath)) {
  4627. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4628. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4629. return -1;
  4630. }
  4631. }
  4632. // We save charset_output to restore it because write_file can change it if needed for
  4633. // output format that does not support UTF8.
  4634. $sav_charset_output = $outputlangs->charset_output;
  4635. if (in_array(get_class($this), array('Adherent'))) {
  4636. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  4637. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  4638. } else {
  4639. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4640. }
  4641. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4642. if ($resultwritefile > 0) {
  4643. $outputlangs->charset_output = $sav_charset_output;
  4644. // We delete old preview
  4645. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4646. dol_delete_preview($this);
  4647. // Index file in database
  4648. if (!empty($obj->result['fullpath'])) {
  4649. $destfull = $obj->result['fullpath'];
  4650. $upload_dir = dirname($destfull);
  4651. $destfile = basename($destfull);
  4652. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4653. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4654. $filename = basename($destfile);
  4655. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4656. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4657. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4658. $ecmfile = new EcmFiles($this->db);
  4659. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4660. // Set the public "share" key
  4661. $setsharekey = false;
  4662. if ($this->element == 'propal') {
  4663. $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
  4664. if ($useonlinesignature) {
  4665. $setsharekey = true;
  4666. }
  4667. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4668. $setsharekey = true;
  4669. }
  4670. }
  4671. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  4672. $setsharekey = true;
  4673. }
  4674. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  4675. $setsharekey = true;
  4676. }
  4677. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4678. $setsharekey = true;
  4679. }
  4680. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  4681. $setsharekey = true;
  4682. }
  4683. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  4684. $setsharekey = true;
  4685. }
  4686. if ($setsharekey) {
  4687. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  4688. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4689. $ecmfile->share = getRandomPassword(true);
  4690. }
  4691. }
  4692. if ($result > 0) {
  4693. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4694. $ecmfile->fullpath_orig = '';
  4695. $ecmfile->gen_or_uploaded = 'generated';
  4696. $ecmfile->description = ''; // indexed content
  4697. $ecmfile->keywords = ''; // keyword content
  4698. $result = $ecmfile->update($user);
  4699. if ($result < 0) {
  4700. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4701. }
  4702. } else {
  4703. $ecmfile->entity = $conf->entity;
  4704. $ecmfile->filepath = $rel_dir;
  4705. $ecmfile->filename = $filename;
  4706. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4707. $ecmfile->fullpath_orig = '';
  4708. $ecmfile->gen_or_uploaded = 'generated';
  4709. $ecmfile->description = ''; // indexed content
  4710. $ecmfile->keywords = ''; // keyword content
  4711. $ecmfile->src_object_type = $this->table_element;
  4712. $ecmfile->src_object_id = $this->id;
  4713. $result = $ecmfile->create($user);
  4714. if ($result < 0) {
  4715. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4716. }
  4717. }
  4718. /*$this->result['fullname']=$destfull;
  4719. $this->result['filepath']=$ecmfile->filepath;
  4720. $this->result['filename']=$ecmfile->filename;*/
  4721. //var_dump($obj->update_main_doc_field);exit;
  4722. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4723. $update_main_doc_field = 0;
  4724. if (!empty($obj->update_main_doc_field)) {
  4725. $update_main_doc_field = 1;
  4726. }
  4727. if ($update_main_doc_field && !empty($this->table_element)) {
  4728. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
  4729. $sql .= ' WHERE rowid = '.$this->id;
  4730. $resql = $this->db->query($sql);
  4731. if (!$resql) {
  4732. dol_print_error($this->db);
  4733. } else {
  4734. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  4735. }
  4736. }
  4737. }
  4738. } else {
  4739. 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);
  4740. }
  4741. // Success in building document. We build meta file.
  4742. dol_meta_create($this);
  4743. return 1;
  4744. } else {
  4745. $outputlangs->charset_output = $sav_charset_output;
  4746. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4747. return -1;
  4748. }
  4749. } else {
  4750. if (!$filefound) {
  4751. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4752. dol_print_error('', $this->error);
  4753. } else {
  4754. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4755. dol_print_error('', $this->error);
  4756. }
  4757. return -1;
  4758. }
  4759. } else {
  4760. return $reshook;
  4761. }
  4762. }
  4763. /**
  4764. * Build thumb
  4765. * @todo Move this into files.lib.php
  4766. *
  4767. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4768. * @return void
  4769. */
  4770. public function addThumbs($file)
  4771. {
  4772. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4773. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4774. $file_osencoded = dol_osencode($file);
  4775. if (file_exists($file_osencoded)) {
  4776. // Create small thumbs for company (Ratio is near 16/9)
  4777. // Used on logon for example
  4778. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4779. // Create mini thumbs for company (Ratio is near 16/9)
  4780. // Used on menu or for setup page for example
  4781. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4782. }
  4783. }
  4784. /* Functions common to commonobject and commonobjectline */
  4785. /* For default values */
  4786. /**
  4787. * Return the default value to use for a field when showing the create form of object.
  4788. * Return values in this order:
  4789. * 1) If parameter is available into POST, we return it first.
  4790. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4791. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4792. * 4) Return value found into database (TODO No yet implemented)
  4793. *
  4794. * @param string $fieldname Name of field
  4795. * @param string $alternatevalue Alternate value to use
  4796. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4797. **/
  4798. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  4799. {
  4800. global $conf, $_POST;
  4801. // If param here has been posted, we use this value first.
  4802. if (GETPOSTISSET($fieldname)) {
  4803. return GETPOST($fieldname, 'alphanohtml', 3);
  4804. }
  4805. if (isset($alternatevalue)) {
  4806. return $alternatevalue;
  4807. }
  4808. $newelement = $this->element;
  4809. if ($newelement == 'facture') {
  4810. $newelement = 'invoice';
  4811. }
  4812. if ($newelement == 'commande') {
  4813. $newelement = 'order';
  4814. }
  4815. if (empty($newelement)) {
  4816. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4817. return '';
  4818. }
  4819. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4820. //var_dump($keyforfieldname);
  4821. if (isset($conf->global->$keyforfieldname)) {
  4822. return $conf->global->$keyforfieldname;
  4823. }
  4824. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4825. }
  4826. /* For triggers */
  4827. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4828. /**
  4829. * Call trigger based on this instance.
  4830. * Some context information may also be provided into array property this->context.
  4831. * NB: Error from trigger are stacked in interface->errors
  4832. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4833. *
  4834. * @param string $triggerName trigger's name to execute
  4835. * @param User $user Object user
  4836. * @return int Result of run_triggers
  4837. */
  4838. public function call_trigger($triggerName, $user)
  4839. {
  4840. // phpcs:enable
  4841. global $langs, $conf;
  4842. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  4843. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4844. $langs = new Translate('', $conf);
  4845. }
  4846. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4847. $interface = new Interfaces($this->db);
  4848. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  4849. if ($result < 0) {
  4850. if (!empty($this->errors)) {
  4851. $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.
  4852. } else {
  4853. $this->errors = $interface->errors;
  4854. }
  4855. }
  4856. return $result;
  4857. }
  4858. /* Functions for data in other language */
  4859. /**
  4860. * Function to get alternative languages of a data into $this->array_languages
  4861. * This method is NOT called by method fetch of objects but must be called separately.
  4862. *
  4863. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  4864. * @see fetch_optionnals()
  4865. */
  4866. public function fetchValuesForExtraLanguages()
  4867. {
  4868. // To avoid SQL errors. Probably not the better solution though
  4869. if (!$this->element) {
  4870. return 0;
  4871. }
  4872. if (!($this->id > 0)) {
  4873. return 0;
  4874. }
  4875. if (is_array($this->array_languages)) {
  4876. return 1;
  4877. }
  4878. $this->array_languages = array();
  4879. $element = $this->element;
  4880. if ($element == 'categorie') {
  4881. $element = 'categories'; // For compatibility
  4882. }
  4883. // Request to get translation values for object
  4884. $sql = "SELECT rowid, property, lang , value";
  4885. $sql .= " FROM ".MAIN_DB_PREFIX."object_lang";
  4886. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  4887. $sql .= " AND fk_object = ".$this->id;
  4888. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4889. $resql = $this->db->query($sql);
  4890. if ($resql) {
  4891. $numrows = $this->db->num_rows($resql);
  4892. if ($numrows) {
  4893. $i = 0;
  4894. while ($i < $numrows) {
  4895. $obj = $this->db->fetch_object($resql);
  4896. $key = $obj->property;
  4897. $value = $obj->value;
  4898. $codelang = $obj->lang;
  4899. $type = $this->fields[$key]['type'];
  4900. // we can add this attribute to object
  4901. if (preg_match('/date/', $type)) {
  4902. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  4903. } else {
  4904. $this->array_languages[$key][$codelang] = $value;
  4905. }
  4906. $i++;
  4907. }
  4908. }
  4909. $this->db->free($resql);
  4910. if ($numrows) {
  4911. return $numrows;
  4912. } else {
  4913. return 0;
  4914. }
  4915. } else {
  4916. dol_print_error($this->db);
  4917. return -1;
  4918. }
  4919. }
  4920. /**
  4921. * Fill array_options property of object by extrafields value (using for data sent by forms)
  4922. *
  4923. * @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.
  4924. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  4925. */
  4926. public function setValuesForExtraLanguages($onlykey = '')
  4927. {
  4928. global $_POST, $langs;
  4929. // Get extra fields
  4930. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  4931. $tmparray = explode('-', $postfieldkey);
  4932. if ($tmparray[0] != 'field') {
  4933. continue;
  4934. }
  4935. $element = $tmparray[1];
  4936. $key = $tmparray[2];
  4937. $codelang = $tmparray[3];
  4938. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  4939. if (!empty($onlykey) && $key != $onlykey) {
  4940. continue;
  4941. }
  4942. if ($element != $this->element) {
  4943. continue;
  4944. }
  4945. $key_type = $this->fields[$key]['type'];
  4946. $enabled = 1;
  4947. if (isset($this->fields[$key]['enabled'])) {
  4948. $enabled = dol_eval($this->fields[$key]['enabled'], 1);
  4949. }
  4950. /*$perms = 1;
  4951. if (isset($this->fields[$key]['perms']))
  4952. {
  4953. $perms = dol_eval($this->fields[$key]['perms'], 1);
  4954. }*/
  4955. if (empty($enabled)) {
  4956. continue;
  4957. }
  4958. //if (empty($perms)) continue;
  4959. if (in_array($key_type, array('date'))) {
  4960. // Clean parameters
  4961. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4962. $value_key = dol_mktime(0, 0, 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4963. } elseif (in_array($key_type, array('datetime'))) {
  4964. // Clean parameters
  4965. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  4966. $value_key = dol_mktime($_POST[$postfieldkey."hour"], $_POST[$postfieldkey."min"], 0, $_POST[$postfieldkey."month"], $_POST[$postfieldkey."day"], $_POST[$postfieldkey."year"]);
  4967. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  4968. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  4969. if (!empty($value_arr)) {
  4970. $value_key = implode(',', $value_arr);
  4971. } else {
  4972. $value_key = '';
  4973. }
  4974. } elseif (in_array($key_type, array('price', 'double'))) {
  4975. $value_arr = GETPOST($postfieldkey, 'alpha');
  4976. $value_key = price2num($value_arr);
  4977. } else {
  4978. $value_key = GETPOST($postfieldkey);
  4979. if (in_array($key_type, array('link')) && $value_key == '-1') {
  4980. $value_key = '';
  4981. }
  4982. }
  4983. $this->array_languages[$key][$codelang] = $value_key;
  4984. /*if ($nofillrequired) {
  4985. $langs->load('errors');
  4986. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  4987. return -1;
  4988. }*/
  4989. }
  4990. return 1;
  4991. }
  4992. /* Functions for extrafields */
  4993. /**
  4994. * Function to make a fetch but set environment to avoid to load computed values before.
  4995. *
  4996. * @param int $id ID of object
  4997. * @return int >0 if OK, 0 if not found, <0 if KO
  4998. */
  4999. public function fetchNoCompute($id)
  5000. {
  5001. global $conf;
  5002. $savDisableCompute = $conf->disable_compute;
  5003. $conf->disable_compute = 1;
  5004. $ret = $this->fetch($id);
  5005. $conf->disable_compute = $savDisableCompute;
  5006. return $ret;
  5007. }
  5008. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5009. /**
  5010. * Function to get extra fields of an object into $this->array_options
  5011. * This method is in most cases called by method fetch of objects but you can call it separately.
  5012. *
  5013. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5014. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5015. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5016. * @see fetchValuesForExtraLanguages()
  5017. */
  5018. public function fetch_optionals($rowid = null, $optionsArray = null)
  5019. {
  5020. // phpcs:enable
  5021. global $conf, $extrafields;
  5022. if (empty($rowid)) {
  5023. $rowid = $this->id;
  5024. }
  5025. if (empty($rowid) && isset($this->rowid)) {
  5026. $rowid = $this->rowid; // deprecated
  5027. }
  5028. // To avoid SQL errors. Probably not the better solution though
  5029. if (!$this->table_element) {
  5030. return 0;
  5031. }
  5032. $this->array_options = array();
  5033. if (!is_array($optionsArray)) {
  5034. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5035. if (!isset($extrafields) || !is_object($extrafields)) {
  5036. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5037. $extrafields = new ExtraFields($this->db);
  5038. }
  5039. // Load array of extrafields for elementype = $this->table_element
  5040. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5041. $extrafields->fetch_name_optionals_label($this->table_element);
  5042. }
  5043. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5044. } else {
  5045. global $extrafields;
  5046. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5047. }
  5048. $table_element = $this->table_element;
  5049. if ($table_element == 'categorie') {
  5050. $table_element = 'categories'; // For compatibility
  5051. }
  5052. // Request to get complementary values
  5053. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5054. $sql = "SELECT rowid";
  5055. foreach ($optionsArray as $name => $label) {
  5056. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5057. $sql .= ", ".$name;
  5058. }
  5059. }
  5060. $sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  5061. $sql .= " WHERE fk_object = ".((int) $rowid);
  5062. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5063. $resql = $this->db->query($sql);
  5064. if ($resql) {
  5065. $numrows = $this->db->num_rows($resql);
  5066. if ($numrows) {
  5067. $tab = $this->db->fetch_array($resql);
  5068. foreach ($tab as $key => $value) {
  5069. // 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)
  5070. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5071. // we can add this attribute to object
  5072. if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5073. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5074. $this->array_options["options_".$key] = $this->db->jdate($value);
  5075. } else {
  5076. $this->array_options["options_".$key] = $value;
  5077. }
  5078. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5079. }
  5080. }
  5081. // If field is a computed field, value must become result of compute
  5082. foreach ($tab as $key => $value) {
  5083. if (!empty($extrafields) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5084. //var_dump($conf->disable_compute);
  5085. if (empty($conf->disable_compute)) {
  5086. $this->array_options["options_".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0);
  5087. }
  5088. }
  5089. }
  5090. }
  5091. $this->db->free($resql);
  5092. if ($numrows) {
  5093. return $numrows;
  5094. } else {
  5095. return 0;
  5096. }
  5097. } else {
  5098. $this->errors[]=$this->db->lasterror;
  5099. return -1;
  5100. }
  5101. }
  5102. return 0;
  5103. }
  5104. /**
  5105. * Delete all extra fields values for the current object.
  5106. *
  5107. * @return int <0 if KO, >0 if OK
  5108. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5109. */
  5110. public function deleteExtraFields()
  5111. {
  5112. global $conf;
  5113. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5114. return 0;
  5115. }
  5116. $this->db->begin();
  5117. $table_element = $this->table_element;
  5118. if ($table_element == 'categorie') {
  5119. $table_element = 'categories'; // For compatibility
  5120. }
  5121. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5122. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  5123. $resql = $this->db->query($sql_del);
  5124. if (!$resql) {
  5125. $this->error = $this->db->lasterror();
  5126. $this->db->rollback();
  5127. return -1;
  5128. } else {
  5129. $this->db->commit();
  5130. return 1;
  5131. }
  5132. }
  5133. /**
  5134. * Add/Update all extra fields values for the current object.
  5135. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5136. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5137. *
  5138. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5139. * @param User $userused Object user
  5140. * @return int -1=error, O=did nothing, 1=OK
  5141. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5142. */
  5143. public function insertExtraFields($trigger = '', $userused = null)
  5144. {
  5145. global $conf, $langs, $user;
  5146. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5147. return 0;
  5148. }
  5149. if (empty($userused)) {
  5150. $userused = $user;
  5151. }
  5152. $error = 0;
  5153. if (!empty($this->array_options)) {
  5154. // Check parameters
  5155. $langs->load('admin');
  5156. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5157. $extrafields = new ExtraFields($this->db);
  5158. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5159. // Eliminate copied source object extra fields that do not exist in target object
  5160. $new_array_options = array();
  5161. foreach ($this->array_options as $key => $value) {
  5162. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5163. $new_array_options[$key] = $value;
  5164. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5165. $new_array_options['options_'.$key] = $value;
  5166. }
  5167. }
  5168. foreach ($new_array_options as $key => $value) {
  5169. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5170. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5171. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5172. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5173. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5174. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5175. // Similar code than into insertExtraFields
  5176. if ($attributeRequired) {
  5177. $mandatorypb = false;
  5178. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5179. $mandatorypb = true;
  5180. }
  5181. if ($this->array_options[$key] === '') {
  5182. $mandatorypb = true;
  5183. }
  5184. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5185. $mandatorypb = true;
  5186. }
  5187. if ($mandatorypb) {
  5188. $langs->load("errors");
  5189. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5190. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5191. return -1;
  5192. }
  5193. }
  5194. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5195. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5196. if (!empty($attrfieldcomputed)) {
  5197. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5198. $value = dol_eval($attrfieldcomputed, 1, 0);
  5199. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5200. $new_array_options[$key] = $value;
  5201. } else {
  5202. $new_array_options[$key] = null;
  5203. }
  5204. }
  5205. switch ($attributeType) {
  5206. case 'int':
  5207. if (!is_numeric($value) && $value != '') {
  5208. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5209. return -1;
  5210. } elseif ($value == '') {
  5211. $new_array_options[$key] = null;
  5212. }
  5213. break;
  5214. case 'price':
  5215. case 'double':
  5216. $value = price2num($value);
  5217. if (!is_numeric($value) && $value != '') {
  5218. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5219. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5220. return -1;
  5221. } elseif ($value == '') {
  5222. $new_array_options[$key] = null;
  5223. }
  5224. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5225. $new_array_options[$key] = $value;
  5226. break;
  5227. /*case 'select': // Not required, we chosed value='0' for undefined values
  5228. if ($value=='-1')
  5229. {
  5230. $this->array_options[$key] = null;
  5231. }
  5232. break;*/
  5233. case 'password':
  5234. $algo = '';
  5235. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5236. // If there is an encryption choice, we use it to crypt data before insert
  5237. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5238. $algo = reset($tmparrays);
  5239. if ($algo != '') {
  5240. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5241. //var_dump($action);
  5242. //var_dump($this->oldcopy);exit;
  5243. 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
  5244. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5245. 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.
  5246. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5247. } else {
  5248. // var_dump($algo);
  5249. $newvalue = dol_hash($this->array_options[$key], $algo);
  5250. $new_array_options[$key] = $newvalue;
  5251. }
  5252. } else {
  5253. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5254. }
  5255. }
  5256. } else // Common usage
  5257. {
  5258. $new_array_options[$key] = $this->array_options[$key];
  5259. }
  5260. break;
  5261. case 'date':
  5262. case 'datetime':
  5263. // If data is a string instead of a timestamp, we convert it
  5264. if (!is_int($this->array_options[$key])) {
  5265. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5266. }
  5267. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5268. break;
  5269. case 'link':
  5270. $param_list = array_keys($attributeParam['options']);
  5271. // 0 : ObjectName
  5272. // 1 : classPath
  5273. $InfoFieldList = explode(":", $param_list[0]);
  5274. dol_include_once($InfoFieldList[1]);
  5275. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5276. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5277. $new_array_options[$key] = '';
  5278. } elseif ($value) {
  5279. $object = new $InfoFieldList[0]($this->db);
  5280. if (is_numeric($value)) {
  5281. $res = $object->fetch($value); // Common case
  5282. } else {
  5283. $res = $object->fetch('', $value); // For compatibility
  5284. }
  5285. if ($res > 0) {
  5286. $new_array_options[$key] = $object->id;
  5287. } else {
  5288. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5289. $this->db->rollback();
  5290. return -1;
  5291. }
  5292. }
  5293. } else {
  5294. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5295. }
  5296. break;
  5297. }
  5298. }
  5299. $this->db->begin();
  5300. $table_element = $this->table_element;
  5301. if ($table_element == 'categorie') {
  5302. $table_element = 'categories'; // For compatibility
  5303. }
  5304. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5305. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  5306. $this->db->query($sql_del);
  5307. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  5308. foreach ($new_array_options as $key => $value) {
  5309. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5310. // Add field of attribut
  5311. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5312. $sql .= ",".$attributeKey;
  5313. }
  5314. }
  5315. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5316. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5317. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5318. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5319. $sql .= ",".$tmpkey;
  5320. }
  5321. }
  5322. }
  5323. $sql .= ") VALUES (".$this->id;
  5324. foreach ($new_array_options as $key => $value) {
  5325. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5326. // Add field of attribute
  5327. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5328. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5329. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5330. } else {
  5331. $sql .= ",null";
  5332. }
  5333. }
  5334. }
  5335. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5336. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5337. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5338. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5339. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5340. $sql .= ", 0";
  5341. } else {
  5342. $sql .= ", ''";
  5343. }
  5344. }
  5345. }
  5346. }
  5347. $sql .= ")";
  5348. $resql = $this->db->query($sql);
  5349. if (!$resql) {
  5350. $this->error = $this->db->lasterror();
  5351. $error++;
  5352. }
  5353. if (!$error && $trigger) {
  5354. // Call trigger
  5355. $this->context = array('extrafieldaddupdate'=>1);
  5356. $result = $this->call_trigger($trigger, $userused);
  5357. if ($result < 0) {
  5358. $error++;
  5359. }
  5360. // End call trigger
  5361. }
  5362. if ($error) {
  5363. $this->db->rollback();
  5364. return -1;
  5365. } else {
  5366. $this->db->commit();
  5367. return 1;
  5368. }
  5369. } else {
  5370. return 0;
  5371. }
  5372. }
  5373. /**
  5374. * Add/Update all extra fields values for the current object.
  5375. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5376. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5377. *
  5378. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5379. * @param User $userused Object user
  5380. * @return int -1=error, O=did nothing, 1=OK
  5381. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5382. */
  5383. public function insertExtraLanguages($trigger = '', $userused = null)
  5384. {
  5385. global $conf, $langs, $user;
  5386. if (empty($userused)) {
  5387. $userused = $user;
  5388. }
  5389. $error = 0;
  5390. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5391. return 0; // For avoid conflicts if trigger used
  5392. }
  5393. if (is_array($this->array_languages)) {
  5394. $new_array_languages = $this->array_languages;
  5395. foreach ($new_array_languages as $key => $value) {
  5396. $attributeKey = $key;
  5397. $attributeType = $this->fields[$attributeKey]['type'];
  5398. $attributeLabel = $this->fields[$attributeKey]['label'];
  5399. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5400. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5401. switch ($attributeType) {
  5402. case 'int':
  5403. if (!is_numeric($value) && $value != '') {
  5404. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5405. return -1;
  5406. } elseif ($value == '') {
  5407. $new_array_languages[$key] = null;
  5408. }
  5409. break;
  5410. case 'double':
  5411. $value = price2num($value);
  5412. if (!is_numeric($value) && $value != '') {
  5413. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5414. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5415. return -1;
  5416. } elseif ($value == '') {
  5417. $new_array_languages[$key] = null;
  5418. }
  5419. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5420. $new_array_languages[$key] = $value;
  5421. break;
  5422. /*case 'select': // Not required, we chosed value='0' for undefined values
  5423. if ($value=='-1')
  5424. {
  5425. $this->array_options[$key] = null;
  5426. }
  5427. break;*/
  5428. }
  5429. }
  5430. $this->db->begin();
  5431. $table_element = $this->table_element;
  5432. if ($table_element == 'categorie') {
  5433. $table_element = 'categories'; // For compatibility
  5434. }
  5435. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5436. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5437. foreach ($langcodearray as $langcode => $value) {
  5438. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."object_lang";
  5439. $sql_del .= " WHERE fk_object = ".$this->id." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5440. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5441. $this->db->query($sql_del);
  5442. if ($value !== '') {
  5443. $sql = "INSERT INTO ".MAIN_DB_PREFIX."object_lang (fk_object, property, type_object, lang, value";
  5444. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5445. $sql .= ")";
  5446. $resql = $this->db->query($sql);
  5447. if (!$resql) {
  5448. $this->error = $this->db->lasterror();
  5449. $error++;
  5450. break;
  5451. }
  5452. }
  5453. }
  5454. }
  5455. if (!$error && $trigger) {
  5456. // Call trigger
  5457. $this->context = array('extralanguagesaddupdate'=>1);
  5458. $result = $this->call_trigger($trigger, $userused);
  5459. if ($result < 0) {
  5460. $error++;
  5461. }
  5462. // End call trigger
  5463. }
  5464. if ($error) {
  5465. $this->db->rollback();
  5466. return -1;
  5467. } else {
  5468. $this->db->commit();
  5469. return 1;
  5470. }
  5471. } else {
  5472. return 0;
  5473. }
  5474. }
  5475. /**
  5476. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5477. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5478. *
  5479. * @param string $key Key of the extrafield to update (without starting 'options_')
  5480. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5481. * @param User $userused Object user
  5482. * @return int -1=error, O=did nothing, 1=OK
  5483. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5484. */
  5485. public function updateExtraField($key, $trigger = null, $userused = null)
  5486. {
  5487. global $conf, $langs, $user;
  5488. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5489. return 0;
  5490. }
  5491. if (empty($userused)) {
  5492. $userused = $user;
  5493. }
  5494. $error = 0;
  5495. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5496. // Check parameters
  5497. $langs->load('admin');
  5498. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5499. $extrafields = new ExtraFields($this->db);
  5500. $extrafields->fetch_name_optionals_label($this->table_element);
  5501. $value = $this->array_options["options_".$key];
  5502. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5503. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5504. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5505. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5506. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5507. // Similar code than into insertExtraFields
  5508. if ($attributeRequired) {
  5509. $mandatorypb = false;
  5510. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5511. $mandatorypb = true;
  5512. }
  5513. if ($this->array_options["options_".$key] === '') {
  5514. $mandatorypb = true;
  5515. }
  5516. if ($mandatorypb) {
  5517. $langs->load("errors");
  5518. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5519. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5520. return -1;
  5521. }
  5522. }
  5523. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5524. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5525. if (!empty($attrfieldcomputed)) {
  5526. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5527. $value = dol_eval($attrfieldcomputed, 1, 0);
  5528. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5529. $this->array_options["options_".$key] = $value;
  5530. } else {
  5531. $this->array_options["options_".$key] = null;
  5532. }
  5533. }
  5534. switch ($attributeType) {
  5535. case 'int':
  5536. if (!is_numeric($value) && $value != '') {
  5537. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5538. return -1;
  5539. } elseif ($value === '') {
  5540. $this->array_options["options_".$key] = null;
  5541. }
  5542. break;
  5543. case 'double':
  5544. $value = price2num($value);
  5545. if (!is_numeric($value) && $value != '') {
  5546. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5547. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5548. return -1;
  5549. } elseif ($value === '') {
  5550. $this->array_options["options_".$key] = null;
  5551. }
  5552. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5553. $this->array_options["options_".$key] = $value;
  5554. break;
  5555. /*case 'select': // Not required, we chosed value='0' for undefined values
  5556. if ($value=='-1')
  5557. {
  5558. $this->array_options[$key] = null;
  5559. }
  5560. break;*/
  5561. case 'price':
  5562. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5563. break;
  5564. case 'date':
  5565. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5566. break;
  5567. case 'datetime':
  5568. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5569. break;
  5570. /*
  5571. case 'link':
  5572. $param_list = array_keys($attributeParam['options']);
  5573. // 0 : ObjectName
  5574. // 1 : classPath
  5575. $InfoFieldList = explode(":", $param_list[0]);
  5576. dol_include_once($InfoFieldList[1]);
  5577. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5578. {
  5579. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5580. {
  5581. $new_array_options[$key] = '';
  5582. } elseif ($value) {
  5583. $object = new $InfoFieldList[0]($this->db);
  5584. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5585. else $res = $object->fetch('', $value); // For compatibility
  5586. if ($res > 0) $new_array_options[$key] = $object->id;
  5587. else {
  5588. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5589. $this->db->rollback();
  5590. return -1;
  5591. }
  5592. }
  5593. } else {
  5594. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5595. }
  5596. break;
  5597. */
  5598. }
  5599. $this->db->begin();
  5600. $linealreadyfound = 0;
  5601. // 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)
  5602. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  5603. $resql = $this->db->query($sql);
  5604. if ($resql) {
  5605. $tmpobj = $this->db->fetch_object($resql);
  5606. if ($tmpobj) {
  5607. $linealreadyfound = $tmpobj->nb;
  5608. }
  5609. }
  5610. if ($linealreadyfound) {
  5611. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5612. $sql .= " WHERE fk_object = ".$this->id;
  5613. } else {
  5614. $result = $this->insertExtraFields('', $user);
  5615. if ($result < 0) {
  5616. $error++;
  5617. }
  5618. }
  5619. $resql = $this->db->query($sql);
  5620. if (!$resql) {
  5621. $error++;
  5622. $this->error = $this->db->lasterror();
  5623. }
  5624. if (!$error && $trigger) {
  5625. // Call trigger
  5626. $this->context = array('extrafieldupdate'=>1);
  5627. $result = $this->call_trigger($trigger, $userused);
  5628. if ($result < 0) {
  5629. $error++;
  5630. }
  5631. // End call trigger
  5632. }
  5633. if ($error) {
  5634. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5635. $this->db->rollback();
  5636. return -1;
  5637. } else {
  5638. $this->db->commit();
  5639. return 1;
  5640. }
  5641. } else {
  5642. return 0;
  5643. }
  5644. }
  5645. /**
  5646. * Update an extra language value for the current object.
  5647. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5648. *
  5649. * @param string $key Key of the extrafield (without starting 'options_')
  5650. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5651. * @param User $userused Object user
  5652. * @return int -1=error, O=did nothing, 1=OK
  5653. * @see updateExtraFields(), insertExtraLanguages()
  5654. */
  5655. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5656. {
  5657. global $conf, $langs, $user;
  5658. if (empty($userused)) {
  5659. $userused = $user;
  5660. }
  5661. $error = 0;
  5662. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5663. return 0; // For avoid conflicts if trigger used
  5664. }
  5665. return 0;
  5666. }
  5667. /**
  5668. * Return HTML string to put an input field into a page
  5669. * Code very similar with showInputField of extra fields
  5670. *
  5671. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  5672. * @param string $key Key of attribute
  5673. * @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)
  5674. * @param string $moreparam To add more parameters on html input tag
  5675. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5676. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5677. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  5678. * @param int $nonewbutton Force to not show the new button on field that are links to object
  5679. * @return string
  5680. */
  5681. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  5682. {
  5683. global $conf, $langs, $form;
  5684. if (!is_object($form)) {
  5685. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5686. $form = new Form($this->db);
  5687. }
  5688. if (!empty($this->fields)) {
  5689. $val = $this->fields[$key];
  5690. }
  5691. $out = '';
  5692. $type = '';
  5693. $isDependList=0;
  5694. $param = array();
  5695. $param['options'] = array();
  5696. $reg = array();
  5697. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  5698. // Because we work on extrafields
  5699. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5700. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5701. $type = 'link';
  5702. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5703. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5704. $type = 'link';
  5705. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  5706. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5707. $type = 'link';
  5708. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5709. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  5710. $type = 'sellist';
  5711. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  5712. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  5713. $type = 'sellist';
  5714. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  5715. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  5716. $type = 'sellist';
  5717. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  5718. $param['options'] = array();
  5719. $type = 'varchar';
  5720. $size = $reg[1];
  5721. } elseif (preg_match('/varchar/', $val['type'])) {
  5722. $param['options'] = array();
  5723. $type = 'varchar';
  5724. } else {
  5725. $param['options'] = array();
  5726. $type = $this->fields[$key]['type'];
  5727. }
  5728. // Special case that force options and type ($type can be integer, varchar, ...)
  5729. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  5730. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  5731. $type = 'select';
  5732. }
  5733. $label = $this->fields[$key]['label'];
  5734. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  5735. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  5736. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  5737. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  5738. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  5739. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  5740. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  5741. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  5742. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  5743. $objectid = $this->id;
  5744. if ($computed) {
  5745. if (!preg_match('/^search_/', $keyprefix)) {
  5746. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  5747. } else {
  5748. return '';
  5749. }
  5750. }
  5751. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  5752. if (empty($morecss) && !empty($val['css'])) {
  5753. $morecss = $val['css'];
  5754. } elseif (empty($morecss)) {
  5755. if ($type == 'date') {
  5756. $morecss = 'minwidth100imp';
  5757. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  5758. $morecss = 'minwidth200imp';
  5759. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5760. $morecss = 'maxwidth75';
  5761. } elseif ($type == 'url') {
  5762. $morecss = 'minwidth400';
  5763. } elseif ($type == 'boolean') {
  5764. $morecss = '';
  5765. } else {
  5766. if (round($size) < 12) {
  5767. $morecss = 'minwidth100';
  5768. } elseif (round($size) <= 48) {
  5769. $morecss = 'minwidth200';
  5770. } else {
  5771. $morecss = 'minwidth400';
  5772. }
  5773. }
  5774. }
  5775. if (in_array($type, array('date'))) {
  5776. $tmp = explode(',', $size);
  5777. $newsize = $tmp[0];
  5778. $showtime = 0;
  5779. // Do not show current date when field not required (see selectDate() method)
  5780. if (!$required && $value == '') {
  5781. $value = '-1';
  5782. }
  5783. // TODO Must also support $moreparam
  5784. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  5785. } elseif (in_array($type, array('datetime'))) {
  5786. $tmp = explode(',', $size);
  5787. $newsize = $tmp[0];
  5788. $showtime = 1;
  5789. // Do not show current date when field not required (see selectDate() method)
  5790. if (!$required && $value == '') $value = '-1';
  5791. // TODO Must also support $moreparam
  5792. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  5793. } elseif (in_array($type, array('duration'))) {
  5794. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  5795. } elseif (in_array($type, array('int', 'integer'))) {
  5796. $tmp = explode(',', $size);
  5797. $newsize = $tmp[0];
  5798. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5799. } elseif (in_array($type, array('real'))) {
  5800. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5801. } elseif (preg_match('/varchar/', $type)) {
  5802. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5803. } elseif (in_array($type, array('mail', 'phone', 'url'))) {
  5804. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  5805. } elseif (preg_match('/^text/', $type)) {
  5806. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5807. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5808. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  5809. $out = $doleditor->Create(1);
  5810. } else {
  5811. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5812. }
  5813. } elseif (preg_match('/^html/', $type)) {
  5814. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  5815. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  5816. $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%');
  5817. $out = $doleditor->Create(1);
  5818. } else {
  5819. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  5820. }
  5821. } elseif ($type == 'boolean') {
  5822. $checked = '';
  5823. if (!empty($value)) {
  5824. $checked = ' checked value="1" ';
  5825. } else {
  5826. $checked = ' value="1" ';
  5827. }
  5828. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  5829. } elseif ($type == 'price') {
  5830. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5831. $value = price($value);
  5832. }
  5833. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  5834. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  5835. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  5836. $value = price($value);
  5837. }
  5838. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  5839. } elseif ($type == 'select') {
  5840. $out = '';
  5841. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5842. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5843. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5844. }
  5845. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5846. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  5847. $out .= '<option value="0">&nbsp;</option>';
  5848. }
  5849. foreach ($param['options'] as $key => $val) {
  5850. if ((string) $key == '') {
  5851. continue;
  5852. }
  5853. list($val, $parent) = explode('|', $val);
  5854. $out .= '<option value="'.$key.'"';
  5855. $out .= (((string) $value == (string) $key) ? ' selected' : '');
  5856. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5857. $out .= '>'.$val.'</option>';
  5858. }
  5859. $out .= '</select>';
  5860. } elseif ($type == 'sellist') {
  5861. $out = '';
  5862. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  5863. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5864. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  5865. }
  5866. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  5867. if (is_array($param['options'])) {
  5868. $param_list = array_keys($param['options']);
  5869. $InfoFieldList = explode(":", $param_list[0]);
  5870. $parentName = '';
  5871. $parentField = '';
  5872. // 0 : tableName
  5873. // 1 : label field name
  5874. // 2 : key fields name (if differ of rowid)
  5875. // 3 : key field parent (for dependent lists)
  5876. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5877. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  5878. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  5879. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5880. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  5881. } else {
  5882. $keyList = $InfoFieldList[2].' as rowid';
  5883. }
  5884. }
  5885. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  5886. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  5887. $keyList .= ', '.$parentField;
  5888. }
  5889. $fields_label = explode('|', $InfoFieldList[1]);
  5890. if (is_array($fields_label)) {
  5891. $keyList .= ', ';
  5892. $keyList .= implode(', ', $fields_label);
  5893. }
  5894. $sqlwhere = '';
  5895. $sql = 'SELECT '.$keyList;
  5896. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  5897. if (!empty($InfoFieldList[4])) {
  5898. // can use SELECT request
  5899. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  5900. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  5901. }
  5902. // current object id can be use into filter
  5903. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  5904. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  5905. } else {
  5906. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  5907. }
  5908. //We have to join on extrafield table
  5909. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5910. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  5911. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  5912. } else {
  5913. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  5914. }
  5915. } else {
  5916. $sqlwhere .= ' WHERE 1=1';
  5917. }
  5918. // Some tables may have field, some other not. For the moment we disable it.
  5919. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  5920. $sqlwhere .= ' AND entity = '.$conf->entity;
  5921. }
  5922. $sql .= $sqlwhere;
  5923. //print $sql;
  5924. $sql .= ' ORDER BY '.implode(', ', $fields_label);
  5925. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  5926. $resql = $this->db->query($sql);
  5927. if ($resql) {
  5928. $out .= '<option value="0">&nbsp;</option>';
  5929. $num = $this->db->num_rows($resql);
  5930. $i = 0;
  5931. while ($i < $num) {
  5932. $labeltoshow = '';
  5933. $obj = $this->db->fetch_object($resql);
  5934. // Several field into label (eq table:code|libelle:rowid)
  5935. $notrans = false;
  5936. $fields_label = explode('|', $InfoFieldList[1]);
  5937. if (count($fields_label) > 1) {
  5938. $notrans = true;
  5939. foreach ($fields_label as $field_toshow) {
  5940. $labeltoshow .= $obj->$field_toshow.' ';
  5941. }
  5942. } else {
  5943. $labeltoshow = $obj->{$InfoFieldList[1]};
  5944. }
  5945. $labeltoshow = dol_trunc($labeltoshow, 45);
  5946. if ($value == $obj->rowid) {
  5947. foreach ($fields_label as $field_toshow) {
  5948. $translabel = $langs->trans($obj->$field_toshow);
  5949. if ($translabel != $obj->$field_toshow) {
  5950. $labeltoshow = dol_trunc($translabel, 18).' ';
  5951. } else {
  5952. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  5953. }
  5954. }
  5955. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5956. } else {
  5957. if (!$notrans) {
  5958. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5959. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5960. $labeltoshow = dol_trunc($translabel, 18);
  5961. } else {
  5962. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5963. }
  5964. }
  5965. if (empty($labeltoshow)) {
  5966. $labeltoshow = '(not defined)';
  5967. }
  5968. if ($value == $obj->rowid) {
  5969. $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5970. }
  5971. if (!empty($InfoFieldList[3]) && $parentField) {
  5972. $parent = $parentName.':'.$obj->{$parentField};
  5973. $isDependList=1;
  5974. }
  5975. $out .= '<option value="'.$obj->rowid.'"';
  5976. $out .= ($value == $obj->rowid ? ' selected' : '');
  5977. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  5978. $out .= '>'.$labeltoshow.'</option>';
  5979. }
  5980. $i++;
  5981. }
  5982. $this->db->free($resql);
  5983. } else {
  5984. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5985. }
  5986. }
  5987. $out .= '</select>';
  5988. } elseif ($type == 'checkbox') {
  5989. $value_arr = explode(',', $value);
  5990. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  5991. } elseif ($type == 'radio') {
  5992. $out = '';
  5993. foreach ($param['options'] as $keyopt => $val) {
  5994. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  5995. $out .= ' value="'.$keyopt.'"';
  5996. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  5997. $out .= ($value == $keyopt ? 'checked' : '');
  5998. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  5999. }
  6000. } elseif ($type == 'chkbxlst') {
  6001. if (is_array($value)) {
  6002. $value_arr = $value;
  6003. } else {
  6004. $value_arr = explode(',', $value);
  6005. }
  6006. if (is_array($param['options'])) {
  6007. $param_list = array_keys($param['options']);
  6008. $InfoFieldList = explode(":", $param_list[0]);
  6009. $parentName = '';
  6010. $parentField = '';
  6011. // 0 : tableName
  6012. // 1 : label field name
  6013. // 2 : key fields name (if differ of rowid)
  6014. // 3 : key field parent (for dependent lists)
  6015. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6016. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6017. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6018. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6019. $keyList .= ', '.$parentField;
  6020. }
  6021. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6022. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6023. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6024. } else {
  6025. $keyList = $InfoFieldList[2].' as rowid';
  6026. }
  6027. }
  6028. $fields_label = explode('|', $InfoFieldList[1]);
  6029. if (is_array($fields_label)) {
  6030. $keyList .= ', ';
  6031. $keyList .= implode(', ', $fields_label);
  6032. }
  6033. $sqlwhere = '';
  6034. $sql = 'SELECT '.$keyList;
  6035. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6036. if (!empty($InfoFieldList[4])) {
  6037. // can use SELECT request
  6038. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6039. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6040. }
  6041. // current object id can be use into filter
  6042. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6043. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6044. } else {
  6045. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6046. }
  6047. // We have to join on extrafield table
  6048. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6049. $sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
  6050. $sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
  6051. } else {
  6052. $sqlwhere .= ' WHERE '.$InfoFieldList[4];
  6053. }
  6054. } else {
  6055. $sqlwhere .= ' WHERE 1=1';
  6056. }
  6057. // Some tables may have field, some other not. For the moment we disable it.
  6058. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6059. $sqlwhere .= ' AND entity = '.$conf->entity;
  6060. }
  6061. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6062. // print $sql;
  6063. $sql .= $sqlwhere;
  6064. dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
  6065. $resql = $this->db->query($sql);
  6066. if ($resql) {
  6067. $num = $this->db->num_rows($resql);
  6068. $i = 0;
  6069. $data = array();
  6070. while ($i < $num) {
  6071. $labeltoshow = '';
  6072. $obj = $this->db->fetch_object($resql);
  6073. $notrans = false;
  6074. // Several field into label (eq table:code|libelle:rowid)
  6075. $fields_label = explode('|', $InfoFieldList[1]);
  6076. if (count($fields_label) > 1) {
  6077. $notrans = true;
  6078. foreach ($fields_label as $field_toshow) {
  6079. $labeltoshow .= $obj->$field_toshow.' ';
  6080. }
  6081. } else {
  6082. $labeltoshow = $obj->{$InfoFieldList[1]};
  6083. }
  6084. $labeltoshow = dol_trunc($labeltoshow, 45);
  6085. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6086. foreach ($fields_label as $field_toshow) {
  6087. $translabel = $langs->trans($obj->$field_toshow);
  6088. if ($translabel != $obj->$field_toshow) {
  6089. $labeltoshow = dol_trunc($translabel, 18).' ';
  6090. } else {
  6091. $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
  6092. }
  6093. }
  6094. $data[$obj->rowid] = $labeltoshow;
  6095. } else {
  6096. if (!$notrans) {
  6097. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6098. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6099. $labeltoshow = dol_trunc($translabel, 18);
  6100. } else {
  6101. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6102. }
  6103. }
  6104. if (empty($labeltoshow)) {
  6105. $labeltoshow = '(not defined)';
  6106. }
  6107. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6108. $data[$obj->rowid] = $labeltoshow;
  6109. }
  6110. if (!empty($InfoFieldList[3]) && $parentField) {
  6111. $parent = $parentName.':'.$obj->{$parentField};
  6112. $isDependList=1;
  6113. }
  6114. $data[$obj->rowid] = $labeltoshow;
  6115. }
  6116. $i++;
  6117. }
  6118. $this->db->free($resql);
  6119. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  6120. } else {
  6121. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  6122. }
  6123. }
  6124. } elseif ($type == 'link') {
  6125. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter]]'
  6126. $param_list_array = explode(':', $param_list[0]);
  6127. $showempty = (($required && $default != '') ? 0 : 1);
  6128. if (!preg_match('/search_/', $keyprefix)) {
  6129. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6130. if (!empty($this->fields[$key]['picto'])) {
  6131. $morecss .= ' widthcentpercentminusxx';
  6132. } else {
  6133. $morecss .= ' widthcentpercentminusx';
  6134. }
  6135. } else {
  6136. if (!empty($this->fields[$key]['picto'])) {
  6137. $morecss .= ' widthcentpercentminusx';
  6138. }
  6139. }
  6140. }
  6141. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6142. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6143. 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".
  6144. list($class, $classfile) = explode(':', $param_list[0]);
  6145. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6146. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6147. } else {
  6148. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6149. }
  6150. $paramforthenewlink = '';
  6151. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6152. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6153. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6154. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6155. $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>';
  6156. }
  6157. }
  6158. } elseif ($type == 'password') {
  6159. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6160. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6161. } elseif ($type == 'array') {
  6162. $newval = $val;
  6163. $newval['type'] = 'varchar(256)';
  6164. $out = '';
  6165. if (!empty($value)) {
  6166. foreach ($value as $option) {
  6167. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6168. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6169. }
  6170. }
  6171. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6172. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6173. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6174. if (!empty($conf->use_javascript_ajax)) {
  6175. $out .= '
  6176. <script>
  6177. $(document).ready(function() {
  6178. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6179. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6180. });
  6181. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6182. $(this).parent().remove();
  6183. });
  6184. });
  6185. </script>';
  6186. }
  6187. }
  6188. if (!empty($hidden)) {
  6189. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6190. }
  6191. if ($isDependList==1) {
  6192. $out .= $this->getJSListDependancies('_common');
  6193. }
  6194. /* Add comments
  6195. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6196. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6197. */
  6198. return $out;
  6199. }
  6200. /**
  6201. * Return HTML string to show a field into a page
  6202. * Code very similar with showOutputField of extra fields
  6203. *
  6204. * @param array $val Array of properties of field to show
  6205. * @param string $key Key of attribute
  6206. * @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)
  6207. * @param string $moreparam To add more parametes on html input tag
  6208. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6209. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6210. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6211. * @return string
  6212. */
  6213. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6214. {
  6215. global $conf, $langs, $form;
  6216. if (!is_object($form)) {
  6217. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6218. $form = new Form($this->db);
  6219. }
  6220. $objectid = $this->id; // Not used ???
  6221. $label = empty($val['label']) ? '' : $val['label'];
  6222. $type = empty($val['type']) ? '' : $val['type'];
  6223. $size = empty($val['css']) ? '' : $val['css'];
  6224. $reg = array();
  6225. // Convert var to be able to share same code than showOutputField of extrafields
  6226. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6227. $type = 'varchar'; // convert varchar(xx) int varchar
  6228. $size = $reg[1];
  6229. } elseif (preg_match('/varchar/', $type)) {
  6230. $type = 'varchar'; // convert varchar(xx) int varchar
  6231. }
  6232. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6233. $type = 'select';
  6234. }
  6235. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6236. $type = 'link';
  6237. }
  6238. $default = empty($val['default']) ? '' : $val['default'];
  6239. $computed = empty($val['computed']) ? '' : $val['computed'];
  6240. $unique = empty($val['unique']) ? '' : $val['unique'];
  6241. $required = empty($val['required']) ? '' : $val['required'];
  6242. $param = array();
  6243. $param['options'] = array();
  6244. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6245. $param['options'] = $val['arrayofkeyval'];
  6246. }
  6247. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6248. $type = 'link';
  6249. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6250. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6251. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6252. $type = 'sellist';
  6253. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6254. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6255. $type = 'sellist';
  6256. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6257. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6258. $type = 'sellist';
  6259. }
  6260. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6261. $list = (empty($val['list']) ? '' : $val['list']);
  6262. $help = (empty($val['help']) ? '' : $val['help']);
  6263. $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)
  6264. if ($hidden) {
  6265. return '';
  6266. }
  6267. // If field is a computed field, value must become result of compute
  6268. if ($computed) {
  6269. // Make the eval of compute string
  6270. //var_dump($computed);
  6271. $value = dol_eval($computed, 1, 0);
  6272. }
  6273. if (empty($morecss)) {
  6274. if ($type == 'date') {
  6275. $morecss = 'minwidth100imp';
  6276. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6277. $morecss = 'minwidth200imp';
  6278. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6279. $morecss = 'maxwidth75';
  6280. } elseif ($type == 'url') {
  6281. $morecss = 'minwidth400';
  6282. } elseif ($type == 'boolean') {
  6283. $morecss = '';
  6284. } else {
  6285. if (is_numeric($size) && round($size) < 12) {
  6286. $morecss = 'minwidth100';
  6287. } elseif (is_numeric($size) && round($size) <= 48) {
  6288. $morecss = 'minwidth200';
  6289. } else {
  6290. $morecss = 'minwidth400';
  6291. }
  6292. }
  6293. }
  6294. // Format output value differently according to properties of field
  6295. if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
  6296. $value = $this->getNomUrl(1, '', 0, '', 1);
  6297. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6298. $value = $this->getLibStatut(3);
  6299. } elseif ($type == 'date') {
  6300. if (!empty($value)) {
  6301. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6302. } else {
  6303. $value = '';
  6304. }
  6305. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6306. if (!empty($value)) {
  6307. $value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6308. } else {
  6309. $value = '';
  6310. }
  6311. } elseif ($type == 'duration') {
  6312. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6313. if (!is_null($value) && $value !== '') {
  6314. $value = convertSecondToTime($value, 'allhourmin');
  6315. }
  6316. } elseif ($type == 'double' || $type == 'real') {
  6317. if (!is_null($value) && $value !== '') {
  6318. $value = price($value);
  6319. }
  6320. } elseif ($type == 'boolean') {
  6321. $checked = '';
  6322. if (!empty($value)) {
  6323. $checked = ' checked ';
  6324. }
  6325. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6326. } elseif ($type == 'mail') {
  6327. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6328. } elseif ($type == 'url') {
  6329. $value = dol_print_url($value, '_blank', 32, 1);
  6330. } elseif ($type == 'phone') {
  6331. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  6332. } elseif ($type == 'price') {
  6333. if (!is_null($value) && $value !== '') {
  6334. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6335. }
  6336. } elseif ($type == 'select') {
  6337. $value = $param['options'][$value];
  6338. } elseif ($type == 'sellist') {
  6339. $param_list = array_keys($param['options']);
  6340. $InfoFieldList = explode(":", $param_list[0]);
  6341. $selectkey = "rowid";
  6342. $keyList = 'rowid';
  6343. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6344. $selectkey = $InfoFieldList[2];
  6345. $keyList = $InfoFieldList[2].' as rowid';
  6346. }
  6347. $fields_label = explode('|', $InfoFieldList[1]);
  6348. if (is_array($fields_label)) {
  6349. $keyList .= ', ';
  6350. $keyList .= implode(', ', $fields_label);
  6351. }
  6352. $sql = 'SELECT '.$keyList;
  6353. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6354. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6355. $sql .= ' as main';
  6356. }
  6357. if ($selectkey == 'rowid' && empty($value)) {
  6358. $sql .= " WHERE ".$selectkey." = 0";
  6359. } elseif ($selectkey == 'rowid') {
  6360. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6361. } else {
  6362. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6363. }
  6364. //$sql.= ' AND entity = '.$conf->entity;
  6365. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6366. $resql = $this->db->query($sql);
  6367. if ($resql) {
  6368. $value = ''; // value was used, so now we reste it to use it to build final output
  6369. $obj = $this->db->fetch_object($resql);
  6370. // Several field into label (eq table:code|libelle:rowid)
  6371. $fields_label = explode('|', $InfoFieldList[1]);
  6372. if (is_array($fields_label) && count($fields_label) > 1) {
  6373. foreach ($fields_label as $field_toshow) {
  6374. $translabel = '';
  6375. if (!empty($obj->$field_toshow)) {
  6376. $translabel = $langs->trans($obj->$field_toshow);
  6377. }
  6378. if ($translabel != $field_toshow) {
  6379. $value .= dol_trunc($translabel, 18).' ';
  6380. } else {
  6381. $value .= $obj->$field_toshow.' ';
  6382. }
  6383. }
  6384. } else {
  6385. $translabel = '';
  6386. if (!empty($obj->{$InfoFieldList[1]})) {
  6387. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6388. }
  6389. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6390. $value = dol_trunc($translabel, 18);
  6391. } else {
  6392. $value = $obj->{$InfoFieldList[1]};
  6393. }
  6394. }
  6395. } else {
  6396. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6397. }
  6398. } elseif ($type == 'radio') {
  6399. $value = $param['options'][$value];
  6400. } elseif ($type == 'checkbox') {
  6401. $value_arr = explode(',', $value);
  6402. $value = '';
  6403. if (is_array($value_arr) && count($value_arr) > 0) {
  6404. $toprint = array();
  6405. foreach ($value_arr as $keyval => $valueval) {
  6406. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6407. }
  6408. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6409. }
  6410. } elseif ($type == 'chkbxlst') {
  6411. $value_arr = explode(',', $value);
  6412. $param_list = array_keys($param['options']);
  6413. $InfoFieldList = explode(":", $param_list[0]);
  6414. $selectkey = "rowid";
  6415. $keyList = 'rowid';
  6416. if (count($InfoFieldList) >= 3) {
  6417. $selectkey = $InfoFieldList[2];
  6418. $keyList = $InfoFieldList[2].' as rowid';
  6419. }
  6420. $fields_label = explode('|', $InfoFieldList[1]);
  6421. if (is_array($fields_label)) {
  6422. $keyList .= ', ';
  6423. $keyList .= implode(', ', $fields_label);
  6424. }
  6425. $sql = 'SELECT '.$keyList;
  6426. $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
  6427. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6428. $sql .= ' as main';
  6429. }
  6430. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6431. // $sql.= ' AND entity = '.$conf->entity;
  6432. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6433. $resql = $this->db->query($sql);
  6434. if ($resql) {
  6435. $value = ''; // value was used, so now we reste it to use it to build final output
  6436. $toprint = array();
  6437. while ($obj = $this->db->fetch_object($resql)) {
  6438. // Several field into label (eq table:code|libelle:rowid)
  6439. $fields_label = explode('|', $InfoFieldList[1]);
  6440. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6441. if (is_array($fields_label) && count($fields_label) > 1) {
  6442. foreach ($fields_label as $field_toshow) {
  6443. $translabel = '';
  6444. if (!empty($obj->$field_toshow)) {
  6445. $translabel = $langs->trans($obj->$field_toshow);
  6446. }
  6447. if ($translabel != $field_toshow) {
  6448. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6449. } else {
  6450. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->$field_toshow.'</li>';
  6451. }
  6452. }
  6453. } else {
  6454. $translabel = '';
  6455. if (!empty($obj->{$InfoFieldList[1]})) {
  6456. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6457. }
  6458. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6459. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.dol_trunc($translabel, 18).'</li>';
  6460. } else {
  6461. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$obj->{$InfoFieldList[1]}.'</li>';
  6462. }
  6463. }
  6464. }
  6465. }
  6466. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6467. } else {
  6468. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6469. }
  6470. } elseif ($type == 'link') {
  6471. $out = '';
  6472. // only if something to display (perf)
  6473. if ($value) {
  6474. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6475. $InfoFieldList = explode(":", $param_list[0]);
  6476. $classname = $InfoFieldList[0];
  6477. $classpath = $InfoFieldList[1];
  6478. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6479. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6480. if (!empty($classpath)) {
  6481. dol_include_once($InfoFieldList[1]);
  6482. if ($classname && class_exists($classname)) {
  6483. $object = new $classname($this->db);
  6484. $object->fetch($value);
  6485. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6486. }
  6487. } else {
  6488. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6489. return 'Error bad setup of extrafield';
  6490. }
  6491. } else {
  6492. $value = '';
  6493. }
  6494. } elseif (preg_match('/^(text|html)/', $type)) {
  6495. $value = dol_htmlentitiesbr($value);
  6496. } elseif ($type == 'password') {
  6497. $value = preg_replace('/./i', '*', $value);
  6498. } elseif ($type == 'array') {
  6499. $value = implode('<br>', $value);
  6500. }
  6501. //print $type.'-'.$size.'-'.$value;
  6502. $out = $value;
  6503. return $out;
  6504. }
  6505. /**
  6506. * Function to show lines of extrafields with output datas.
  6507. * 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
  6508. *
  6509. * @param Extrafields $extrafields Extrafield Object
  6510. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  6511. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  6512. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  6513. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  6514. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  6515. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  6516. * @return string
  6517. */
  6518. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  6519. {
  6520. global $db, $conf, $langs, $action, $form, $hookmanager;
  6521. if (!is_object($form)) {
  6522. $form = new Form($db);
  6523. }
  6524. $out = '';
  6525. $parameters = array();
  6526. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  6527. if (empty($reshook)) {
  6528. if (key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  6529. $out .= "\n";
  6530. $out .= '<!-- showOptionals --> ';
  6531. $out .= "\n";
  6532. $extrafields_collapse_num = '';
  6533. $e = 0;
  6534. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  6535. // Show only the key field in params
  6536. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  6537. continue;
  6538. }
  6539. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  6540. $enabled = 1;
  6541. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  6542. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1);
  6543. }
  6544. if (empty($enabled)) {
  6545. continue;
  6546. }
  6547. $visibility = 1;
  6548. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  6549. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  6550. }
  6551. $perms = 1;
  6552. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  6553. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  6554. }
  6555. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  6556. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  6557. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  6558. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  6559. } elseif ($mode == 'view' && empty($visibility)) {
  6560. continue;
  6561. }
  6562. if (empty($perms)) {
  6563. continue;
  6564. }
  6565. // Load language if required
  6566. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  6567. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  6568. }
  6569. $colspan = '';
  6570. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  6571. if (array_key_exists('cols', $params)) {
  6572. $colspan = $params['cols'];
  6573. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  6574. $reg = array();
  6575. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  6576. $colspan = $reg[1];
  6577. } else {
  6578. $colspan = $params['colspan'];
  6579. }
  6580. }
  6581. }
  6582. switch ($mode) {
  6583. case "view":
  6584. $value = $this->array_options["options_".$key.$keysuffix]; // Value may be clean or formated later
  6585. break;
  6586. case "create":
  6587. case "edit":
  6588. // We get the value of property found with GETPOST so it takes into account:
  6589. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  6590. $check = 'alphanohtml';
  6591. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  6592. $check = 'restricthtml';
  6593. }
  6594. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  6595. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  6596. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  6597. if (is_array($getposttemp)) {
  6598. // $getposttemp is an array but following code expects a comma separated string
  6599. $value = implode(",", $getposttemp);
  6600. } else {
  6601. $value = $getposttemp;
  6602. }
  6603. } else {
  6604. $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.
  6605. }
  6606. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  6607. break;
  6608. }
  6609. // Output value of the current field
  6610. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  6611. $extrafields_collapse_num = '';
  6612. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  6613. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  6614. $extrafield_param_list = array_keys($extrafield_param['options']);
  6615. if (count($extrafield_param_list) > 0) {
  6616. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  6617. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  6618. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  6619. }
  6620. }
  6621. }
  6622. $out .= $extrafields->showSeparator($key, $this, ($colspan + 1), $display_type);
  6623. } else {
  6624. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  6625. $csstyle = '';
  6626. if (is_array($params) && count($params) > 0) {
  6627. if (array_key_exists('class', $params)) {
  6628. $class .= $params['class'].' ';
  6629. }
  6630. if (array_key_exists('style', $params)) {
  6631. $csstyle = $params['style'];
  6632. }
  6633. }
  6634. // add html5 elements
  6635. $domData = ' data-element="extrafield"';
  6636. $domData .= ' data-targetelement="'.$this->element.'"';
  6637. $domData .= ' data-targetid="'.$this->id.'"';
  6638. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  6639. if ($display_type=='card') {
  6640. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  6641. $colspan = '0';
  6642. }
  6643. if ($action == 'selectlines') {
  6644. $colspan++;
  6645. }
  6646. }
  6647. // Convert date into timestamp format (value in memory must be a timestamp)
  6648. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  6649. $datenotinstring = $this->array_options['options_'.$key];
  6650. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6651. $datenotinstring = $this->db->jdate($datenotinstring);
  6652. }
  6653. $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;
  6654. }
  6655. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  6656. $datenotinstring = $this->array_options['options_'.$key];
  6657. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  6658. $datenotinstring = $this->db->jdate($datenotinstring);
  6659. }
  6660. $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;
  6661. }
  6662. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  6663. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  6664. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? price2num($value) : $this->array_options['options_'.$key];
  6665. }
  6666. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  6667. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int'))) {
  6668. if ($action == 'create') {
  6669. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  6670. }
  6671. }
  6672. $labeltoshow = $langs->trans($label);
  6673. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  6674. if ($display_type == 'card') {
  6675. $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldcreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  6676. $out .= '<td class="wordbreak';
  6677. } elseif ($display_type == 'line') {
  6678. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="valuefieldlinecreate '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >';
  6679. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  6680. }
  6681. //$out .= "titlefield";
  6682. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  6683. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  6684. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  6685. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  6686. $out .= '">';
  6687. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6688. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6689. } else {
  6690. $out .= $labeltoshow;
  6691. }
  6692. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6693. $out .= '&nbsp;<font color="red">*</font>';
  6694. }
  6695. } else {
  6696. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  6697. $out .= ' fieldrequired';
  6698. }
  6699. $out .= '">';
  6700. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  6701. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  6702. } else {
  6703. $out .= $labeltoshow;
  6704. }
  6705. }
  6706. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  6707. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  6708. if ($display_type == 'card') {
  6709. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  6710. } elseif ($display_type == 'line') {
  6711. $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').' style="display: inline-block" class="'.$this->element.'_extras_'.$key.'">';
  6712. }
  6713. switch ($mode) {
  6714. case "view":
  6715. $out .= $extrafields->showOutputField($key, $value);
  6716. break;
  6717. case "create":
  6718. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6719. break;
  6720. case "edit":
  6721. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  6722. break;
  6723. }
  6724. $out .= ($display_type=='card' ? '</td>' : '</div>');
  6725. /*for($ii = 0; $ii < ($colspan - 1); $ii++)
  6726. {
  6727. $out .='<td class="'.$this->element.'_extras_'.$key.'"></td>';
  6728. }*/
  6729. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  6730. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  6731. } else {
  6732. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  6733. }
  6734. $e++;
  6735. }
  6736. }
  6737. $out .= "\n";
  6738. // Add code to manage list depending on others
  6739. if (!empty($conf->use_javascript_ajax)) {
  6740. $out .= $this->getJSListDependancies();
  6741. }
  6742. $out .= '<!-- /showOptionals --> '."\n";
  6743. }
  6744. }
  6745. $out .= $hookmanager->resPrint;
  6746. return $out;
  6747. }
  6748. /**
  6749. * @param string $type Type for prefix
  6750. * @return string Javacript code to manage dependency
  6751. */
  6752. public function getJSListDependancies($type = '_extra')
  6753. {
  6754. $out = '
  6755. <script>
  6756. jQuery(document).ready(function() {
  6757. function showOptions'.$type.'(child_list, parent_list, orig_select)
  6758. {
  6759. var val = $("select[name=\""+parent_list+"\"]").val();
  6760. var parentVal = parent_list + ":" + val;
  6761. if(typeof val == "string"){
  6762. if(val != "") {
  6763. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  6764. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6765. $("select[name=\""+child_list+"\"]").append(options);
  6766. } else {
  6767. var options = orig_select.find("option[parent]").clone();
  6768. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6769. $("select[name=\""+child_list+"\"]").append(options);
  6770. }
  6771. } else if(val > 0) {
  6772. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  6773. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6774. $("select[name=\""+child_list+"\"]").append(options);
  6775. } else {
  6776. var options = orig_select.find("option[parent]").clone();
  6777. $("select[name=\""+child_list+"\"] option[parent]").remove();
  6778. $("select[name=\""+child_list+"\"]").append(options);
  6779. }
  6780. }
  6781. function setListDependencies'.$type.'() {
  6782. jQuery("select option[parent]").parent().each(function() {
  6783. var orig_select = {};
  6784. var child_list = $(this).attr("name");
  6785. orig_select[child_list] = $(this).clone();
  6786. var parent = $(this).find("option[parent]:first").attr("parent");
  6787. var infos = parent.split(":");
  6788. var parent_list = infos[0];
  6789. //Hide daughters lists
  6790. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  6791. $("#"+child_list).hide();
  6792. //Show mother lists
  6793. } else if ($("#"+parent_list).val() != 0){
  6794. $("#"+parent_list).show();
  6795. }
  6796. //Show the child list if the parent list value is selected
  6797. $("select[name=\""+parent_list+"\"]").click(function() {
  6798. if ($(this).val() != 0){
  6799. $("#"+child_list).show()
  6800. }
  6801. });
  6802. //When we change parent list
  6803. $("select[name=\""+parent_list+"\"]").change(function() {
  6804. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  6805. //Select the value 0 on child list after a change on the parent list
  6806. $("#"+child_list).val(0).trigger("change");
  6807. //Hide child lists if the parent value is set to 0
  6808. if ($(this).val() == 0){
  6809. $("#"+child_list).hide();
  6810. }
  6811. });
  6812. });
  6813. }
  6814. setListDependencies'.$type.'();
  6815. });
  6816. </script>'."\n";
  6817. return $out;
  6818. }
  6819. /**
  6820. * Returns the rights used for this class
  6821. * @return stdClass
  6822. */
  6823. public function getRights()
  6824. {
  6825. global $user;
  6826. $element = $this->element;
  6827. if ($element == 'facturerec') {
  6828. $element = 'facture';
  6829. }
  6830. return $user->rights->{$element};
  6831. }
  6832. /**
  6833. * Function used to replace a thirdparty id with another one.
  6834. * This function is meant to be called from replaceThirdparty with the appropiate tables
  6835. * Column name fk_soc MUST be used to identify thirdparties
  6836. *
  6837. * @param DoliDB $db Database handler
  6838. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  6839. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  6840. * @param string[] $tables Tables that need to be changed
  6841. * @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)
  6842. * @return bool True if success, False if error
  6843. */
  6844. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  6845. {
  6846. foreach ($tables as $table) {
  6847. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  6848. if (!$db->query($sql)) {
  6849. if ($ignoreerrors) {
  6850. return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B.
  6851. }
  6852. //$this->errors = $db->lasterror();
  6853. return false;
  6854. }
  6855. }
  6856. return true;
  6857. }
  6858. /**
  6859. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  6860. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  6861. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  6862. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  6863. * else set min buy price as buy price
  6864. *
  6865. * @param float $unitPrice Product unit price
  6866. * @param float $discountPercent Line discount percent
  6867. * @param int $fk_product Product id
  6868. * @return float <0 if KO, buyprice if OK
  6869. */
  6870. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  6871. {
  6872. global $conf;
  6873. $buyPrice = 0;
  6874. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  6875. // When ForceBuyingPriceIfNull is set
  6876. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  6877. } else {
  6878. // Get cost price for margin calculation
  6879. if (!empty($fk_product)) {
  6880. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  6881. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6882. $product = new Product($this->db);
  6883. $result = $product->fetch($fk_product);
  6884. if ($result <= 0) {
  6885. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6886. return -1;
  6887. }
  6888. if ($product->cost_price > 0) {
  6889. $buyPrice = $product->cost_price;
  6890. } elseif ($product->pmp > 0) {
  6891. $buyPrice = $product->pmp;
  6892. }
  6893. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  6894. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6895. $product = new Product($this->db);
  6896. $result = $product->fetch($fk_product);
  6897. if ($result <= 0) {
  6898. $this->errors[] = 'ErrorProductIdDoesNotExists';
  6899. return -1;
  6900. }
  6901. if ($product->pmp > 0) {
  6902. $buyPrice = $product->pmp;
  6903. }
  6904. }
  6905. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  6906. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6907. $productFournisseur = new ProductFournisseur($this->db);
  6908. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  6909. $buyPrice = $productFournisseur->fourn_unitprice;
  6910. } elseif ($result < 0) {
  6911. $this->errors[] = $productFournisseur->error;
  6912. return -2;
  6913. }
  6914. }
  6915. }
  6916. }
  6917. return $buyPrice;
  6918. }
  6919. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6920. /**
  6921. * Show photos of an object (nbmax maximum), into several columns
  6922. *
  6923. * @param string $modulepart 'product', 'ticket', ...
  6924. * @param string $sdir Directory to scan (full absolute path)
  6925. * @param int $size 0=original size, 1='small' use thumbnail if possible
  6926. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  6927. * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1.
  6928. * @param int $showfilename 1=Show filename
  6929. * @param int $showaction 1=Show icon with action links (resize, delete)
  6930. * @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.
  6931. * @param int $maxWidth Max width of original image when size='small'
  6932. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  6933. * @param int $notitle Do not add title tag on image
  6934. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  6935. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  6936. */
  6937. 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)
  6938. {
  6939. // phpcs:enable
  6940. global $conf, $user, $langs;
  6941. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6942. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  6943. $sortfield = 'position_name';
  6944. $sortorder = 'asc';
  6945. $dir = $sdir.'/';
  6946. $pdir = '/';
  6947. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  6948. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  6949. // For backward compatibility
  6950. if ($modulepart == 'product') {
  6951. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  6952. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6953. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  6954. }
  6955. }
  6956. // Defined relative dir to DOL_DATA_ROOT
  6957. $relativedir = '';
  6958. if ($dir) {
  6959. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  6960. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  6961. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  6962. }
  6963. $dirthumb = $dir.'thumbs/';
  6964. $pdirthumb = $pdir.'thumbs/';
  6965. $return = '<!-- Photo -->'."\n";
  6966. $nbphoto = 0;
  6967. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  6968. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  6969. {
  6970. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  6971. $filearray=array_merge($filearray, $filearrayold);
  6972. }*/
  6973. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  6974. if (count($filearray)) {
  6975. if ($sortfield && $sortorder) {
  6976. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  6977. }
  6978. foreach ($filearray as $key => $val) {
  6979. $photo = '';
  6980. $file = $val['name'];
  6981. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  6982. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  6983. if (image_format_supported($file) >= 0) {
  6984. $nbphoto++;
  6985. $photo = $file;
  6986. $viewfilename = $file;
  6987. if ($size == 1 || $size == 'small') { // Format vignette
  6988. // Find name of thumb file
  6989. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  6990. if (!dol_is_file($dirthumb.$photo_vignette)) {
  6991. $photo_vignette = '';
  6992. }
  6993. // Get filesize of original file
  6994. $imgarray = dol_getImageSize($dir.$photo);
  6995. if ($nbbyrow > 0) {
  6996. if ($nbphoto == 1) {
  6997. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  6998. }
  6999. if ($nbphoto % $nbbyrow == 1) {
  7000. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7001. }
  7002. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7003. } elseif ($nbbyrow < 0) {
  7004. $return .= '<div class="inline-block">';
  7005. }
  7006. $return .= "\n";
  7007. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7008. if (empty($nolink)) {
  7009. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7010. if ($urladvanced) {
  7011. $return .= '<a href="'.$urladvanced.'">';
  7012. } else {
  7013. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
  7014. }
  7015. }
  7016. // Show image (width height=$maxHeight)
  7017. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7018. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7019. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7020. if ($notitle) {
  7021. $alt = '';
  7022. }
  7023. if ($usesharelink) {
  7024. if ($val['share']) {
  7025. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7026. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7027. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7028. } else {
  7029. $return .= '<!-- Show original file -->';
  7030. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7031. }
  7032. } else {
  7033. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7034. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7035. }
  7036. } else {
  7037. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) {
  7038. $return .= '<!-- Show thumb -->';
  7039. $return .= '<img class="photo photowithmargin maxwidth150onsmartphone" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  7040. } else {
  7041. $return .= '<!-- Show original file -->';
  7042. $return .= '<img class="photo photowithmargin" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  7043. }
  7044. }
  7045. if (empty($nolink)) {
  7046. $return .= '</a>';
  7047. }
  7048. $return .= "\n";
  7049. if ($showfilename) {
  7050. $return .= '<br>'.$viewfilename;
  7051. }
  7052. if ($showaction) {
  7053. $return .= '<br>';
  7054. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7055. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7056. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=addthumb&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
  7057. }
  7058. // Special cas for product
  7059. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7060. // Link to resize
  7061. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7062. // Link to delete
  7063. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  7064. $return .= img_delete().'</a>';
  7065. }
  7066. }
  7067. $return .= "\n";
  7068. if ($nbbyrow > 0) {
  7069. $return .= '</td>';
  7070. if (($nbphoto % $nbbyrow) == 0) {
  7071. $return .= '</tr>';
  7072. }
  7073. } elseif ($nbbyrow < 0) {
  7074. $return .= '</div>';
  7075. }
  7076. }
  7077. if (empty($size)) { // Format origine
  7078. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7079. if ($showfilename) {
  7080. $return .= '<br>'.$viewfilename;
  7081. }
  7082. if ($showaction) {
  7083. // Special case for product
  7084. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7085. // Link to resize
  7086. $return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  7087. // Link to delete
  7088. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;token='.newToken().'&amp;file='.urlencode($pdir.$viewfilename).'">';
  7089. $return .= img_delete().'</a>';
  7090. }
  7091. }
  7092. }
  7093. // On continue ou on arrete de boucler ?
  7094. if ($nbmax && $nbphoto >= $nbmax) {
  7095. break;
  7096. }
  7097. }
  7098. }
  7099. if ($size == 1 || $size == 'small') {
  7100. if ($nbbyrow > 0) {
  7101. // Ferme tableau
  7102. while ($nbphoto % $nbbyrow) {
  7103. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7104. $nbphoto++;
  7105. }
  7106. if ($nbphoto) {
  7107. $return .= '</table>';
  7108. }
  7109. }
  7110. }
  7111. }
  7112. $this->nbphoto = $nbphoto;
  7113. return $return;
  7114. }
  7115. /**
  7116. * Function test if type is array
  7117. *
  7118. * @param array $info content informations of field
  7119. * @return bool true if array
  7120. */
  7121. protected function isArray($info)
  7122. {
  7123. if (is_array($info)) {
  7124. if (isset($info['type']) && $info['type'] == 'array') {
  7125. return true;
  7126. } else {
  7127. return false;
  7128. }
  7129. }
  7130. return false;
  7131. }
  7132. /**
  7133. * Function test if type is date
  7134. *
  7135. * @param array $info content informations of field
  7136. * @return bool true if date
  7137. */
  7138. public function isDate($info)
  7139. {
  7140. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7141. return true;
  7142. }
  7143. return false;
  7144. }
  7145. /**
  7146. * Function test if type is duration
  7147. *
  7148. * @param array $info content informations of field
  7149. * @return bool true if field of type duration
  7150. */
  7151. public function isDuration($info)
  7152. {
  7153. if (is_array($info)) {
  7154. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7155. return true;
  7156. } else {
  7157. return false;
  7158. }
  7159. } else {
  7160. return false;
  7161. }
  7162. }
  7163. /**
  7164. * Function test if type is integer
  7165. *
  7166. * @param array $info content informations of field
  7167. * @return bool true if integer
  7168. */
  7169. public function isInt($info)
  7170. {
  7171. if (is_array($info)) {
  7172. if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) {
  7173. return true;
  7174. } else {
  7175. return false;
  7176. }
  7177. } else {
  7178. return false;
  7179. }
  7180. }
  7181. /**
  7182. * Function test if type is float
  7183. *
  7184. * @param array $info content informations of field
  7185. * @return bool true if float
  7186. */
  7187. public function isFloat($info)
  7188. {
  7189. if (is_array($info)) {
  7190. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7191. return true;
  7192. } else {
  7193. return false;
  7194. }
  7195. }
  7196. return false;
  7197. }
  7198. /**
  7199. * Function test if type is text
  7200. *
  7201. * @param array $info content informations of field
  7202. * @return bool true if type text
  7203. */
  7204. public function isText($info)
  7205. {
  7206. if (is_array($info)) {
  7207. if (isset($info['type']) && $info['type'] == 'text') {
  7208. return true;
  7209. } else {
  7210. return false;
  7211. }
  7212. }
  7213. return false;
  7214. }
  7215. /**
  7216. * Function test if field can be null
  7217. *
  7218. * @param array $info content informations of field
  7219. * @return bool true if it can be null
  7220. */
  7221. protected function canBeNull($info)
  7222. {
  7223. if (is_array($info)) {
  7224. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7225. return true;
  7226. } else {
  7227. return false;
  7228. }
  7229. }
  7230. return true;
  7231. }
  7232. /**
  7233. * Function test if field is forced to null if zero or empty
  7234. *
  7235. * @param array $info content informations of field
  7236. * @return bool true if forced to null
  7237. */
  7238. protected function isForcedToNullIfZero($info)
  7239. {
  7240. if (is_array($info)) {
  7241. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7242. return true;
  7243. } else {
  7244. return false;
  7245. }
  7246. }
  7247. return false;
  7248. }
  7249. /**
  7250. * Function test if is indexed
  7251. *
  7252. * @param array $info content informations of field
  7253. * @return bool
  7254. */
  7255. protected function isIndex($info)
  7256. {
  7257. if (is_array($info)) {
  7258. if (isset($info['index']) && $info['index'] == true) {
  7259. return true;
  7260. } else {
  7261. return false;
  7262. }
  7263. }
  7264. return false;
  7265. }
  7266. /**
  7267. * Function to prepare a part of the query for insert.
  7268. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  7269. * $this->${field} should be a clean value. The page can run
  7270. *
  7271. * @return array
  7272. */
  7273. protected function setSaveQuery()
  7274. {
  7275. global $conf;
  7276. $queryarray = array();
  7277. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  7278. // Depending on field type ('datetime', ...)
  7279. if ($this->isDate($info)) {
  7280. if (empty($this->{$field})) {
  7281. $queryarray[$field] = null;
  7282. } else {
  7283. $queryarray[$field] = $this->db->idate($this->{$field});
  7284. }
  7285. } elseif ($this->isArray($info)) {
  7286. if (!empty($this->{$field})) {
  7287. if (!is_array($this->{$field})) {
  7288. $this->{$field} = array($this->{$field});
  7289. }
  7290. $queryarray[$field] = serialize($this->{$field});
  7291. } else {
  7292. $queryarray[$field] = null;
  7293. }
  7294. } elseif ($this->isDuration($info)) {
  7295. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7296. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7297. if (!isset($this->{$field})) {
  7298. $queryarray[$field] = 0;
  7299. } else {
  7300. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7301. }
  7302. } else {
  7303. $queryarray[$field] = null;
  7304. }
  7305. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  7306. if ($field == 'entity' && is_null($this->{$field})) {
  7307. $queryarray[$field] = $conf->entity;
  7308. } else {
  7309. // $this->{$field} may be null, '', 0, '0', 123, '123'
  7310. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  7311. if (!isset($this->{$field})) {
  7312. $queryarray[$field] = 0;
  7313. } elseif ($this->isInt($info)) {
  7314. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7315. } elseif ($this->isFloat($info)) {
  7316. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  7317. }
  7318. } else {
  7319. $queryarray[$field] = null;
  7320. }
  7321. }
  7322. } else {
  7323. $queryarray[$field] = $this->{$field};
  7324. }
  7325. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  7326. unset($queryarray[$field]);
  7327. }
  7328. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  7329. $queryarray[$field] = null; // May force 0 to null
  7330. }
  7331. }
  7332. return $queryarray;
  7333. }
  7334. /**
  7335. * Function to load data from a SQL pointer into properties of current object $this
  7336. *
  7337. * @param stdClass $obj Contain data of object from database
  7338. * @return void
  7339. */
  7340. public function setVarsFromFetchObj(&$obj)
  7341. {
  7342. global $db;
  7343. foreach ($this->fields as $field => $info) {
  7344. if ($this->isDate($info)) {
  7345. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  7346. $this->{$field} = '';
  7347. } else {
  7348. $this->{$field} = $db->jdate($obj->{$field});
  7349. }
  7350. } elseif ($this->isArray($info)) {
  7351. if (!empty($obj->{$field})) {
  7352. $this->{$field} = @unserialize($obj->{$field});
  7353. // Hack for data not in UTF8
  7354. if ($this->{$field } === false) {
  7355. @unserialize(utf8_decode($obj->{$field}));
  7356. }
  7357. } else {
  7358. $this->{$field} = array();
  7359. }
  7360. } elseif ($this->isInt($info)) {
  7361. if ($field == 'rowid') {
  7362. $this->id = (int) $obj->{$field};
  7363. } else {
  7364. if ($this->isForcedToNullIfZero($info)) {
  7365. if (empty($obj->{$field})) {
  7366. $this->{$field} = null;
  7367. } else {
  7368. $this->{$field} = (double) $obj->{$field};
  7369. }
  7370. } else {
  7371. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7372. $this->{$field} = (int) $obj->{$field};
  7373. } else {
  7374. $this->{$field} = null;
  7375. }
  7376. }
  7377. }
  7378. } elseif ($this->isFloat($info)) {
  7379. if ($this->isForcedToNullIfZero($info)) {
  7380. if (empty($obj->{$field})) {
  7381. $this->{$field} = null;
  7382. } else {
  7383. $this->{$field} = (double) $obj->{$field};
  7384. }
  7385. } else {
  7386. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  7387. $this->{$field} = (double) $obj->{$field};
  7388. } else {
  7389. $this->{$field} = null;
  7390. }
  7391. }
  7392. } else {
  7393. $this->{$field} = $obj->{$field};
  7394. }
  7395. }
  7396. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  7397. if (!isset($this->fields['ref']) && isset($this->id)) {
  7398. $this->ref = $this->id;
  7399. }
  7400. }
  7401. /**
  7402. * Function to concat keys of fields
  7403. *
  7404. * @param string $alias String of alias of table for fields. For example 't'.
  7405. * @return string list of alias fields
  7406. */
  7407. public function getFieldList($alias = '')
  7408. {
  7409. $keys = array_keys($this->fields);
  7410. if (!empty($alias)) {
  7411. $keys_with_alias = array();
  7412. foreach ($keys as $fieldname) {
  7413. $keys_with_alias[] = $alias . '.' . $fieldname;
  7414. }
  7415. return implode(',', $keys_with_alias);
  7416. } else {
  7417. return implode(',', $keys);
  7418. }
  7419. }
  7420. /**
  7421. * Add quote to field value if necessary
  7422. *
  7423. * @param string|int $value Value to protect
  7424. * @param array $fieldsentry Properties of field
  7425. * @return string
  7426. */
  7427. protected function quote($value, $fieldsentry)
  7428. {
  7429. if (is_null($value)) {
  7430. return 'NULL';
  7431. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  7432. return $this->db->escape("$value");
  7433. } elseif ($fieldsentry['type'] == 'boolean') {
  7434. if ($value) {
  7435. return 'true';
  7436. } else {
  7437. return 'false';
  7438. }
  7439. } else {
  7440. return "'".$this->db->escape($value)."'";
  7441. }
  7442. }
  7443. /**
  7444. * Create object into database
  7445. *
  7446. * @param User $user User that creates
  7447. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7448. * @return int <0 if KO, Id of created object if OK
  7449. */
  7450. public function createCommon(User $user, $notrigger = false)
  7451. {
  7452. global $langs;
  7453. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  7454. $error = 0;
  7455. $now = dol_now();
  7456. $fieldvalues = $this->setSaveQuery();
  7457. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  7458. $fieldvalues['date_creation'] = $this->db->idate($now);
  7459. }
  7460. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  7461. $fieldvalues['fk_user_creat'] = $user->id;
  7462. }
  7463. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  7464. if (array_key_exists('ref', $fieldvalues)) {
  7465. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7466. }
  7467. $keys = array();
  7468. $values = array(); // Array to store string forged for SQL syntax
  7469. foreach ($fieldvalues as $k => $v) {
  7470. $keys[$k] = $k;
  7471. $value = $this->fields[$k];
  7472. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  7473. }
  7474. // Clean and check mandatory
  7475. foreach ($keys as $key) {
  7476. // If field is an implicit foreign key field
  7477. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7478. $values[$key] = '';
  7479. }
  7480. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7481. $values[$key] = '';
  7482. }
  7483. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  7484. $error++;
  7485. $langs->load("errors");
  7486. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  7487. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7488. }
  7489. // If value is null and there is a default value for field
  7490. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  7491. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  7492. }
  7493. // If field is an implicit foreign key field
  7494. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  7495. if (isset($this->fields[$key]['default'])) {
  7496. $values[$key] = $this->fields[$key]['default'];
  7497. } else {
  7498. $values[$key] = 'null';
  7499. }
  7500. }
  7501. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  7502. $values[$key] = 'null';
  7503. }
  7504. }
  7505. if ($error) {
  7506. return -1;
  7507. }
  7508. $this->db->begin();
  7509. if (!$error) {
  7510. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
  7511. $sql .= ' ('.implode(", ", $keys).')';
  7512. $sql .= ' VALUES ('.implode(", ", $values).')';
  7513. $res = $this->db->query($sql);
  7514. if ($res === false) {
  7515. $error++;
  7516. $this->errors[] = $this->db->lasterror();
  7517. }
  7518. }
  7519. if (!$error) {
  7520. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  7521. }
  7522. // If we have a field ref with a default value of (PROV)
  7523. if (!$error) {
  7524. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  7525. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ref = '(PROV".$this->id.")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  7526. $resqlupdate = $this->db->query($sql);
  7527. if ($resqlupdate === false) {
  7528. $error++;
  7529. $this->errors[] = $this->db->lasterror();
  7530. } else {
  7531. $this->ref = '(PROV'.$this->id.')';
  7532. }
  7533. }
  7534. }
  7535. // Create extrafields
  7536. if (!$error) {
  7537. $result = $this->insertExtraFields();
  7538. if ($result < 0) {
  7539. $error++;
  7540. }
  7541. }
  7542. // Create lines
  7543. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  7544. $num = (is_array($this->lines) ? count($this->lines) : 0);
  7545. for ($i = 0; $i < $num; $i++) {
  7546. $line = $this->lines[$i];
  7547. $keyforparent = $this->fk_element;
  7548. $line->$keyforparent = $this->id;
  7549. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  7550. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  7551. if (!is_object($line)) {
  7552. $line = (object) $line;
  7553. }
  7554. $result = $line->create($user, 1);
  7555. if ($result < 0) {
  7556. $this->error = $line->error;
  7557. $this->db->rollback();
  7558. return -1;
  7559. }
  7560. }
  7561. }
  7562. // Triggers
  7563. if (!$error && !$notrigger) {
  7564. // Call triggers
  7565. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  7566. if ($result < 0) {
  7567. $error++;
  7568. }
  7569. // End call triggers
  7570. }
  7571. // Commit or rollback
  7572. if ($error) {
  7573. $this->db->rollback();
  7574. return -1;
  7575. } else {
  7576. $this->db->commit();
  7577. return $this->id;
  7578. }
  7579. }
  7580. /**
  7581. * Load object in memory from the database
  7582. *
  7583. * @param int $id Id object
  7584. * @param string $ref Ref
  7585. * @param string $morewhere More SQL filters (' AND ...')
  7586. * @return int <0 if KO, 0 if not found, >0 if OK
  7587. */
  7588. public function fetchCommon($id, $ref = null, $morewhere = '')
  7589. {
  7590. if (empty($id) && empty($ref) && empty($morewhere)) {
  7591. return -1;
  7592. }
  7593. $fieldlist = $this->getFieldList('t');
  7594. if (empty($fieldlist)) {
  7595. return 0;
  7596. }
  7597. $sql = 'SELECT '.$fieldlist;
  7598. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  7599. if (!empty($id)) {
  7600. $sql .= ' WHERE t.rowid = '.((int) $id);
  7601. } elseif (!empty($ref)) {
  7602. $sql .= " WHERE t.ref = ".$this->quote($ref, $this->fields['ref']);
  7603. } else {
  7604. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  7605. }
  7606. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  7607. $sql .= ' AND t.entity IN ('.getEntity($this->table_element).')';
  7608. }
  7609. if ($morewhere) {
  7610. $sql .= $morewhere;
  7611. }
  7612. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  7613. $res = $this->db->query($sql);
  7614. if ($res) {
  7615. $obj = $this->db->fetch_object($res);
  7616. if ($obj) {
  7617. $this->setVarsFromFetchObj($obj);
  7618. // Retrieve all extrafield
  7619. // fetch optionals attributes and labels
  7620. $this->fetch_optionals();
  7621. dol_syslog("aaa=".$this->id);
  7622. return $this->id;
  7623. } else {
  7624. return 0;
  7625. }
  7626. } else {
  7627. $this->error = $this->db->lasterror();
  7628. $this->errors[] = $this->error;
  7629. return -1;
  7630. }
  7631. }
  7632. /**
  7633. * Load object in memory from the database
  7634. *
  7635. * @param string $morewhere More SQL filters (' AND ...')
  7636. * @return int <0 if KO, 0 if not found, >0 if OK
  7637. */
  7638. public function fetchLinesCommon($morewhere = '')
  7639. {
  7640. $objectlineclassname = get_class($this).'Line';
  7641. if (!class_exists($objectlineclassname)) {
  7642. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  7643. return -1;
  7644. }
  7645. $objectline = new $objectlineclassname($this->db);
  7646. $sql = 'SELECT '.$objectline->getFieldList('l');
  7647. $sql .= ' FROM '.MAIN_DB_PREFIX.$objectline->table_element.' as l';
  7648. $sql .= ' WHERE l.fk_'.$this->element.' = '.$this->id;
  7649. if ($morewhere) {
  7650. $sql .= $morewhere;
  7651. }
  7652. if (isset($objectline->fields['position'])) {
  7653. $sql .= $this->db->order('position', 'ASC');
  7654. }
  7655. $resql = $this->db->query($sql);
  7656. if ($resql) {
  7657. $num_rows = $this->db->num_rows($resql);
  7658. $i = 0;
  7659. while ($i < $num_rows) {
  7660. $obj = $this->db->fetch_object($resql);
  7661. if ($obj) {
  7662. $newline = new $objectlineclassname($this->db);
  7663. $newline->setVarsFromFetchObj($obj);
  7664. $this->lines[] = $newline;
  7665. }
  7666. $i++;
  7667. }
  7668. return 1;
  7669. } else {
  7670. $this->error = $this->db->lasterror();
  7671. $this->errors[] = $this->error;
  7672. return -1;
  7673. }
  7674. }
  7675. /**
  7676. * Update object into database
  7677. *
  7678. * @param User $user User that modifies
  7679. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7680. * @return int <0 if KO, >0 if OK
  7681. */
  7682. public function updateCommon(User $user, $notrigger = false)
  7683. {
  7684. global $conf, $langs;
  7685. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  7686. $error = 0;
  7687. $now = dol_now();
  7688. $fieldvalues = $this->setSaveQuery();
  7689. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  7690. $fieldvalues['date_modification'] = $this->db->idate($now);
  7691. }
  7692. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  7693. $fieldvalues['fk_user_modif'] = $user->id;
  7694. }
  7695. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  7696. if (array_key_exists('ref', $fieldvalues)) {
  7697. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  7698. }
  7699. // Add quotes and escape on fields with type string
  7700. $keys = array();
  7701. $values = array();
  7702. $tmp = array();
  7703. foreach ($fieldvalues as $k => $v) {
  7704. $keys[$k] = $k;
  7705. $value = $this->fields[$k];
  7706. $values[$k] = $this->quote($v, $value);
  7707. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  7708. }
  7709. // Clean and check mandatory fields
  7710. foreach ($keys as $key) {
  7711. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  7712. $values[$key] = ''; // This is an implicit foreign key field
  7713. }
  7714. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  7715. $values[$key] = ''; // This is an explicit foreign key field
  7716. }
  7717. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  7718. /*
  7719. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  7720. {
  7721. $error++;
  7722. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  7723. }*/
  7724. }
  7725. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  7726. $this->db->begin();
  7727. if (!$error) {
  7728. $res = $this->db->query($sql);
  7729. if ($res === false) {
  7730. $error++;
  7731. $this->errors[] = $this->db->lasterror();
  7732. }
  7733. }
  7734. // Update extrafield
  7735. if (!$error) {
  7736. $result = $this->insertExtraFields();
  7737. if ($result < 0) {
  7738. $error++;
  7739. }
  7740. }
  7741. // Triggers
  7742. if (!$error && !$notrigger) {
  7743. // Call triggers
  7744. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  7745. if ($result < 0) {
  7746. $error++;
  7747. } //Do also here what you must do to rollback action if trigger fail
  7748. // End call triggers
  7749. }
  7750. // Commit or rollback
  7751. if ($error) {
  7752. $this->db->rollback();
  7753. return -1;
  7754. } else {
  7755. $this->db->commit();
  7756. return $this->id;
  7757. }
  7758. }
  7759. /**
  7760. * Delete object in database
  7761. *
  7762. * @param User $user User that deletes
  7763. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7764. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  7765. * @return int <=0 if KO, >0 if OK
  7766. */
  7767. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  7768. {
  7769. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  7770. $error = 0;
  7771. $this->db->begin();
  7772. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  7773. foreach ($this->childtables as $table) {
  7774. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7775. $resql = $this->db->query($sql);
  7776. if (!$resql) {
  7777. $this->error = $this->db->lasterror();
  7778. $this->errors[] = $this->error;
  7779. $this->db->rollback();
  7780. return -1;
  7781. }
  7782. }
  7783. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  7784. $objectisused = $this->isObjectUsed($this->id);
  7785. if (!empty($objectisused)) {
  7786. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  7787. $this->error = 'ErrorRecordHasChildren';
  7788. $this->errors[] = $this->error;
  7789. $this->db->rollback();
  7790. return 0;
  7791. }
  7792. }
  7793. // Delete cascade first
  7794. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  7795. foreach ($this->childtablesoncascade as $table) {
  7796. $deleteFromObject = explode(':', $table);
  7797. if (count($deleteFromObject) >= 2) {
  7798. $className = str_replace('@', '', $deleteFromObject[0]);
  7799. $filePath = $deleteFromObject[1];
  7800. $columnName = $deleteFromObject[2];
  7801. if (dol_include_once($filePath)) {
  7802. $childObject = new $className($this->db);
  7803. if (method_exists($childObject, 'deleteByParentField')) {
  7804. $result = $childObject->deleteByParentField($this->id, $columnName);
  7805. if ($result < 0) {
  7806. $error++;
  7807. $this->errors[] = $childObject->error;
  7808. break;
  7809. }
  7810. } else {
  7811. $error++;
  7812. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  7813. break;
  7814. }
  7815. } else {
  7816. $error++;
  7817. $this->errors[] = 'Cannot include child class file '.$filePath;
  7818. break;
  7819. }
  7820. } else {
  7821. // Delete record in child table
  7822. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
  7823. $resql = $this->db->query($sql);
  7824. if (!$resql) {
  7825. $error++;
  7826. $this->error = $this->db->lasterror();
  7827. $this->errors[] = $this->error;
  7828. break;
  7829. }
  7830. }
  7831. }
  7832. }
  7833. if (!$error) {
  7834. if (!$notrigger) {
  7835. // Call triggers
  7836. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  7837. if ($result < 0) {
  7838. $error++;
  7839. } // Do also here what you must do to rollback action if trigger fail
  7840. // End call triggers
  7841. }
  7842. }
  7843. // Delete llx_ecm_files
  7844. if (!$error) {
  7845. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  7846. if (!$res) {
  7847. $error++;
  7848. }
  7849. }
  7850. if (!$error && !empty($this->isextrafieldmanaged)) {
  7851. $result = $this->deleteExtraFields();
  7852. if ($result < 0) {
  7853. $error++;
  7854. }
  7855. }
  7856. if (!$error) {
  7857. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
  7858. $resql = $this->db->query($sql);
  7859. if (!$resql) {
  7860. $error++;
  7861. $this->errors[] = $this->db->lasterror();
  7862. }
  7863. }
  7864. // Commit or rollback
  7865. if ($error) {
  7866. $this->db->rollback();
  7867. return -1;
  7868. } else {
  7869. $this->db->commit();
  7870. return 1;
  7871. }
  7872. }
  7873. /**
  7874. * Delete all child object from a parent ID
  7875. *
  7876. * @param int $parentId Parent Id
  7877. * @param string $parentField Name of Foreign key parent column
  7878. * @return int <0 if KO, >0 if OK
  7879. * @throws Exception
  7880. */
  7881. public function deleteByParentField($parentId = 0, $parentField = '')
  7882. {
  7883. global $user;
  7884. $error = 0;
  7885. $deleted = 0;
  7886. if (!empty($parentId) && !empty($parentField)) {
  7887. $this->db->begin();
  7888. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$this->table_element;
  7889. $sql .= ' WHERE '.$parentField.' = '.(int) $parentId;
  7890. $resql = $this->db->query($sql);
  7891. if (!$resql) {
  7892. $this->errors[] = $this->db->lasterror();
  7893. $error++;
  7894. } else {
  7895. while ($obj = $this->db->fetch_object($resql)) {
  7896. $result = $this->fetch($obj->rowid);
  7897. if ($result < 0) {
  7898. $error++;
  7899. $this->errors[] = $this->error;
  7900. } else {
  7901. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  7902. $result = $this->delete();
  7903. } else {
  7904. $result = $this->delete($user);
  7905. }
  7906. if ($result < 0) {
  7907. $error++;
  7908. $this->errors[] = $this->error;
  7909. } else {
  7910. $deleted++;
  7911. }
  7912. }
  7913. }
  7914. }
  7915. if (empty($error)) {
  7916. $this->db->commit();
  7917. return $deleted;
  7918. } else {
  7919. $this->error = implode(', ', $this->errors);
  7920. $this->db->rollback();
  7921. return $error * -1;
  7922. }
  7923. }
  7924. return $deleted;
  7925. }
  7926. /**
  7927. * Delete a line of object in database
  7928. *
  7929. * @param User $user User that delete
  7930. * @param int $idline Id of line to delete
  7931. * @param bool $notrigger false=launch triggers after, true=disable triggers
  7932. * @return int >0 if OK, <0 if KO
  7933. */
  7934. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  7935. {
  7936. global $conf;
  7937. $error = 0;
  7938. $tmpforobjectclass = get_class($this);
  7939. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  7940. // Call trigger
  7941. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  7942. if ($result < 0) {
  7943. return -1;
  7944. }
  7945. // End call triggers
  7946. $this->db->begin();
  7947. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  7948. $sql .= " WHERE rowid = ".((int) $idline);
  7949. dol_syslog(get_class($this)."::deleteLineCommon", LOG_DEBUG);
  7950. $resql = $this->db->query($sql);
  7951. if (!$resql) {
  7952. $this->error = "Error ".$this->db->lasterror();
  7953. $error++;
  7954. }
  7955. if (empty($error)) {
  7956. // Remove extrafields
  7957. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  7958. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  7959. $tmpobjectline->id = $idline;
  7960. $result = $tmpobjectline->deleteExtraFields();
  7961. if ($result < 0) {
  7962. $error++;
  7963. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  7964. }
  7965. }
  7966. }
  7967. if (empty($error)) {
  7968. $this->db->commit();
  7969. return 1;
  7970. } else {
  7971. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  7972. $this->db->rollback();
  7973. return -1;
  7974. }
  7975. }
  7976. /**
  7977. * Set to a status
  7978. *
  7979. * @param User $user Object user that modify
  7980. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  7981. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  7982. * @param string $triggercode Trigger code to use
  7983. * @return int <0 if KO, >0 if OK
  7984. */
  7985. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  7986. {
  7987. $error = 0;
  7988. $this->db->begin();
  7989. $statusfield = 'status';
  7990. if ($this->element == 'don' || $this->element == 'donation') {
  7991. $statusfield = 'fk_statut';
  7992. }
  7993. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  7994. $sql .= " SET ".$statusfield." = ".((int) $status);
  7995. $sql .= " WHERE rowid = ".$this->id;
  7996. if ($this->db->query($sql)) {
  7997. if (!$error) {
  7998. $this->oldcopy = clone $this;
  7999. }
  8000. if (!$error && !$notrigger) {
  8001. // Call trigger
  8002. $result = $this->call_trigger($triggercode, $user);
  8003. if ($result < 0) {
  8004. $error++;
  8005. }
  8006. }
  8007. if (!$error) {
  8008. $this->status = $status;
  8009. $this->db->commit();
  8010. return 1;
  8011. } else {
  8012. $this->db->rollback();
  8013. return -1;
  8014. }
  8015. } else {
  8016. $this->error = $this->db->error();
  8017. $this->db->rollback();
  8018. return -1;
  8019. }
  8020. }
  8021. /**
  8022. * Initialise object with example values
  8023. * Id must be 0 if object instance is a specimen
  8024. *
  8025. * @return int
  8026. */
  8027. public function initAsSpecimenCommon()
  8028. {
  8029. global $user;
  8030. $this->id = 0;
  8031. $this->specimen = 1;
  8032. $fields = array(
  8033. 'label' => 'This is label',
  8034. 'ref' => 'ABCD1234',
  8035. 'description' => 'This is a description',
  8036. 'qty' => 123.12,
  8037. 'note_public' => 'Public note',
  8038. 'note_private' => 'Private note',
  8039. 'date_creation' => (dol_now() - 3600 * 48),
  8040. 'date_modification' => (dol_now() - 3600 * 24),
  8041. 'fk_user_creat' => $user->id,
  8042. 'fk_user_modif' => $user->id,
  8043. 'date' => dol_now(),
  8044. );
  8045. foreach ($fields as $key => $value) {
  8046. if (array_key_exists($key, $this->fields)) {
  8047. $this->{$key} = $value;
  8048. }
  8049. }
  8050. return 1;
  8051. }
  8052. /* Part for comments */
  8053. /**
  8054. * Load comments linked with current task
  8055. * @return boolean 1 if ok
  8056. */
  8057. public function fetchComments()
  8058. {
  8059. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8060. $comment = new Comment($this->db);
  8061. $result = $comment->fetchAllFor($this->element, $this->id);
  8062. if ($result < 0) {
  8063. $this->errors = array_merge($this->errors, $comment->errors);
  8064. return -1;
  8065. } else {
  8066. $this->comments = $comment->comments;
  8067. }
  8068. return count($this->comments);
  8069. }
  8070. /**
  8071. * Return nb comments already posted
  8072. *
  8073. * @return int
  8074. */
  8075. public function getNbComments()
  8076. {
  8077. return count($this->comments);
  8078. }
  8079. /**
  8080. * Trim object parameters
  8081. *
  8082. * @param string[] $parameters array of parameters to trim
  8083. * @return void
  8084. */
  8085. public function trimParameters($parameters)
  8086. {
  8087. if (!is_array($parameters)) {
  8088. return;
  8089. }
  8090. foreach ($parameters as $parameter) {
  8091. if (isset($this->$parameter)) {
  8092. $this->$parameter = trim($this->$parameter);
  8093. }
  8094. }
  8095. }
  8096. /* Part for categories/tags */
  8097. /**
  8098. * Sets object to given categories.
  8099. *
  8100. * Deletes object from existing categories not supplied.
  8101. * Adds it to non existing supplied categories.
  8102. * Existing categories are left untouch.
  8103. *
  8104. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8105. * @return int Array of category objects or < 0 if KO
  8106. */
  8107. public function getCategoriesCommon($type_categ)
  8108. {
  8109. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8110. // Get current categories
  8111. $c = new Categorie($this->db);
  8112. $existing = $c->containing($this->id, $type_categ, 'id');
  8113. return $existing;
  8114. }
  8115. /**
  8116. * Sets object to given categories.
  8117. *
  8118. * Adds it to non existing supplied categories.
  8119. * Deletes object from existing categories not supplied (if remove_existing==true).
  8120. * Existing categories are left untouch.
  8121. *
  8122. * @param int[]|int $categories Category ID or array of Categories IDs
  8123. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8124. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8125. * @return int <0 if KO, >0 if OK
  8126. */
  8127. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8128. {
  8129. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8130. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8131. if (empty($type_categ)) {
  8132. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8133. return -1;
  8134. }
  8135. // Handle single category
  8136. if (!is_array($categories)) {
  8137. $categories = array($categories);
  8138. }
  8139. // Get current categories
  8140. $c = new Categorie($this->db);
  8141. $existing = $c->containing($this->id, $type_categ, 'id');
  8142. if ($remove_existing) {
  8143. // Diff
  8144. if (is_array($existing)) {
  8145. $to_del = array_diff($existing, $categories);
  8146. $to_add = array_diff($categories, $existing);
  8147. } else {
  8148. $to_del = array(); // Nothing to delete
  8149. $to_add = $categories;
  8150. }
  8151. } else {
  8152. $to_del = array(); // Nothing to delete
  8153. $to_add = array_diff($categories, $existing);
  8154. }
  8155. $error = 0;
  8156. $ok=0;
  8157. // Process
  8158. foreach ($to_del as $del) {
  8159. if ($c->fetch($del) > 0) {
  8160. $result=$c->del_type($this, $type_categ);
  8161. if ($result < 0) {
  8162. $error++;
  8163. $this->error = $c->error;
  8164. $this->errors = $c->errors;
  8165. break;
  8166. } else {
  8167. $ok+=$result;
  8168. }
  8169. }
  8170. }
  8171. foreach ($to_add as $add) {
  8172. if ($c->fetch($add) > 0) {
  8173. $result = $c->add_type($this, $type_categ);
  8174. if ($result < 0) {
  8175. $error++;
  8176. $this->error = $c->error;
  8177. $this->errors = $c->errors;
  8178. break;
  8179. } else {
  8180. $ok+=$result;
  8181. }
  8182. }
  8183. }
  8184. return $error ? -1 * $error : $ok;
  8185. }
  8186. /**
  8187. * Copy related categories to another object
  8188. *
  8189. * @param int $fromId Id object source
  8190. * @param int $toId Id object cible
  8191. * @param string $type Type of category ('product', ...)
  8192. * @return int < 0 if error, > 0 if ok
  8193. */
  8194. public function cloneCategories($fromId, $toId, $type = '')
  8195. {
  8196. $this->db->begin();
  8197. if (empty($type)) {
  8198. $type = $this->table_element;
  8199. }
  8200. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8201. $categorystatic = new Categorie($this->db);
  8202. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8203. $sql .= " SELECT fk_categorie, $toId FROM ".MAIN_DB_PREFIX."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8204. $sql .= " WHERE fk_product = ".((int) $fromId);
  8205. if (!$this->db->query($sql)) {
  8206. $this->error = $this->db->lasterror();
  8207. $this->db->rollback();
  8208. return -1;
  8209. }
  8210. $this->db->commit();
  8211. return 1;
  8212. }
  8213. /**
  8214. * Delete related files of object in database
  8215. *
  8216. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8217. * @return bool True if OK, False if KO
  8218. */
  8219. public function deleteEcmFiles($mode = 0)
  8220. {
  8221. global $conf;
  8222. $this->db->begin();
  8223. // Delete in database with mode 0
  8224. if ($mode == 0) {
  8225. switch ($this->element) {
  8226. case 'propal':
  8227. $element = 'propale';
  8228. break;
  8229. case 'product':
  8230. $element = 'produit';
  8231. break;
  8232. case 'order_supplier':
  8233. $element = 'fournisseur/commande';
  8234. break;
  8235. case 'invoice_supplier':
  8236. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8237. break;
  8238. case 'shipping':
  8239. $element = 'expedition/sending';
  8240. break;
  8241. default:
  8242. $element = $this->element;
  8243. }
  8244. // Delete ecm_files extrafields
  8245. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files_extrafields WHERE fk_object IN (";
  8246. $sql .= " SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8247. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  8248. $sql .= ")";
  8249. if (!$this->db->query($sql)) {
  8250. $this->error = $this->db->lasterror();
  8251. $this->db->rollback();
  8252. return false;
  8253. }
  8254. // Delete ecm_files
  8255. $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_files";
  8256. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  8257. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".$conf->entity; // No need of getEntity here
  8258. if (!$this->db->query($sql)) {
  8259. $this->error = $this->db->lasterror();
  8260. $this->db->rollback();
  8261. return false;
  8262. }
  8263. }
  8264. // Delete in database with mode 1
  8265. if ($mode == 1) {
  8266. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files_extrafields";
  8267. $sql .= " WHERE fk_object IN (SELECT rowid FROM ".MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id.")";
  8268. $resql = $this->db->query($sql);
  8269. if (!$resql) {
  8270. $this->error = $this->db->lasterror();
  8271. $this->db->rollback();
  8272. return false;
  8273. }
  8274. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files";
  8275. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".((int) $this->id);
  8276. $resql = $this->db->query($sql);
  8277. if (!$resql) {
  8278. $this->error = $this->db->lasterror();
  8279. $this->db->rollback();
  8280. return false;
  8281. }
  8282. }
  8283. $this->db->commit();
  8284. return true;
  8285. }
  8286. }