commonobject.class.php 360 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2022 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  18. * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/core/class/commonobject.class.php
  35. * \ingroup core
  36. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  37. */
  38. /**
  39. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  40. */
  41. abstract class CommonObject
  42. {
  43. const TRIGGER_PREFIX = ''; // to be overriden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
  44. /**
  45. * @var DoliDb Database handler (result of a new DoliDB)
  46. */
  47. public $db;
  48. /**
  49. * @var int The object identifier
  50. */
  51. public $id;
  52. /**
  53. * @var int The environment ID when using a multicompany module
  54. */
  55. public $entity;
  56. /**
  57. * @var string Error string
  58. * @see $errors
  59. */
  60. public $error;
  61. /**
  62. * @var string Error string that is hidden but can be used to store complementatry technical code.
  63. */
  64. public $errorhidden;
  65. /**
  66. * @var string[] Array of error strings
  67. */
  68. public $errors = array();
  69. /**
  70. * @var array To store error results of ->validateField()
  71. */
  72. private $validateFieldsErrors = array();
  73. /**
  74. * @var string ID to identify managed object
  75. */
  76. public $element;
  77. /**
  78. * @var string Name to use for 'features' parameter to check module permissions user->rights->feature with restrictedArea().
  79. * Undefined means same value than $element. Can be use to force a check on another element for example for class of line, we mention here the parent element.
  80. */
  81. public $element_for_permission;
  82. /**
  83. * @var string Name of table without prefix where object is stored
  84. */
  85. public $table_element;
  86. /**
  87. * @var string Name of subtable line
  88. */
  89. public $table_element_line = '';
  90. /**
  91. * @var string Key value used to track if data is coming from import wizard
  92. */
  93. public $import_key;
  94. /**
  95. * @var mixed Contains data to manage extrafields
  96. */
  97. public $array_options = array();
  98. /**
  99. * @var mixed Array to store alternative languages values of object
  100. */
  101. public $array_languages = null; // Value is array() when load already tried
  102. /**
  103. * @var array To store result of ->liste_contact()
  104. */
  105. public $contacts_ids;
  106. /**
  107. * @var mixed Array of linked objects, set and used when calling ->create() to be able to create links during the creation of object
  108. */
  109. public $linked_objects;
  110. /**
  111. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  112. */
  113. public $linkedObjectsIds;
  114. /**
  115. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  116. */
  117. public $linkedObjects;
  118. /**
  119. * @var boolean[] Array of boolean with object id as key and value as true if linkedObjects full loaded for object id. Loaded by ->fetchObjectLinked. Important for pdf generation time reduction.
  120. */
  121. private $linkedObjectsFullLoaded = array();
  122. /**
  123. * @var CommonObject To store a cloned copy of object before to edit it and keep track of old properties
  124. */
  125. public $oldcopy;
  126. /**
  127. * @var string Column name of the ref field.
  128. */
  129. protected $table_ref_field = '';
  130. /**
  131. * @var integer 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  132. */
  133. public $restrictiononfksoc = 0;
  134. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  135. /**
  136. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  137. */
  138. public $context = array();
  139. /**
  140. * @var string Contains canvas name if record is an alternative canvas record
  141. */
  142. public $canvas;
  143. /**
  144. * @var Project The related project object
  145. * @see fetch_projet()
  146. */
  147. public $project;
  148. /**
  149. * @var int The related project ID
  150. * @see setProject(), project
  151. */
  152. public $fk_project;
  153. /**
  154. * @deprecated
  155. * @see project
  156. */
  157. public $projet;
  158. /**
  159. * @deprecated
  160. * @see $fk_project
  161. */
  162. public $fk_projet;
  163. /**
  164. * @var Contact A related contact object
  165. * @see fetch_contact()
  166. */
  167. public $contact;
  168. /**
  169. * @var int The related contact ID
  170. * @see fetch_contact()
  171. */
  172. public $contact_id;
  173. /**
  174. * @var Societe A related thirdparty object
  175. * @see fetch_thirdparty()
  176. */
  177. public $thirdparty;
  178. /**
  179. * @var User A related user
  180. * @see fetch_user()
  181. */
  182. public $user;
  183. /**
  184. * @var string The type of originating object ('commande', 'facture', ...). Note: on some object this field is called $origin_type
  185. * @see fetch_origin()
  186. */
  187. public $origin;
  188. /**
  189. * @var int The id of originating object
  190. * @see fetch_origin()
  191. */
  192. public $origin_id;
  193. /**
  194. * @var string The object's reference
  195. */
  196. public $ref;
  197. /**
  198. * @var string An external reference for the object
  199. */
  200. public $ref_ext;
  201. /**
  202. * @var string The object's previous reference
  203. */
  204. public $ref_previous;
  205. /**
  206. * @var string The object's next reference
  207. */
  208. public $ref_next;
  209. /**
  210. * @var string Ref to store on object to save the new ref to use for example when making a validate() of an object
  211. */
  212. public $newref;
  213. /**
  214. * @var int The object's status. Prefer use of status.
  215. * @see setStatut()
  216. */
  217. public $statut;
  218. /**
  219. * @var int The object's status
  220. * @see setStatut()
  221. */
  222. public $status;
  223. /**
  224. * @var string
  225. * @see getFullAddress()
  226. */
  227. public $country;
  228. /**
  229. * @var int
  230. * @see getFullAddress(), country
  231. */
  232. public $country_id;
  233. /**
  234. * @var string The ISO country code on 2 chars.
  235. * @see getFullAddress(), isInEEC(), country
  236. */
  237. public $country_code;
  238. /**
  239. * @var string
  240. * @see getFullAddress()
  241. */
  242. public $state;
  243. /**
  244. * @var int
  245. * @see getFullAddress(), state
  246. */
  247. public $state_id;
  248. /**
  249. * @var string
  250. * @see getFullAddress(), $state
  251. */
  252. public $state_code;
  253. /**
  254. * @var int
  255. * @see getFullAddress(), $region_code, $region
  256. */
  257. public $region_id;
  258. /**
  259. * @var string
  260. * @see getFullAddress(), $region_id, $region
  261. */
  262. public $region_code;
  263. /**
  264. * @var string
  265. * @see getFullAddress(), $region_id, $region_code
  266. */
  267. public $region;
  268. /**
  269. * @var int
  270. * @see fetch_barcode()
  271. */
  272. public $barcode_type;
  273. /**
  274. * @var string
  275. * @see fetch_barcode(), barcode_type
  276. */
  277. public $barcode_type_code;
  278. /**
  279. * @var string
  280. * @see fetch_barcode(), barcode_type
  281. */
  282. public $barcode_type_label;
  283. /**
  284. * @var string
  285. * @see fetch_barcode(), barcode_type
  286. */
  287. public $barcode_type_coder;
  288. /**
  289. * @var int Payment method ID (cheque, cash, ...)
  290. * @see setPaymentMethods()
  291. */
  292. public $mode_reglement_id;
  293. /**
  294. * @var int Payment terms ID
  295. * @see setPaymentTerms()
  296. */
  297. public $cond_reglement_id;
  298. /**
  299. * @var int Demand reason ID
  300. */
  301. public $demand_reason_id;
  302. /**
  303. * @var int Transport mode ID (For module intracomm report)
  304. * @see setTransportMode()
  305. */
  306. public $transport_mode_id;
  307. /**
  308. * @var int Payment terms ID
  309. * @deprecated Kept for compatibility
  310. * @see cond_reglement_id;
  311. */
  312. public $cond_reglement;
  313. /**
  314. * @var int Delivery address ID
  315. * @see setDeliveryAddress()
  316. * @deprecated
  317. */
  318. public $fk_delivery_address;
  319. /**
  320. * @var int Shipping method ID
  321. * @see setShippingMethod()
  322. */
  323. public $shipping_method_id;
  324. /**
  325. * @var string
  326. * @see SetDocModel()
  327. */
  328. public $model_pdf;
  329. /**
  330. * @var string
  331. * @deprecated
  332. * @see $model_pdf
  333. */
  334. public $modelpdf;
  335. /**
  336. * @var string
  337. * Contains relative path of last generated main file
  338. */
  339. public $last_main_doc;
  340. /**
  341. * @var int Bank account ID sometimes, ID of record into llx_bank sometimes
  342. * @deprecated
  343. * @see $fk_account
  344. */
  345. public $fk_bank;
  346. /**
  347. * @var int Bank account ID
  348. * @see SetBankAccount()
  349. */
  350. public $fk_account;
  351. /**
  352. * @var string Open ID
  353. */
  354. public $openid;
  355. /**
  356. * @var string Public note
  357. * @see update_note()
  358. */
  359. public $note_public;
  360. /**
  361. * @var string Private note
  362. * @see update_note()
  363. */
  364. public $note_private;
  365. /**
  366. * @deprecated
  367. * @see $note_private
  368. */
  369. public $note;
  370. /**
  371. * @var float Total amount before taxes
  372. * @see update_price()
  373. */
  374. public $total_ht;
  375. /**
  376. * @var float Total VAT amount
  377. * @see update_price()
  378. */
  379. public $total_tva;
  380. /**
  381. * @var float Total local tax 1 amount
  382. * @see update_price()
  383. */
  384. public $total_localtax1;
  385. /**
  386. * @var float Total local tax 2 amount
  387. * @see update_price()
  388. */
  389. public $total_localtax2;
  390. /**
  391. * @var float Total amount with taxes
  392. * @see update_price()
  393. */
  394. public $total_ttc;
  395. /**
  396. * @var CommonObjectLine[]
  397. */
  398. public $lines;
  399. /**
  400. * @var mixed Contains comments
  401. * @see fetchComments()
  402. */
  403. public $comments = array();
  404. /**
  405. * @var string The name
  406. */
  407. public $name;
  408. /**
  409. * @var string The lastname
  410. */
  411. public $lastname;
  412. /**
  413. * @var string The firstname
  414. */
  415. public $firstname;
  416. /**
  417. * @var string The civility code, not an integer
  418. */
  419. public $civility_id;
  420. // Dates
  421. /**
  422. * @var integer|string date_creation
  423. */
  424. public $date_creation;
  425. /**
  426. * @var integer|string $date_validation;
  427. */
  428. public $date_validation; // Date validation
  429. /**
  430. * @var integer|string $date_modification;
  431. */
  432. public $date_modification; // Date last change (tms field)
  433. /**
  434. * @var integer|string $date_cloture;
  435. */
  436. public $date_cloture; // Date closing (tms field)
  437. /**
  438. * @var User|int User author/creation
  439. * @TODO Merge with user_creation
  440. */
  441. public $user_author;
  442. /**
  443. * @var User|int User author/creation
  444. * @TODO Remove type id
  445. */
  446. public $user_creation;
  447. /**
  448. * @var int User id author/creation
  449. */
  450. public $user_creation_id;
  451. /**
  452. * @var User|int User of validation
  453. * @TODO Merge with user_validation
  454. */
  455. public $user_valid;
  456. /**
  457. * @var User|int User of validation
  458. * @TODO Remove type id
  459. */
  460. public $user_validation;
  461. /**
  462. * @var int User id of validation
  463. */
  464. public $user_validation_id;
  465. /**
  466. * @var int User id closing object
  467. */
  468. public $user_closing_id;
  469. /**
  470. * @var User|int User last modifier
  471. * @TODO Remove type id
  472. */
  473. public $user_modification;
  474. /**
  475. * @var int User id last modifier
  476. */
  477. public $user_modification_id;
  478. public $next_prev_filter;
  479. /**
  480. * @var int 1 if object is specimen
  481. */
  482. public $specimen = 0;
  483. /**
  484. * @var int Id of contact to send object (used by the trigger of module Agenda)
  485. */
  486. public $sendtoid;
  487. /**
  488. * @var float Amount already paid (used to show correct status)
  489. */
  490. public $alreadypaid;
  491. private $labelStatus;
  492. private $labelStatusShort;
  493. /**
  494. * @var array List of child tables. To test if we can delete object.
  495. */
  496. protected $childtables = array();
  497. /**
  498. * @var array List of child tables. To know object to delete on cascade.
  499. * If name is like '@ClassName:FilePathClass:ParentFkFieldName', it will
  500. * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object.
  501. */
  502. protected $childtablesoncascade = array();
  503. // No constructor as it is an abstract class
  504. /**
  505. * Check an object id/ref exists
  506. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  507. *
  508. * @param string $element String of element ('product', 'facture', ...)
  509. * @param int $id Id of object
  510. * @param string $ref Ref of object to check
  511. * @param string $ref_ext Ref ext of object to check
  512. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  513. */
  514. public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
  515. {
  516. global $db, $conf;
  517. $sql = "SELECT rowid, ref, ref_ext";
  518. $sql .= " FROM " . $db->prefix() . $element;
  519. $sql .= " WHERE entity IN (" . getEntity($element) . ")";
  520. if ($id > 0) {
  521. $sql .= " AND rowid = " . ((int) $id);
  522. } elseif ($ref) {
  523. $sql .= " AND ref = '" . $db->escape($ref) . "'";
  524. } elseif ($ref_ext) {
  525. $sql .= " AND ref_ext = '" . $db->escape($ref_ext) . "'";
  526. } else {
  527. $error = 'ErrorWrongParameters';
  528. dol_print_error(get_class() . "::isExistingObject " . $error, LOG_ERR);
  529. return -1;
  530. }
  531. if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
  532. $sql .= " AND entity = " . ((int) $conf->entity);
  533. }
  534. dol_syslog(get_class() . "::isExistingObject", LOG_DEBUG);
  535. $resql = $db->query($sql);
  536. if ($resql) {
  537. $num = $db->num_rows($resql);
  538. if ($num > 0) {
  539. return 1;
  540. } else {
  541. return 0;
  542. }
  543. }
  544. return -1;
  545. }
  546. /**
  547. * Method to output saved errors
  548. *
  549. * @return string String with errors
  550. */
  551. public function errorsToString()
  552. {
  553. return $this->error . (is_array($this->errors) ? (($this->error != '' ? ', ' : '') . join(', ', $this->errors)) : '');
  554. }
  555. /**
  556. * Return customer ref for screen output.
  557. *
  558. * @param string $objref Customer ref
  559. * @return string Customer ref formated
  560. */
  561. public function getFormatedCustomerRef($objref)
  562. {
  563. global $hookmanager;
  564. $parameters = array('objref' => $objref);
  565. $action = '';
  566. $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  567. if ($reshook > 0) {
  568. return $hookmanager->resArray['objref'];
  569. }
  570. return $objref . (isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  571. }
  572. /**
  573. * Return supplier ref for screen output.
  574. *
  575. * @param string $objref Supplier ref
  576. * @return string Supplier ref formated
  577. */
  578. public function getFormatedSupplierRef($objref)
  579. {
  580. global $hookmanager;
  581. $parameters = array('objref' => $objref);
  582. $action = '';
  583. $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  584. if ($reshook > 0) {
  585. return $hookmanager->resArray['objref'];
  586. }
  587. return $objref . (isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
  588. }
  589. /**
  590. * Return full name (civility+' '+name+' '+lastname)
  591. *
  592. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  593. * @param int $option 0=No option, 1=Add civility
  594. * @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
  595. * @param int $maxlen Maximum length
  596. * @return string String with full name
  597. */
  598. public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
  599. {
  600. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  601. $lastname = $this->lastname;
  602. $firstname = $this->firstname;
  603. if (empty($lastname)) {
  604. $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 : '')))));
  605. }
  606. $ret = '';
  607. if (!empty($option) && !empty($this->civility_code)) {
  608. if ($langs->transnoentitiesnoconv("Civility" . $this->civility_code) != "Civility" . $this->civility_code) {
  609. $ret .= $langs->transnoentitiesnoconv("Civility" . $this->civility_code) . ' ';
  610. } else {
  611. $ret .= $this->civility_code . ' ';
  612. }
  613. }
  614. $ret .= dolGetFirstLastname($firstname, $lastname, $nameorder);
  615. return dol_trunc($ret, $maxlen);
  616. }
  617. /**
  618. * Set to upper or ucwords/lower if needed
  619. *
  620. * @return void;
  621. */
  622. public function setUpperOrLowerCase()
  623. {
  624. global $conf;
  625. if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
  626. $this->lastname = dol_ucwords(dol_strtolower($this->lastname));
  627. $this->firstname = dol_ucwords(dol_strtolower($this->firstname));
  628. $this->name = dol_ucwords(dol_strtolower($this->name));
  629. $this->name_alias = isset($this->name_alias) ? dol_ucwords(dol_strtolower($this->name_alias)) : '';
  630. }
  631. if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
  632. $this->lastname = dol_strtoupper($this->lastname);
  633. $this->name = dol_strtoupper($this->name);
  634. $this->name_alias = dol_strtoupper($this->name_alias);
  635. }
  636. if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
  637. $this->address = dol_strtoupper($this->address);
  638. $this->town = dol_strtoupper($this->town);
  639. }
  640. if (isset($this->email)) {
  641. $this->email = dol_strtolower($this->email);
  642. }
  643. if (isset($this->personal_email)) {
  644. $this->personal_email = dol_strtolower($this->personal_email);
  645. }
  646. }
  647. /**
  648. * Return clicable link of object (with eventually picto)
  649. *
  650. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  651. * @return string HTML Code for Kanban thumb.
  652. */
  653. public function getKanbanView($option = '')
  654. {
  655. $return = '<div class="box-flex-item box-flex-grow-zero">';
  656. $return .= '<div class="info-box info-box-sm">';
  657. $return .= '<span class="info-box-icon bg-infobox-action">';
  658. $return .= img_picto('', $this->picto);
  659. $return .= '</span>';
  660. $return .= '<div class="info-box-content">';
  661. $return .= '<span class="info-box-ref">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref) . '</span>';
  662. if (property_exists($this, 'label')) {
  663. $return .= '<br><span class="info-box-label opacitymedium">' . $this->label . '</span>';
  664. }
  665. if (method_exists($this, 'getLibStatut')) {
  666. $return .= '<br><div class="info-box-status margintoponly">' . $this->getLibStatut(5) . '</div>';
  667. }
  668. $return .= '</div>';
  669. $return .= '</div>';
  670. $return .= '</div>';
  671. return $return;
  672. }
  673. /**
  674. * Return full address of contact
  675. *
  676. * @param int $withcountry 1=Add country into address string
  677. * @param string $sep Separator to use to build string
  678. * @param int $withregion 1=Add region into address string
  679. * @param string $extralangcode User extralanguages as value
  680. * @return string Full address string
  681. */
  682. public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
  683. {
  684. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
  685. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  686. $tmparray = getCountry($this->country_id, 'all');
  687. $this->country_code = $tmparray['code'];
  688. $this->country = $tmparray['label'];
  689. }
  690. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
  691. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  692. $tmparray = getState($this->state_id, 'all', 0, 1);
  693. $this->state_code = $tmparray['code'];
  694. $this->state = $tmparray['label'];
  695. $this->region_code = $tmparray['region_code'];
  696. $this->region = $tmparray['region'];
  697. }
  698. return dol_format_address($this, $withcountry, $sep, '', 0, $extralangcode);
  699. }
  700. /**
  701. * Return full address for banner
  702. *
  703. * @param string $htmlkey HTML id to make banner content unique
  704. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  705. * @return string Full address string
  706. */
  707. public function getBannerAddress($htmlkey, $object)
  708. {
  709. global $conf, $langs, $form, $extralanguages;
  710. $countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  711. $contactid = 0;
  712. $thirdpartyid = 0;
  713. $elementforaltlanguage = $this->element;
  714. if ($this->element == 'societe') {
  715. $thirdpartyid = $this->id;
  716. }
  717. if ($this->element == 'contact') {
  718. $contactid = $this->id;
  719. $thirdpartyid = empty($this->fk_soc) ? 0 : $this->fk_soc;
  720. }
  721. if ($this->element == 'user') {
  722. $contactid = $this->contact_id;
  723. $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
  724. }
  725. $out = '';
  726. $outdone = 0;
  727. $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
  728. if ($coords) {
  729. if (!empty($conf->use_javascript_ajax)) {
  730. // Add picto with tooltip on map
  731. $namecoords = '';
  732. if ($this->element == 'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
  733. $namecoords .= $object->name . '<br>';
  734. }
  735. $namecoords .= $this->getFullName($langs, 1) . '<br>' . $coords;
  736. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  737. $out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\'' . dol_escape_js($namecoords) . '\',\'' . dol_escape_js($langs->trans("HelpCopyToClipboard")) . '\');">';
  738. $out .= img_picto($langs->trans("Address"), 'map-marker-alt');
  739. $out .= '</a> ';
  740. }
  741. $address = dol_print_address($coords, 'address_' . $htmlkey . '_' . $this->id, $this->element, $this->id, 1, ', ');
  742. if ($address) {
  743. $out .= $address;
  744. $outdone++;
  745. }
  746. $outdone++;
  747. // List of extra languages
  748. $arrayoflangcode = array();
  749. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  750. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  751. }
  752. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  753. if (!is_object($extralanguages)) {
  754. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  755. $extralanguages = new ExtraLanguages($this->db);
  756. }
  757. $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
  758. if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
  759. $out .= "<!-- alternatelanguage for '" . $elementforaltlanguage . "' set to fields '" . join(',', $extralanguages->attributes[$elementforaltlanguage]) . "' -->\n";
  760. $this->fetchValuesForExtraLanguages();
  761. if (!is_object($form)) {
  762. $form = new Form($this->db);
  763. }
  764. $htmltext = '';
  765. // If there is extra languages
  766. foreach ($arrayoflangcode as $extralangcode) {
  767. $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  768. // This also call dol_format_address()
  769. $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
  770. $htmltext .= $s . dol_print_address($coords, 'address_' . $htmlkey . '_' . $this->id, $this->element, $this->id, 1, ', ');
  771. }
  772. $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  773. }
  774. }
  775. }
  776. // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
  777. if (
  778. !in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)
  779. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state
  780. ) {
  781. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  782. $out .= ($outdone ? ' - ' : '') . $this->region . ' - ' . $this->state;
  783. } else {
  784. $out .= ($outdone ? ' - ' : '') . $this->state;
  785. }
  786. $outdone++;
  787. }
  788. if ($outdone) {
  789. $out = '<div class="address inline-block">' . $out . '</div>';
  790. }
  791. 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)) {
  792. $out .= ($outdone ? '<br>' : '');
  793. }
  794. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  795. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  796. $outdone++;
  797. }
  798. if (!empty($this->phone_pro)) {
  799. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  800. $outdone++;
  801. }
  802. if (!empty($this->phone_mobile)) {
  803. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  804. $outdone++;
  805. }
  806. if (!empty($this->phone_perso)) {
  807. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  808. $outdone++;
  809. }
  810. if (!empty($this->office_phone)) {
  811. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  812. $outdone++;
  813. }
  814. if (!empty($this->user_mobile)) {
  815. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  816. $outdone++;
  817. }
  818. if (!empty($this->fax)) {
  819. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  820. $outdone++;
  821. }
  822. if (!empty($this->office_fax)) {
  823. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  824. $outdone++;
  825. }
  826. if ($out) {
  827. $out .= '<div style="clear: both;"></div>';
  828. }
  829. $outdone = 0;
  830. if (!empty($this->email)) {
  831. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  832. $outdone++;
  833. }
  834. if (!empty($this->url)) {
  835. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  836. $out .= dol_print_url($this->url, '_blank', 0, 1);
  837. $outdone++;
  838. }
  839. if (isModEnabled('socialnetworks')) {
  840. $outsocialnetwork = '';
  841. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  842. $socialnetworksdict = getArrayOfSocialNetworks();
  843. foreach ($this->socialnetworks as $key => $value) {
  844. if ($value) {
  845. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  846. }
  847. $outdone++;
  848. }
  849. } else { // Old code to remove
  850. if (!empty($this->skype)) {
  851. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  852. }
  853. $outdone++;
  854. if (!empty($this->jabberid)) {
  855. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  856. }
  857. $outdone++;
  858. if (!empty($this->twitter)) {
  859. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  860. }
  861. $outdone++;
  862. if (!empty($this->facebook)) {
  863. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  864. }
  865. $outdone++;
  866. if (!empty($this->linkedin)) {
  867. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  868. }
  869. $outdone++;
  870. }
  871. if ($outsocialnetwork) {
  872. $out .= '<div style="clear: both;">' . $outsocialnetwork . '</div>';
  873. }
  874. }
  875. if ($out) {
  876. return '<!-- BEGIN part to show address block -->' . "\n" . $out . '<!-- END Part to show address block -->' . "\n";
  877. } else {
  878. return '';
  879. }
  880. }
  881. /**
  882. * Return the link of last main doc file for direct public download.
  883. *
  884. * @param string $modulepart Module related to document
  885. * @param int $initsharekey Init the share key if it was not yet defined
  886. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  887. * @return string Link or empty string if there is no download link
  888. */
  889. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  890. {
  891. global $user, $dolibarr_main_url_root;
  892. if (empty($this->last_main_doc)) {
  893. return ''; // No way to known which document name to use
  894. }
  895. include_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
  896. $ecmfile = new EcmFiles($this->db);
  897. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  898. if ($result < 0) {
  899. $this->error = $ecmfile->error;
  900. $this->errors = $ecmfile->errors;
  901. return -1;
  902. }
  903. if (empty($ecmfile->id)) {
  904. // Add entry into index
  905. if ($initsharekey) {
  906. require_once DOL_DOCUMENT_ROOT . '/core/lib/security2.lib.php';
  907. // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
  908. /*
  909. $ecmfile->filepath = $rel_dir;
  910. $ecmfile->filename = $filename;
  911. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  912. $ecmfile->fullpath_orig = '';
  913. $ecmfile->gen_or_uploaded = 'generated';
  914. $ecmfile->description = ''; // indexed content
  915. $ecmfile->keywords = ''; // keyword content
  916. $ecmfile->share = getRandomPassword(true);
  917. $result = $ecmfile->create($user);
  918. if ($result < 0)
  919. {
  920. $this->error = $ecmfile->error;
  921. $this->errors = $ecmfile->errors;
  922. }
  923. */
  924. } else {
  925. return '';
  926. }
  927. } elseif (empty($ecmfile->share)) {
  928. // Add entry into index
  929. if ($initsharekey) {
  930. require_once DOL_DOCUMENT_ROOT . '/core/lib/security2.lib.php';
  931. $ecmfile->share = getRandomPassword(true);
  932. $ecmfile->update($user);
  933. } else {
  934. return '';
  935. }
  936. }
  937. // Define $urlwithroot
  938. $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($dolibarr_main_url_root));
  939. // This is to use external domain name found into config file
  940. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  941. //else
  942. $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT;
  943. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  944. $forcedownload = 0;
  945. $paramlink = '';
  946. //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  947. //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  948. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  949. if (!empty($ecmfile->share)) {
  950. $paramlink .= ($paramlink ? '&' : '') . 'hashp=' . $ecmfile->share; // Hash for public share
  951. }
  952. if ($forcedownload) {
  953. $paramlink .= ($paramlink ? '&' : '') . 'attachment=1';
  954. }
  955. if ($relativelink) {
  956. $linktoreturn = 'document.php' . ($paramlink ? '?' . $paramlink : '');
  957. } else {
  958. $linktoreturn = $urlwithroot . '/document.php' . ($paramlink ? '?' . $paramlink : '');
  959. }
  960. // Here $ecmfile->share is defined
  961. return $linktoreturn;
  962. }
  963. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  964. /**
  965. * Add a link between element $this->element and a contact
  966. *
  967. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  968. * @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
  969. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  970. * @param int $notrigger Disable all triggers
  971. * @return int <0 if KO, 0 if already added, >0 if OK
  972. */
  973. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  974. {
  975. // phpcs:enable
  976. global $user, $langs;
  977. dol_syslog(get_class($this) . "::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  978. // Check parameters
  979. if ($fk_socpeople <= 0) {
  980. $langs->load("errors");
  981. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  982. dol_syslog(get_class($this) . "::add_contact " . $this->error, LOG_ERR);
  983. return -1;
  984. }
  985. if (!$type_contact) {
  986. $langs->load("errors");
  987. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  988. dol_syslog(get_class($this) . "::add_contact " . $this->error, LOG_ERR);
  989. return -2;
  990. }
  991. $id_type_contact = 0;
  992. if (is_numeric($type_contact)) {
  993. $id_type_contact = $type_contact;
  994. } else {
  995. // We look for id type_contact
  996. $sql = "SELECT tc.rowid";
  997. $sql .= " FROM " . $this->db->prefix() . "c_type_contact as tc";
  998. $sql .= " WHERE tc.element='" . $this->db->escape($this->element) . "'";
  999. $sql .= " AND tc.source='" . $this->db->escape($source) . "'";
  1000. $sql .= " AND tc.code='" . $this->db->escape($type_contact) . "' AND tc.active=1";
  1001. //print $sql;
  1002. $resql = $this->db->query($sql);
  1003. if ($resql) {
  1004. $obj = $this->db->fetch_object($resql);
  1005. if ($obj) {
  1006. $id_type_contact = $obj->rowid;
  1007. }
  1008. }
  1009. }
  1010. if ($id_type_contact == 0) {
  1011. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  1012. 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");
  1013. return -3;
  1014. }
  1015. $datecreate = dol_now();
  1016. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  1017. $TListeContacts = $this->liste_contact(-1, $source);
  1018. $already_added = false;
  1019. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  1020. foreach ($TListeContacts as $array_contact) {
  1021. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  1022. $already_added = true;
  1023. break;
  1024. }
  1025. }
  1026. }
  1027. if (!$already_added) {
  1028. $this->db->begin();
  1029. // Insert into database
  1030. $sql = "INSERT INTO " . $this->db->prefix() . "element_contact";
  1031. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  1032. $sql .= " VALUES (" . $this->id . ", " . ((int) $fk_socpeople) . " , ";
  1033. $sql .= "'" . $this->db->idate($datecreate) . "'";
  1034. $sql .= ", 4, " . ((int) $id_type_contact);
  1035. $sql .= ")";
  1036. $resql = $this->db->query($sql);
  1037. if ($resql) {
  1038. if (!$notrigger) {
  1039. $result = $this->call_trigger(strtoupper($this->element) . '_ADD_CONTACT', $user);
  1040. if ($result < 0) {
  1041. $this->db->rollback();
  1042. return -1;
  1043. }
  1044. }
  1045. $this->db->commit();
  1046. return 1;
  1047. } else {
  1048. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1049. $this->error = $this->db->errno();
  1050. $this->db->rollback();
  1051. return -2;
  1052. } else {
  1053. $this->error = $this->db->lasterror();
  1054. $this->db->rollback();
  1055. return -1;
  1056. }
  1057. }
  1058. } else {
  1059. return 0;
  1060. }
  1061. }
  1062. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1063. /**
  1064. * Copy contact from one element to current
  1065. *
  1066. * @param CommonObject $objFrom Source element
  1067. * @param string $source Nature of contact ('internal' or 'external')
  1068. * @return int >0 if OK, <0 if KO
  1069. */
  1070. public function copy_linked_contact($objFrom, $source = 'internal')
  1071. {
  1072. // phpcs:enable
  1073. $contacts = $objFrom->liste_contact(-1, $source);
  1074. foreach ($contacts as $contact) {
  1075. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  1076. return -1;
  1077. }
  1078. }
  1079. return 1;
  1080. }
  1081. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1082. /**
  1083. * Update a link to contact line
  1084. *
  1085. * @param int $rowid Id of line contact-element
  1086. * @param int $statut New status of link
  1087. * @param int $type_contact_id Id of contact type (not modified if 0)
  1088. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1089. * @return int <0 if KO, >= 0 if OK
  1090. */
  1091. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1092. {
  1093. // phpcs:enable
  1094. // Insert into database
  1095. $sql = "UPDATE " . $this->db->prefix() . "element_contact set";
  1096. $sql .= " statut = " . $statut;
  1097. if ($type_contact_id) {
  1098. $sql .= ", fk_c_type_contact = " . ((int) $type_contact_id);
  1099. }
  1100. if ($fk_socpeople) {
  1101. $sql .= ", fk_socpeople = " . ((int) $fk_socpeople);
  1102. }
  1103. $sql .= " where rowid = " . ((int) $rowid);
  1104. $resql = $this->db->query($sql);
  1105. if ($resql) {
  1106. return 0;
  1107. } else {
  1108. $this->error = $this->db->lasterror();
  1109. return -1;
  1110. }
  1111. }
  1112. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1113. /**
  1114. * Delete a link to contact line
  1115. *
  1116. * @param int $rowid Id of contact link line to delete
  1117. * @param int $notrigger Disable all triggers
  1118. * @return int >0 if OK, <0 if KO
  1119. */
  1120. public function delete_contact($rowid, $notrigger = 0)
  1121. {
  1122. // phpcs:enable
  1123. global $user;
  1124. $this->db->begin();
  1125. $sql = "DELETE FROM " . $this->db->prefix() . "element_contact";
  1126. $sql .= " WHERE rowid = " . ((int) $rowid);
  1127. dol_syslog(get_class($this) . "::delete_contact", LOG_DEBUG);
  1128. if ($this->db->query($sql)) {
  1129. if (!$notrigger) {
  1130. $result = $this->call_trigger(strtoupper($this->element) . '_DELETE_CONTACT', $user);
  1131. if ($result < 0) {
  1132. $this->db->rollback();
  1133. return -1;
  1134. }
  1135. }
  1136. $this->db->commit();
  1137. return 1;
  1138. } else {
  1139. $this->error = $this->db->lasterror();
  1140. $this->db->rollback();
  1141. return -1;
  1142. }
  1143. }
  1144. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1145. /**
  1146. * Delete all links between an object $this and all its contacts in llx_element_contact
  1147. *
  1148. * @param string $source '' or 'internal' or 'external'
  1149. * @param string $code Type of contact (code or id)
  1150. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1151. */
  1152. public function delete_linked_contact($source = '', $code = '')
  1153. {
  1154. // phpcs:enable
  1155. $listId = '';
  1156. $temp = array();
  1157. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1158. if (!empty($typeContact)) {
  1159. foreach ($typeContact as $key => $value) {
  1160. array_push($temp, $key);
  1161. }
  1162. $listId = implode(",", $temp);
  1163. }
  1164. // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
  1165. // any type or record instead of only the ones of the current object. So we do nothing in such a case.
  1166. if (empty($listId)) {
  1167. return 0;
  1168. }
  1169. $sql = "DELETE FROM " . $this->db->prefix() . "element_contact";
  1170. $sql .= " WHERE element_id = " . ((int) $this->id);
  1171. $sql .= " AND fk_c_type_contact IN (" . $this->db->sanitize($listId) . ")";
  1172. dol_syslog(get_class($this) . "::delete_linked_contact", LOG_DEBUG);
  1173. if ($this->db->query($sql)) {
  1174. return 1;
  1175. } else {
  1176. $this->error = $this->db->lasterror();
  1177. return -1;
  1178. }
  1179. }
  1180. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1181. /**
  1182. * Get array of all contacts for an object
  1183. *
  1184. * @param int $statusoflink Status of links to get (-1=all). Not used.
  1185. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1186. * @param int $list 0:Returned array contains all properties, 1:Return array contains just id
  1187. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1188. * @param int $status Status of user or company
  1189. * @param array $arrayoftcids Array with ID of type of contacts. If we provide this, we can make a ec.fk_c_type_contact in ($arrayoftcids) to avoid link on tc table. TODO Not implemented.
  1190. * @return array|int Array of contacts, -1 if error
  1191. */
  1192. public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
  1193. {
  1194. // phpcs:enable
  1195. global $langs;
  1196. $tab = array();
  1197. $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
  1198. if ($source == 'internal') {
  1199. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1200. }
  1201. if ($source == 'external' || $source == 'thirdparty') {
  1202. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1203. }
  1204. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1205. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1206. $sql .= " FROM " . $this->db->prefix() . "c_type_contact tc";
  1207. $sql .= ", " . $this->db->prefix() . "element_contact ec";
  1208. if ($source == 'internal') { // internal contact (user)
  1209. $sql .= " LEFT JOIN " . $this->db->prefix() . "user t on ec.fk_socpeople = t.rowid";
  1210. }
  1211. if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
  1212. $sql .= " LEFT JOIN " . $this->db->prefix() . "socpeople t on ec.fk_socpeople = t.rowid";
  1213. }
  1214. $sql .= " WHERE ec.element_id = " . ((int) $this->id);
  1215. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1216. $sql .= " AND tc.element = '" . $this->db->escape($this->element) . "'";
  1217. if ($code) {
  1218. $sql .= " AND tc.code = '" . $this->db->escape($code) . "'";
  1219. }
  1220. if ($source == 'internal') {
  1221. $sql .= " AND tc.source = 'internal'";
  1222. if ($status >= 0) {
  1223. $sql .= " AND t.statut = " . ((int) $status);
  1224. }
  1225. }
  1226. if ($source == 'external' || $source == 'thirdparty') {
  1227. $sql .= " AND tc.source = 'external'";
  1228. if ($status >= 0) {
  1229. $sql .= " AND t.statut = " . ((int) $status); // t is llx_socpeople
  1230. }
  1231. }
  1232. $sql .= " AND tc.active = 1";
  1233. if ($statusoflink >= 0) {
  1234. $sql .= " AND ec.statut = " . ((int) $statusoflink);
  1235. }
  1236. $sql .= " ORDER BY t.lastname ASC";
  1237. dol_syslog(get_class($this) . "::liste_contact", LOG_DEBUG);
  1238. $resql = $this->db->query($sql);
  1239. if ($resql) {
  1240. $num = $this->db->num_rows($resql);
  1241. $i = 0;
  1242. while ($i < $num) {
  1243. $obj = $this->db->fetch_object($resql);
  1244. if (!$list) {
  1245. $transkey = "TypeContact_" . $obj->element . "_" . $obj->source . "_" . $obj->code;
  1246. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1247. $tab[$i] = array(
  1248. 'source' => $obj->source,
  1249. 'socid' => $obj->socid,
  1250. 'id' => $obj->id,
  1251. 'nom' => $obj->lastname, // For backward compatibility
  1252. 'civility' => $obj->civility,
  1253. 'lastname' => $obj->lastname,
  1254. 'firstname' => $obj->firstname,
  1255. 'email' => $obj->email,
  1256. 'login' => (empty($obj->login) ? '' : $obj->login),
  1257. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1258. 'statuscontact' => $obj->statuscontact,
  1259. 'rowid' => $obj->rowid,
  1260. 'code' => $obj->code,
  1261. 'libelle' => $libelle_type,
  1262. 'status' => $obj->statuslink,
  1263. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1264. );
  1265. } else {
  1266. $tab[$i] = $obj->id;
  1267. }
  1268. $i++;
  1269. }
  1270. return $tab;
  1271. } else {
  1272. $this->error = $this->db->lasterror();
  1273. dol_print_error($this->db);
  1274. return -1;
  1275. }
  1276. }
  1277. /**
  1278. * Update status of a contact linked to object
  1279. *
  1280. * @param int $rowid Id of link between object and contact
  1281. * @return int <0 if KO, >=0 if OK
  1282. */
  1283. public function swapContactStatus($rowid)
  1284. {
  1285. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1286. $sql .= " tc.code, tc.libelle";
  1287. $sql .= " FROM (" . $this->db->prefix() . "element_contact as ec, " . $this->db->prefix() . "c_type_contact as tc)";
  1288. $sql .= " WHERE ec.rowid =" . ((int) $rowid);
  1289. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1290. $sql .= " AND tc.element = '" . $this->db->escape($this->element) . "'";
  1291. dol_syslog(get_class($this) . "::swapContactStatus", LOG_DEBUG);
  1292. $resql = $this->db->query($sql);
  1293. if ($resql) {
  1294. $obj = $this->db->fetch_object($resql);
  1295. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1296. $result = $this->update_contact($rowid, $newstatut);
  1297. $this->db->free($resql);
  1298. return $result;
  1299. } else {
  1300. $this->error = $this->db->error();
  1301. dol_print_error($this->db);
  1302. return -1;
  1303. }
  1304. }
  1305. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1306. /**
  1307. * Return array with list of possible values for type of contacts
  1308. *
  1309. * @param string $source 'internal', 'external' or 'all'
  1310. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1311. * @param int $option 0=Return array id->label, 1=Return array code->label
  1312. * @param int $activeonly 0=all status of contact, 1=only the active
  1313. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1314. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1315. */
  1316. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1317. {
  1318. // phpcs:enable
  1319. global $langs;
  1320. if (empty($order)) {
  1321. $order = 'position';
  1322. }
  1323. if ($order == 'position') {
  1324. $order .= ',code';
  1325. }
  1326. $tab = array();
  1327. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1328. $sql .= " FROM " . $this->db->prefix() . "c_type_contact as tc";
  1329. $sql .= " WHERE tc.element='" . $this->db->escape($this->element) . "'";
  1330. if ($activeonly == 1) {
  1331. $sql .= " AND tc.active=1"; // only the active types
  1332. }
  1333. if (!empty($source) && $source != 'all') {
  1334. $sql .= " AND tc.source='" . $this->db->escape($source) . "'";
  1335. }
  1336. if (!empty($code)) {
  1337. $sql .= " AND tc.code='" . $this->db->escape($code) . "'";
  1338. }
  1339. $sql .= $this->db->order($order, 'ASC');
  1340. //print "sql=".$sql;
  1341. $resql = $this->db->query($sql);
  1342. if ($resql) {
  1343. $num = $this->db->num_rows($resql);
  1344. $i = 0;
  1345. while ($i < $num) {
  1346. $obj = $this->db->fetch_object($resql);
  1347. $transkey = "TypeContact_" . $this->element . "_" . $source . "_" . $obj->code;
  1348. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1349. if (empty($option)) {
  1350. $tab[$obj->rowid] = $libelle_type;
  1351. } else {
  1352. $tab[$obj->code] = $libelle_type;
  1353. }
  1354. $i++;
  1355. }
  1356. return $tab;
  1357. } else {
  1358. $this->error = $this->db->lasterror();
  1359. //dol_print_error($this->db);
  1360. return null;
  1361. }
  1362. }
  1363. /**
  1364. * Return array with list of possible values for type of contacts
  1365. *
  1366. * @param string $source 'internal', 'external' or 'all'
  1367. * @param int $option 0=Return array id->label, 1=Return array code->label
  1368. * @param int $activeonly 0=all status of contact, 1=only the active
  1369. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1370. * @param string $element Filter on 1 element type
  1371. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1372. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1373. */
  1374. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1375. {
  1376. global $langs, $conf;
  1377. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1378. $tab = array();
  1379. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1380. $sql .= " FROM " . $this->db->prefix() . "c_type_contact as tc";
  1381. $sqlWhere = array();
  1382. if (!empty($element)) {
  1383. $sqlWhere[] = " tc.element='" . $this->db->escape($element) . "'";
  1384. }
  1385. if (!empty($excludeelement)) {
  1386. $sqlWhere[] = " tc.element <> '" . $this->db->escape($excludeelement) . "'";
  1387. }
  1388. if ($activeonly == 1) {
  1389. $sqlWhere[] = " tc.active=1"; // only the active types
  1390. }
  1391. if (!empty($source) && $source != 'all') {
  1392. $sqlWhere[] = " tc.source='" . $this->db->escape($source) . "'";
  1393. }
  1394. if (!empty($code)) {
  1395. $sqlWhere[] = " tc.code='" . $this->db->escape($code) . "'";
  1396. }
  1397. if (count($sqlWhere) > 0) {
  1398. $sql .= " WHERE " . implode(' AND ', $sqlWhere);
  1399. }
  1400. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1401. dol_syslog(__METHOD__, LOG_DEBUG);
  1402. $resql = $this->db->query($sql);
  1403. if ($resql) {
  1404. $num = $this->db->num_rows($resql);
  1405. if ($num > 0) {
  1406. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1407. while ($obj = $this->db->fetch_object($resql)) {
  1408. $modulename = $obj->element;
  1409. if (strpos($obj->element, 'project') !== false) {
  1410. $modulename = 'projet';
  1411. } elseif ($obj->element == 'contrat') {
  1412. $element = 'contract';
  1413. } elseif ($obj->element == 'action') {
  1414. $modulename = 'agenda';
  1415. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1416. $modulename = 'fournisseur';
  1417. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1418. $modulename = 'fournisseur';
  1419. }
  1420. if (!empty($conf->{$modulename}->enabled)) {
  1421. $libelle_element = $langs->trans('ContactDefault_' . $obj->element);
  1422. $tmpelement = $obj->element;
  1423. $transkey = "TypeContact_" . $tmpelement . "_" . $source . "_" . $obj->code;
  1424. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1425. if (empty($option)) {
  1426. $tab[$obj->rowid] = $libelle_element . ' - ' . $libelle_type;
  1427. } else {
  1428. $tab[$obj->rowid] = $libelle_element . ' - ' . $libelle_type;
  1429. }
  1430. }
  1431. }
  1432. }
  1433. return $tab;
  1434. } else {
  1435. $this->error = $this->db->lasterror();
  1436. return null;
  1437. }
  1438. }
  1439. /**
  1440. * Return id of contacts for a source and a contact code.
  1441. * Example: contact client de facturation ('external', 'BILLING')
  1442. * Example: contact client de livraison ('external', 'SHIPPING')
  1443. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1444. *
  1445. * @param string $source 'external' or 'internal'
  1446. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1447. * @param int $status limited to a certain status
  1448. * @return array List of id for such contacts
  1449. */
  1450. public function getIdContact($source, $code, $status = 0)
  1451. {
  1452. global $conf;
  1453. $result = array();
  1454. $i = 0;
  1455. //cas particulier pour les expeditions
  1456. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1457. $id = $this->origin_id;
  1458. $element = 'commande';
  1459. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1460. $id = $this->origin_id;
  1461. $element = 'order_supplier';
  1462. } else {
  1463. $id = $this->id;
  1464. $element = $this->element;
  1465. }
  1466. $sql = "SELECT ec.fk_socpeople";
  1467. $sql .= " FROM " . $this->db->prefix() . "element_contact as ec,";
  1468. if ($source == 'internal') {
  1469. $sql .= " " . $this->db->prefix() . "user as c,";
  1470. }
  1471. if ($source == 'external') {
  1472. $sql .= " " . $this->db->prefix() . "socpeople as c,";
  1473. }
  1474. $sql .= " " . $this->db->prefix() . "c_type_contact as tc";
  1475. $sql .= " WHERE ec.element_id = " . ((int) $id);
  1476. $sql .= " AND ec.fk_socpeople = c.rowid";
  1477. if ($source == 'internal') {
  1478. $sql .= " AND c.entity IN (" . getEntity('user') . ")";
  1479. }
  1480. if ($source == 'external') {
  1481. $sql .= " AND c.entity IN (" . getEntity('societe') . ")";
  1482. }
  1483. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1484. $sql .= " AND tc.element = '" . $this->db->escape($element) . "'";
  1485. $sql .= " AND tc.source = '" . $this->db->escape($source) . "'";
  1486. if ($code) {
  1487. $sql .= " AND tc.code = '" . $this->db->escape($code) . "'";
  1488. }
  1489. $sql .= " AND tc.active = 1";
  1490. if ($status) {
  1491. $sql .= " AND ec.statut = " . ((int) $status);
  1492. }
  1493. dol_syslog(get_class($this) . "::getIdContact", LOG_DEBUG);
  1494. $resql = $this->db->query($sql);
  1495. if ($resql) {
  1496. while ($obj = $this->db->fetch_object($resql)) {
  1497. $result[$i] = $obj->fk_socpeople;
  1498. $i++;
  1499. }
  1500. } else {
  1501. $this->error = $this->db->error();
  1502. return null;
  1503. }
  1504. return $result;
  1505. }
  1506. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1507. /**
  1508. * Load object contact with id=$this->contact_id into $this->contact
  1509. *
  1510. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1511. * @return int <0 if KO, >0 if OK
  1512. */
  1513. public function fetch_contact($contactid = null)
  1514. {
  1515. // phpcs:enable
  1516. if (empty($contactid)) {
  1517. $contactid = $this->contact_id;
  1518. }
  1519. if (empty($contactid)) {
  1520. return 0;
  1521. }
  1522. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  1523. $contact = new Contact($this->db);
  1524. $result = $contact->fetch($contactid);
  1525. $this->contact = $contact;
  1526. return $result;
  1527. }
  1528. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1529. /**
  1530. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1531. *
  1532. * @param int $force_thirdparty_id Force thirdparty id
  1533. * @return int <0 if KO, >0 if OK
  1534. */
  1535. public function fetch_thirdparty($force_thirdparty_id = 0)
  1536. {
  1537. // phpcs:enable
  1538. global $conf;
  1539. if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
  1540. return 0;
  1541. }
  1542. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  1543. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
  1544. if ($force_thirdparty_id) {
  1545. $idtofetch = $force_thirdparty_id;
  1546. }
  1547. if ($idtofetch) {
  1548. $thirdparty = new Societe($this->db);
  1549. $result = $thirdparty->fetch($idtofetch);
  1550. if ($result < 0) {
  1551. $this->errors = array_merge($this->errors, $thirdparty->errors);
  1552. }
  1553. $this->thirdparty = $thirdparty;
  1554. // Use first price level if level not defined for third party
  1555. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1556. $this->thirdparty->price_level = 1;
  1557. }
  1558. return $result;
  1559. } else {
  1560. return -1;
  1561. }
  1562. }
  1563. /**
  1564. * Looks for an object with ref matching the wildcard provided
  1565. * It does only work when $this->table_ref_field is set
  1566. *
  1567. * @param string $ref Wildcard
  1568. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1569. */
  1570. public function fetchOneLike($ref)
  1571. {
  1572. if (!$this->table_ref_field) {
  1573. return 0;
  1574. }
  1575. $sql = "SELECT rowid FROM " . $this->db->prefix() . $this->table_element . " WHERE " . $this->table_ref_field . " LIKE '" . $this->db->escape($ref) . "' LIMIT 1";
  1576. $query = $this->db->query($sql);
  1577. if (!$this->db->num_rows($query)) {
  1578. return 0;
  1579. }
  1580. $result = $this->db->fetch_object($query);
  1581. return $this->fetch($result->rowid);
  1582. }
  1583. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1584. /**
  1585. * Load data for barcode into properties ->barcode_type*
  1586. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1587. * if it is not defined, ->element must be defined to know default barcode type.
  1588. *
  1589. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1590. */
  1591. public function fetch_barcode()
  1592. {
  1593. // phpcs:enable
  1594. global $conf;
  1595. dol_syslog(get_class($this) . '::fetch_barcode this->element=' . $this->element . ' this->barcode_type=' . $this->barcode_type);
  1596. $idtype = $this->barcode_type;
  1597. 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
  1598. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1599. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1600. } elseif ($this->element == 'societe') {
  1601. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1602. } else {
  1603. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1604. }
  1605. }
  1606. if ($idtype > 0) {
  1607. 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
  1608. $sql = "SELECT rowid, code, libelle as label, coder";
  1609. $sql .= " FROM " . $this->db->prefix() . "c_barcode_type";
  1610. $sql .= " WHERE rowid = " . ((int) $idtype);
  1611. dol_syslog(get_class($this) . '::fetch_barcode', LOG_DEBUG);
  1612. $resql = $this->db->query($sql);
  1613. if ($resql) {
  1614. $obj = $this->db->fetch_object($resql);
  1615. $this->barcode_type = $obj->rowid;
  1616. $this->barcode_type_code = $obj->code;
  1617. $this->barcode_type_label = $obj->label;
  1618. $this->barcode_type_coder = $obj->coder;
  1619. return 1;
  1620. } else {
  1621. dol_print_error($this->db);
  1622. return -1;
  1623. }
  1624. }
  1625. }
  1626. return 0;
  1627. }
  1628. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1629. /**
  1630. * Load the project with id $this->fk_project into this->project
  1631. *
  1632. * @return int <0 if KO, >=0 if OK
  1633. */
  1634. public function fetch_project()
  1635. {
  1636. // phpcs:enable
  1637. return $this->fetch_projet();
  1638. }
  1639. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1640. /**
  1641. * Load the project with id $this->fk_project into this->project
  1642. *
  1643. * @return int <0 if KO, >=0 if OK
  1644. */
  1645. public function fetch_projet()
  1646. {
  1647. // phpcs:enable
  1648. include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  1649. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1650. $this->fk_project = $this->fk_projet; // For backward compatibility
  1651. }
  1652. if (empty($this->fk_project)) {
  1653. return 0;
  1654. }
  1655. $project = new Project($this->db);
  1656. $result = $project->fetch($this->fk_project);
  1657. $this->projet = $project; // deprecated
  1658. $this->project = $project;
  1659. return $result;
  1660. }
  1661. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1662. /**
  1663. * Load the product with id $this->fk_product into this->product
  1664. *
  1665. * @return int <0 if KO, >=0 if OK
  1666. */
  1667. public function fetch_product()
  1668. {
  1669. // phpcs:enable
  1670. include_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  1671. if (empty($this->fk_product)) {
  1672. return 0;
  1673. }
  1674. $product = new Product($this->db);
  1675. $result = $product->fetch($this->fk_product);
  1676. $this->product = $product;
  1677. return $result;
  1678. }
  1679. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1680. /**
  1681. * Load the user with id $userid into this->user
  1682. *
  1683. * @param int $userid Id du contact
  1684. * @return int <0 if KO, >0 if OK
  1685. */
  1686. public function fetch_user($userid)
  1687. {
  1688. // phpcs:enable
  1689. $user = new User($this->db);
  1690. $result = $user->fetch($userid);
  1691. $this->user = $user;
  1692. return $result;
  1693. }
  1694. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1695. /**
  1696. * Read linked origin object
  1697. *
  1698. * @return void
  1699. */
  1700. public function fetch_origin()
  1701. {
  1702. // phpcs:enable
  1703. if ($this->origin == 'shipping') {
  1704. $this->origin = 'expedition';
  1705. }
  1706. if ($this->origin == 'delivery') {
  1707. $this->origin = 'livraison';
  1708. }
  1709. if ($this->origin == 'order_supplier') {
  1710. $this->origin = 'commandeFournisseur';
  1711. }
  1712. $origin = $this->origin;
  1713. $classname = ucfirst($origin);
  1714. $this->$origin = new $classname($this->db);
  1715. $this->$origin->fetch($this->origin_id);
  1716. }
  1717. /**
  1718. * Load object from specific field
  1719. *
  1720. * @param string $table Table element or element line
  1721. * @param string $field Field selected
  1722. * @param string $key Import key
  1723. * @param string $element Element name
  1724. * @return int <0 if KO, >0 if OK
  1725. */
  1726. public function fetchObjectFrom($table, $field, $key, $element = null)
  1727. {
  1728. global $conf;
  1729. $result = false;
  1730. $sql = "SELECT rowid FROM " . $this->db->prefix() . $table;
  1731. $sql .= " WHERE " . $field . " = '" . $this->db->escape($key) . "'";
  1732. if (!empty($element)) {
  1733. $sql .= " AND entity IN (" . getEntity($element) . ")";
  1734. } else {
  1735. $sql .= " AND entity = " . ((int) $conf->entity);
  1736. }
  1737. dol_syslog(get_class($this) . '::fetchObjectFrom', LOG_DEBUG);
  1738. $resql = $this->db->query($sql);
  1739. if ($resql) {
  1740. $row = $this->db->fetch_row($resql);
  1741. // Test for avoid error -1
  1742. if ($row[0] > 0) {
  1743. $result = $this->fetch($row[0]);
  1744. }
  1745. }
  1746. return $result;
  1747. }
  1748. /**
  1749. * Getter generic. Load value from a specific field
  1750. *
  1751. * @param string $table Table of element or element line
  1752. * @param int $id Element id
  1753. * @param string $field Field selected
  1754. * @return int <0 if KO, >0 if OK
  1755. */
  1756. public function getValueFrom($table, $id, $field)
  1757. {
  1758. $result = false;
  1759. if (!empty($id) && !empty($field) && !empty($table)) {
  1760. $sql = "SELECT " . $field . " FROM " . $this->db->prefix() . $table;
  1761. $sql .= " WHERE rowid = " . ((int) $id);
  1762. dol_syslog(get_class($this) . '::getValueFrom', LOG_DEBUG);
  1763. $resql = $this->db->query($sql);
  1764. if ($resql) {
  1765. $row = $this->db->fetch_row($resql);
  1766. $result = $row[0];
  1767. }
  1768. }
  1769. return $result;
  1770. }
  1771. /**
  1772. * Setter generic. Update a specific field into database.
  1773. * Warning: Trigger is run only if param trigkey is provided.
  1774. *
  1775. * @param string $field Field to update
  1776. * @param mixed $value New value
  1777. * @param string $table To force other table element or element line (should not be used)
  1778. * @param int $id To force other object id (should not be used)
  1779. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1780. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1781. * @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'
  1782. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1783. * @param string $fk_user_field Name of field to save user id making change
  1784. * @return int <0 if KO, >0 if OK
  1785. * @see updateExtraField()
  1786. */
  1787. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1788. {
  1789. global $user, $langs, $conf;
  1790. if (empty($table)) {
  1791. $table = $this->table_element;
  1792. }
  1793. if (empty($id)) {
  1794. $id = $this->id;
  1795. }
  1796. if (empty($format)) {
  1797. $format = 'text';
  1798. }
  1799. if (empty($id_field)) {
  1800. $id_field = 'rowid';
  1801. }
  1802. $error = 0;
  1803. $this->db->begin();
  1804. // Special case
  1805. if ($table == 'product' && $field == 'note_private') {
  1806. $field = 'note';
  1807. }
  1808. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1809. $fk_user_field = 'fk_user_mod';
  1810. }
  1811. $sql = "UPDATE " . $this->db->prefix() . $table . " SET ";
  1812. if ($format == 'text') {
  1813. $sql .= $field . " = '" . $this->db->escape($value) . "'";
  1814. } elseif ($format == 'int') {
  1815. $sql .= $field . " = " . ((int) $value);
  1816. } elseif ($format == 'date') {
  1817. $sql .= $field . " = " . ($value ? "'" . $this->db->idate($value) . "'" : "null");
  1818. }
  1819. if ($fk_user_field) {
  1820. if (!empty($fuser) && is_object($fuser)) {
  1821. $sql .= ", " . $fk_user_field . " = " . ((int) $fuser->id);
  1822. } elseif (empty($fuser) || $fuser != 'none') {
  1823. $sql .= ", " . $fk_user_field . " = " . ((int) $user->id);
  1824. }
  1825. }
  1826. $sql .= " WHERE " . $id_field . " = " . ((int) $id);
  1827. dol_syslog(__METHOD__ . "", LOG_DEBUG);
  1828. $resql = $this->db->query($sql);
  1829. if ($resql) {
  1830. if ($trigkey) {
  1831. // call trigger with updated object values
  1832. if (method_exists($this, 'fetch')) {
  1833. $result = $this->fetch($id);
  1834. } else {
  1835. $result = $this->fetchCommon($id);
  1836. }
  1837. if ($result >= 0) {
  1838. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1839. }
  1840. if ($result < 0) {
  1841. $error++;
  1842. }
  1843. }
  1844. if (!$error) {
  1845. if (property_exists($this, $field)) {
  1846. $this->$field = $value;
  1847. }
  1848. $this->db->commit();
  1849. return 1;
  1850. } else {
  1851. $this->db->rollback();
  1852. return -2;
  1853. }
  1854. } else {
  1855. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1856. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1857. } else {
  1858. $this->error = $this->db->lasterror();
  1859. }
  1860. $this->db->rollback();
  1861. return -1;
  1862. }
  1863. }
  1864. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1865. /**
  1866. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1867. *
  1868. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1869. * @param string $fieldid Name of field to use for the select MAX and MIN
  1870. * @param int $nodbprefix Do not include DB prefix to forge table name
  1871. * @return int <0 if KO, >0 if OK
  1872. */
  1873. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1874. {
  1875. // phpcs:enable
  1876. global $conf, $user;
  1877. if (!$this->table_element) {
  1878. dol_print_error('', get_class($this) . "::load_previous_next_ref was called on objet with property table_element not defined");
  1879. return -1;
  1880. }
  1881. if ($fieldid == 'none') {
  1882. return 1;
  1883. }
  1884. // For backward compatibility
  1885. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1886. $fieldid = 'titre';
  1887. }
  1888. // Security on socid
  1889. $socid = 0;
  1890. if ($user->socid > 0) {
  1891. $socid = $user->socid;
  1892. }
  1893. // this->ismultientitymanaged contains
  1894. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1895. $aliastablesociete = 's';
  1896. if ($this->element == 'societe') {
  1897. $aliastablesociete = 'te'; // te as table_element
  1898. }
  1899. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1900. $sql = "SELECT MAX(te." . $fieldid . ")";
  1901. $sql .= " FROM " . (empty($nodbprefix) ? $this->db->prefix() : '') . $this->table_element . " as te";
  1902. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1903. $sql .= "," . $this->db->prefix() . "usergroup_user as ug";
  1904. }
  1905. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1906. $tmparray = explode('@', $this->ismultientitymanaged);
  1907. $sql .= ", " . $this->db->prefix() . $tmparray[1] . " as " . ($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1908. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1909. $sql .= ", " . $this->db->prefix() . "societe as s"; // If we need to link to societe to limit select to socid
  1910. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1911. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1912. }
  1913. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1914. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe_commerciaux as sc ON " . $aliastablesociete . ".rowid = sc.fk_soc";
  1915. }
  1916. $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)
  1917. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1918. $sql .= " AND sc.fk_user = " . ((int) $user->id);
  1919. }
  1920. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1921. $sql .= " AND (sc.fk_user = " . ((int) $user->id) . ' OR te.fk_soc IS NULL)';
  1922. }
  1923. if (!empty($filter)) {
  1924. if (!preg_match('/^\s*AND/i', $filter)) {
  1925. $sql .= " AND "; // For backward compatibility
  1926. }
  1927. $sql .= $filter;
  1928. }
  1929. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1930. $tmparray = explode('@', $this->ismultientitymanaged);
  1931. $sql .= " AND te." . $tmparray[0] . " = " . ($tmparray[1] == "societe" ? "s" : "parenttable") . ".rowid"; // If we need to link to this table to limit select to entity
  1932. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1933. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1934. }
  1935. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1936. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1937. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1938. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1939. } else {
  1940. $sql .= " AND ug.fk_user = te.rowid";
  1941. $sql .= " AND ug.entity IN (" . getEntity('usergroup') . ")";
  1942. }
  1943. } else {
  1944. $sql .= ' AND te.entity IN (' . getEntity($this->element) . ')';
  1945. }
  1946. }
  1947. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1948. $tmparray = explode('@', $this->ismultientitymanaged);
  1949. $sql .= ' AND parenttable.entity IN (' . getEntity($tmparray[1]) . ')';
  1950. }
  1951. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1952. $sql .= ' AND te.fk_soc = ' . ((int) $socid);
  1953. }
  1954. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1955. $sql .= ' AND (te.fk_soc = ' . ((int) $socid) . ' OR te.fk_soc IS NULL)';
  1956. }
  1957. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1958. $sql .= ' AND te.rowid = ' . ((int) $socid);
  1959. }
  1960. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1961. $result = $this->db->query($sql);
  1962. if (!$result) {
  1963. $this->error = $this->db->lasterror();
  1964. return -1;
  1965. }
  1966. $row = $this->db->fetch_row($result);
  1967. $this->ref_previous = $row[0];
  1968. $sql = "SELECT MIN(te." . $fieldid . ")";
  1969. $sql .= " FROM " . (empty($nodbprefix) ? $this->db->prefix() : '') . $this->table_element . " as te";
  1970. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1971. $sql .= "," . $this->db->prefix() . "usergroup_user as ug";
  1972. }
  1973. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1974. $tmparray = explode('@', $this->ismultientitymanaged);
  1975. $sql .= ", " . $this->db->prefix() . $tmparray[1] . " as " . ($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
  1976. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1977. $sql .= ", " . $this->db->prefix() . "societe as s"; // If we need to link to societe to limit select to socid
  1978. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1979. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1980. }
  1981. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1982. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe_commerciaux as sc ON " . $aliastablesociete . ".rowid = sc.fk_soc";
  1983. }
  1984. $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)
  1985. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1986. $sql .= " AND sc.fk_user = " . ((int) $user->id);
  1987. }
  1988. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1989. $sql .= " AND (sc.fk_user = " . ((int) $user->id) . ' OR te.fk_soc IS NULL)';
  1990. }
  1991. if (!empty($filter)) {
  1992. if (!preg_match('/^\s*AND/i', $filter)) {
  1993. $sql .= " AND "; // For backward compatibility
  1994. }
  1995. $sql .= $filter;
  1996. }
  1997. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1998. $tmparray = explode('@', $this->ismultientitymanaged);
  1999. $sql .= " AND te." . $tmparray[0] . " = " . ($tmparray[1] == "societe" ? "s" : "parenttable") . ".rowid"; // If we need to link to this table to limit select to entity
  2000. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  2001. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  2002. }
  2003. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  2004. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  2005. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  2006. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  2007. } else {
  2008. $sql .= " AND ug.fk_user = te.rowid";
  2009. $sql .= " AND ug.entity IN (" . getEntity('usergroup') . ")";
  2010. }
  2011. } else {
  2012. $sql .= ' AND te.entity IN (' . getEntity($this->element) . ')';
  2013. }
  2014. }
  2015. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  2016. $tmparray = explode('@', $this->ismultientitymanaged);
  2017. $sql .= ' AND parenttable.entity IN (' . getEntity($tmparray[1]) . ')';
  2018. }
  2019. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  2020. $sql .= ' AND te.fk_soc = ' . ((int) $socid);
  2021. }
  2022. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  2023. $sql .= ' AND (te.fk_soc = ' . ((int) $socid) . ' OR te.fk_soc IS NULL)';
  2024. }
  2025. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  2026. $sql .= ' AND te.rowid = ' . ((int) $socid);
  2027. }
  2028. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  2029. // 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
  2030. $result = $this->db->query($sql);
  2031. if (!$result) {
  2032. $this->error = $this->db->lasterror();
  2033. return -2;
  2034. }
  2035. $row = $this->db->fetch_row($result);
  2036. $this->ref_next = $row[0];
  2037. return 1;
  2038. }
  2039. /**
  2040. * Return list of id of contacts of object
  2041. *
  2042. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  2043. * @return array Array of id of contacts (if source=external or internal)
  2044. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  2045. */
  2046. public function getListContactId($source = 'external')
  2047. {
  2048. $contactAlreadySelected = array();
  2049. $tab = $this->liste_contact(-1, $source);
  2050. $num = count($tab);
  2051. $i = 0;
  2052. while ($i < $num) {
  2053. if ($source == 'thirdparty') {
  2054. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  2055. } else {
  2056. $contactAlreadySelected[$i] = $tab[$i]['id'];
  2057. }
  2058. $i++;
  2059. }
  2060. return $contactAlreadySelected;
  2061. }
  2062. /**
  2063. * Link element with a project
  2064. *
  2065. * @param int $projectid Project id to link element to
  2066. * @param int $notrigger Disable the trigger
  2067. * @return int <0 if KO, >0 if OK
  2068. */
  2069. public function setProject($projectid, $notrigger = 0)
  2070. {
  2071. global $user;
  2072. $error = 0;
  2073. if (!$this->table_element) {
  2074. dol_syslog(get_class($this) . "::setProject was called on objet with property table_element not defined", LOG_ERR);
  2075. return -1;
  2076. }
  2077. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  2078. if (!empty($this->fields['fk_project'])) { // Common case
  2079. if ($projectid) {
  2080. $sql .= " SET fk_project = " . ((int) $projectid);
  2081. } else {
  2082. $sql .= " SET fk_project = NULL";
  2083. }
  2084. $sql .= ' WHERE rowid = ' . ((int) $this->id);
  2085. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  2086. if ($projectid) {
  2087. $sql .= " SET fk_project = " . ((int) $projectid);
  2088. } else {
  2089. $sql .= " SET fk_project = NULL";
  2090. }
  2091. $sql .= ' WHERE id = ' . ((int) $this->id);
  2092. } else // Special case for old architecture objects
  2093. {
  2094. if ($projectid) {
  2095. $sql .= ' SET fk_projet = ' . ((int) $projectid);
  2096. } else {
  2097. $sql .= ' SET fk_projet = NULL';
  2098. }
  2099. $sql .= " WHERE rowid = " . ((int) $this->id);
  2100. }
  2101. $this->db->begin();
  2102. dol_syslog(get_class($this) . "::setProject", LOG_DEBUG);
  2103. if ($this->db->query($sql)) {
  2104. $this->fk_project = ((int) $projectid);
  2105. } else {
  2106. dol_print_error($this->db);
  2107. $error++;
  2108. }
  2109. // Triggers
  2110. if (!$error && !$notrigger) {
  2111. // Call triggers
  2112. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2113. if ($result < 0) {
  2114. $error++;
  2115. } //Do also here what you must do to rollback action if trigger fail
  2116. // End call triggers
  2117. }
  2118. // Commit or rollback
  2119. if ($error) {
  2120. $this->db->rollback();
  2121. return -1;
  2122. } else {
  2123. $this->db->commit();
  2124. return 1;
  2125. }
  2126. }
  2127. /**
  2128. * Change the payments methods
  2129. *
  2130. * @param int $id Id of new payment method
  2131. * @return int >0 if OK, <0 if KO
  2132. */
  2133. public function setPaymentMethods($id)
  2134. {
  2135. global $user;
  2136. $error = 0;
  2137. $notrigger = 0;
  2138. dol_syslog(get_class($this) . '::setPaymentMethods(' . $id . ')');
  2139. if ($this->statut >= 0 || $this->element == 'societe') {
  2140. // TODO uniformize field name
  2141. $fieldname = 'fk_mode_reglement';
  2142. if ($this->element == 'societe') {
  2143. $fieldname = 'mode_reglement';
  2144. }
  2145. if (get_class($this) == 'Fournisseur') {
  2146. $fieldname = 'mode_reglement_supplier';
  2147. }
  2148. if (get_class($this) == 'Tva') {
  2149. $fieldname = 'fk_typepayment';
  2150. }
  2151. if (get_class($this) == 'Salary') {
  2152. $fieldname = 'fk_typepayment';
  2153. }
  2154. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  2155. $sql .= " SET " . $fieldname . " = " . (($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2156. $sql .= ' WHERE rowid=' . ((int) $this->id);
  2157. if ($this->db->query($sql)) {
  2158. $this->mode_reglement_id = $id;
  2159. // for supplier
  2160. if (get_class($this) == 'Fournisseur') {
  2161. $this->mode_reglement_supplier_id = $id;
  2162. }
  2163. // Triggers
  2164. if (!$error && !$notrigger) {
  2165. // Call triggers
  2166. if (get_class($this) == 'Commande') {
  2167. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2168. } else {
  2169. $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $user);
  2170. }
  2171. if ($result < 0) {
  2172. $error++;
  2173. }
  2174. // End call triggers
  2175. }
  2176. return 1;
  2177. } else {
  2178. dol_syslog(get_class($this) . '::setPaymentMethods Error ' . $this->db->error());
  2179. $this->error = $this->db->error();
  2180. return -1;
  2181. }
  2182. } else {
  2183. dol_syslog(get_class($this) . '::setPaymentMethods, status of the object is incompatible');
  2184. $this->error = 'Status of the object is incompatible ' . $this->statut;
  2185. return -2;
  2186. }
  2187. }
  2188. /**
  2189. * Change the multicurrency code
  2190. *
  2191. * @param string $code multicurrency code
  2192. * @return int >0 if OK, <0 if KO
  2193. */
  2194. public function setMulticurrencyCode($code)
  2195. {
  2196. dol_syslog(get_class($this) . '::setMulticurrencyCode(' . $code . ')');
  2197. if ($this->statut >= 0 || $this->element == 'societe') {
  2198. $fieldname = 'multicurrency_code';
  2199. $sql = 'UPDATE ' . $this->db->prefix() . $this->table_element;
  2200. $sql .= " SET " . $fieldname . " = '" . $this->db->escape($code) . "'";
  2201. $sql .= ' WHERE rowid=' . ((int) $this->id);
  2202. if ($this->db->query($sql)) {
  2203. $this->multicurrency_code = $code;
  2204. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2205. if ($rate) {
  2206. $this->setMulticurrencyRate($rate, 2);
  2207. }
  2208. return 1;
  2209. } else {
  2210. dol_syslog(get_class($this) . '::setMulticurrencyCode Error ' . $sql . ' - ' . $this->db->error());
  2211. $this->error = $this->db->error();
  2212. return -1;
  2213. }
  2214. } else {
  2215. dol_syslog(get_class($this) . '::setMulticurrencyCode, status of the object is incompatible');
  2216. $this->error = 'Status of the object is incompatible ' . $this->statut;
  2217. return -2;
  2218. }
  2219. }
  2220. /**
  2221. * Change the multicurrency rate
  2222. *
  2223. * @param double $rate multicurrency rate
  2224. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2225. * @return int >0 if OK, <0 if KO
  2226. */
  2227. public function setMulticurrencyRate($rate, $mode = 1)
  2228. {
  2229. dol_syslog(get_class($this) . '::setMulticurrencyRate(' . $rate . ',' . $mode . ')');
  2230. if ($this->statut >= 0 || $this->element == 'societe') {
  2231. $fieldname = 'multicurrency_tx';
  2232. $sql = 'UPDATE ' . $this->db->prefix() . $this->table_element;
  2233. $sql .= " SET " . $fieldname . " = " . ((float) $rate);
  2234. $sql .= ' WHERE rowid=' . ((int) $this->id);
  2235. if ($this->db->query($sql)) {
  2236. $this->multicurrency_tx = $rate;
  2237. // Update line price
  2238. if (!empty($this->lines)) {
  2239. foreach ($this->lines as &$line) {
  2240. // Amounts in company currency will be recalculated
  2241. if ($mode == 1) {
  2242. $line->subprice = 0;
  2243. }
  2244. // Amounts in foreign currency will be recalculated
  2245. if ($mode == 2) {
  2246. $line->multicurrency_subprice = 0;
  2247. }
  2248. switch ($this->element) {
  2249. case 'propal':
  2250. $this->updateline(
  2251. $line->id,
  2252. $line->subprice,
  2253. $line->qty,
  2254. $line->remise_percent,
  2255. $line->tva_tx,
  2256. $line->localtax1_tx,
  2257. $line->localtax2_tx,
  2258. ($line->description ? $line->description : $line->desc),
  2259. 'HT',
  2260. $line->info_bits,
  2261. $line->special_code,
  2262. $line->fk_parent_line,
  2263. $line->skip_update_total,
  2264. $line->fk_fournprice,
  2265. $line->pa_ht,
  2266. $line->label,
  2267. $line->product_type,
  2268. $line->date_start,
  2269. $line->date_end,
  2270. $line->array_options,
  2271. $line->fk_unit,
  2272. $line->multicurrency_subprice
  2273. );
  2274. break;
  2275. case 'commande':
  2276. $this->updateline(
  2277. $line->id,
  2278. ($line->description ? $line->description : $line->desc),
  2279. $line->subprice,
  2280. $line->qty,
  2281. $line->remise_percent,
  2282. $line->tva_tx,
  2283. $line->localtax1_tx,
  2284. $line->localtax2_tx,
  2285. 'HT',
  2286. $line->info_bits,
  2287. $line->date_start,
  2288. $line->date_end,
  2289. $line->product_type,
  2290. $line->fk_parent_line,
  2291. $line->skip_update_total,
  2292. $line->fk_fournprice,
  2293. $line->pa_ht,
  2294. $line->label,
  2295. $line->special_code,
  2296. $line->array_options,
  2297. $line->fk_unit,
  2298. $line->multicurrency_subprice
  2299. );
  2300. break;
  2301. case 'facture':
  2302. $this->updateline(
  2303. $line->id,
  2304. ($line->description ? $line->description : $line->desc),
  2305. $line->subprice,
  2306. $line->qty,
  2307. $line->remise_percent,
  2308. $line->date_start,
  2309. $line->date_end,
  2310. $line->tva_tx,
  2311. $line->localtax1_tx,
  2312. $line->localtax2_tx,
  2313. 'HT',
  2314. $line->info_bits,
  2315. $line->product_type,
  2316. $line->fk_parent_line,
  2317. $line->skip_update_total,
  2318. $line->fk_fournprice,
  2319. $line->pa_ht,
  2320. $line->label,
  2321. $line->special_code,
  2322. $line->array_options,
  2323. $line->situation_percent,
  2324. $line->fk_unit,
  2325. $line->multicurrency_subprice
  2326. );
  2327. break;
  2328. case 'supplier_proposal':
  2329. $this->updateline(
  2330. $line->id,
  2331. $line->subprice,
  2332. $line->qty,
  2333. $line->remise_percent,
  2334. $line->tva_tx,
  2335. $line->localtax1_tx,
  2336. $line->localtax2_tx,
  2337. ($line->description ? $line->description : $line->desc),
  2338. 'HT',
  2339. $line->info_bits,
  2340. $line->special_code,
  2341. $line->fk_parent_line,
  2342. $line->skip_update_total,
  2343. $line->fk_fournprice,
  2344. $line->pa_ht,
  2345. $line->label,
  2346. $line->product_type,
  2347. $line->array_options,
  2348. $line->ref_fourn,
  2349. $line->multicurrency_subprice
  2350. );
  2351. break;
  2352. case 'order_supplier':
  2353. $this->updateline(
  2354. $line->id,
  2355. ($line->description ? $line->description : $line->desc),
  2356. $line->subprice,
  2357. $line->qty,
  2358. $line->remise_percent,
  2359. $line->tva_tx,
  2360. $line->localtax1_tx,
  2361. $line->localtax2_tx,
  2362. 'HT',
  2363. $line->info_bits,
  2364. $line->product_type,
  2365. false,
  2366. $line->date_start,
  2367. $line->date_end,
  2368. $line->array_options,
  2369. $line->fk_unit,
  2370. $line->multicurrency_subprice,
  2371. $line->ref_supplier
  2372. );
  2373. break;
  2374. case 'invoice_supplier':
  2375. $this->updateline(
  2376. $line->id,
  2377. ($line->description ? $line->description : $line->desc),
  2378. $line->subprice,
  2379. $line->tva_tx,
  2380. $line->localtax1_tx,
  2381. $line->localtax2_tx,
  2382. $line->qty,
  2383. 0,
  2384. 'HT',
  2385. $line->info_bits,
  2386. $line->product_type,
  2387. $line->remise_percent,
  2388. false,
  2389. $line->date_start,
  2390. $line->date_end,
  2391. $line->array_options,
  2392. $line->fk_unit,
  2393. $line->multicurrency_subprice,
  2394. $line->ref_supplier
  2395. );
  2396. break;
  2397. default:
  2398. dol_syslog(get_class($this) . '::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2399. break;
  2400. }
  2401. }
  2402. }
  2403. return 1;
  2404. } else {
  2405. dol_syslog(get_class($this) . '::setMulticurrencyRate Error ' . $sql . ' - ' . $this->db->error());
  2406. $this->error = $this->db->error();
  2407. return -1;
  2408. }
  2409. } else {
  2410. dol_syslog(get_class($this) . '::setMulticurrencyRate, status of the object is incompatible');
  2411. $this->error = 'Status of the object is incompatible ' . $this->statut;
  2412. return -2;
  2413. }
  2414. }
  2415. /**
  2416. * Change the payments terms
  2417. *
  2418. * @param int $id Id of new payment terms
  2419. * @param string $deposit_percent % of deposit if needed by payment terms
  2420. * @return int >0 if OK, <0 if KO
  2421. */
  2422. public function setPaymentTerms($id, $deposit_percent = null)
  2423. {
  2424. dol_syslog(get_class($this) . '::setPaymentTerms(' . $id . ', ' . var_export($deposit_percent, true) . ')');
  2425. if ($this->statut >= 0 || $this->element == 'societe') {
  2426. // TODO uniformize field name
  2427. $fieldname = 'fk_cond_reglement';
  2428. if ($this->element == 'societe') {
  2429. $fieldname = 'cond_reglement';
  2430. }
  2431. if (get_class($this) == 'Fournisseur') {
  2432. $fieldname = 'cond_reglement_supplier';
  2433. }
  2434. if (empty($deposit_percent) || $deposit_percent < 0) {
  2435. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2436. }
  2437. if ($deposit_percent > 100) {
  2438. $deposit_percent = 100;
  2439. }
  2440. $sql = 'UPDATE ' . $this->db->prefix() . $this->table_element;
  2441. $sql .= " SET " . $fieldname . " = " . (($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2442. if (in_array($this->table_element, array('propal', 'commande'))) {
  2443. $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'" . $this->db->escape($deposit_percent) . "'");
  2444. }
  2445. $sql .= ' WHERE rowid=' . ((int) $this->id);
  2446. if ($this->db->query($sql)) {
  2447. $this->cond_reglement_id = $id;
  2448. // for supplier
  2449. if (get_class($this) == 'Fournisseur') {
  2450. $this->cond_reglement_supplier_id = $id;
  2451. }
  2452. $this->cond_reglement = $id; // for compatibility
  2453. $this->deposit_percent = $deposit_percent;
  2454. return 1;
  2455. } else {
  2456. dol_syslog(get_class($this) . '::setPaymentTerms Error ' . $sql . ' - ' . $this->db->error());
  2457. $this->error = $this->db->error();
  2458. return -1;
  2459. }
  2460. } else {
  2461. dol_syslog(get_class($this) . '::setPaymentTerms, status of the object is incompatible');
  2462. $this->error = 'Status of the object is incompatible ' . $this->statut;
  2463. return -2;
  2464. }
  2465. }
  2466. /**
  2467. * Change the transport mode methods
  2468. *
  2469. * @param int $id Id of transport mode
  2470. * @return int >0 if OK, <0 if KO
  2471. */
  2472. public function setTransportMode($id)
  2473. {
  2474. dol_syslog(get_class($this) . '::setTransportMode(' . $id . ')');
  2475. if ($this->statut >= 0 || $this->element == 'societe') {
  2476. $fieldname = 'fk_transport_mode';
  2477. if ($this->element == 'societe') {
  2478. $fieldname = 'transport_mode';
  2479. }
  2480. if (get_class($this) == 'Fournisseur') {
  2481. $fieldname = 'transport_mode_supplier';
  2482. }
  2483. $sql = 'UPDATE ' . $this->db->prefix() . $this->table_element;
  2484. $sql .= " SET " . $fieldname . " = " . (($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2485. $sql .= ' WHERE rowid=' . ((int) $this->id);
  2486. if ($this->db->query($sql)) {
  2487. $this->transport_mode_id = $id;
  2488. // for supplier
  2489. if (get_class($this) == 'Fournisseur') {
  2490. $this->transport_mode_supplier_id = $id;
  2491. }
  2492. return 1;
  2493. } else {
  2494. dol_syslog(get_class($this) . '::setTransportMode Error ' . $sql . ' - ' . $this->db->error());
  2495. $this->error = $this->db->error();
  2496. return -1;
  2497. }
  2498. } else {
  2499. dol_syslog(get_class($this) . '::setTransportMode, status of the object is incompatible');
  2500. $this->error = 'Status of the object is incompatible ' . $this->statut;
  2501. return -2;
  2502. }
  2503. }
  2504. /**
  2505. * Change the retained warranty payments terms
  2506. *
  2507. * @param int $id Id of new payment terms
  2508. * @return int >0 if OK, <0 if KO
  2509. */
  2510. public function setRetainedWarrantyPaymentTerms($id)
  2511. {
  2512. dol_syslog(get_class($this) . '::setRetainedWarrantyPaymentTerms(' . $id . ')');
  2513. if ($this->statut >= 0 || $this->element == 'societe') {
  2514. $fieldname = 'retained_warranty_fk_cond_reglement';
  2515. $sql = 'UPDATE ' . $this->db->prefix() . $this->table_element;
  2516. $sql .= " SET " . $fieldname . " = " . ((int) $id);
  2517. $sql .= ' WHERE rowid=' . ((int) $this->id);
  2518. if ($this->db->query($sql)) {
  2519. $this->retained_warranty_fk_cond_reglement = $id;
  2520. return 1;
  2521. } else {
  2522. dol_syslog(get_class($this) . '::setRetainedWarrantyPaymentTerms Error ' . $sql . ' - ' . $this->db->error());
  2523. $this->error = $this->db->error();
  2524. return -1;
  2525. }
  2526. } else {
  2527. dol_syslog(get_class($this) . '::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2528. $this->error = 'Status of the object is incompatible ' . $this->statut;
  2529. return -2;
  2530. }
  2531. }
  2532. /**
  2533. * Define delivery address
  2534. * @deprecated
  2535. *
  2536. * @param int $id Address id
  2537. * @return int <0 si ko, >0 si ok
  2538. */
  2539. public function setDeliveryAddress($id)
  2540. {
  2541. $fieldname = 'fk_delivery_address';
  2542. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2543. $fieldname = 'fk_address';
  2544. }
  2545. $sql = "UPDATE " . $this->db->prefix() . $this->table_element . " SET " . $fieldname . " = " . ((int) $id);
  2546. $sql .= " WHERE rowid = " . ((int) $this->id) . " AND fk_statut = 0";
  2547. if ($this->db->query($sql)) {
  2548. $this->fk_delivery_address = $id;
  2549. return 1;
  2550. } else {
  2551. $this->error = $this->db->error();
  2552. dol_syslog(get_class($this) . '::setDeliveryAddress Error ' . $this->error);
  2553. return -1;
  2554. }
  2555. }
  2556. /**
  2557. * Change the shipping method
  2558. *
  2559. * @param int $shipping_method_id Id of shipping method
  2560. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2561. * @param User $userused Object user
  2562. *
  2563. * @return int 1 if OK, 0 if KO
  2564. */
  2565. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2566. {
  2567. global $user;
  2568. if (empty($userused)) {
  2569. $userused = $user;
  2570. }
  2571. $error = 0;
  2572. if (!$this->table_element) {
  2573. dol_syslog(get_class($this) . "::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2574. return -1;
  2575. }
  2576. $this->db->begin();
  2577. if ($shipping_method_id < 0) {
  2578. $shipping_method_id = 'NULL';
  2579. }
  2580. dol_syslog(get_class($this) . '::setShippingMethod(' . $shipping_method_id . ')');
  2581. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  2582. $sql .= " SET fk_shipping_method = " . ((int) $shipping_method_id);
  2583. $sql .= " WHERE rowid=" . ((int) $this->id);
  2584. $resql = $this->db->query($sql);
  2585. if (!$resql) {
  2586. dol_syslog(get_class($this) . '::setShippingMethod Error ', LOG_DEBUG);
  2587. $this->error = $this->db->lasterror();
  2588. $error++;
  2589. } else {
  2590. if (!$notrigger) {
  2591. // Call trigger
  2592. $this->context = array('shippingmethodupdate' => 1);
  2593. $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
  2594. if ($result < 0) {
  2595. $error++;
  2596. }
  2597. // End call trigger
  2598. }
  2599. }
  2600. if ($error) {
  2601. $this->db->rollback();
  2602. return -1;
  2603. } else {
  2604. $this->shipping_method_id = ($shipping_method_id == 'NULL') ? null : $shipping_method_id;
  2605. $this->db->commit();
  2606. return 1;
  2607. }
  2608. }
  2609. /**
  2610. * Change the warehouse
  2611. *
  2612. * @param int $warehouse_id Id of warehouse
  2613. * @return int 1 if OK, 0 if KO
  2614. */
  2615. public function setWarehouse($warehouse_id)
  2616. {
  2617. if (!$this->table_element) {
  2618. dol_syslog(get_class($this) . "::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2619. return -1;
  2620. }
  2621. if ($warehouse_id < 0) {
  2622. $warehouse_id = 'NULL';
  2623. }
  2624. dol_syslog(get_class($this) . '::setWarehouse(' . $warehouse_id . ')');
  2625. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  2626. $sql .= " SET fk_warehouse = " . ((int) $warehouse_id);
  2627. $sql .= " WHERE rowid=" . ((int) $this->id);
  2628. if ($this->db->query($sql)) {
  2629. $this->warehouse_id = ($warehouse_id == 'NULL') ? null : $warehouse_id;
  2630. return 1;
  2631. } else {
  2632. dol_syslog(get_class($this) . '::setWarehouse Error ', LOG_DEBUG);
  2633. $this->error = $this->db->error();
  2634. return 0;
  2635. }
  2636. }
  2637. /**
  2638. * Set last model used by doc generator
  2639. *
  2640. * @param User $user User object that make change
  2641. * @param string $modelpdf Modele name
  2642. * @return int <0 if KO, >0 if OK
  2643. */
  2644. public function setDocModel($user, $modelpdf)
  2645. {
  2646. if (!$this->table_element) {
  2647. dol_syslog(get_class($this) . "::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2648. return -1;
  2649. }
  2650. $newmodelpdf = dol_trunc($modelpdf, 255);
  2651. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  2652. $sql .= " SET model_pdf = '" . $this->db->escape($newmodelpdf) . "'";
  2653. $sql .= " WHERE rowid = " . ((int) $this->id);
  2654. dol_syslog(get_class($this) . "::setDocModel", LOG_DEBUG);
  2655. $resql = $this->db->query($sql);
  2656. if ($resql) {
  2657. $this->model_pdf = $modelpdf;
  2658. $this->modelpdf = $modelpdf; // For bakward compatibility
  2659. return 1;
  2660. } else {
  2661. dol_print_error($this->db);
  2662. return 0;
  2663. }
  2664. }
  2665. /**
  2666. * Change the bank account
  2667. *
  2668. * @param int $fk_account Id of bank account
  2669. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2670. * @param User $userused Object user
  2671. * @return int 1 if OK, 0 if KO
  2672. */
  2673. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2674. {
  2675. global $user;
  2676. if (empty($userused)) {
  2677. $userused = $user;
  2678. }
  2679. $error = 0;
  2680. if (!$this->table_element) {
  2681. dol_syslog(get_class($this) . "::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2682. return -1;
  2683. }
  2684. $this->db->begin();
  2685. if ($fk_account < 0) {
  2686. $fk_account = 'NULL';
  2687. }
  2688. dol_syslog(get_class($this) . '::setBankAccount(' . $fk_account . ')');
  2689. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  2690. $sql .= " SET fk_account = " . ((int) $fk_account);
  2691. $sql .= " WHERE rowid=" . ((int) $this->id);
  2692. $resql = $this->db->query($sql);
  2693. if (!$resql) {
  2694. dol_syslog(get_class($this) . '::setBankAccount Error ' . $sql . ' - ' . $this->db->error());
  2695. $this->error = $this->db->lasterror();
  2696. $error++;
  2697. } else {
  2698. if (!$notrigger) {
  2699. // Call trigger
  2700. $this->context = array('bankaccountupdate' => 1);
  2701. $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
  2702. if ($result < 0) {
  2703. $error++;
  2704. }
  2705. // End call trigger
  2706. }
  2707. }
  2708. if ($error) {
  2709. $this->db->rollback();
  2710. return -1;
  2711. } else {
  2712. $this->fk_account = ($fk_account == 'NULL') ? null : $fk_account;
  2713. $this->db->commit();
  2714. return 1;
  2715. }
  2716. }
  2717. // TODO: Move line related operations to CommonObjectLine?
  2718. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2719. /**
  2720. * Save a new position (field rang) for details lines.
  2721. * You can choose to set position for lines with already a position or lines without any position defined.
  2722. *
  2723. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2724. * @param string $rowidorder ASC or DESC
  2725. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2726. * @return int <0 if KO, >0 if OK
  2727. */
  2728. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2729. {
  2730. // phpcs:enable
  2731. if (!$this->table_element_line) {
  2732. dol_syslog(get_class($this) . "::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2733. return -1;
  2734. }
  2735. if (!$this->fk_element) {
  2736. dol_syslog(get_class($this) . "::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2737. return -1;
  2738. }
  2739. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2740. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2741. $fieldposition = 'position';
  2742. }
  2743. // Count number of lines to reorder (according to choice $renum)
  2744. $nl = 0;
  2745. $sql = "SELECT count(rowid) FROM " . $this->db->prefix() . $this->table_element_line;
  2746. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  2747. if (!$renum) {
  2748. $sql .= " AND " . $fieldposition . " = 0";
  2749. }
  2750. if ($renum) {
  2751. $sql .= " AND " . $fieldposition . " <> 0";
  2752. }
  2753. dol_syslog(get_class($this) . "::line_order", LOG_DEBUG);
  2754. $resql = $this->db->query($sql);
  2755. if ($resql) {
  2756. $row = $this->db->fetch_row($resql);
  2757. $nl = $row[0];
  2758. } else {
  2759. dol_print_error($this->db);
  2760. }
  2761. if ($nl > 0) {
  2762. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2763. $rows = array();
  2764. // We first search all lines that are parent lines (for multilevel details lines)
  2765. $sql = "SELECT rowid FROM " . $this->db->prefix() . $this->table_element_line;
  2766. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  2767. if ($fk_parent_line) {
  2768. $sql .= ' AND fk_parent_line IS NULL';
  2769. }
  2770. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2771. dol_syslog(get_class($this) . "::line_order search all parent lines", LOG_DEBUG);
  2772. $resql = $this->db->query($sql);
  2773. if ($resql) {
  2774. $i = 0;
  2775. $num = $this->db->num_rows($resql);
  2776. while ($i < $num) {
  2777. $row = $this->db->fetch_row($resql);
  2778. $rows[] = $row[0]; // Add parent line into array rows
  2779. $childrens = $this->getChildrenOfLine($row[0]);
  2780. if (!empty($childrens)) {
  2781. foreach ($childrens as $child) {
  2782. array_push($rows, $child);
  2783. }
  2784. }
  2785. $i++;
  2786. }
  2787. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2788. if (!empty($rows)) {
  2789. foreach ($rows as $key => $row) {
  2790. $this->updateRangOfLine($row, ($key + 1));
  2791. }
  2792. }
  2793. } else {
  2794. dol_print_error($this->db);
  2795. }
  2796. }
  2797. return 1;
  2798. }
  2799. /**
  2800. * Get children of line
  2801. *
  2802. * @param int $id Id of parent line
  2803. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2804. * @return array Array with list of children lines id
  2805. */
  2806. public function getChildrenOfLine($id, $includealltree = 0)
  2807. {
  2808. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2809. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2810. $fieldposition = 'position';
  2811. }
  2812. $rows = array();
  2813. $sql = "SELECT rowid FROM " . $this->db->prefix() . $this->table_element_line;
  2814. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  2815. $sql .= ' AND fk_parent_line = ' . ((int) $id);
  2816. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2817. dol_syslog(get_class($this) . "::getChildrenOfLine search children lines for line " . $id, LOG_DEBUG);
  2818. $resql = $this->db->query($sql);
  2819. if ($resql) {
  2820. if ($this->db->num_rows($resql) > 0) {
  2821. while ($row = $this->db->fetch_row($resql)) {
  2822. $rows[] = $row[0];
  2823. if (!empty($includealltree)) {
  2824. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2825. }
  2826. }
  2827. }
  2828. }
  2829. return $rows;
  2830. }
  2831. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2832. /**
  2833. * Update a line to have a lower rank
  2834. *
  2835. * @param int $rowid Id of line
  2836. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2837. * @return void
  2838. */
  2839. public function line_up($rowid, $fk_parent_line = true)
  2840. {
  2841. // phpcs:enable
  2842. $this->line_order(false, 'ASC', $fk_parent_line);
  2843. // Get rang of line
  2844. $rang = $this->getRangOfLine($rowid);
  2845. // Update position of line
  2846. $this->updateLineUp($rowid, $rang);
  2847. }
  2848. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2849. /**
  2850. * Update a line to have a higher rank
  2851. *
  2852. * @param int $rowid Id of line
  2853. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2854. * @return void
  2855. */
  2856. public function line_down($rowid, $fk_parent_line = true)
  2857. {
  2858. // phpcs:enable
  2859. $this->line_order(false, 'ASC', $fk_parent_line);
  2860. // Get rang of line
  2861. $rang = $this->getRangOfLine($rowid);
  2862. // Get max value for rang
  2863. $max = $this->line_max();
  2864. // Update position of line
  2865. $this->updateLineDown($rowid, $rang, $max);
  2866. }
  2867. /**
  2868. * Update position of line (rang)
  2869. *
  2870. * @param int $rowid Id of line
  2871. * @param int $rang Position
  2872. * @return int <0 if KO, >0 if OK
  2873. */
  2874. public function updateRangOfLine($rowid, $rang)
  2875. {
  2876. global $hookmanager;
  2877. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2878. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2879. $fieldposition = 'position';
  2880. }
  2881. $sql = "UPDATE " . $this->db->prefix() . $this->table_element_line . " SET " . $fieldposition . " = " . ((int) $rang);
  2882. $sql .= ' WHERE rowid = ' . ((int) $rowid);
  2883. dol_syslog(get_class($this) . "::updateRangOfLine", LOG_DEBUG);
  2884. if (!$this->db->query($sql)) {
  2885. dol_print_error($this->db);
  2886. return -1;
  2887. } else {
  2888. $parameters = array('rowid' => $rowid, 'rang' => $rang, 'fieldposition' => $fieldposition);
  2889. $action = '';
  2890. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2891. return 1;
  2892. }
  2893. }
  2894. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2895. /**
  2896. * Update position of line with ajax (rang)
  2897. *
  2898. * @param array $rows Array of rows
  2899. * @return void
  2900. */
  2901. public function line_ajaxorder($rows)
  2902. {
  2903. // phpcs:enable
  2904. $num = count($rows);
  2905. for ($i = 0; $i < $num; $i++) {
  2906. $this->updateRangOfLine($rows[$i], ($i + 1));
  2907. }
  2908. }
  2909. /**
  2910. * Update position of line up (rang)
  2911. *
  2912. * @param int $rowid Id of line
  2913. * @param int $rang Position
  2914. * @return void
  2915. */
  2916. public function updateLineUp($rowid, $rang)
  2917. {
  2918. if ($rang > 1) {
  2919. $fieldposition = 'rang';
  2920. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2921. $fieldposition = 'position';
  2922. }
  2923. $sql = "UPDATE " . $this->db->prefix() . $this->table_element_line . " SET " . $fieldposition . " = " . ((int) $rang);
  2924. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  2925. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2926. if ($this->db->query($sql)) {
  2927. $sql = "UPDATE " . $this->db->prefix() . $this->table_element_line . " SET " . $fieldposition . " = " . ((int) ($rang - 1));
  2928. $sql .= ' WHERE rowid = ' . ((int) $rowid);
  2929. if (!$this->db->query($sql)) {
  2930. dol_print_error($this->db);
  2931. }
  2932. } else {
  2933. dol_print_error($this->db);
  2934. }
  2935. }
  2936. }
  2937. /**
  2938. * Update position of line down (rang)
  2939. *
  2940. * @param int $rowid Id of line
  2941. * @param int $rang Position
  2942. * @param int $max Max
  2943. * @return void
  2944. */
  2945. public function updateLineDown($rowid, $rang, $max)
  2946. {
  2947. if ($rang < $max) {
  2948. $fieldposition = 'rang';
  2949. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2950. $fieldposition = 'position';
  2951. }
  2952. $sql = "UPDATE " . $this->db->prefix() . $this->table_element_line . " SET " . $fieldposition . " = " . ((int) $rang);
  2953. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  2954. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2955. if ($this->db->query($sql)) {
  2956. $sql = "UPDATE " . $this->db->prefix() . $this->table_element_line . " SET " . $fieldposition . " = " . ((int) ($rang + 1));
  2957. $sql .= ' WHERE rowid = ' . ((int) $rowid);
  2958. if (!$this->db->query($sql)) {
  2959. dol_print_error($this->db);
  2960. }
  2961. } else {
  2962. dol_print_error($this->db);
  2963. }
  2964. }
  2965. }
  2966. /**
  2967. * Get position of line (rang)
  2968. *
  2969. * @param int $rowid Id of line
  2970. * @return int Value of rang in table of lines
  2971. */
  2972. public function getRangOfLine($rowid)
  2973. {
  2974. $fieldposition = 'rang';
  2975. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2976. $fieldposition = 'position';
  2977. }
  2978. $sql = "SELECT " . $fieldposition . " FROM " . $this->db->prefix() . $this->table_element_line;
  2979. $sql .= " WHERE rowid = " . ((int) $rowid);
  2980. dol_syslog(get_class($this) . "::getRangOfLine", LOG_DEBUG);
  2981. $resql = $this->db->query($sql);
  2982. if ($resql) {
  2983. $row = $this->db->fetch_row($resql);
  2984. return $row[0];
  2985. }
  2986. }
  2987. /**
  2988. * Get rowid of the line relative to its position
  2989. *
  2990. * @param int $rang Rang value
  2991. * @return int Rowid of the line
  2992. */
  2993. public function getIdOfLine($rang)
  2994. {
  2995. $fieldposition = 'rang';
  2996. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2997. $fieldposition = 'position';
  2998. }
  2999. $sql = "SELECT rowid FROM " . $this->db->prefix() . $this->table_element_line;
  3000. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  3001. $sql .= " AND " . $fieldposition . " = " . ((int) $rang);
  3002. $resql = $this->db->query($sql);
  3003. if ($resql) {
  3004. $row = $this->db->fetch_row($resql);
  3005. return $row[0];
  3006. }
  3007. }
  3008. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3009. /**
  3010. * Get max value used for position of line (rang)
  3011. *
  3012. * @param int $fk_parent_line Parent line id
  3013. * @return int Max value of rang in table of lines
  3014. */
  3015. public function line_max($fk_parent_line = 0)
  3016. {
  3017. // phpcs:enable
  3018. $positionfield = 'rang';
  3019. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  3020. $positionfield = 'position';
  3021. }
  3022. // Search the last rang with fk_parent_line
  3023. if ($fk_parent_line) {
  3024. $sql = "SELECT max(" . $positionfield . ") FROM " . $this->db->prefix() . $this->table_element_line;
  3025. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  3026. $sql .= " AND fk_parent_line = " . ((int) $fk_parent_line);
  3027. dol_syslog(get_class($this) . "::line_max", LOG_DEBUG);
  3028. $resql = $this->db->query($sql);
  3029. if ($resql) {
  3030. $row = $this->db->fetch_row($resql);
  3031. if (!empty($row[0])) {
  3032. return $row[0];
  3033. } else {
  3034. return $this->getRangOfLine($fk_parent_line);
  3035. }
  3036. }
  3037. } else {
  3038. // If not, search the last rang of element
  3039. $sql = "SELECT max(" . $positionfield . ") FROM " . $this->db->prefix() . $this->table_element_line;
  3040. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  3041. dol_syslog(get_class($this) . "::line_max", LOG_DEBUG);
  3042. $resql = $this->db->query($sql);
  3043. if ($resql) {
  3044. $row = $this->db->fetch_row($resql);
  3045. return $row[0];
  3046. }
  3047. }
  3048. }
  3049. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3050. /**
  3051. * Update external ref of element
  3052. *
  3053. * @param string $ref_ext Update field ref_ext
  3054. * @return int <0 if KO, >0 if OK
  3055. */
  3056. public function update_ref_ext($ref_ext)
  3057. {
  3058. // phpcs:enable
  3059. if (!$this->table_element) {
  3060. dol_syslog(get_class($this) . "::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  3061. return -1;
  3062. }
  3063. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  3064. $sql .= " SET ref_ext = '" . $this->db->escape($ref_ext) . "'";
  3065. $sql .= " WHERE " . (isset($this->table_rowid) ? $this->table_rowid : 'rowid') . " = " . ((int) $this->id);
  3066. dol_syslog(get_class($this) . "::update_ref_ext", LOG_DEBUG);
  3067. if ($this->db->query($sql)) {
  3068. $this->ref_ext = $ref_ext;
  3069. return 1;
  3070. } else {
  3071. $this->error = $this->db->error();
  3072. return -1;
  3073. }
  3074. }
  3075. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3076. /**
  3077. * Update note of element
  3078. *
  3079. * @param string $note New value for note
  3080. * @param string $suffix '', '_public' or '_private'
  3081. * @return int <0 if KO, >0 if OK
  3082. */
  3083. public function update_note($note, $suffix = '')
  3084. {
  3085. // phpcs:enable
  3086. global $user;
  3087. if (!$this->table_element) {
  3088. $this->error = 'update_note was called on objet with property table_element not defined';
  3089. dol_syslog(get_class($this) . "::update_note was called on objet with property table_element not defined", LOG_ERR);
  3090. return -1;
  3091. }
  3092. if (!in_array($suffix, array('', '_public', '_private'))) {
  3093. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3094. dol_syslog(get_class($this) . "::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3095. return -2;
  3096. }
  3097. $newsuffix = $suffix;
  3098. // Special cas
  3099. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3100. $newsuffix = '';
  3101. }
  3102. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3103. $fieldusermod = "fk_user_mod";
  3104. } elseif ($this->table_element == 'ecm_files') {
  3105. $fieldusermod = "fk_user_m";
  3106. } else {
  3107. $fieldusermod = "fk_user_modif";
  3108. }
  3109. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  3110. $sql .= " SET note" . $newsuffix . " = " . (!empty($note) ? ("'" . $this->db->escape($note) . "'") : "NULL");
  3111. $sql .= ", " . $fieldusermod . " = " . ((int) $user->id);
  3112. $sql .= " WHERE rowid = " . ((int) $this->id);
  3113. dol_syslog(get_class($this) . "::update_note", LOG_DEBUG);
  3114. if ($this->db->query($sql)) {
  3115. if ($suffix == '_public') {
  3116. $this->note_public = $note;
  3117. } elseif ($suffix == '_private') {
  3118. $this->note_private = $note;
  3119. } else {
  3120. $this->note = $note; // deprecated
  3121. $this->note_private = $note;
  3122. }
  3123. return 1;
  3124. } else {
  3125. $this->error = $this->db->lasterror();
  3126. return -1;
  3127. }
  3128. }
  3129. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3130. /**
  3131. * Update public note (kept for backward compatibility)
  3132. *
  3133. * @param string $note New value for note
  3134. * @return int <0 if KO, >0 if OK
  3135. * @deprecated
  3136. * @see update_note()
  3137. */
  3138. public function update_note_public($note)
  3139. {
  3140. // phpcs:enable
  3141. return $this->update_note($note, '_public');
  3142. }
  3143. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3144. /**
  3145. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3146. * Must be called at end of methods addline or updateline.
  3147. *
  3148. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3149. * @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
  3150. * @param int $nodatabaseupdate 1=Do not update database total fields of the main object. Update only properties in memory. Can be used to save SQL when this method is called several times, so we can do it only once at end.
  3151. * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object (used to analyze lines to check corrupted data).
  3152. * @return int <0 if KO, >0 if OK
  3153. */
  3154. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3155. {
  3156. // phpcs:enable
  3157. global $conf, $hookmanager, $action;
  3158. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3159. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3160. if ($reshook > 0) {
  3161. return 1; // replacement code
  3162. } elseif ($reshook < 0) {
  3163. return -1; // failure
  3164. } // reshook = 0 => execute normal code
  3165. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3166. $MODULE = "";
  3167. if ($this->element == 'propal') {
  3168. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3169. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3170. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3171. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3172. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3173. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3174. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3175. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3176. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3177. } elseif ($this->element == 'supplier_proposal') {
  3178. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3179. }
  3180. if (!empty($MODULE)) {
  3181. if (!empty($conf->global->$MODULE)) {
  3182. $modsactivated = explode(',', $conf->global->$MODULE);
  3183. foreach ($modsactivated as $mod) {
  3184. if (isModEnabled($mod)) {
  3185. return 1; // update was disabled by specific setup
  3186. }
  3187. }
  3188. }
  3189. }
  3190. include_once DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php';
  3191. $forcedroundingmode = $roundingadjust;
  3192. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3193. $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
  3194. } elseif ($forcedroundingmode == 'auto') {
  3195. $forcedroundingmode = '0';
  3196. }
  3197. $error = 0;
  3198. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3199. // Define constants to find lines to sum (field name int the table_element_line not into table_element)
  3200. $fieldtva = 'total_tva';
  3201. $fieldlocaltax1 = 'total_localtax1';
  3202. $fieldlocaltax2 = 'total_localtax2';
  3203. $fieldup = 'subprice';
  3204. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3205. $fieldtva = 'tva';
  3206. $fieldup = 'pu_ht';
  3207. }
  3208. if ($this->element == 'invoice_supplier_rec') {
  3209. $fieldup = 'pu_ht';
  3210. }
  3211. if ($this->element == 'expensereport') {
  3212. $fieldup = 'value_unit';
  3213. }
  3214. $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,";
  3215. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3216. if ($this->table_element_line == 'facturedet') {
  3217. $sql .= ', situation_percent';
  3218. }
  3219. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3220. $sql .= " FROM " . $this->db->prefix() . $this->table_element_line;
  3221. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  3222. if ($exclspec) {
  3223. $product_field = 'product_type';
  3224. if ($this->table_element_line == 'contratdet') {
  3225. $product_field = ''; // contratdet table has no product_type field
  3226. }
  3227. if ($product_field) {
  3228. $sql .= " AND " . $product_field . " <> 9";
  3229. }
  3230. }
  3231. $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
  3232. dol_syslog(get_class($this) . "::update_price", LOG_DEBUG);
  3233. $resql = $this->db->query($sql);
  3234. if ($resql) {
  3235. $this->total_ht = 0;
  3236. $this->total_tva = 0;
  3237. $this->total_localtax1 = 0;
  3238. $this->total_localtax2 = 0;
  3239. $this->total_ttc = 0;
  3240. $total_ht_by_vats = array();
  3241. $total_tva_by_vats = array();
  3242. $total_ttc_by_vats = array();
  3243. $this->multicurrency_total_ht = 0;
  3244. $this->multicurrency_total_tva = 0;
  3245. $this->multicurrency_total_ttc = 0;
  3246. $num = $this->db->num_rows($resql);
  3247. $i = 0;
  3248. while ($i < $num) {
  3249. $obj = $this->db->fetch_object($resql);
  3250. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3251. $parameters = array('fk_element' => $obj->rowid);
  3252. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3253. 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'
  3254. // This part of code is to fix data. We should not call it too often.
  3255. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3256. $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);
  3257. $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price and unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
  3258. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3259. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
  3260. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3261. if ($diff_on_current_total) {
  3262. // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
  3263. $sqlfix = "UPDATE " . $this->db->prefix() . $this->table_element_line . " SET " . $fieldtva . " = " . price2num((float) $tmpcal[1]) . ", total_ttc = " . price2num((float) $tmpcal[2]) . " WHERE rowid = " . ((int) $obj->rowid);
  3264. dol_syslog('We found unconsistent data into detailed line (diff_on_current_total = ' . $diff_on_current_total . ') for line rowid = ' . $obj->rowid . " (ht=" . $obj->total_ht . " vat=" . $obj->total_tva . " tax1=" . $obj->total_localtax1 . " tax2=" . $obj->total_localtax2 . " ttc=" . $obj->total_ttc . "). We fix the total_vat and total_ttc of line by running sqlfix = " . $sqlfix, LOG_WARNING);
  3265. $resqlfix = $this->db->query($sqlfix);
  3266. if (!$resqlfix) {
  3267. dol_print_error($this->db, 'Failed to update line');
  3268. }
  3269. $obj->total_tva = $tmpcal[1];
  3270. $obj->total_ttc = $tmpcal[2];
  3271. } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
  3272. // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
  3273. // we ask to force the use of rounding on line (like done on calculation) so we force update of line
  3274. $sqlfix = "UPDATE " . $this->db->prefix() . $this->table_element_line . " SET " . $fieldtva . " = " . price2num((float) $tmpcal[1]) . ", total_ttc = " . price2num((float) $tmpcal[2]) . " WHERE rowid = " . ((int) $obj->rowid);
  3275. dol_syslog('We found a line with different rounding data into detailed line (diff_when_using_price_ht = ' . $diff_when_using_price_ht . ' and diff_on_current_total = ' . $diff_on_current_total . ') for line rowid = ' . $obj->rowid . " (total vat of line calculated=" . $tmpcal[1] . ", database=" . $obj->total_tva . "). We fix the total_vat and total_ttc of line by running sqlfix = " . $sqlfix);
  3276. $resqlfix = $this->db->query($sqlfix);
  3277. if (!$resqlfix) {
  3278. dol_print_error($this->db, 'Failed to update line');
  3279. }
  3280. $obj->total_tva = $tmpcal[1];
  3281. $obj->total_ttc = $tmpcal[2];
  3282. }
  3283. }
  3284. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3285. $this->total_tva += $obj->total_tva;
  3286. $this->total_localtax1 += $obj->total_localtax1;
  3287. $this->total_localtax2 += $obj->total_localtax2;
  3288. $this->total_ttc += $obj->total_ttc;
  3289. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3290. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3291. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3292. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3293. $total_ht_by_vats[$obj->vatrate] = 0;
  3294. }
  3295. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3296. $total_tva_by_vats[$obj->vatrate] = 0;
  3297. }
  3298. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3299. $total_ttc_by_vats[$obj->vatrate] = 0;
  3300. }
  3301. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3302. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3303. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3304. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3305. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3306. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3307. //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";
  3308. if ($diff) {
  3309. if (abs($diff) > 0.1) {
  3310. $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.';
  3311. dol_syslog($errmsg, LOG_WARNING);
  3312. dol_print_error('', $errmsg);
  3313. exit;
  3314. }
  3315. $sqlfix = "UPDATE " . $this->db->prefix() . $this->table_element_line . " SET " . $fieldtva . " = " . price2num($obj->total_tva - $diff) . ", total_ttc = " . price2num($obj->total_ttc - $diff) . " WHERE rowid = " . ((int) $obj->rowid);
  3316. 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);
  3317. $resqlfix = $this->db->query($sqlfix);
  3318. if (!$resqlfix) {
  3319. dol_print_error($this->db, 'Failed to update line');
  3320. }
  3321. $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
  3322. $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
  3323. $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
  3324. $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
  3325. }
  3326. }
  3327. $i++;
  3328. }
  3329. // Add revenue stamp to total
  3330. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3331. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3332. // Situations totals
  3333. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3334. $prev_sits = $this->get_prev_sits();
  3335. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3336. $this->total_ht -= $sit->total_ht;
  3337. $this->total_tva -= $sit->total_tva;
  3338. $this->total_localtax1 -= $sit->total_localtax1;
  3339. $this->total_localtax2 -= $sit->total_localtax2;
  3340. $this->total_ttc -= $sit->total_ttc;
  3341. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3342. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3343. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3344. }
  3345. }
  3346. // Clean total
  3347. $this->total_ht = (float) price2num($this->total_ht);
  3348. $this->total_tva = (float) price2num($this->total_tva);
  3349. $this->total_localtax1 = (float) price2num($this->total_localtax1);
  3350. $this->total_localtax2 = (float) price2num($this->total_localtax2);
  3351. $this->total_ttc = (float) price2num($this->total_ttc);
  3352. $this->db->free($resql);
  3353. // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
  3354. $fieldht = 'total_ht';
  3355. $fieldtva = 'tva';
  3356. $fieldlocaltax1 = 'localtax1';
  3357. $fieldlocaltax2 = 'localtax2';
  3358. $fieldttc = 'total_ttc';
  3359. // Specific code for backward compatibility with old field names
  3360. if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
  3361. $fieldtva = 'total_tva';
  3362. }
  3363. if (empty($nodatabaseupdate)) {
  3364. $sql = "UPDATE " . $this->db->prefix() . $this->table_element . ' SET';
  3365. $sql .= " " . $fieldht . " = " . ((float) price2num($this->total_ht, 'MT', 1)) . ",";
  3366. $sql .= " " . $fieldtva . " = " . ((float) price2num($this->total_tva, 'MT', 1)) . ",";
  3367. $sql .= " " . $fieldlocaltax1 . " = " . ((float) price2num($this->total_localtax1, 'MT', 1)) . ",";
  3368. $sql .= " " . $fieldlocaltax2 . " = " . ((float) price2num($this->total_localtax2, 'MT', 1)) . ",";
  3369. $sql .= " " . $fieldttc . " = " . ((float) price2num($this->total_ttc, 'MT', 1));
  3370. $sql .= ", multicurrency_total_ht = " . ((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3371. $sql .= ", multicurrency_total_tva = " . ((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3372. $sql .= ", multicurrency_total_ttc = " . ((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3373. $sql .= " WHERE rowid = " . ((int) $this->id);
  3374. dol_syslog(get_class($this) . "::update_price", LOG_DEBUG);
  3375. $resql = $this->db->query($sql);
  3376. if (!$resql) {
  3377. $error++;
  3378. $this->error = $this->db->lasterror();
  3379. $this->errors[] = $this->db->lasterror();
  3380. }
  3381. }
  3382. if (!$error) {
  3383. return 1;
  3384. } else {
  3385. return -1;
  3386. }
  3387. } else {
  3388. dol_print_error($this->db, 'Bad request in update_price');
  3389. return -1;
  3390. }
  3391. }
  3392. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3393. /**
  3394. * Add an object link into llx_element_element.
  3395. *
  3396. * @param string $origin Linked element type
  3397. * @param int $origin_id Linked element id
  3398. * @param User $f_user User that create
  3399. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3400. * @return int <=0 if KO, >0 if OK
  3401. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3402. */
  3403. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3404. {
  3405. // phpcs:enable
  3406. global $user, $hookmanager, $action;
  3407. $origin = (!empty($origin) ? $origin : $this->origin);
  3408. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3409. $f_user = isset($f_user) ? $f_user : $user;
  3410. // Special case
  3411. if ($origin == 'order') {
  3412. $origin = 'commande';
  3413. }
  3414. if ($origin == 'invoice') {
  3415. $origin = 'facture';
  3416. }
  3417. if ($origin == 'invoice_template') {
  3418. $origin = 'facturerec';
  3419. }
  3420. if ($origin == 'supplierorder') {
  3421. $origin = 'order_supplier';
  3422. }
  3423. // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
  3424. // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
  3425. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3426. // Add module part to target type if object has $module property and isn't in core modules.
  3427. $targettype = ((!empty($this->module) && !in_array($this->module, $coremodule)) ? $this->module . '_' : '') . $this->element;
  3428. $parameters = array('targettype' => $targettype);
  3429. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3430. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3431. if ($reshook > 0) {
  3432. if (!empty($hookmanager->resArray['targettype']))
  3433. $targettype = $hookmanager->resArray['targettype'];
  3434. }
  3435. $this->db->begin();
  3436. $error = 0;
  3437. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3438. $sql .= "fk_source";
  3439. $sql .= ", sourcetype";
  3440. $sql .= ", fk_target";
  3441. $sql .= ", targettype";
  3442. $sql .= ") VALUES (";
  3443. $sql .= ((int) $origin_id);
  3444. $sql .= ", '" . $this->db->escape($origin) . "'";
  3445. $sql .= ", " . ((int) $this->id);
  3446. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3447. $sql .= ")";
  3448. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3449. if ($this->db->query($sql)) {
  3450. if (!$notrigger) {
  3451. // Call trigger
  3452. $this->context['link_origin'] = $origin;
  3453. $this->context['link_origin_id'] = $origin_id;
  3454. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3455. if ($result < 0) {
  3456. $error++;
  3457. }
  3458. // End call triggers
  3459. }
  3460. } else {
  3461. $this->error = $this->db->lasterror();
  3462. $error++;
  3463. }
  3464. if (!$error) {
  3465. $this->db->commit();
  3466. return 1;
  3467. } else {
  3468. $this->db->rollback();
  3469. return 0;
  3470. }
  3471. }
  3472. /**
  3473. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3474. * this->linkedObjectsIds array +
  3475. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3476. * Possible usage for parameters:
  3477. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3478. * - source id+type -> will get list of targets linked to source
  3479. * - target id+type -> will get list of sources linked to target
  3480. * - source id+type + target type -> will get list of targets of the type linked to source
  3481. * - target id+type + source type -> will get list of sources of the type linked to target
  3482. *
  3483. * @param int $sourceid Object source id (if not defined, id of object)
  3484. * @param string $sourcetype Object source type (if not defined, element name of object)
  3485. * @param int $targetid Object target id (if not defined, id of object)
  3486. * @param string $targettype Object target type (if not defined, element name of object)
  3487. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3488. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3489. * @param string $orderby SQL 'ORDER BY' clause
  3490. * @param int|string $loadalsoobjects Load also array this->linkedObjects. Use 0 to increase performances, Use 1 to load all, Use value of type ('facture', 'facturerec', ...) to load only a type of object.
  3491. * @return int <0 if KO, >0 if OK
  3492. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3493. */
  3494. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3495. {
  3496. global $conf, $hookmanager, $action;
  3497. // Important for pdf generation time reduction
  3498. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3499. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3500. return 1;
  3501. }
  3502. $this->linkedObjectsIds = array();
  3503. $this->linkedObjects = array();
  3504. $justsource = false;
  3505. $justtarget = false;
  3506. $withtargettype = false;
  3507. $withsourcetype = false;
  3508. $parameters = array('sourcetype' => $sourcetype, 'sourceid' => $sourceid, 'targettype' => $targettype, 'targetid' => $targetid);
  3509. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3510. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3511. if ($reshook > 0) {
  3512. if (!empty($hookmanager->resArray['sourcetype']))
  3513. $sourcetype = $hookmanager->resArray['sourcetype'];
  3514. if (!empty($hookmanager->resArray['sourceid']))
  3515. $sourceid = $hookmanager->resArray['sourceid'];
  3516. if (!empty($hookmanager->resArray['targettype']))
  3517. $targettype = $hookmanager->resArray['targettype'];
  3518. if (!empty($hookmanager->resArray['targetid']))
  3519. $targetid = $hookmanager->resArray['targetid'];
  3520. }
  3521. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3522. $justsource = true; // the source (id and type) is a search criteria
  3523. if (!empty($targettype)) {
  3524. $withtargettype = true;
  3525. }
  3526. }
  3527. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3528. $justtarget = true; // the target (id and type) is a search criteria
  3529. if (!empty($sourcetype)) {
  3530. $withsourcetype = true;
  3531. }
  3532. }
  3533. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3534. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3535. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3536. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3537. /*if (empty($sourceid) && empty($targetid))
  3538. {
  3539. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3540. return -1;
  3541. }*/
  3542. // Links between objects are stored in table element_element
  3543. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3544. $sql .= " FROM " . $this->db->prefix() . "element_element";
  3545. $sql .= " WHERE ";
  3546. if ($justsource || $justtarget) {
  3547. if ($justsource) {
  3548. $sql .= "fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3549. if ($withtargettype) {
  3550. $sql .= " AND targettype = '" . $this->db->escape($targettype) . "'";
  3551. }
  3552. } elseif ($justtarget) {
  3553. $sql .= "fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3554. if ($withsourcetype) {
  3555. $sql .= " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3556. }
  3557. }
  3558. } else {
  3559. $sql .= "(fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "')";
  3560. $sql .= " " . $clause . " (fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "')";
  3561. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3562. $this->linkedObjectsFullLoaded[$this->id] = true;
  3563. }
  3564. }
  3565. $sql .= " ORDER BY " . $orderby;
  3566. dol_syslog(get_class($this) . "::fetchObjectLink", LOG_DEBUG);
  3567. $resql = $this->db->query($sql);
  3568. if ($resql) {
  3569. $num = $this->db->num_rows($resql);
  3570. $i = 0;
  3571. while ($i < $num) {
  3572. $obj = $this->db->fetch_object($resql);
  3573. if ($justsource || $justtarget) {
  3574. if ($justsource) {
  3575. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3576. } elseif ($justtarget) {
  3577. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3578. }
  3579. } else {
  3580. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3581. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3582. }
  3583. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3584. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3585. }
  3586. }
  3587. $i++;
  3588. }
  3589. if (!empty($this->linkedObjectsIds)) {
  3590. $tmparray = $this->linkedObjectsIds;
  3591. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3592. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3593. $module = $element = $subelement = $objecttype;
  3594. $regs = array();
  3595. if (
  3596. $objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3597. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)
  3598. ) {
  3599. $module = $element = $regs[1];
  3600. $subelement = $regs[2];
  3601. }
  3602. $classpath = $element . '/class';
  3603. // To work with non standard classpath or module name
  3604. if ($objecttype == 'facture') {
  3605. $classpath = 'compta/facture/class';
  3606. } elseif ($objecttype == 'facturerec') {
  3607. $classpath = 'compta/facture/class';
  3608. $module = 'facture';
  3609. } elseif ($objecttype == 'propal') {
  3610. $classpath = 'comm/propal/class';
  3611. } elseif ($objecttype == 'supplier_proposal') {
  3612. $classpath = 'supplier_proposal/class';
  3613. } elseif ($objecttype == 'shipping') {
  3614. $classpath = 'expedition/class';
  3615. $subelement = 'expedition';
  3616. $module = 'expedition_bon';
  3617. } elseif ($objecttype == 'delivery') {
  3618. $classpath = 'delivery/class';
  3619. $subelement = 'delivery';
  3620. $module = 'delivery_note';
  3621. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3622. $classpath = 'fourn/class';
  3623. $module = 'fournisseur';
  3624. } elseif ($objecttype == 'fichinter') {
  3625. $classpath = 'fichinter/class';
  3626. $subelement = 'fichinter';
  3627. $module = 'ficheinter';
  3628. } elseif ($objecttype == 'subscription') {
  3629. $classpath = 'adherents/class';
  3630. $module = 'adherent';
  3631. } elseif ($objecttype == 'contact') {
  3632. $module = 'societe';
  3633. }
  3634. // Set classfile
  3635. $classfile = strtolower($subelement);
  3636. $classname = ucfirst($subelement);
  3637. if ($objecttype == 'order') {
  3638. $classfile = 'commande';
  3639. $classname = 'Commande';
  3640. } elseif ($objecttype == 'invoice_supplier') {
  3641. $classfile = 'fournisseur.facture';
  3642. $classname = 'FactureFournisseur';
  3643. } elseif ($objecttype == 'order_supplier') {
  3644. $classfile = 'fournisseur.commande';
  3645. $classname = 'CommandeFournisseur';
  3646. } elseif ($objecttype == 'supplier_proposal') {
  3647. $classfile = 'supplier_proposal';
  3648. $classname = 'SupplierProposal';
  3649. } elseif ($objecttype == 'facturerec') {
  3650. $classfile = 'facture-rec';
  3651. $classname = 'FactureRec';
  3652. } elseif ($objecttype == 'subscription') {
  3653. $classfile = 'subscription';
  3654. $classname = 'Subscription';
  3655. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3656. $classpath = 'projet/class';
  3657. $classfile = 'project';
  3658. $classname = 'Project';
  3659. } elseif ($objecttype == 'conferenceorboothattendee') {
  3660. $classpath = 'eventorganization/class';
  3661. $classfile = 'conferenceorboothattendee';
  3662. $classname = 'ConferenceOrBoothAttendee';
  3663. $module = 'eventorganization';
  3664. } elseif ($objecttype == 'conferenceorbooth') {
  3665. $classpath = 'eventorganization/class';
  3666. $classfile = 'conferenceorbooth';
  3667. $classname = 'ConferenceOrBooth';
  3668. $module = 'eventorganization';
  3669. } elseif ($objecttype == 'mo') {
  3670. $classpath = 'mrp/class';
  3671. $classfile = 'mo';
  3672. $classname = 'Mo';
  3673. $module = 'mrp';
  3674. }
  3675. // Here $module, $classfile and $classname are set, we can use them.
  3676. if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
  3677. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3678. dol_include_once('/' . $classpath . '/' . $classfile . '.class.php');
  3679. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3680. if (class_exists($classname)) {
  3681. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3682. $object = new $classname($this->db);
  3683. $ret = $object->fetch($objectid);
  3684. if ($ret >= 0) {
  3685. $this->linkedObjects[$objecttype][$i] = $object;
  3686. }
  3687. }
  3688. }
  3689. }
  3690. } else {
  3691. unset($this->linkedObjectsIds[$objecttype]);
  3692. }
  3693. }
  3694. }
  3695. return 1;
  3696. } else {
  3697. dol_print_error($this->db);
  3698. return -1;
  3699. }
  3700. }
  3701. /**
  3702. * Clear the cache saying that all linked object were already loaded. So next fetchObjectLinked will reload all links.
  3703. *
  3704. * @return int <0 if KO, >0 if OK
  3705. * @see fetchObjectLinked()
  3706. */
  3707. public function clearObjectLinkedCache()
  3708. {
  3709. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3710. unset($this->linkedObjectsFullLoaded[$this->id]);
  3711. }
  3712. return 1;
  3713. }
  3714. /**
  3715. * Update object linked of a current object
  3716. *
  3717. * @param int $sourceid Object source id
  3718. * @param string $sourcetype Object source type
  3719. * @param int $targetid Object target id
  3720. * @param string $targettype Object target type
  3721. * @param User $f_user User that create
  3722. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3723. * @return int >0 if OK, <0 if KO
  3724. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3725. */
  3726. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3727. {
  3728. global $user;
  3729. $updatesource = false;
  3730. $updatetarget = false;
  3731. $f_user = isset($f_user) ? $f_user : $user;
  3732. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3733. $updatesource = true;
  3734. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3735. $updatetarget = true;
  3736. }
  3737. $this->db->begin();
  3738. $error = 0;
  3739. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3740. if ($updatesource) {
  3741. $sql .= "fk_source = " . ((int) $sourceid);
  3742. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3743. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3744. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3745. } elseif ($updatetarget) {
  3746. $sql .= "fk_target = " . ((int) $targetid);
  3747. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3748. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3749. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3750. }
  3751. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3752. if ($this->db->query($sql)) {
  3753. if (!$notrigger) {
  3754. // Call trigger
  3755. $this->context['link_source_id'] = $sourceid;
  3756. $this->context['link_source_type'] = $sourcetype;
  3757. $this->context['link_target_id'] = $targetid;
  3758. $this->context['link_target_type'] = $targettype;
  3759. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3760. if ($result < 0) {
  3761. $error++;
  3762. }
  3763. // End call triggers
  3764. }
  3765. } else {
  3766. $this->error = $this->db->lasterror();
  3767. $error++;
  3768. }
  3769. if (!$error) {
  3770. $this->db->commit();
  3771. return 1;
  3772. } else {
  3773. $this->db->rollback();
  3774. return -1;
  3775. }
  3776. }
  3777. /**
  3778. * Delete all links between an object $this
  3779. *
  3780. * @param int $sourceid Object source id
  3781. * @param string $sourcetype Object source type
  3782. * @param int $targetid Object target id
  3783. * @param string $targettype Object target type
  3784. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3785. * @param User $f_user User that create
  3786. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3787. * @return int >0 if OK, <0 if KO
  3788. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3789. */
  3790. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3791. {
  3792. global $user;
  3793. $deletesource = false;
  3794. $deletetarget = false;
  3795. $f_user = isset($f_user) ? $f_user : $user;
  3796. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3797. $deletesource = true;
  3798. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3799. $deletetarget = true;
  3800. }
  3801. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3802. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3803. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3804. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3805. $this->db->begin();
  3806. $error = 0;
  3807. if (!$notrigger) {
  3808. // Call trigger
  3809. $this->context['link_id'] = $rowid;
  3810. $this->context['link_source_id'] = $sourceid;
  3811. $this->context['link_source_type'] = $sourcetype;
  3812. $this->context['link_target_id'] = $targetid;
  3813. $this->context['link_target_type'] = $targettype;
  3814. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3815. if ($result < 0) {
  3816. $error++;
  3817. }
  3818. // End call triggers
  3819. }
  3820. if (!$error) {
  3821. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3822. $sql .= " WHERE";
  3823. if ($rowid > 0) {
  3824. $sql .= " rowid = " . ((int) $rowid);
  3825. } else {
  3826. if ($deletesource) {
  3827. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3828. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3829. } elseif ($deletetarget) {
  3830. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3831. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3832. } else {
  3833. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3834. $sql .= " OR";
  3835. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3836. }
  3837. }
  3838. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3839. if (!$this->db->query($sql)) {
  3840. $this->error = $this->db->lasterror();
  3841. $this->errors[] = $this->error;
  3842. $error++;
  3843. }
  3844. }
  3845. if (!$error) {
  3846. $this->db->commit();
  3847. return 1;
  3848. } else {
  3849. $this->db->rollback();
  3850. return 0;
  3851. }
  3852. }
  3853. /**
  3854. * Function used to get an array with all items linked to an object id in association table
  3855. *
  3856. * @param int $fk_object_where id of object we need to get linked items
  3857. * @param string $field_select name of field we need to get a list
  3858. * @param string $field_where name of field of object we need to get linked items
  3859. * @param string $table_element name of association table
  3860. * @return array Array of record
  3861. */
  3862. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3863. {
  3864. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3865. return -1;
  3866. }
  3867. global $db;
  3868. $sql = "SELECT " . $field_select . " FROM " . $db->prefix() . $table_element . " WHERE " . $field_where . " = " . ((int) $fk_object_where);
  3869. $resql = $db->query($sql);
  3870. $TRes = array();
  3871. if (!empty($resql)) {
  3872. while ($res = $db->fetch_object($resql)) {
  3873. $TRes[] = $res->{$field_select};
  3874. }
  3875. }
  3876. return $TRes;
  3877. }
  3878. /**
  3879. * Function used to remove all items linked to an object id in association table
  3880. *
  3881. * @param int $fk_object_where id of object we need to remove linked items
  3882. * @param string $field_where name of field of object we need to delete linked items
  3883. * @param string $table_element name of association table
  3884. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3885. */
  3886. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3887. {
  3888. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3889. return -1;
  3890. }
  3891. global $db;
  3892. $sql = "DELETE FROM " . $db->prefix() . $table_element . " WHERE " . $field_where . " = " . ((int) $fk_object_where);
  3893. $resql = $db->query($sql);
  3894. if (empty($resql)) {
  3895. return 0;
  3896. }
  3897. return 1;
  3898. }
  3899. /**
  3900. * Set status of an object.
  3901. *
  3902. * @param int $status Status to set
  3903. * @param int $elementId Id of element to force (use this->id by default if null)
  3904. * @param string $elementType Type of element to force (use this->table_element by default)
  3905. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated.
  3906. * @param string $fieldstatus Name of status field in this->table_element
  3907. * @return int <0 if KO, >0 if OK
  3908. */
  3909. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3910. {
  3911. global $user, $langs, $conf;
  3912. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3913. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3914. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3915. $this->db->begin();
  3916. if ($elementTable == 'facture_rec') {
  3917. $fieldstatus = "suspended";
  3918. }
  3919. if ($elementTable == 'mailing') {
  3920. $fieldstatus = "statut";
  3921. }
  3922. if ($elementTable == 'cronjob') {
  3923. $fieldstatus = "status";
  3924. }
  3925. if ($elementTable == 'user') {
  3926. $fieldstatus = "statut";
  3927. }
  3928. if ($elementTable == 'expensereport') {
  3929. $fieldstatus = "fk_statut";
  3930. }
  3931. if ($elementTable == 'commande_fournisseur_dispatch') {
  3932. $fieldstatus = "status";
  3933. }
  3934. if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3935. $fieldstatus = 'status';
  3936. }
  3937. $sql = "UPDATE " . $this->db->prefix() . $elementTable;
  3938. $sql .= " SET " . $fieldstatus . " = " . ((int) $status);
  3939. // If status = 1 = validated, update also fk_user_valid
  3940. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3941. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3942. $sql .= ", fk_user_valid = " . ((int) $user->id);
  3943. }
  3944. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3945. $sql .= ", date_valid = '" . $this->db->idate(dol_now()) . "'";
  3946. }
  3947. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3948. $sql .= ", date_validation = '" . $this->db->idate(dol_now()) . "'";
  3949. }
  3950. $sql .= " WHERE rowid = " . ((int) $elementId);
  3951. $sql .= " AND " . $fieldstatus . " <> " . ((int) $status); // We avoid update if status already correct
  3952. dol_syslog(get_class($this) . "::setStatut", LOG_DEBUG);
  3953. $resql = $this->db->query($sql);
  3954. if ($resql) {
  3955. $error = 0;
  3956. $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
  3957. if ($nb_rows_affected > 0) {
  3958. if (empty($trigkey)) {
  3959. // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
  3960. if ($this->element == 'supplier_proposal' && $status == 2) {
  3961. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3962. }
  3963. if ($this->element == 'supplier_proposal' && $status == 3) {
  3964. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3965. }
  3966. if ($this->element == 'supplier_proposal' && $status == 4) {
  3967. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3968. }
  3969. if ($this->element == 'fichinter' && $status == 3) {
  3970. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3971. }
  3972. if ($this->element == 'fichinter' && $status == 2) {
  3973. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3974. }
  3975. if ($this->element == 'fichinter' && $status == 1) {
  3976. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3977. }
  3978. }
  3979. if ($trigkey) {
  3980. // Call trigger
  3981. $result = $this->call_trigger($trigkey, $user);
  3982. if ($result < 0) {
  3983. $error++;
  3984. }
  3985. // End call triggers
  3986. }
  3987. } else {
  3988. // The status was probably already good. We do nothing more, no triggers.
  3989. }
  3990. if (!$error) {
  3991. $this->db->commit();
  3992. if (empty($savElementId)) {
  3993. // If the element we update is $this (so $elementId was provided as null)
  3994. if ($fieldstatus == 'tosell') {
  3995. $this->status = $status;
  3996. } elseif ($fieldstatus == 'tobuy') {
  3997. $this->status_buy = $status;
  3998. } else {
  3999. $this->statut = $status;
  4000. $this->status = $status;
  4001. }
  4002. }
  4003. return 1;
  4004. } else {
  4005. $this->db->rollback();
  4006. dol_syslog(get_class($this) . "::setStatut " . $this->error, LOG_ERR);
  4007. return -1;
  4008. }
  4009. } else {
  4010. $this->error = $this->db->lasterror();
  4011. $this->db->rollback();
  4012. return -1;
  4013. }
  4014. }
  4015. /**
  4016. * Load type of canvas of an object if it exists
  4017. *
  4018. * @param int $id Record id
  4019. * @param string $ref Record ref
  4020. * @return int <0 if KO, 0 if nothing done, >0 if OK
  4021. */
  4022. public function getCanvas($id = 0, $ref = '')
  4023. {
  4024. global $conf;
  4025. if (empty($id) && empty($ref)) {
  4026. return 0;
  4027. }
  4028. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  4029. return 0; // To increase speed. Not enabled by default.
  4030. }
  4031. // Clean parameters
  4032. $ref = trim($ref);
  4033. $sql = "SELECT rowid, canvas";
  4034. $sql .= " FROM " . $this->db->prefix() . $this->table_element;
  4035. $sql .= " WHERE entity IN (" . getEntity($this->element) . ")";
  4036. if (!empty($id)) {
  4037. $sql .= " AND rowid = " . ((int) $id);
  4038. }
  4039. if (!empty($ref)) {
  4040. $sql .= " AND ref = '" . $this->db->escape($ref) . "'";
  4041. }
  4042. $resql = $this->db->query($sql);
  4043. if ($resql) {
  4044. $obj = $this->db->fetch_object($resql);
  4045. if ($obj) {
  4046. $this->canvas = $obj->canvas;
  4047. return 1;
  4048. } else {
  4049. return 0;
  4050. }
  4051. } else {
  4052. dol_print_error($this->db);
  4053. return -1;
  4054. }
  4055. }
  4056. /**
  4057. * Get special code of a line
  4058. *
  4059. * @param int $lineid Id of line
  4060. * @return int Special code
  4061. */
  4062. public function getSpecialCode($lineid)
  4063. {
  4064. $sql = "SELECT special_code FROM " . $this->db->prefix() . $this->table_element_line;
  4065. $sql .= " WHERE rowid = " . ((int) $lineid);
  4066. $resql = $this->db->query($sql);
  4067. if ($resql) {
  4068. $row = $this->db->fetch_row($resql);
  4069. return $row[0];
  4070. }
  4071. }
  4072. /**
  4073. * Function to check if an object is used by others.
  4074. * Check is done into this->childtables. There is no check into llx_element_element.
  4075. *
  4076. * @param int $id Force id of object
  4077. * @param int $entity Force entity to check
  4078. * @return int <0 if KO, 0 if not used, >0 if already used
  4079. */
  4080. public function isObjectUsed($id = 0, $entity = 0)
  4081. {
  4082. global $langs;
  4083. if (empty($id)) {
  4084. $id = $this->id;
  4085. }
  4086. // Check parameters
  4087. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  4088. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  4089. return -1;
  4090. }
  4091. $arraytoscan = $this->childtables;
  4092. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  4093. $tmparray = array_keys($this->childtables);
  4094. if (is_numeric($tmparray[0])) {
  4095. $arraytoscan = array_flip($this->childtables);
  4096. }
  4097. // Test if child exists
  4098. $haschild = 0;
  4099. foreach ($arraytoscan as $table => $element) {
  4100. //print $id.'-'.$table.'-'.$elementname.'<br>';
  4101. // Check if element can be deleted
  4102. $sql = "SELECT COUNT(*) as nb";
  4103. $sql .= " FROM " . $this->db->prefix() . $table . " as c";
  4104. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4105. $sql .= ", " . $this->db->prefix() . $element['parent'] . " as p";
  4106. }
  4107. $sql .= " WHERE c." . $this->fk_element . " = " . ((int) $id);
  4108. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4109. $sql .= " AND c." . $element['parentkey'] . " = p.rowid";
  4110. }
  4111. if (!empty($entity)) {
  4112. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4113. $sql .= " AND p.entity = " . ((int) $entity);
  4114. } else {
  4115. $sql .= " AND c.entity = " . ((int) $entity);
  4116. }
  4117. }
  4118. $resql = $this->db->query($sql);
  4119. if ($resql) {
  4120. $obj = $this->db->fetch_object($resql);
  4121. if ($obj->nb > 0) {
  4122. $langs->load("errors");
  4123. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4124. $haschild += $obj->nb;
  4125. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4126. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4127. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4128. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4129. } else { // new usage: $element['name']=Translation key
  4130. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4131. }
  4132. break; // We found at least one, we stop here
  4133. }
  4134. } else {
  4135. $this->errors[] = $this->db->lasterror();
  4136. return -1;
  4137. }
  4138. }
  4139. if ($haschild > 0) {
  4140. $this->errors[] = "ErrorRecordHasChildren";
  4141. return $haschild;
  4142. } else {
  4143. return 0;
  4144. }
  4145. }
  4146. /**
  4147. * Function to say how many lines object contains
  4148. *
  4149. * @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
  4150. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4151. */
  4152. public function hasProductsOrServices($predefined = -1)
  4153. {
  4154. $nb = 0;
  4155. foreach ($this->lines as $key => $val) {
  4156. $qualified = 0;
  4157. if ($predefined == -1) {
  4158. $qualified = 1;
  4159. }
  4160. if ($predefined == 1 && $val->fk_product > 0) {
  4161. $qualified = 1;
  4162. }
  4163. if ($predefined == 0 && $val->fk_product <= 0) {
  4164. $qualified = 1;
  4165. }
  4166. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4167. $qualified = 1;
  4168. }
  4169. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4170. $qualified = 1;
  4171. }
  4172. if ($qualified) {
  4173. $nb++;
  4174. }
  4175. }
  4176. dol_syslog(get_class($this) . '::hasProductsOrServices we found ' . $nb . ' qualified lines of products/servcies');
  4177. return $nb;
  4178. }
  4179. /**
  4180. * Function that returns the total amount HT of discounts applied for all lines.
  4181. *
  4182. * @return float|string Total amout of discount
  4183. */
  4184. public function getTotalDiscount()
  4185. {
  4186. if (!empty($this->table_element_line)) {
  4187. $total_discount = 0.00;
  4188. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4189. $sql .= " FROM " . $this->db->prefix() . $this->table_element_line;
  4190. $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  4191. dol_syslog(get_class($this) . '::getTotalDiscount', LOG_DEBUG);
  4192. $resql = $this->db->query($sql);
  4193. if ($resql) {
  4194. $num = $this->db->num_rows($resql);
  4195. $i = 0;
  4196. while ($i < $num) {
  4197. $obj = $this->db->fetch_object($resql);
  4198. $pu_ht = $obj->pu_ht;
  4199. $qty = $obj->qty;
  4200. $total_ht = $obj->total_ht;
  4201. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4202. $total_discount += $total_discount_line;
  4203. $i++;
  4204. }
  4205. }
  4206. //print $total_discount; exit;
  4207. return price2num($total_discount);
  4208. }
  4209. return null;
  4210. }
  4211. /**
  4212. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4213. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4214. *
  4215. * @return array array('weight'=>...,'volume'=>...)
  4216. */
  4217. public function getTotalWeightVolume()
  4218. {
  4219. $totalWeight = 0;
  4220. $totalVolume = 0;
  4221. // defined for shipment only
  4222. $totalOrdered = '';
  4223. // defined for shipment only
  4224. $totalToShip = '';
  4225. foreach ($this->lines as $line) {
  4226. if (isset($line->qty_asked)) {
  4227. if (empty($totalOrdered)) {
  4228. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4229. }
  4230. $totalOrdered += $line->qty_asked; // defined for shipment only
  4231. }
  4232. if (isset($line->qty_shipped)) {
  4233. if (empty($totalToShip)) {
  4234. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4235. }
  4236. $totalToShip += $line->qty_shipped; // defined for shipment only
  4237. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4238. if (empty($totalToShip)) {
  4239. $totalToShip = 0;
  4240. }
  4241. $totalToShip += $line->qty; // defined for reception only
  4242. }
  4243. // Define qty, weight, volume, weight_units, volume_units
  4244. if ($this->element == 'shipping') {
  4245. // for shipments
  4246. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4247. } else {
  4248. $qty = $line->qty ? $line->qty : 0;
  4249. }
  4250. $weight = !empty($line->weight) ? $line->weight : 0;
  4251. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4252. $volume = !empty($line->volume) ? $line->volume : 0;
  4253. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4254. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4255. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4256. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4257. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4258. $weightUnit = 0;
  4259. $volumeUnit = 0;
  4260. if (!empty($weight_units)) {
  4261. $weightUnit = $weight_units;
  4262. }
  4263. if (!empty($volume_units)) {
  4264. $volumeUnit = $volume_units;
  4265. }
  4266. if (empty($totalWeight)) {
  4267. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4268. }
  4269. if (empty($totalVolume)) {
  4270. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4271. }
  4272. //var_dump($line->volume_units);
  4273. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4274. $trueWeightUnit = pow(10, $weightUnit);
  4275. $totalWeight += $weight * $qty * $trueWeightUnit;
  4276. } else {
  4277. if ($weight_units == 99) {
  4278. // conversion 1 Pound = 0.45359237 KG
  4279. $trueWeightUnit = 0.45359237;
  4280. $totalWeight += $weight * $qty * $trueWeightUnit;
  4281. } elseif ($weight_units == 98) {
  4282. // conversion 1 Ounce = 0.0283495 KG
  4283. $trueWeightUnit = 0.0283495;
  4284. $totalWeight += $weight * $qty * $trueWeightUnit;
  4285. } else {
  4286. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4287. }
  4288. }
  4289. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4290. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4291. $trueVolumeUnit = pow(10, $volumeUnit);
  4292. //print $line->volume;
  4293. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4294. } else {
  4295. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4296. }
  4297. }
  4298. return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
  4299. }
  4300. /**
  4301. * Set extra parameters
  4302. *
  4303. * @return int <0 if KO, >0 if OK
  4304. */
  4305. public function setExtraParameters()
  4306. {
  4307. $this->db->begin();
  4308. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4309. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  4310. $sql .= " SET extraparams = " . (!empty($extraparams) ? "'" . $this->db->escape($extraparams) . "'" : "null");
  4311. $sql .= " WHERE rowid = " . ((int) $this->id);
  4312. dol_syslog(get_class($this) . "::setExtraParameters", LOG_DEBUG);
  4313. $resql = $this->db->query($sql);
  4314. if (!$resql) {
  4315. $this->error = $this->db->lasterror();
  4316. $this->db->rollback();
  4317. return -1;
  4318. } else {
  4319. $this->db->commit();
  4320. return 1;
  4321. }
  4322. }
  4323. // --------------------
  4324. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4325. // --------------------
  4326. /* This is to show add lines */
  4327. /**
  4328. * Show add free and predefined products/services form
  4329. *
  4330. * @param int $dateSelector 1=Show also date range input fields
  4331. * @param Societe $seller Object thirdparty who sell
  4332. * @param Societe $buyer Object thirdparty who buy
  4333. * @param string $defaulttpldir Directory where to find the template
  4334. * @return void
  4335. */
  4336. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4337. {
  4338. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4339. global $form;
  4340. // Line extrafield
  4341. if (!is_object($extrafields)) {
  4342. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  4343. $extrafields = new ExtraFields($this->db);
  4344. }
  4345. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4346. // Output template part (modules that overwrite templates must declare this into descriptor)
  4347. // Use global variables + $dateSelector + $seller and $buyer
  4348. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4349. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4350. foreach ($dirtpls as $module => $reldir) {
  4351. if (!empty($module)) {
  4352. $tpl = dol_buildpath($reldir . '/objectline_create.tpl.php');
  4353. } else {
  4354. $tpl = DOL_DOCUMENT_ROOT . $reldir . '/objectline_create.tpl.php';
  4355. }
  4356. if (empty($conf->file->strict_mode)) {
  4357. $res = @include $tpl;
  4358. } else {
  4359. $res = include $tpl; // for debug
  4360. }
  4361. if ($res) {
  4362. break;
  4363. }
  4364. }
  4365. }
  4366. /* This is to show array of line of details */
  4367. /**
  4368. * Return HTML table for object lines
  4369. * TODO Move this into an output class file (htmlline.class.php)
  4370. * If lines are into a template, title must also be into a template
  4371. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4372. *
  4373. * @param string $action Action code
  4374. * @param string $seller Object of seller third party
  4375. * @param string $buyer Object of buyer third party
  4376. * @param int $selected Object line selected
  4377. * @param int $dateSelector 1=Show also date range input fields
  4378. * @param string $defaulttpldir Directory where to find the template
  4379. * @return void
  4380. */
  4381. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4382. {
  4383. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4384. // TODO We should not use global var for this
  4385. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4386. // Define usemargins
  4387. $usemargins = 0;
  4388. if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4389. $usemargins = 1;
  4390. }
  4391. $num = count($this->lines);
  4392. // Line extrafield
  4393. if (!is_object($extrafields)) {
  4394. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  4395. $extrafields = new ExtraFields($this->db);
  4396. }
  4397. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4398. $parameters = array('num' => $num, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $this->table_element_line);
  4399. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4400. if (empty($reshook)) {
  4401. // Output template part (modules that overwrite templates must declare this into descriptor)
  4402. // Use global variables + $dateSelector + $seller and $buyer
  4403. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4404. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4405. foreach ($dirtpls as $module => $reldir) {
  4406. $res = 0;
  4407. if (!empty($module)) {
  4408. $tpl = dol_buildpath($reldir . '/objectline_title.tpl.php');
  4409. } else {
  4410. $tpl = DOL_DOCUMENT_ROOT . $reldir . '/objectline_title.tpl.php';
  4411. }
  4412. if (file_exists($tpl)) {
  4413. if (empty($conf->file->strict_mode)) {
  4414. $res = @include $tpl;
  4415. } else {
  4416. $res = include $tpl; // for debug
  4417. }
  4418. }
  4419. if ($res) {
  4420. break;
  4421. }
  4422. }
  4423. }
  4424. $i = 0;
  4425. print "<!-- begin printObjectLines() --><tbody>\n";
  4426. foreach ($this->lines as $line) {
  4427. //Line extrafield
  4428. $line->fetch_optionals();
  4429. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
  4430. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4431. if (empty($line->fk_parent_line)) {
  4432. $parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $line->table_element);
  4433. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4434. } else {
  4435. $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);
  4436. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4437. }
  4438. }
  4439. if (empty($reshook)) {
  4440. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4441. }
  4442. $i++;
  4443. }
  4444. print "</tbody><!-- end printObjectLines() -->\n";
  4445. }
  4446. /**
  4447. * Return HTML content of a detail line
  4448. * TODO Move this into an output class file (htmlline.class.php)
  4449. *
  4450. * @param string $action GET/POST action
  4451. * @param CommonObjectLine $line Selected object line to output
  4452. * @param string $var Not used
  4453. * @param int $num Number of line (0)
  4454. * @param int $i I
  4455. * @param int $dateSelector 1=Show also date range input fields
  4456. * @param string $seller Object of seller third party
  4457. * @param string $buyer Object of buyer third party
  4458. * @param int $selected Object line selected
  4459. * @param Extrafields $extrafields Object of extrafields
  4460. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4461. * @return void
  4462. */
  4463. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4464. {
  4465. global $conf, $langs, $user, $object, $hookmanager;
  4466. global $form;
  4467. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4468. $object_rights = $this->getRights();
  4469. $element = $this->element;
  4470. $text = '';
  4471. $description = '';
  4472. // Line in view mode
  4473. if ($action != 'editline' || $selected != $line->id) {
  4474. // Product
  4475. if (!empty($line->fk_product) && $line->fk_product > 0) {
  4476. $product_static = new Product($this->db);
  4477. $product_static->fetch($line->fk_product);
  4478. $product_static->ref = $line->ref; //can change ref in hook
  4479. $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
  4480. $text = $product_static->getNomUrl(1);
  4481. // Define output language and label
  4482. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  4483. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4484. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4485. return;
  4486. }
  4487. $prod = new Product($this->db);
  4488. $prod->fetch($line->fk_product);
  4489. $outputlangs = $langs;
  4490. $newlang = '';
  4491. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4492. $newlang = GETPOST('lang_id', 'aZ09');
  4493. }
  4494. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4495. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4496. }
  4497. if (!empty($newlang)) {
  4498. $outputlangs = new Translate("", $conf);
  4499. $outputlangs->setDefaultLang($newlang);
  4500. }
  4501. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4502. } else {
  4503. $label = $line->product_label;
  4504. }
  4505. $text .= ' - ' . (!empty($line->label) ? $line->label : $label);
  4506. $description .= (getDolGlobalInt('PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
  4507. }
  4508. $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
  4509. // Output template part (modules that overwrite templates must declare this into descriptor)
  4510. // Use global variables + $dateSelector + $seller and $buyer
  4511. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4512. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4513. foreach ($dirtpls as $module => $reldir) {
  4514. $res = 0;
  4515. if (!empty($module)) {
  4516. $tpl = dol_buildpath($reldir . '/objectline_view.tpl.php');
  4517. } else {
  4518. $tpl = DOL_DOCUMENT_ROOT . $reldir . '/objectline_view.tpl.php';
  4519. }
  4520. if (file_exists($tpl)) {
  4521. if (empty($conf->file->strict_mode)) {
  4522. $res = @include $tpl;
  4523. } else {
  4524. $res = include $tpl; // for debug
  4525. }
  4526. }
  4527. if ($res) {
  4528. break;
  4529. }
  4530. }
  4531. }
  4532. // Line in update mode
  4533. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4534. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4535. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4536. // Output template part (modules that overwrite templates must declare this into descriptor)
  4537. // Use global variables + $dateSelector + $seller and $buyer
  4538. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4539. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4540. foreach ($dirtpls as $module => $reldir) {
  4541. if (!empty($module)) {
  4542. $tpl = dol_buildpath($reldir . '/objectline_edit.tpl.php');
  4543. } else {
  4544. $tpl = DOL_DOCUMENT_ROOT . $reldir . '/objectline_edit.tpl.php';
  4545. }
  4546. if (empty($conf->file->strict_mode)) {
  4547. $res = @include $tpl;
  4548. } else {
  4549. $res = include $tpl; // for debug
  4550. }
  4551. if ($res) {
  4552. break;
  4553. }
  4554. }
  4555. }
  4556. }
  4557. /* This is to show array of line of details of source object */
  4558. /**
  4559. * Return HTML table table of source object lines
  4560. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4561. * If lines are into a template, title must also be into a template
  4562. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4563. *
  4564. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4565. * @param array $selectedLines Array of lines id for selected lines
  4566. * @return void
  4567. */
  4568. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4569. {
  4570. global $langs, $hookmanager, $conf, $form, $action;
  4571. print '<tr class="liste_titre">';
  4572. print '<td class="linecolref">' . $langs->trans('Ref') . '</td>';
  4573. print '<td class="linecoldescription">' . $langs->trans('Description') . '</td>';
  4574. print '<td class="linecolvat right">' . $langs->trans('VATRate') . '</td>';
  4575. print '<td class="linecoluht right">' . $langs->trans('PriceUHT') . '</td>';
  4576. if (isModEnabled("multicurrency")) {
  4577. print '<td class="linecoluht_currency right">' . $langs->trans('PriceUHTCurrency') . '</td>';
  4578. }
  4579. print '<td class="linecolqty right">' . $langs->trans('Qty') . '</td>';
  4580. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4581. print '<td class="linecoluseunit left">' . $langs->trans('Unit') . '</td>';
  4582. }
  4583. print '<td class="linecoldiscount right">' . $langs->trans('ReductionShort') . '</td>';
  4584. print '<td class="linecolht right">' . $langs->trans('TotalHT') . '</td>';
  4585. print '<td class="center">' . $form->showCheckAddButtons('checkforselect', 1) . '</td>';
  4586. print '</tr>';
  4587. $i = 0;
  4588. if (!empty($this->lines)) {
  4589. foreach ($this->lines as $line) {
  4590. $reshook = 0;
  4591. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4592. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4593. $parameters = array('line' => $line, 'i' => $i, 'restrictlist' => $restrictlist, 'selectedLines' => $selectedLines);
  4594. if (!empty($line->fk_parent_line)) {
  4595. $parameters['fk_parent_line'] = $line->fk_parent_line;
  4596. }
  4597. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4598. }
  4599. if (empty($reshook)) {
  4600. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4601. }
  4602. $i++;
  4603. }
  4604. }
  4605. }
  4606. /**
  4607. * Return HTML with a line of table array of source object lines
  4608. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4609. * If lines are into a template, title must also be into a template
  4610. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4611. *
  4612. * @param CommonObjectLine $line Line
  4613. * @param string $var Var
  4614. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4615. * @param string $defaulttpldir Directory where to find the template
  4616. * @param array $selectedLines Array of lines id for selected lines
  4617. * @return void
  4618. */
  4619. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4620. {
  4621. global $langs, $conf;
  4622. //var_dump($line);
  4623. if (!empty($line->date_start)) {
  4624. $date_start = $line->date_start;
  4625. } else {
  4626. $date_start = $line->date_debut_prevue;
  4627. if ($line->date_debut_reel) {
  4628. $date_start = $line->date_debut_reel;
  4629. }
  4630. }
  4631. if (!empty($line->date_end)) {
  4632. $date_end = $line->date_end;
  4633. } else {
  4634. $date_end = $line->date_fin_prevue;
  4635. if ($line->date_fin_reel) {
  4636. $date_end = $line->date_fin_reel;
  4637. }
  4638. }
  4639. $this->tpl['id'] = $line->id;
  4640. $this->tpl['label'] = '';
  4641. if (!empty($line->fk_parent_line)) {
  4642. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4643. }
  4644. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4645. $discount = new DiscountAbsolute($this->db);
  4646. $discount->fk_soc = $this->socid;
  4647. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4648. } elseif (!empty($line->fk_product)) {
  4649. $productstatic = new Product($this->db);
  4650. $productstatic->id = $line->fk_product;
  4651. $productstatic->ref = $line->ref;
  4652. $productstatic->type = $line->fk_product_type;
  4653. if (empty($productstatic->ref)) {
  4654. $line->fetch_product();
  4655. $productstatic = $line->product;
  4656. }
  4657. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4658. $this->tpl['label'] .= ' - ' . (!empty($line->label) ? $line->label : $line->product_label);
  4659. // Dates
  4660. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4661. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4662. }
  4663. } else {
  4664. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4665. if (!empty($line->desc)) {
  4666. $this->tpl['label'] .= $line->desc;
  4667. } else {
  4668. $this->tpl['label'] .= ($line->label ? '&nbsp;' . $line->label : '');
  4669. }
  4670. // Dates
  4671. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4672. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4673. }
  4674. }
  4675. if (!empty($line->desc)) {
  4676. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4677. $discount = new DiscountAbsolute($this->db);
  4678. $discount->fetch($line->fk_remise_except);
  4679. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4680. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4681. $discount = new DiscountAbsolute($this->db);
  4682. $discount->fetch($line->fk_remise_except);
  4683. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4684. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4685. $discount = new DiscountAbsolute($this->db);
  4686. $discount->fetch($line->fk_remise_except);
  4687. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4688. } elseif ($line->desc == '(EXCESS PAID)') {
  4689. $discount = new DiscountAbsolute($this->db);
  4690. $discount->fetch($line->fk_remise_except);
  4691. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4692. } else {
  4693. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4694. }
  4695. } else {
  4696. $this->tpl['description'] = '&nbsp;';
  4697. }
  4698. // VAT Rate
  4699. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4700. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4701. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4702. $this->tpl['vat_rate'] .= ' (' . $line->vat_src_code . ')';
  4703. }
  4704. $this->tpl['price'] = price($line->subprice);
  4705. $this->tpl['total_ht'] = price($line->total_ht);
  4706. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4707. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4708. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4709. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4710. }
  4711. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4712. // Is the line strike or not
  4713. $this->tpl['strike'] = 0;
  4714. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4715. $this->tpl['strike'] = 1;
  4716. }
  4717. // Output template part (modules that overwrite templates must declare this into descriptor)
  4718. // Use global variables + $dateSelector + $seller and $buyer
  4719. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4720. foreach ($dirtpls as $module => $reldir) {
  4721. if (!empty($module)) {
  4722. $tpl = dol_buildpath($reldir . '/originproductline.tpl.php');
  4723. } else {
  4724. $tpl = DOL_DOCUMENT_ROOT . $reldir . '/originproductline.tpl.php';
  4725. }
  4726. if (empty($conf->file->strict_mode)) {
  4727. $res = @include $tpl;
  4728. } else {
  4729. $res = include $tpl; // for debug
  4730. }
  4731. if ($res) {
  4732. break;
  4733. }
  4734. }
  4735. }
  4736. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4737. /**
  4738. * Add resources to the current object : add entry into llx_element_resources
  4739. * Need $this->element & $this->id
  4740. *
  4741. * @param int $resource_id Resource id
  4742. * @param string $resource_type 'resource'
  4743. * @param int $busy Busy or not
  4744. * @param int $mandatory Mandatory or not
  4745. * @return int <=0 if KO, >0 if OK
  4746. */
  4747. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4748. {
  4749. // phpcs:enable
  4750. $this->db->begin();
  4751. $sql = "INSERT INTO " . $this->db->prefix() . "element_resources (";
  4752. $sql .= "resource_id";
  4753. $sql .= ", resource_type";
  4754. $sql .= ", element_id";
  4755. $sql .= ", element_type";
  4756. $sql .= ", busy";
  4757. $sql .= ", mandatory";
  4758. $sql .= ") VALUES (";
  4759. $sql .= $resource_id;
  4760. $sql .= ", '" . $this->db->escape($resource_type) . "'";
  4761. $sql .= ", '" . $this->db->escape($this->id) . "'";
  4762. $sql .= ", '" . $this->db->escape($this->element) . "'";
  4763. $sql .= ", '" . $this->db->escape($busy) . "'";
  4764. $sql .= ", '" . $this->db->escape($mandatory) . "'";
  4765. $sql .= ")";
  4766. dol_syslog(get_class($this) . "::add_element_resource", LOG_DEBUG);
  4767. if ($this->db->query($sql)) {
  4768. $this->db->commit();
  4769. return 1;
  4770. } else {
  4771. $this->error = $this->db->lasterror();
  4772. $this->db->rollback();
  4773. return 0;
  4774. }
  4775. }
  4776. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4777. /**
  4778. * Delete a link to resource line
  4779. *
  4780. * @param int $rowid Id of resource line to delete
  4781. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4782. * @param int $notrigger Disable all triggers
  4783. * @return int >0 if OK, <0 if KO
  4784. */
  4785. public function delete_resource($rowid, $element, $notrigger = 0)
  4786. {
  4787. // phpcs:enable
  4788. global $user;
  4789. $this->db->begin();
  4790. $sql = "DELETE FROM " . $this->db->prefix() . "element_resources";
  4791. $sql .= " WHERE rowid = " . ((int) $rowid);
  4792. dol_syslog(get_class($this) . "::delete_resource", LOG_DEBUG);
  4793. $resql = $this->db->query($sql);
  4794. if (!$resql) {
  4795. $this->error = $this->db->lasterror();
  4796. $this->db->rollback();
  4797. return -1;
  4798. } else {
  4799. if (!$notrigger) {
  4800. $result = $this->call_trigger(strtoupper($element) . '_DELETE_RESOURCE', $user);
  4801. if ($result < 0) {
  4802. $this->db->rollback();
  4803. return -1;
  4804. }
  4805. }
  4806. $this->db->commit();
  4807. return 1;
  4808. }
  4809. }
  4810. /**
  4811. * Overwrite magic function to solve problem of cloning object that are kept as references
  4812. *
  4813. * @return void
  4814. */
  4815. public function __clone()
  4816. {
  4817. // Force a copy of this->lines, otherwise it will point to same object.
  4818. if (isset($this->lines) && is_array($this->lines)) {
  4819. $nboflines = count($this->lines);
  4820. for ($i = 0; $i < $nboflines; $i++) {
  4821. $this->lines[$i] = clone $this->lines[$i];
  4822. }
  4823. }
  4824. }
  4825. /**
  4826. * Common function for all objects extending CommonObject for generating documents
  4827. *
  4828. * @param string $modelspath Relative folder where generators are placed
  4829. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4830. * @param Translate $outputlangs Output language to use
  4831. * @param int $hidedetails 1 to hide details. 0 by default
  4832. * @param int $hidedesc 1 to hide product description. 0 by default
  4833. * @param int $hideref 1 to hide product reference. 0 by default
  4834. * @param null|array $moreparams Array to provide more information
  4835. * @return int >0 if OK, <0 if KO
  4836. * @see addFileIntoDatabaseIndex()
  4837. */
  4838. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4839. {
  4840. global $conf, $langs, $user, $hookmanager, $action;
  4841. $srctemplatepath = '';
  4842. $parameters = array('modelspath' => $modelspath, 'modele' => $modele, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'hidedesc' => $hidedesc, 'hideref' => $hideref, 'moreparams' => $moreparams);
  4843. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4844. if (empty($reshook)) {
  4845. dol_syslog("commonGenerateDocument modele=" . $modele . " outputlangs->defaultlang=" . (is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4846. if (empty($modele)) {
  4847. $this->error = 'BadValueForParameterModele';
  4848. return -1;
  4849. }
  4850. // Increase limit for PDF build
  4851. $err = error_reporting();
  4852. error_reporting(0);
  4853. @set_time_limit(120);
  4854. error_reporting($err);
  4855. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4856. $tmp = explode(':', $modele, 2);
  4857. if (!empty($tmp[1])) {
  4858. $modele = $tmp[0];
  4859. $srctemplatepath = $tmp[1];
  4860. }
  4861. // Search template files
  4862. $file = '';
  4863. $classname = '';
  4864. $filefound = '';
  4865. $dirmodels = array('/');
  4866. if (is_array($conf->modules_parts['models'])) {
  4867. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4868. }
  4869. foreach ($dirmodels as $reldir) {
  4870. foreach (array('doc', 'pdf') as $prefix) {
  4871. if (in_array(get_class($this), array('Adherent'))) {
  4872. // Member module use prefix_modele.class.php
  4873. $file = $prefix . "_" . $modele . ".class.php";
  4874. } else {
  4875. // Other module use prefix_modele.modules.php
  4876. $file = $prefix . "_" . $modele . ".modules.php";
  4877. }
  4878. // On verifie l'emplacement du modele
  4879. $file = dol_buildpath($reldir . $modelspath . $file, 0);
  4880. if (file_exists($file)) {
  4881. $filefound = $file;
  4882. $classname = $prefix . '_' . $modele;
  4883. break;
  4884. }
  4885. }
  4886. if ($filefound) {
  4887. break;
  4888. }
  4889. }
  4890. // If generator was found
  4891. if ($filefound) {
  4892. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4893. require_once $file;
  4894. $obj = new $classname($this->db);
  4895. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4896. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4897. $varfortemplatedir = $obj->scandir;
  4898. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4899. $dirtoscan = $conf->global->$varfortemplatedir;
  4900. $listoffiles = array();
  4901. // Now we add first model found in directories scanned
  4902. $listofdir = explode(',', $dirtoscan);
  4903. foreach ($listofdir as $key => $tmpdir) {
  4904. $tmpdir = trim($tmpdir);
  4905. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4906. if (!$tmpdir) {
  4907. unset($listofdir[$key]);
  4908. continue;
  4909. }
  4910. if (is_dir($tmpdir)) {
  4911. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4912. if (count($tmpfiles)) {
  4913. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4914. }
  4915. }
  4916. }
  4917. if (count($listoffiles)) {
  4918. foreach ($listoffiles as $record) {
  4919. $srctemplatepath = $record['fullname'];
  4920. break;
  4921. }
  4922. }
  4923. }
  4924. if (empty($srctemplatepath)) {
  4925. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4926. return -1;
  4927. }
  4928. }
  4929. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4930. if (!dol_is_file($srctemplatepath)) {
  4931. dol_syslog("Failed to locate template file " . $srctemplatepath, LOG_WARNING);
  4932. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4933. return -1;
  4934. }
  4935. }
  4936. // We save charset_output to restore it because write_file can change it if needed for
  4937. // output format that does not support UTF8.
  4938. $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
  4939. if (in_array(get_class($this), array('Adherent'))) {
  4940. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4941. } else {
  4942. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4943. }
  4944. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4945. if ($resultwritefile > 0) {
  4946. $outputlangs->charset_output = $sav_charset_output;
  4947. // We delete old preview
  4948. require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  4949. dol_delete_preview($this);
  4950. // Index file in database
  4951. if (!empty($obj->result['fullpath'])) {
  4952. $destfull = $obj->result['fullpath'];
  4953. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4954. $update_main_doc_field = 0;
  4955. if (!empty($obj->update_main_doc_field)) {
  4956. $update_main_doc_field = 1;
  4957. }
  4958. $this->indexFile($destfull, $update_main_doc_field);
  4959. } else {
  4960. 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);
  4961. }
  4962. // Success in building document. We build meta file.
  4963. dol_meta_create($this);
  4964. return 1;
  4965. } else {
  4966. $outputlangs->charset_output = $sav_charset_output;
  4967. $this->error = $obj->error;
  4968. $this->errors = $obj->errors;
  4969. dol_syslog("Error generating document for " . __CLASS__ . ". Error: " . $obj->error, LOG_ERR);
  4970. return -1;
  4971. }
  4972. } else {
  4973. if (!$filefound) {
  4974. $this->error = $langs->trans("Error") . ' Failed to load doc generator with modelpaths=' . $modelspath . ' - modele=' . $modele;
  4975. $this->errors[] = $this->error;
  4976. dol_syslog($this->error, LOG_ERR);
  4977. } else {
  4978. $this->error = $langs->trans("Error") . " " . $langs->trans("ErrorFileDoesNotExists", $filefound);
  4979. $this->errors[] = $this->error;
  4980. dol_syslog($this->error, LOG_ERR);
  4981. }
  4982. return -1;
  4983. }
  4984. } else {
  4985. return $reshook;
  4986. }
  4987. }
  4988. /**
  4989. * Index a file into the ECM database
  4990. *
  4991. * @param string $destfull Full path of file to index
  4992. * @param int $update_main_doc_field Update field main_doc fied into the table of object.
  4993. * This param is set when called for a document generation if document generator hase
  4994. * ->update_main_doc_field set and returns ->result['fullpath'].
  4995. * @return int <0 if KO, >0 if OK
  4996. */
  4997. public function indexFile($destfull, $update_main_doc_field)
  4998. {
  4999. global $conf, $user;
  5000. $upload_dir = dirname($destfull);
  5001. $destfile = basename($destfull);
  5002. $rel_dir = preg_replace('/^' . preg_quote(DOL_DATA_ROOT, '/') . '/', '', $upload_dir);
  5003. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  5004. $filename = basename($destfile);
  5005. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  5006. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  5007. include_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
  5008. $ecmfile = new EcmFiles($this->db);
  5009. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir . '/' : '') . $filename);
  5010. // Set the public "share" key
  5011. $setsharekey = false;
  5012. if ($this->element == 'propal' || $this->element == 'proposal') {
  5013. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  5014. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  5015. }
  5016. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  5017. $setsharekey = true;
  5018. }
  5019. }
  5020. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  5021. $setsharekey = true;
  5022. }
  5023. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  5024. $setsharekey = true;
  5025. }
  5026. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5027. $setsharekey = true;
  5028. }
  5029. if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5030. $setsharekey = true;
  5031. }
  5032. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5033. $setsharekey = true;
  5034. }
  5035. if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
  5036. $setsharekey = true;
  5037. }
  5038. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  5039. $setsharekey = true;
  5040. }
  5041. if ($setsharekey) {
  5042. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  5043. require_once DOL_DOCUMENT_ROOT . '/core/lib/security2.lib.php';
  5044. $ecmfile->share = getRandomPassword(true);
  5045. }
  5046. }
  5047. if ($result > 0) {
  5048. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5049. $ecmfile->fullpath_orig = '';
  5050. $ecmfile->gen_or_uploaded = 'generated';
  5051. $ecmfile->description = ''; // indexed content
  5052. $ecmfile->keywords = ''; // keyword content
  5053. $result = $ecmfile->update($user);
  5054. if ($result < 0) {
  5055. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5056. return -1;
  5057. }
  5058. } else {
  5059. $ecmfile->entity = $conf->entity;
  5060. $ecmfile->filepath = $rel_dir;
  5061. $ecmfile->filename = $filename;
  5062. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5063. $ecmfile->fullpath_orig = '';
  5064. $ecmfile->gen_or_uploaded = 'generated';
  5065. $ecmfile->description = ''; // indexed content
  5066. $ecmfile->keywords = ''; // keyword content
  5067. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  5068. $ecmfile->src_object_id = $this->id;
  5069. $result = $ecmfile->create($user);
  5070. if ($result < 0) {
  5071. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5072. return -1;
  5073. }
  5074. }
  5075. /*$this->result['fullname']=$destfull;
  5076. $this->result['filepath']=$ecmfile->filepath;
  5077. $this->result['filename']=$ecmfile->filename;*/
  5078. //var_dump($obj->update_main_doc_field);exit;
  5079. if ($update_main_doc_field && !empty($this->table_element)) {
  5080. $sql = "UPDATE " . $this->db->prefix() . $this->table_element . " SET last_main_doc = '" . $this->db->escape($ecmfile->filepath . "/" . $ecmfile->filename) . "'";
  5081. $sql .= " WHERE rowid = " . ((int) $this->id);
  5082. $resql = $this->db->query($sql);
  5083. if (!$resql) {
  5084. dol_print_error($this->db);
  5085. return -1;
  5086. } else {
  5087. $this->last_main_doc = $ecmfile->filepath . '/' . $ecmfile->filename;
  5088. }
  5089. }
  5090. }
  5091. return 1;
  5092. }
  5093. /**
  5094. * Build thumb
  5095. * @todo Move this into files.lib.php
  5096. *
  5097. * @param string $file Path file in UTF8 to original file to create thumbs from.
  5098. * @return void
  5099. */
  5100. public function addThumbs($file)
  5101. {
  5102. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  5103. require_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  5104. $file_osencoded = dol_osencode($file);
  5105. if (file_exists($file_osencoded)) {
  5106. // Create small thumbs for company (Ratio is near 16/9)
  5107. // Used on logon for example
  5108. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  5109. // Create mini thumbs for company (Ratio is near 16/9)
  5110. // Used on menu or for setup page for example
  5111. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  5112. }
  5113. }
  5114. /* Functions common to commonobject and commonobjectline */
  5115. /* For default values */
  5116. /**
  5117. * Return the default value to use for a field when showing the create form of object.
  5118. * Return values in this order:
  5119. * 1) If parameter is available into POST, we return it first.
  5120. * 2) If not but an alternate value was provided as parameter of function, we return it.
  5121. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  5122. * 4) Return value found into database (TODO No yet implemented)
  5123. *
  5124. * @param string $fieldname Name of field
  5125. * @param string $alternatevalue Alternate value to use
  5126. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  5127. **/
  5128. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  5129. {
  5130. global $conf, $_POST;
  5131. // If param here has been posted, we use this value first.
  5132. if (GETPOSTISSET($fieldname)) {
  5133. return GETPOST($fieldname, 'alphanohtml', 3);
  5134. }
  5135. if (isset($alternatevalue)) {
  5136. return $alternatevalue;
  5137. }
  5138. $newelement = $this->element;
  5139. if ($newelement == 'facture') {
  5140. $newelement = 'invoice';
  5141. }
  5142. if ($newelement == 'commande') {
  5143. $newelement = 'order';
  5144. }
  5145. if (empty($newelement)) {
  5146. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5147. return '';
  5148. }
  5149. $keyforfieldname = strtoupper($newelement . '_DEFAULT_' . $fieldname);
  5150. //var_dump($keyforfieldname);
  5151. if (isset($conf->global->$keyforfieldname)) {
  5152. return $conf->global->$keyforfieldname;
  5153. }
  5154. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5155. }
  5156. /* For triggers */
  5157. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5158. /**
  5159. * Call trigger based on this instance.
  5160. * Some context information may also be provided into array property this->context.
  5161. * NB: Error from trigger are stacked in interface->errors
  5162. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5163. *
  5164. * @param string $triggerName trigger's name to execute
  5165. * @param User $user Object user
  5166. * @return int Result of run_triggers
  5167. */
  5168. public function call_trigger($triggerName, $user)
  5169. {
  5170. // phpcs:enable
  5171. global $langs, $conf;
  5172. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5173. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5174. exit;
  5175. }
  5176. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5177. include_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
  5178. $langs = new Translate('', $conf);
  5179. }
  5180. include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
  5181. $interface = new Interfaces($this->db);
  5182. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5183. if ($result < 0) {
  5184. if (!empty($this->errors)) {
  5185. $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.
  5186. } else {
  5187. $this->errors = $interface->errors;
  5188. }
  5189. }
  5190. return $result;
  5191. }
  5192. /* Functions for data in other language */
  5193. /**
  5194. * Function to get alternative languages of a data into $this->array_languages
  5195. * This method is NOT called by method fetch of objects but must be called separately.
  5196. *
  5197. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5198. * @see fetch_optionnals()
  5199. */
  5200. public function fetchValuesForExtraLanguages()
  5201. {
  5202. // To avoid SQL errors. Probably not the better solution though
  5203. if (!$this->element) {
  5204. return 0;
  5205. }
  5206. if (!($this->id > 0)) {
  5207. return 0;
  5208. }
  5209. if (is_array($this->array_languages)) {
  5210. return 1;
  5211. }
  5212. $this->array_languages = array();
  5213. $element = $this->element;
  5214. if ($element == 'categorie') {
  5215. $element = 'categories'; // For compatibility
  5216. }
  5217. // Request to get translation values for object
  5218. $sql = "SELECT rowid, property, lang , value";
  5219. $sql .= " FROM " . $this->db->prefix() . "object_lang";
  5220. $sql .= " WHERE type_object = '" . $this->db->escape($element) . "'";
  5221. $sql .= " AND fk_object = " . ((int) $this->id);
  5222. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5223. $resql = $this->db->query($sql);
  5224. if ($resql) {
  5225. $numrows = $this->db->num_rows($resql);
  5226. if ($numrows) {
  5227. $i = 0;
  5228. while ($i < $numrows) {
  5229. $obj = $this->db->fetch_object($resql);
  5230. $key = $obj->property;
  5231. $value = $obj->value;
  5232. $codelang = $obj->lang;
  5233. $type = $this->fields[$key]['type'];
  5234. // we can add this attribute to object
  5235. if (preg_match('/date/', $type)) {
  5236. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5237. } else {
  5238. $this->array_languages[$key][$codelang] = $value;
  5239. }
  5240. $i++;
  5241. }
  5242. }
  5243. $this->db->free($resql);
  5244. if ($numrows) {
  5245. return $numrows;
  5246. } else {
  5247. return 0;
  5248. }
  5249. } else {
  5250. dol_print_error($this->db);
  5251. return -1;
  5252. }
  5253. }
  5254. /**
  5255. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5256. *
  5257. * @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.
  5258. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5259. */
  5260. public function setValuesForExtraLanguages($onlykey = '')
  5261. {
  5262. global $_POST, $langs;
  5263. // Get extra fields
  5264. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5265. $tmparray = explode('-', $postfieldkey);
  5266. if ($tmparray[0] != 'field') {
  5267. continue;
  5268. }
  5269. $element = $tmparray[1];
  5270. $key = $tmparray[2];
  5271. $codelang = $tmparray[3];
  5272. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5273. if (!empty($onlykey) && $key != $onlykey) {
  5274. continue;
  5275. }
  5276. if ($element != $this->element) {
  5277. continue;
  5278. }
  5279. $key_type = $this->fields[$key]['type'];
  5280. $enabled = 1;
  5281. if (isset($this->fields[$key]['enabled'])) {
  5282. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5283. }
  5284. /*$perms = 1;
  5285. if (isset($this->fields[$key]['perms']))
  5286. {
  5287. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5288. }*/
  5289. if (empty($enabled)) {
  5290. continue;
  5291. }
  5292. //if (empty($perms)) continue;
  5293. if (in_array($key_type, array('date'))) {
  5294. // Clean parameters
  5295. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5296. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey . "month", 'int'), GETPOST($postfieldkey . "day", 'int'), GETPOST($postfieldkey . "year", 'int'));
  5297. } elseif (in_array($key_type, array('datetime'))) {
  5298. // Clean parameters
  5299. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5300. $value_key = dol_mktime(GETPOST($postfieldkey . "hour", 'int'), GETPOST($postfieldkey . "min", 'int'), 0, GETPOST($postfieldkey . "month", 'int'), GETPOST($postfieldkey . "day", 'int'), GETPOST($postfieldkey . "year", 'int'));
  5301. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5302. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5303. if (!empty($value_arr)) {
  5304. $value_key = implode(',', $value_arr);
  5305. } else {
  5306. $value_key = '';
  5307. }
  5308. } elseif (in_array($key_type, array('price', 'double'))) {
  5309. $value_arr = GETPOST($postfieldkey, 'alpha');
  5310. $value_key = price2num($value_arr);
  5311. } else {
  5312. $value_key = GETPOST($postfieldkey);
  5313. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5314. $value_key = '';
  5315. }
  5316. }
  5317. $this->array_languages[$key][$codelang] = $value_key;
  5318. /*if ($nofillrequired) {
  5319. $langs->load('errors');
  5320. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5321. return -1;
  5322. }*/
  5323. }
  5324. return 1;
  5325. }
  5326. /* Functions for extrafields */
  5327. /**
  5328. * Function to make a fetch but set environment to avoid to load computed values before.
  5329. *
  5330. * @param int $id ID of object
  5331. * @return int >0 if OK, 0 if not found, <0 if KO
  5332. */
  5333. public function fetchNoCompute($id)
  5334. {
  5335. global $conf;
  5336. $savDisableCompute = $conf->disable_compute;
  5337. $conf->disable_compute = 1;
  5338. $ret = $this->fetch($id);
  5339. $conf->disable_compute = $savDisableCompute;
  5340. return $ret;
  5341. }
  5342. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5343. /**
  5344. * Function to get extra fields of an object into $this->array_options
  5345. * This method is in most cases called by method fetch of objects but you can call it separately.
  5346. *
  5347. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5348. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5349. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5350. * @see fetchValuesForExtraLanguages()
  5351. */
  5352. public function fetch_optionals($rowid = null, $optionsArray = null)
  5353. {
  5354. // phpcs:enable
  5355. global $conf, $extrafields;
  5356. if (empty($rowid)) {
  5357. $rowid = $this->id;
  5358. }
  5359. if (empty($rowid) && isset($this->rowid)) {
  5360. $rowid = $this->rowid; // deprecated
  5361. }
  5362. // To avoid SQL errors. Probably not the better solution though
  5363. if (!$this->table_element) {
  5364. return 0;
  5365. }
  5366. $this->array_options = array();
  5367. if (!is_array($optionsArray)) {
  5368. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5369. if (!isset($extrafields) || !is_object($extrafields)) {
  5370. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  5371. $extrafields = new ExtraFields($this->db);
  5372. }
  5373. // Load array of extrafields for elementype = $this->table_element
  5374. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5375. $extrafields->fetch_name_optionals_label($this->table_element);
  5376. }
  5377. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5378. } else {
  5379. global $extrafields;
  5380. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5381. }
  5382. $table_element = $this->table_element;
  5383. if ($table_element == 'categorie') {
  5384. $table_element = 'categories'; // For compatibility
  5385. }
  5386. // Request to get complementary values
  5387. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5388. $sql = "SELECT rowid";
  5389. foreach ($optionsArray as $name => $label) {
  5390. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5391. $sql .= ", " . $name;
  5392. }
  5393. }
  5394. $sql .= " FROM " . $this->db->prefix() . $table_element . "_extrafields";
  5395. $sql .= " WHERE fk_object = " . ((int) $rowid);
  5396. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5397. $resql = $this->db->query($sql);
  5398. if ($resql) {
  5399. $numrows = $this->db->num_rows($resql);
  5400. if ($numrows) {
  5401. $tab = $this->db->fetch_array($resql);
  5402. foreach ($tab as $key => $value) {
  5403. // 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)
  5404. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5405. // we can add this attribute to object
  5406. if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5407. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5408. $this->array_options["options_" . $key] = $this->db->jdate($value);
  5409. } else {
  5410. $this->array_options["options_" . $key] = $value;
  5411. }
  5412. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5413. }
  5414. }
  5415. }
  5416. // If field is a computed field, value must become result of compute (regardless of whether a row exists
  5417. // in the element's extrafields table)
  5418. if (is_array($extrafields->attributes[$this->table_element]['label'])) {
  5419. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  5420. if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5421. //var_dump($conf->disable_compute);
  5422. if (empty($conf->disable_compute)) {
  5423. global $objectoffield; // We set a global variable to $objectoffield so
  5424. $objectoffield = $this; // we can use it inside computed formula
  5425. $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5426. }
  5427. }
  5428. }
  5429. }
  5430. $this->db->free($resql);
  5431. if ($numrows) {
  5432. return $numrows;
  5433. } else {
  5434. return 0;
  5435. }
  5436. } else {
  5437. $this->errors[] = $this->db->lasterror;
  5438. return -1;
  5439. }
  5440. }
  5441. return 0;
  5442. }
  5443. /**
  5444. * Delete all extra fields values for the current object.
  5445. *
  5446. * @return int <0 if KO, >0 if OK
  5447. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5448. */
  5449. public function deleteExtraFields()
  5450. {
  5451. global $conf;
  5452. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5453. return 0;
  5454. }
  5455. $this->db->begin();
  5456. $table_element = $this->table_element;
  5457. if ($table_element == 'categorie') {
  5458. $table_element = 'categories'; // For compatibility
  5459. }
  5460. dol_syslog(get_class($this) . "::deleteExtraFields delete", LOG_DEBUG);
  5461. $sql_del = "DELETE FROM " . $this->db->prefix() . $table_element . "_extrafields WHERE fk_object = " . ((int) $this->id);
  5462. $resql = $this->db->query($sql_del);
  5463. if (!$resql) {
  5464. $this->error = $this->db->lasterror();
  5465. $this->db->rollback();
  5466. return -1;
  5467. } else {
  5468. $this->db->commit();
  5469. return 1;
  5470. }
  5471. }
  5472. /**
  5473. * Add/Update all extra fields values for the current object.
  5474. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5475. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5476. *
  5477. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5478. * @param User $userused Object user
  5479. * @return int -1=error, O=did nothing, 1=OK
  5480. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5481. */
  5482. public function insertExtraFields($trigger = '', $userused = null)
  5483. {
  5484. global $conf, $langs, $user;
  5485. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5486. return 0;
  5487. }
  5488. if (empty($userused)) {
  5489. $userused = $user;
  5490. }
  5491. $error = 0;
  5492. if (!empty($this->array_options)) {
  5493. // Check parameters
  5494. $langs->load('admin');
  5495. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  5496. $extrafields = new ExtraFields($this->db);
  5497. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5498. // Eliminate copied source object extra fields that do not exist in target object
  5499. $new_array_options = array();
  5500. foreach ($this->array_options as $key => $value) {
  5501. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5502. $new_array_options[$key] = $value;
  5503. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5504. $new_array_options['options_' . $key] = $value;
  5505. }
  5506. }
  5507. foreach ($new_array_options as $key => $value) {
  5508. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5509. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5510. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5511. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5512. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5513. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5514. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5515. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5516. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5517. if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
  5518. $new_array_options[$key] = null;
  5519. }
  5520. // Similar code than into insertExtraFields
  5521. if ($attributeRequired) {
  5522. $mandatorypb = false;
  5523. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5524. $mandatorypb = true;
  5525. }
  5526. if ($this->array_options[$key] === '') {
  5527. $mandatorypb = true;
  5528. }
  5529. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5530. $mandatorypb = true;
  5531. }
  5532. if ($mandatorypb) {
  5533. $langs->load("errors");
  5534. dol_syslog("Mandatory field '" . $key . "' is empty during create and set to required into definition of extrafields");
  5535. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5536. return -1;
  5537. }
  5538. }
  5539. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5540. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5541. if (!empty($attrfieldcomputed)) {
  5542. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5543. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5544. dol_syslog($langs->trans("Extrafieldcomputed") . " sur " . $attributeLabel . "(" . $value . ")", LOG_DEBUG);
  5545. $new_array_options[$key] = $value;
  5546. } else {
  5547. $new_array_options[$key] = null;
  5548. }
  5549. }
  5550. switch ($attributeType) {
  5551. case 'int':
  5552. if (!is_numeric($value) && $value != '') {
  5553. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5554. return -1;
  5555. } elseif ($value == '') {
  5556. $new_array_options[$key] = null;
  5557. }
  5558. break;
  5559. case 'price':
  5560. case 'double':
  5561. $value = price2num($value);
  5562. if (!is_numeric($value) && $value != '') {
  5563. dol_syslog($langs->trans("ExtraFieldHasWrongValue") . " for " . $attributeLabel . "(" . $value . "is not '" . $attributeType . "')", LOG_DEBUG);
  5564. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5565. return -1;
  5566. } elseif ($value == '') {
  5567. $value = null;
  5568. }
  5569. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5570. $new_array_options[$key] = $value;
  5571. break;
  5572. /*case 'select': // Not required, we chosed value='0' for undefined values
  5573. if ($value=='-1')
  5574. {
  5575. $this->array_options[$key] = null;
  5576. }
  5577. break;*/
  5578. case 'password':
  5579. $algo = '';
  5580. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5581. // If there is an encryption choice, we use it to crypt data before insert
  5582. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5583. $algo = reset($tmparrays);
  5584. if ($algo != '') {
  5585. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5586. //var_dump($action);
  5587. //var_dump($this->oldcopy);exit;
  5588. 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
  5589. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5590. if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) { // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
  5591. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5592. } else {
  5593. // var_dump($algo);
  5594. $newvalue = dol_hash($this->array_options[$key], $algo);
  5595. $new_array_options[$key] = $newvalue;
  5596. }
  5597. } else {
  5598. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5599. }
  5600. }
  5601. } else // Common usage
  5602. {
  5603. $new_array_options[$key] = $this->array_options[$key];
  5604. }
  5605. break;
  5606. case 'date':
  5607. case 'datetime':
  5608. // If data is a string instead of a timestamp, we convert it
  5609. if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
  5610. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5611. }
  5612. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5613. break;
  5614. case 'link':
  5615. $param_list = array_keys($attributeParam['options']);
  5616. // 0 : ObjectName
  5617. // 1 : classPath
  5618. $InfoFieldList = explode(":", $param_list[0]);
  5619. dol_include_once($InfoFieldList[1]);
  5620. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5621. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5622. $new_array_options[$key] = '';
  5623. } elseif ($value) {
  5624. $object = new $InfoFieldList[0]($this->db);
  5625. if (is_numeric($value)) {
  5626. $res = $object->fetch($value); // Common case
  5627. } else {
  5628. $res = $object->fetch('', $value); // For compatibility
  5629. }
  5630. if ($res > 0) {
  5631. $new_array_options[$key] = $object->id;
  5632. } else {
  5633. $this->error = "Id/Ref '" . $value . "' for object '" . $object->element . "' not found";
  5634. return -1;
  5635. }
  5636. }
  5637. } else {
  5638. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5639. }
  5640. break;
  5641. }
  5642. }
  5643. $this->db->begin();
  5644. $table_element = $this->table_element;
  5645. if ($table_element == 'categorie') {
  5646. $table_element = 'categories'; // For compatibility
  5647. }
  5648. dol_syslog(get_class($this) . "::insertExtraFields delete then insert", LOG_DEBUG);
  5649. $sql_del = "DELETE FROM " . $this->db->prefix() . $table_element . "_extrafields WHERE fk_object = " . ((int) $this->id);
  5650. $this->db->query($sql_del);
  5651. $sql = "INSERT INTO " . $this->db->prefix() . $table_element . "_extrafields (fk_object";
  5652. foreach ($new_array_options as $key => $value) {
  5653. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5654. // Add field of attribut
  5655. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5656. $sql .= "," . $attributeKey;
  5657. }
  5658. }
  5659. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5660. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5661. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5662. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5663. $sql .= "," . $tmpkey;
  5664. }
  5665. }
  5666. }
  5667. $sql .= ") VALUES (" . $this->id;
  5668. foreach ($new_array_options as $key => $value) {
  5669. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5670. // Add field of attribute
  5671. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5672. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5673. $sql .= ",'" . $this->db->escape($new_array_options[$key]) . "'";
  5674. } else {
  5675. $sql .= ",null";
  5676. }
  5677. }
  5678. }
  5679. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5680. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5681. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5682. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5683. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5684. $sql .= ", 0";
  5685. } else {
  5686. $sql .= ", ''";
  5687. }
  5688. }
  5689. }
  5690. }
  5691. $sql .= ")";
  5692. $resql = $this->db->query($sql);
  5693. if (!$resql) {
  5694. $this->error = $this->db->lasterror();
  5695. $error++;
  5696. }
  5697. if (!$error && $trigger) {
  5698. // Call trigger
  5699. $this->context = array('extrafieldaddupdate' => 1);
  5700. $result = $this->call_trigger($trigger, $userused);
  5701. if ($result < 0) {
  5702. $error++;
  5703. }
  5704. // End call trigger
  5705. }
  5706. if ($error) {
  5707. $this->db->rollback();
  5708. return -1;
  5709. } else {
  5710. $this->db->commit();
  5711. return 1;
  5712. }
  5713. } else {
  5714. return 0;
  5715. }
  5716. }
  5717. /**
  5718. * Add/Update all extra fields values for the current object.
  5719. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5720. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5721. *
  5722. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5723. * @param User $userused Object user
  5724. * @return int -1=error, O=did nothing, 1=OK
  5725. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5726. */
  5727. public function insertExtraLanguages($trigger = '', $userused = null)
  5728. {
  5729. global $conf, $langs, $user;
  5730. if (empty($userused)) {
  5731. $userused = $user;
  5732. }
  5733. $error = 0;
  5734. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5735. return 0; // For avoid conflicts if trigger used
  5736. }
  5737. if (is_array($this->array_languages)) {
  5738. $new_array_languages = $this->array_languages;
  5739. foreach ($new_array_languages as $key => $value) {
  5740. $attributeKey = $key;
  5741. $attributeType = $this->fields[$attributeKey]['type'];
  5742. $attributeLabel = $this->fields[$attributeKey]['label'];
  5743. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5744. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5745. switch ($attributeType) {
  5746. case 'int':
  5747. if (!is_numeric($value) && $value != '') {
  5748. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5749. return -1;
  5750. } elseif ($value == '') {
  5751. $new_array_languages[$key] = null;
  5752. }
  5753. break;
  5754. case 'double':
  5755. $value = price2num($value);
  5756. if (!is_numeric($value) && $value != '') {
  5757. dol_syslog($langs->trans("ExtraLanguageHasWrongValue") . " sur " . $attributeLabel . "(" . $value . "is not '" . $attributeType . "')", LOG_DEBUG);
  5758. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5759. return -1;
  5760. } elseif ($value == '') {
  5761. $new_array_languages[$key] = null;
  5762. }
  5763. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5764. $new_array_languages[$key] = $value;
  5765. break;
  5766. /*case 'select': // Not required, we chosed value='0' for undefined values
  5767. if ($value=='-1')
  5768. {
  5769. $this->array_options[$key] = null;
  5770. }
  5771. break;*/
  5772. }
  5773. }
  5774. $this->db->begin();
  5775. $table_element = $this->table_element;
  5776. if ($table_element == 'categorie') {
  5777. $table_element = 'categories'; // For compatibility
  5778. }
  5779. dol_syslog(get_class($this) . "::insertExtraLanguages delete then insert", LOG_DEBUG);
  5780. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5781. foreach ($langcodearray as $langcode => $value) {
  5782. $sql_del = "DELETE FROM " . $this->db->prefix() . "object_lang";
  5783. $sql_del .= " WHERE fk_object = " . ((int) $this->id) . " AND property = '" . $this->db->escape($key) . "' AND type_object = '" . $this->db->escape($table_element) . "'";
  5784. $sql_del .= " AND lang = '" . $this->db->escape($langcode) . "'";
  5785. $this->db->query($sql_del);
  5786. if ($value !== '') {
  5787. $sql = "INSERT INTO " . $this->db->prefix() . "object_lang (fk_object, property, type_object, lang, value";
  5788. $sql .= ") VALUES (" . $this->id . ", '" . $this->db->escape($key) . "', '" . $this->db->escape($table_element) . "', '" . $this->db->escape($langcode) . "', '" . $this->db->escape($value) . "'";
  5789. $sql .= ")";
  5790. $resql = $this->db->query($sql);
  5791. if (!$resql) {
  5792. $this->error = $this->db->lasterror();
  5793. $error++;
  5794. break;
  5795. }
  5796. }
  5797. }
  5798. }
  5799. if (!$error && $trigger) {
  5800. // Call trigger
  5801. $this->context = array('extralanguagesaddupdate' => 1);
  5802. $result = $this->call_trigger($trigger, $userused);
  5803. if ($result < 0) {
  5804. $error++;
  5805. }
  5806. // End call trigger
  5807. }
  5808. if ($error) {
  5809. $this->db->rollback();
  5810. return -1;
  5811. } else {
  5812. $this->db->commit();
  5813. return 1;
  5814. }
  5815. } else {
  5816. return 0;
  5817. }
  5818. }
  5819. /**
  5820. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5821. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5822. *
  5823. * @param string $key Key of the extrafield to update (without starting 'options_')
  5824. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5825. * @param User $userused Object user
  5826. * @return int -1=error, O=did nothing, 1=OK
  5827. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5828. */
  5829. public function updateExtraField($key, $trigger = null, $userused = null)
  5830. {
  5831. global $conf, $langs, $user;
  5832. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5833. return 0;
  5834. }
  5835. if (empty($userused)) {
  5836. $userused = $user;
  5837. }
  5838. $error = 0;
  5839. if (!empty($this->array_options) && isset($this->array_options["options_" . $key])) {
  5840. // Check parameters
  5841. $langs->load('admin');
  5842. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  5843. $extrafields = new ExtraFields($this->db);
  5844. $extrafields->fetch_name_optionals_label($this->table_element);
  5845. $value = $this->array_options["options_" . $key];
  5846. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5847. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5848. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5849. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5850. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5851. // Similar code than into insertExtraFields
  5852. if ($attributeRequired) {
  5853. $mandatorypb = false;
  5854. if ($attributeType == 'link' && $this->array_options["options_" . $key] == '-1') {
  5855. $mandatorypb = true;
  5856. }
  5857. if ($this->array_options["options_" . $key] === '') {
  5858. $mandatorypb = true;
  5859. }
  5860. if ($mandatorypb) {
  5861. $langs->load("errors");
  5862. dol_syslog("Mandatory field 'options_" . $key . "' is empty during update and set to required into definition of extrafields");
  5863. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5864. return -1;
  5865. }
  5866. }
  5867. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5868. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5869. if (!empty($attrfieldcomputed)) {
  5870. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5871. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5872. dol_syslog($langs->trans("Extrafieldcomputed") . " sur " . $attributeLabel . "(" . $value . ")", LOG_DEBUG);
  5873. $this->array_options["options_" . $key] = $value;
  5874. } else {
  5875. $this->array_options["options_" . $key] = null;
  5876. }
  5877. }
  5878. switch ($attributeType) {
  5879. case 'int':
  5880. if (!is_numeric($value) && $value != '') {
  5881. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5882. return -1;
  5883. } elseif ($value === '') {
  5884. $this->array_options["options_" . $key] = null;
  5885. }
  5886. break;
  5887. case 'double':
  5888. $value = price2num($value);
  5889. if (!is_numeric($value) && $value != '') {
  5890. dol_syslog($langs->trans("ExtraFieldHasWrongValue") . " sur " . $attributeLabel . "(" . $value . "is not '" . $attributeType . "')", LOG_DEBUG);
  5891. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5892. return -1;
  5893. } elseif ($value === '') {
  5894. $value = null;
  5895. }
  5896. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5897. $this->array_options["options_" . $key] = $value;
  5898. break;
  5899. /*case 'select': // Not required, we chosed value='0' for undefined values
  5900. if ($value=='-1')
  5901. {
  5902. $this->array_options[$key] = null;
  5903. }
  5904. break;*/
  5905. case 'price':
  5906. $this->array_options["options_" . $key] = price2num($this->array_options["options_" . $key]);
  5907. break;
  5908. case 'date':
  5909. case 'datetime':
  5910. if (empty($this->array_options["options_" . $key])) {
  5911. $this->array_options["options_" . $key] = null;
  5912. } else {
  5913. $this->array_options["options_" . $key] = $this->db->idate($this->array_options["options_" . $key]);
  5914. }
  5915. break;
  5916. case 'boolean':
  5917. if (empty($this->array_options["options_" . $key])) {
  5918. $this->array_options["options_" . $key] = null;
  5919. }
  5920. break;
  5921. /*
  5922. case 'link':
  5923. $param_list = array_keys($attributeParam['options']);
  5924. // 0 : ObjectName
  5925. // 1 : classPath
  5926. $InfoFieldList = explode(":", $param_list[0]);
  5927. dol_include_once($InfoFieldList[1]);
  5928. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5929. {
  5930. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5931. {
  5932. $new_array_options[$key] = '';
  5933. } elseif ($value) {
  5934. $object = new $InfoFieldList[0]($this->db);
  5935. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5936. else $res = $object->fetch('', $value); // For compatibility
  5937. if ($res > 0) $new_array_options[$key] = $object->id;
  5938. else {
  5939. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5940. $this->db->rollback();
  5941. return -1;
  5942. }
  5943. }
  5944. } else {
  5945. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5946. }
  5947. break;
  5948. */
  5949. }
  5950. $this->db->begin();
  5951. $linealreadyfound = 0;
  5952. // 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)
  5953. $sql = "SELECT COUNT(rowid) as nb FROM " . $this->db->prefix() . $this->table_element . "_extrafields WHERE fk_object = " . ((int) $this->id);
  5954. $resql = $this->db->query($sql);
  5955. if ($resql) {
  5956. $tmpobj = $this->db->fetch_object($resql);
  5957. if ($tmpobj) {
  5958. $linealreadyfound = $tmpobj->nb;
  5959. }
  5960. }
  5961. if ($linealreadyfound) {
  5962. if ($this->array_options["options_" . $key] === null) {
  5963. $sql = "UPDATE " . $this->db->prefix() . $this->table_element . "_extrafields SET " . $key . " = null";
  5964. } else {
  5965. $sql = "UPDATE " . $this->db->prefix() . $this->table_element . "_extrafields SET " . $key . " = '" . $this->db->escape($this->array_options["options_" . $key]) . "'";
  5966. }
  5967. $sql .= " WHERE fk_object = " . ((int) $this->id);
  5968. } else {
  5969. $result = $this->insertExtraFields('', $user);
  5970. if ($result < 0) {
  5971. $error++;
  5972. }
  5973. }
  5974. $resql = $this->db->query($sql);
  5975. if (!$resql) {
  5976. $error++;
  5977. $this->error = $this->db->lasterror();
  5978. }
  5979. if (!$error && $trigger) {
  5980. // Call trigger
  5981. $this->context = array('extrafieldupdate' => 1);
  5982. $result = $this->call_trigger($trigger, $userused);
  5983. if ($result < 0) {
  5984. $error++;
  5985. }
  5986. // End call trigger
  5987. }
  5988. if ($error) {
  5989. dol_syslog(__METHOD__ . $this->error, LOG_ERR);
  5990. $this->db->rollback();
  5991. return -1;
  5992. } else {
  5993. $this->db->commit();
  5994. return 1;
  5995. }
  5996. } else {
  5997. return 0;
  5998. }
  5999. }
  6000. /**
  6001. * Update an extra language value for the current object.
  6002. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  6003. *
  6004. * @param string $key Key of the extrafield (without starting 'options_')
  6005. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  6006. * @param User $userused Object user
  6007. * @return int -1=error, O=did nothing, 1=OK
  6008. * @see updateExtraFields(), insertExtraLanguages()
  6009. */
  6010. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  6011. {
  6012. global $conf, $langs, $user;
  6013. if (empty($userused)) {
  6014. $userused = $user;
  6015. }
  6016. $error = 0;
  6017. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  6018. return 0; // For avoid conflicts if trigger used
  6019. }
  6020. return 0;
  6021. }
  6022. /**
  6023. * Return HTML string to put an input field into a page
  6024. * Code very similar with showInputField of extra fields
  6025. *
  6026. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  6027. * @param string $key Key of attribute
  6028. * @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)
  6029. * @param string $moreparam To add more parameters on html input tag
  6030. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6031. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6032. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  6033. * @param int $nonewbutton Force to not show the new button on field that are links to object
  6034. * @return string
  6035. */
  6036. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  6037. {
  6038. global $conf, $langs, $form;
  6039. if (!is_object($form)) {
  6040. require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php';
  6041. $form = new Form($this->db);
  6042. }
  6043. if (!empty($this->fields)) {
  6044. $val = $this->fields[$key];
  6045. }
  6046. // Validation tests and output
  6047. $fieldValidationErrorMsg = '';
  6048. $validationClass = '';
  6049. $fieldValidationErrorMsg = $this->getFieldError($key);
  6050. if (!empty($fieldValidationErrorMsg)) {
  6051. $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
  6052. } else {
  6053. $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
  6054. }
  6055. $out = '';
  6056. $type = '';
  6057. $isDependList = 0;
  6058. $param = array();
  6059. $param['options'] = array();
  6060. $reg = array();
  6061. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  6062. // Because we work on extrafields
  6063. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6064. $param['options'] = array($reg[2] . ':' . $reg[3] . ':' . $reg[4] . ':' . $reg[5] => 'N');
  6065. $type = 'link';
  6066. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6067. $param['options'] = array($reg[2] . ':' . $reg[3] . ':' . $reg[4] => 'N');
  6068. $type = 'link';
  6069. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  6070. $param['options'] = array($reg[2] . ':' . $reg[3] => 'N');
  6071. $type = 'link';
  6072. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6073. $param['options'] = array($reg[2] . ':' . $reg[3] . ':' . $reg[4] . ':' . $reg[5] => 'N');
  6074. $type = 'sellist';
  6075. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6076. $param['options'] = array($reg[2] . ':' . $reg[3] . ':' . $reg[4] => 'N');
  6077. $type = 'sellist';
  6078. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  6079. $param['options'] = array($reg[2] . ':' . $reg[3] => 'N');
  6080. $type = 'sellist';
  6081. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6082. $param['options'] = array($reg[1] => 'N');
  6083. $type = 'chkbxlst';
  6084. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  6085. $param['options'] = array();
  6086. $type = 'varchar';
  6087. $size = $reg[1];
  6088. } elseif (preg_match('/varchar/', $val['type'])) {
  6089. $param['options'] = array();
  6090. $type = 'varchar';
  6091. } else {
  6092. $param['options'] = array();
  6093. $type = $this->fields[$key]['type'];
  6094. }
  6095. // Special case that force options and type ($type can be integer, varchar, ...)
  6096. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  6097. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  6098. $type = 'select';
  6099. }
  6100. $label = $this->fields[$key]['label'];
  6101. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  6102. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  6103. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  6104. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  6105. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  6106. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  6107. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  6108. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  6109. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  6110. $objectid = $this->id;
  6111. if ($computed) {
  6112. if (!preg_match('/^search_/', $keyprefix)) {
  6113. return '<span class="opacitymedium">' . $langs->trans("AutomaticallyCalculated") . '</span>';
  6114. } else {
  6115. return '';
  6116. }
  6117. }
  6118. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  6119. if (empty($morecss) && !empty($val['css'])) {
  6120. $morecss = $val['css'];
  6121. } elseif (empty($morecss)) {
  6122. if ($type == 'date') {
  6123. $morecss = 'minwidth100imp';
  6124. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  6125. $morecss = 'minwidth200imp';
  6126. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6127. $morecss = 'maxwidth75';
  6128. } elseif ($type == 'url') {
  6129. $morecss = 'minwidth400';
  6130. } elseif ($type == 'boolean') {
  6131. $morecss = '';
  6132. } else {
  6133. if (round($size) < 12) {
  6134. $morecss = 'minwidth100';
  6135. } elseif (round($size) <= 48) {
  6136. $morecss = 'minwidth200';
  6137. } else {
  6138. $morecss = 'minwidth400';
  6139. }
  6140. }
  6141. }
  6142. // Add validation state class
  6143. if (!empty($validationClass)) {
  6144. $morecss .= $validationClass;
  6145. }
  6146. if (in_array($type, array('date'))) {
  6147. $tmp = explode(',', $size);
  6148. $newsize = $tmp[0];
  6149. $showtime = 0;
  6150. // Do not show current date when field not required (see selectDate() method)
  6151. if (!$required && $value == '') {
  6152. $value = '-1';
  6153. }
  6154. // TODO Must also support $moreparam
  6155. $out = $form->selectDate($value, $keyprefix . $key . $keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6156. } elseif (in_array($type, array('datetime'))) {
  6157. $tmp = explode(',', $size);
  6158. $newsize = $tmp[0];
  6159. $showtime = 1;
  6160. // Do not show current date when field not required (see selectDate() method)
  6161. if (!$required && $value == '')
  6162. $value = '-1';
  6163. // TODO Must also support $moreparam
  6164. $out = $form->selectDate($value, $keyprefix . $key . $keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6165. } elseif (in_array($type, array('duration'))) {
  6166. $out = $form->select_duration($keyprefix . $key . $keysuffix, $value, 0, 'text', 0, 1);
  6167. } elseif (in_array($type, array('int', 'integer'))) {
  6168. $tmp = explode(',', $size);
  6169. $newsize = $tmp[0];
  6170. $out = '<input type="text" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '"' . ($newsize > 0 ? ' maxlength="' . $newsize . '"' : '') . ' value="' . dol_escape_htmltag($value) . '"' . ($moreparam ? $moreparam : '') . ($autofocusoncreate ? ' autofocus' : '') . '>';
  6171. } elseif (in_array($type, array('real'))) {
  6172. $out = '<input type="text" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . dol_escape_htmltag($value) . '"' . ($moreparam ? $moreparam : '') . ($autofocusoncreate ? ' autofocus' : '') . '>';
  6173. } elseif (preg_match('/varchar/', $type)) {
  6174. $out = '<input type="text" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '"' . ($size > 0 ? ' maxlength="' . $size . '"' : '') . ' value="' . dol_escape_htmltag($value) . '"' . ($moreparam ? $moreparam : '') . ($autofocusoncreate ? ' autofocus' : '') . '>';
  6175. } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
  6176. $out = '<input type="text" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . dol_escape_htmltag($value) . '" ' . ($moreparam ? $moreparam : '') . ($autofocusoncreate ? ' autofocus' : '') . '>';
  6177. } elseif (preg_match('/^text/', $type)) {
  6178. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6179. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  6180. $doleditor = new DolEditor($keyprefix . $key . $keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6181. $out = $doleditor->Create(1);
  6182. } else {
  6183. $out = '<input type="text" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . dol_escape_htmltag($value) . '" ' . ($moreparam ? $moreparam : '') . '>';
  6184. }
  6185. } elseif (preg_match('/^html/', $type)) {
  6186. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6187. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  6188. $doleditor = new DolEditor($keyprefix . $key . $keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
  6189. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6190. } else {
  6191. $out = '<input type="text" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . dol_escape_htmltag($value) . '" ' . ($moreparam ? $moreparam : '') . '>';
  6192. }
  6193. } elseif ($type == 'boolean') {
  6194. $checked = '';
  6195. if (!empty($value)) {
  6196. $checked = ' checked value="1" ';
  6197. } else {
  6198. $checked = ' value="1" ';
  6199. }
  6200. $out = '<input type="checkbox" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" ' . $checked . ' ' . ($moreparam ? $moreparam : '') . '>';
  6201. } elseif ($type == 'price') {
  6202. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6203. $value = price($value);
  6204. }
  6205. $out = '<input type="text" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . $value . '" ' . ($moreparam ? $moreparam : '') . '> ' . $langs->getCurrencySymbol($conf->currency);
  6206. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6207. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6208. $value = price($value);
  6209. }
  6210. $out = '<input type="text" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . $value . '" ' . ($moreparam ? $moreparam : '') . '> ';
  6211. } elseif ($type == 'select') {
  6212. $out = '';
  6213. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6214. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6215. $out .= ajax_combobox($keyprefix . $key . $keysuffix, array(), 0);
  6216. }
  6217. $out .= '<select class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" ' . ($moreparam ? $moreparam : '') . '>';
  6218. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6219. $out .= '<option value="0">&nbsp;</option>';
  6220. }
  6221. foreach ($param['options'] as $keyb => $valb) {
  6222. if ((string) $keyb == '') {
  6223. continue;
  6224. }
  6225. if (strpos($valb, "|") !== false) {
  6226. list($valb, $parent) = explode('|', $valb);
  6227. }
  6228. $out .= '<option value="' . $keyb . '"';
  6229. $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
  6230. $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
  6231. $out .= '>' . $valb . '</option>';
  6232. }
  6233. $out .= '</select>';
  6234. } elseif ($type == 'sellist') {
  6235. $out = '';
  6236. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6237. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6238. $out .= ajax_combobox($keyprefix . $key . $keysuffix, array(), 0);
  6239. }
  6240. $out .= '<select class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" ' . ($moreparam ? $moreparam : '') . '>';
  6241. if (is_array($param['options'])) {
  6242. $param_list = array_keys($param['options']);
  6243. $InfoFieldList = explode(":", $param_list[0]);
  6244. $parentName = '';
  6245. $parentField = '';
  6246. // 0 : tableName
  6247. // 1 : label field name
  6248. // 2 : key fields name (if differ of rowid)
  6249. // 3 : key field parent (for dependent lists)
  6250. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6251. // 5 : id category type
  6252. // 6 : ids categories list separated by comma for category root
  6253. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
  6254. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6255. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6256. $keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
  6257. } else {
  6258. $keyList = $InfoFieldList[2] . ' as rowid';
  6259. }
  6260. }
  6261. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6262. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6263. $keyList .= ', ' . $parentField;
  6264. }
  6265. $filter_categorie = false;
  6266. if (count($InfoFieldList) > 5) {
  6267. if ($InfoFieldList[0] == 'categorie') {
  6268. $filter_categorie = true;
  6269. }
  6270. }
  6271. if ($filter_categorie === false) {
  6272. $fields_label = explode('|', $InfoFieldList[1]);
  6273. if (is_array($fields_label)) {
  6274. $keyList .= ', ';
  6275. $keyList .= implode(', ', $fields_label);
  6276. }
  6277. $sqlwhere = '';
  6278. $sql = "SELECT " . $keyList;
  6279. $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
  6280. if (!empty($InfoFieldList[4])) {
  6281. // can use SELECT request
  6282. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6283. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6284. }
  6285. // current object id can be use into filter
  6286. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6287. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6288. } else {
  6289. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6290. }
  6291. //We have to join on extrafield table
  6292. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6293. $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra";
  6294. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6295. } else {
  6296. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6297. }
  6298. } else {
  6299. $sqlwhere .= ' WHERE 1=1';
  6300. }
  6301. // Some tables may have field, some other not. For the moment we disable it.
  6302. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6303. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6304. }
  6305. $sql .= $sqlwhere;
  6306. //print $sql;
  6307. $sql .= ' ORDER BY ' . implode(', ', $fields_label);
  6308. dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
  6309. $resql = $this->db->query($sql);
  6310. if ($resql) {
  6311. $out .= '<option value="0">&nbsp;</option>';
  6312. $num = $this->db->num_rows($resql);
  6313. $i = 0;
  6314. while ($i < $num) {
  6315. $labeltoshow = '';
  6316. $obj = $this->db->fetch_object($resql);
  6317. // Several field into label (eq table:code|libelle:rowid)
  6318. $notrans = false;
  6319. $fields_label = explode('|', $InfoFieldList[1]);
  6320. if (count($fields_label) > 1) {
  6321. $notrans = true;
  6322. foreach ($fields_label as $field_toshow) {
  6323. $labeltoshow .= $obj->$field_toshow . ' ';
  6324. }
  6325. } else {
  6326. $labeltoshow = $obj->{$InfoFieldList[1]};
  6327. }
  6328. $labeltoshow = dol_trunc($labeltoshow, 45);
  6329. if ($value == $obj->rowid) {
  6330. foreach ($fields_label as $field_toshow) {
  6331. $translabel = $langs->trans($obj->$field_toshow);
  6332. if ($translabel != $obj->$field_toshow) {
  6333. $labeltoshow = dol_trunc($translabel) . ' ';
  6334. } else {
  6335. $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
  6336. }
  6337. }
  6338. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6339. } else {
  6340. if (!$notrans) {
  6341. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6342. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6343. $labeltoshow = dol_trunc($translabel, 18);
  6344. } else {
  6345. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6346. }
  6347. }
  6348. if (empty($labeltoshow)) {
  6349. $labeltoshow = '(not defined)';
  6350. }
  6351. if ($value == $obj->rowid) {
  6352. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6353. }
  6354. if (!empty($InfoFieldList[3]) && $parentField) {
  6355. $parent = $parentName . ':' . $obj->{$parentField};
  6356. $isDependList = 1;
  6357. }
  6358. $out .= '<option value="' . $obj->rowid . '"';
  6359. $out .= ($value == $obj->rowid ? ' selected' : '');
  6360. $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
  6361. $out .= '>' . $labeltoshow . '</option>';
  6362. }
  6363. $i++;
  6364. }
  6365. $this->db->free($resql);
  6366. } else {
  6367. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6368. }
  6369. } else {
  6370. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6371. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6372. $out .= '<option value="0">&nbsp;</option>';
  6373. foreach ($data as $data_key => $data_value) {
  6374. $out .= '<option value="' . $data_key . '"';
  6375. $out .= ($value == $data_key ? ' selected' : '');
  6376. $out .= '>' . $data_value . '</option>';
  6377. }
  6378. }
  6379. }
  6380. $out .= '</select>';
  6381. } elseif ($type == 'checkbox') {
  6382. $value_arr = explode(',', $value);
  6383. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, (empty($param['options']) ? null : $param['options']), $value_arr, '', 0, $morecss, 0, '100%');
  6384. } elseif ($type == 'radio') {
  6385. $out = '';
  6386. foreach ($param['options'] as $keyopt => $valopt) {
  6387. $out .= '<input class="flat ' . $morecss . '" type="radio" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" ' . ($moreparam ? $moreparam : '');
  6388. $out .= ' value="' . $keyopt . '"';
  6389. $out .= ' id="' . $keyprefix . $key . $keysuffix . '_' . $keyopt . '"';
  6390. $out .= ($value == $keyopt ? 'checked' : '');
  6391. $out .= '/><label for="' . $keyprefix . $key . $keysuffix . '_' . $keyopt . '">' . $valopt . '</label><br>';
  6392. }
  6393. } elseif ($type == 'chkbxlst') {
  6394. if (is_array($value)) {
  6395. $value_arr = $value;
  6396. } else {
  6397. $value_arr = explode(',', $value);
  6398. }
  6399. if (is_array($param['options'])) {
  6400. $param_list = array_keys($param['options']);
  6401. $InfoFieldList = explode(":", $param_list[0]);
  6402. $parentName = '';
  6403. $parentField = '';
  6404. // 0 : tableName
  6405. // 1 : label field name
  6406. // 2 : key fields name (if differ of rowid)
  6407. // 3 : key field parent (for dependent lists)
  6408. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6409. // 5 : id category type
  6410. // 6 : ids categories list separated by comma for category root
  6411. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
  6412. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6413. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6414. $keyList .= ', ' . $parentField;
  6415. }
  6416. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6417. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6418. $keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
  6419. } else {
  6420. $keyList = $InfoFieldList[2] . ' as rowid';
  6421. }
  6422. }
  6423. $filter_categorie = false;
  6424. if (count($InfoFieldList) > 5) {
  6425. if ($InfoFieldList[0] == 'categorie') {
  6426. $filter_categorie = true;
  6427. }
  6428. }
  6429. if ($filter_categorie === false) {
  6430. $fields_label = explode('|', $InfoFieldList[1]);
  6431. if (is_array($fields_label)) {
  6432. $keyList .= ', ';
  6433. $keyList .= implode(', ', $fields_label);
  6434. }
  6435. $sqlwhere = '';
  6436. $sql = "SELECT " . $keyList;
  6437. $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
  6438. if (!empty($InfoFieldList[4])) {
  6439. // can use SELECT request
  6440. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6441. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6442. }
  6443. // current object id can be use into filter
  6444. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6445. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6446. } else {
  6447. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6448. }
  6449. // We have to join on extrafield table
  6450. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6451. $sql .= ' as main, ' . $this->db->prefix() . $InfoFieldList[0] . '_extrafields as extra';
  6452. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6453. } else {
  6454. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6455. }
  6456. } else {
  6457. $sqlwhere .= ' WHERE 1=1';
  6458. }
  6459. // Some tables may have field, some other not. For the moment we disable it.
  6460. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6461. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6462. }
  6463. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6464. // print $sql;
  6465. $sql .= $sqlwhere;
  6466. dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
  6467. $resql = $this->db->query($sql);
  6468. if ($resql) {
  6469. $num = $this->db->num_rows($resql);
  6470. $i = 0;
  6471. $data = array();
  6472. while ($i < $num) {
  6473. $labeltoshow = '';
  6474. $obj = $this->db->fetch_object($resql);
  6475. $notrans = false;
  6476. // Several field into label (eq table:code|libelle:rowid)
  6477. $fields_label = explode('|', $InfoFieldList[1]);
  6478. if (count($fields_label) > 1) {
  6479. $notrans = true;
  6480. foreach ($fields_label as $field_toshow) {
  6481. $labeltoshow .= $obj->$field_toshow . ' ';
  6482. }
  6483. } else {
  6484. $labeltoshow = $obj->{$InfoFieldList[1]};
  6485. }
  6486. $labeltoshow = dol_trunc($labeltoshow, 45);
  6487. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6488. foreach ($fields_label as $field_toshow) {
  6489. $translabel = $langs->trans($obj->$field_toshow);
  6490. if ($translabel != $obj->$field_toshow) {
  6491. $labeltoshow = dol_trunc($translabel, 18) . ' ';
  6492. } else {
  6493. $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
  6494. }
  6495. }
  6496. $data[$obj->rowid] = $labeltoshow;
  6497. } else {
  6498. if (!$notrans) {
  6499. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6500. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6501. $labeltoshow = dol_trunc($translabel, 18);
  6502. } else {
  6503. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6504. }
  6505. }
  6506. if (empty($labeltoshow)) {
  6507. $labeltoshow = '(not defined)';
  6508. }
  6509. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6510. $data[$obj->rowid] = $labeltoshow;
  6511. }
  6512. if (!empty($InfoFieldList[3]) && $parentField) {
  6513. $parent = $parentName . ':' . $obj->{$parentField};
  6514. $isDependList = 1;
  6515. }
  6516. $data[$obj->rowid] = $labeltoshow;
  6517. }
  6518. $i++;
  6519. }
  6520. $this->db->free($resql);
  6521. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6522. } else {
  6523. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6524. }
  6525. } else {
  6526. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6527. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6528. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6529. }
  6530. }
  6531. } elseif ($type == 'link') {
  6532. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6533. $param_list_array = explode(':', $param_list[0]);
  6534. $showempty = (($required && $default != '') ? 0 : 1);
  6535. if (!preg_match('/search_/', $keyprefix)) {
  6536. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6537. if (!empty($this->fields[$key]['picto'])) {
  6538. $morecss .= ' widthcentpercentminusxx';
  6539. } else {
  6540. $morecss .= ' widthcentpercentminusx';
  6541. }
  6542. } else {
  6543. if (!empty($this->fields[$key]['picto'])) {
  6544. $morecss .= ' widthcentpercentminusx';
  6545. }
  6546. }
  6547. }
  6548. $out = $form->selectForForms($param_list[0], $keyprefix . $key . $keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6549. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6550. 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".
  6551. list($class, $classfile) = explode(':', $param_list[0]);
  6552. if (file_exists(dol_buildpath(dirname(dirname($classfile)) . '/card.php'))) {
  6553. $url_path = dol_buildpath(dirname(dirname($classfile)) . '/card.php', 1);
  6554. } else {
  6555. $url_path = dol_buildpath(dirname(dirname($classfile)) . '/' . strtolower($class) . '_card.php', 1);
  6556. }
  6557. $paramforthenewlink = '';
  6558. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action=' . GETPOST('action', 'aZ09') : '');
  6559. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id=' . GETPOST('id', 'int') : '');
  6560. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin=' . GETPOST('origin', 'aZ09') : '');
  6561. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid=' . GETPOST('originid', 'int') : '');
  6562. $paramforthenewlink .= '&fk_' . strtolower($class) . '=--IDFORBACKTOPAGE--';
  6563. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6564. $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>';
  6565. }
  6566. }
  6567. } elseif ($type == 'password') {
  6568. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6569. $out = '<input type="' . ($keyprefix == 'search_' ? 'text' : 'password') . '" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . $value . '" ' . ($moreparam ? $moreparam : '') . '>';
  6570. } elseif ($type == 'array') {
  6571. $newval = $val;
  6572. $newval['type'] = 'varchar(256)';
  6573. $out = '';
  6574. if (!empty($value)) {
  6575. foreach ($value as $option) {
  6576. $out .= '<span><a class="' . dol_escape_htmltag($keyprefix . $key . $keysuffix) . '_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6577. $out .= $this->showInputField($newval, $keyprefix . $key . $keysuffix . '[]', $option, $moreparam, '', '', $morecss) . '<br></span>';
  6578. }
  6579. }
  6580. $out .= '<a id="' . dol_escape_htmltag($keyprefix . $key . $keysuffix) . '_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6581. $newInput = '<span><a class="' . dol_escape_htmltag($keyprefix . $key . $keysuffix) . '_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6582. $newInput .= $this->showInputField($newval, $keyprefix . $key . $keysuffix . '[]', '', $moreparam, '', '', $morecss) . '<br></span>';
  6583. if (!empty($conf->use_javascript_ajax)) {
  6584. $out .= '
  6585. <script>
  6586. $(document).ready(function() {
  6587. $("a#' . dol_escape_js($keyprefix . $key . $keysuffix) . '_add").click(function() {
  6588. $("' . dol_escape_js($newInput) . '").insertBefore(this);
  6589. });
  6590. $(document).on("click", "a.' . dol_escape_js($keyprefix . $key . $keysuffix) . '_del", function() {
  6591. $(this).parent().remove();
  6592. });
  6593. });
  6594. </script>';
  6595. }
  6596. }
  6597. if (!empty($hidden)) {
  6598. $out = '<input type="hidden" value="' . $value . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '"/>';
  6599. }
  6600. if ($isDependList == 1) {
  6601. $out .= $this->getJSListDependancies('_common');
  6602. }
  6603. /* Add comments
  6604. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6605. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6606. */
  6607. // Display error message for field
  6608. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6609. $out .= ' ' . getFieldErrorIcon($fieldValidationErrorMsg);
  6610. }
  6611. return $out;
  6612. }
  6613. /**
  6614. * Return HTML string to show a field into a page
  6615. * Code very similar with showOutputField of extra fields
  6616. *
  6617. * @param array $val Array of properties of field to show
  6618. * @param string $key Key of attribute
  6619. * @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)
  6620. * @param string $moreparam To add more parametes on html input tag
  6621. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6622. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6623. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6624. * @return string
  6625. */
  6626. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6627. {
  6628. global $conf, $langs, $form;
  6629. if (!is_object($form)) {
  6630. require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php';
  6631. $form = new Form($this->db);
  6632. }
  6633. $objectid = $this->id; // Not used ???
  6634. $label = empty($val['label']) ? '' : $val['label'];
  6635. $type = empty($val['type']) ? '' : $val['type'];
  6636. $size = empty($val['css']) ? '' : $val['css'];
  6637. $reg = array();
  6638. // Convert var to be able to share same code than showOutputField of extrafields
  6639. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6640. $type = 'varchar'; // convert varchar(xx) int varchar
  6641. $size = $reg[1];
  6642. } elseif (preg_match('/varchar/', $type)) {
  6643. $type = 'varchar'; // convert varchar(xx) int varchar
  6644. }
  6645. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6646. $type = 'select';
  6647. }
  6648. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6649. $type = 'link';
  6650. }
  6651. $default = empty($val['default']) ? '' : $val['default'];
  6652. $computed = empty($val['computed']) ? '' : $val['computed'];
  6653. $unique = empty($val['unique']) ? '' : $val['unique'];
  6654. $required = empty($val['required']) ? '' : $val['required'];
  6655. $param = array();
  6656. $param['options'] = array();
  6657. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6658. $param['options'] = $val['arrayofkeyval'];
  6659. }
  6660. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6661. $type = 'link';
  6662. $param['options'] = array($reg[1] . ':' . $reg[2] => $reg[1] . ':' . $reg[2]);
  6663. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6664. $param['options'] = array($reg[1] . ':' . $reg[2] . ':' . $reg[3] . ':' . $reg[4] => 'N');
  6665. $type = 'sellist';
  6666. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6667. $param['options'] = array($reg[1] . ':' . $reg[2] . ':' . $reg[3] => 'N');
  6668. $type = 'sellist';
  6669. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6670. $param['options'] = array($reg[1] . ':' . $reg[2] => 'N');
  6671. $type = 'sellist';
  6672. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6673. $param['options'] = array($reg[1] => 'N');
  6674. $type = 'chkbxlst';
  6675. }
  6676. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6677. $list = (empty($val['list']) ? '' : $val['list']);
  6678. $help = (empty($val['help']) ? '' : $val['help']);
  6679. $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)
  6680. if ($hidden) {
  6681. return '';
  6682. }
  6683. // If field is a computed field, value must become result of compute
  6684. if ($computed) {
  6685. // Make the eval of compute string
  6686. //var_dump($computed);
  6687. $value = dol_eval($computed, 1, 0, '');
  6688. }
  6689. if (empty($morecss)) {
  6690. if ($type == 'date') {
  6691. $morecss = 'minwidth100imp';
  6692. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6693. $morecss = 'minwidth200imp';
  6694. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6695. $morecss = 'maxwidth75';
  6696. } elseif ($type == 'url') {
  6697. $morecss = 'minwidth400';
  6698. } elseif ($type == 'boolean') {
  6699. $morecss = '';
  6700. } else {
  6701. if (is_numeric($size) && round($size) < 12) {
  6702. $morecss = 'minwidth100';
  6703. } elseif (is_numeric($size) && round($size) <= 48) {
  6704. $morecss = 'minwidth200';
  6705. } else {
  6706. $morecss = 'minwidth400';
  6707. }
  6708. }
  6709. }
  6710. // Format output value differently according to properties of field
  6711. if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
  6712. if ($key != 'rowid' || empty($this->fields['ref'])) { // If we want ref field or if we want ID and there is no ref field, we show the link.
  6713. $value = $this->getNomUrl(1, '', 0, '', 1);
  6714. }
  6715. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6716. $value = $this->getLibStatut(2);
  6717. } elseif ($type == 'date') {
  6718. if (!empty($value)) {
  6719. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6720. } else {
  6721. $value = '';
  6722. }
  6723. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6724. if (!empty($value)) {
  6725. $value = date('Y-m-d H:i:s', $value);
  6726. //$value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6727. } else {
  6728. $value = '';
  6729. }
  6730. } elseif ($type == 'duration') {
  6731. include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  6732. if (!is_null($value) && $value !== '') {
  6733. $value = convertSecondToTime($value, 'allhourmin');
  6734. }
  6735. } elseif ($type == 'double' || $type == 'real') {
  6736. if (!is_null($value) && $value !== '') {
  6737. $value = price($value);
  6738. }
  6739. } elseif ($type == 'boolean') {
  6740. $checked = '';
  6741. if (!empty($value)) {
  6742. $checked = ' checked ';
  6743. }
  6744. $value = '<input type="checkbox" ' . $checked . ' ' . ($moreparam ? $moreparam : '') . ' readonly disabled>';
  6745. } elseif ($type == 'mail' || $type == 'email') {
  6746. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6747. } elseif ($type == 'url') {
  6748. $value = dol_print_url($value, '_blank', 32, 1);
  6749. } elseif ($type == 'phone') {
  6750. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
  6751. } elseif ($type == 'ip') {
  6752. $value = dol_print_ip($value, 0);
  6753. } elseif ($type == 'price') {
  6754. if (!is_null($value) && $value !== '') {
  6755. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6756. }
  6757. } elseif ($type == 'select') {
  6758. $value = isset($param['options'][$value]) ? $param['options'][$value] : '';
  6759. } elseif ($type == 'sellist') {
  6760. $param_list = array_keys($param['options']);
  6761. $InfoFieldList = explode(":", $param_list[0]);
  6762. $selectkey = "rowid";
  6763. $keyList = 'rowid';
  6764. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6765. $selectkey = $InfoFieldList[2];
  6766. $keyList = $InfoFieldList[2] . ' as rowid';
  6767. }
  6768. $fields_label = explode('|', $InfoFieldList[1]);
  6769. if (is_array($fields_label)) {
  6770. $keyList .= ', ';
  6771. $keyList .= implode(', ', $fields_label);
  6772. }
  6773. $filter_categorie = false;
  6774. if (count($InfoFieldList) > 5) {
  6775. if ($InfoFieldList[0] == 'categorie') {
  6776. $filter_categorie = true;
  6777. }
  6778. }
  6779. $sql = "SELECT " . $keyList;
  6780. $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
  6781. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6782. $sql .= ' as main';
  6783. }
  6784. if ($selectkey == 'rowid' && empty($value)) {
  6785. $sql .= " WHERE " . $selectkey . " = 0";
  6786. } elseif ($selectkey == 'rowid') {
  6787. $sql .= " WHERE " . $selectkey . " = " . ((int) $value);
  6788. } else {
  6789. $sql .= " WHERE " . $selectkey . " = '" . $this->db->escape($value) . "'";
  6790. }
  6791. //$sql.= ' AND entity = '.$conf->entity;
  6792. dol_syslog(get_class($this) . ':showOutputField:$type=sellist', LOG_DEBUG);
  6793. $resql = $this->db->query($sql);
  6794. if ($resql) {
  6795. if ($filter_categorie === false) {
  6796. $value = ''; // value was used, so now we reste it to use it to build final output
  6797. $numrows = $this->db->num_rows($resql);
  6798. if ($numrows) {
  6799. $obj = $this->db->fetch_object($resql);
  6800. // Several field into label (eq table:code|libelle:rowid)
  6801. $fields_label = explode('|', $InfoFieldList[1]);
  6802. if (is_array($fields_label) && count($fields_label) > 1) {
  6803. foreach ($fields_label as $field_toshow) {
  6804. $translabel = '';
  6805. if (!empty($obj->$field_toshow)) {
  6806. $translabel = $langs->trans($obj->$field_toshow);
  6807. }
  6808. if ($translabel != $field_toshow) {
  6809. $value .= dol_trunc($translabel, 18) . ' ';
  6810. } else {
  6811. $value .= $obj->$field_toshow . ' ';
  6812. }
  6813. }
  6814. } else {
  6815. $translabel = '';
  6816. if (!empty($obj->{$InfoFieldList[1]})) {
  6817. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6818. }
  6819. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6820. $value = dol_trunc($translabel, 18);
  6821. } else {
  6822. $value = $obj->{$InfoFieldList[1]};
  6823. }
  6824. }
  6825. }
  6826. } else {
  6827. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6828. $toprint = array();
  6829. $obj = $this->db->fetch_object($resql);
  6830. $c = new Categorie($this->db);
  6831. $c->fetch($obj->rowid);
  6832. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  6833. foreach ($ways as $way) {
  6834. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  6835. }
  6836. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  6837. }
  6838. } else {
  6839. dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
  6840. }
  6841. } elseif ($type == 'radio') {
  6842. $value = $param['options'][$value];
  6843. } elseif ($type == 'checkbox') {
  6844. $value_arr = explode(',', $value);
  6845. $value = '';
  6846. if (is_array($value_arr) && count($value_arr) > 0) {
  6847. $toprint = array();
  6848. foreach ($value_arr as $keyval => $valueval) {
  6849. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param['options'][$valueval] . '</li>';
  6850. }
  6851. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  6852. }
  6853. } elseif ($type == 'chkbxlst') {
  6854. $value_arr = explode(',', $value);
  6855. $param_list = array_keys($param['options']);
  6856. $InfoFieldList = explode(":", $param_list[0]);
  6857. $selectkey = "rowid";
  6858. $keyList = 'rowid';
  6859. if (count($InfoFieldList) >= 3) {
  6860. $selectkey = $InfoFieldList[2];
  6861. $keyList = $InfoFieldList[2] . ' as rowid';
  6862. }
  6863. $fields_label = explode('|', $InfoFieldList[1]);
  6864. if (is_array($fields_label)) {
  6865. $keyList .= ', ';
  6866. $keyList .= implode(', ', $fields_label);
  6867. }
  6868. $filter_categorie = false;
  6869. if (count($InfoFieldList) > 5) {
  6870. if ($InfoFieldList[0] == 'categorie') {
  6871. $filter_categorie = true;
  6872. }
  6873. }
  6874. $sql = "SELECT " . $keyList;
  6875. $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
  6876. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6877. $sql .= ' as main';
  6878. }
  6879. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6880. // $sql.= ' AND entity = '.$conf->entity;
  6881. dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6882. $resql = $this->db->query($sql);
  6883. if ($resql) {
  6884. if ($filter_categorie === false) {
  6885. $value = ''; // value was used, so now we reste it to use it to build final output
  6886. $toprint = array();
  6887. while ($obj = $this->db->fetch_object($resql)) {
  6888. // Several field into label (eq table:code|libelle:rowid)
  6889. $fields_label = explode('|', $InfoFieldList[1]);
  6890. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6891. if (is_array($fields_label) && count($fields_label) > 1) {
  6892. foreach ($fields_label as $field_toshow) {
  6893. $translabel = '';
  6894. if (!empty($obj->$field_toshow)) {
  6895. $translabel = $langs->trans($obj->$field_toshow);
  6896. }
  6897. if ($translabel != $field_toshow) {
  6898. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  6899. } else {
  6900. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
  6901. }
  6902. }
  6903. } else {
  6904. $translabel = '';
  6905. if (!empty($obj->{$InfoFieldList[1]})) {
  6906. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6907. }
  6908. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6909. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  6910. } else {
  6911. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
  6912. }
  6913. }
  6914. }
  6915. }
  6916. } else {
  6917. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6918. $toprint = array();
  6919. while ($obj = $this->db->fetch_object($resql)) {
  6920. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6921. $c = new Categorie($this->db);
  6922. $c->fetch($obj->rowid);
  6923. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  6924. foreach ($ways as $way) {
  6925. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  6926. }
  6927. }
  6928. }
  6929. }
  6930. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  6931. } else {
  6932. dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
  6933. }
  6934. } elseif ($type == 'link') {
  6935. $out = '';
  6936. // only if something to display (perf)
  6937. if ($value) {
  6938. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6939. $InfoFieldList = explode(":", $param_list[0]);
  6940. $classname = $InfoFieldList[0];
  6941. $classpath = $InfoFieldList[1];
  6942. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6943. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6944. if (!empty($classpath)) {
  6945. dol_include_once($InfoFieldList[1]);
  6946. if ($classname && class_exists($classname)) {
  6947. $object = new $classname($this->db);
  6948. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6949. $result = $object->fetch($value, '', '', '', 0, 1, 1);
  6950. } else {
  6951. $result = $object->fetch($value);
  6952. }
  6953. if ($result > 0) {
  6954. if ($object->element === 'product') {
  6955. $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
  6956. if (isset($val['get_name_url_params'])) {
  6957. $get_name_url_params = explode(':', $val['get_name_url_params']);
  6958. if (!empty($get_name_url_params)) {
  6959. $param_num_max = count($get_name_url_param_arr) - 1;
  6960. foreach ($get_name_url_params as $param_num => $param_value) {
  6961. if ($param_num > $param_num_max) {
  6962. break;
  6963. }
  6964. $get_name_url_param_arr[$param_num] = $param_value;
  6965. }
  6966. }
  6967. }
  6968. /**
  6969. * @var Product $object
  6970. */
  6971. $value = $object->getNomUrl($get_name_url_param_arr[0], $get_name_url_param_arr[1], $get_name_url_param_arr[2], $get_name_url_param_arr[3], $get_name_url_param_arr[4], $get_name_url_param_arr[5], $get_name_url_param_arr[6]);
  6972. } else {
  6973. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6974. }
  6975. } else {
  6976. $value = '';
  6977. }
  6978. }
  6979. } else {
  6980. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6981. return 'Error bad setup of extrafield';
  6982. }
  6983. } else {
  6984. $value = '';
  6985. }
  6986. } elseif ($type == 'password') {
  6987. $value = preg_replace('/./i', '*', $value);
  6988. } elseif ($type == 'array') {
  6989. $value = implode('<br>', $value);
  6990. } else { // text|html|varchar
  6991. $value = dol_htmlentitiesbr($value);
  6992. }
  6993. //print $type.'-'.$size.'-'.$value;
  6994. $out = $value;
  6995. return $out;
  6996. }
  6997. /**
  6998. * clear validation message result for a field
  6999. *
  7000. * @param string $fieldKey Key of attribute to clear
  7001. * @return null
  7002. */
  7003. public function clearFieldError($fieldKey)
  7004. {
  7005. $this->error = '';
  7006. unset($this->validateFieldsErrors[$fieldKey]);
  7007. }
  7008. /**
  7009. * set validation error message a field
  7010. *
  7011. * @param string $fieldKey Key of attribute
  7012. * @param string $msg the field error message
  7013. * @return null
  7014. */
  7015. public function setFieldError($fieldKey, $msg = '')
  7016. {
  7017. global $langs;
  7018. if (empty($msg)) {
  7019. $msg = $langs->trans("UnknowError");
  7020. }
  7021. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  7022. }
  7023. /**
  7024. * get field error message
  7025. *
  7026. * @param string $fieldKey Key of attribute
  7027. * @return string Error message of validation ('' if no error)
  7028. */
  7029. public function getFieldError($fieldKey)
  7030. {
  7031. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  7032. return $this->validateFieldsErrors[$fieldKey];
  7033. }
  7034. return '';
  7035. }
  7036. /**
  7037. * Return validation test result for a field
  7038. *
  7039. * @param array $val Array of properties of field to show
  7040. * @param string $fieldKey Key of attribute
  7041. * @param string $fieldValue value of attribute
  7042. * @return bool return false if fail true on success, see $this->error for error message
  7043. */
  7044. public function validateField($val, $fieldKey, $fieldValue)
  7045. {
  7046. global $langs;
  7047. if (!class_exists('Validate')) {
  7048. require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php';
  7049. }
  7050. $this->clearFieldError($fieldKey);
  7051. if (!isset($val[$fieldKey])) {
  7052. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  7053. return false;
  7054. }
  7055. $param = array();
  7056. $param['options'] = array();
  7057. $type = $val[$fieldKey]['type'];
  7058. $required = false;
  7059. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  7060. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  7061. $required = true;
  7062. }
  7063. $maxSize = 0;
  7064. $minSize = 0;
  7065. //
  7066. // PREPARE Elements
  7067. //
  7068. // Convert var to be able to share same code than showOutputField of extrafields
  7069. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  7070. $type = 'varchar'; // convert varchar(xx) int varchar
  7071. $maxSize = $reg[1];
  7072. } elseif (preg_match('/varchar/', $type)) {
  7073. $type = 'varchar'; // convert varchar(xx) int varchar
  7074. }
  7075. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7076. $type = 'select';
  7077. }
  7078. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7079. $type = 'link';
  7080. }
  7081. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7082. $param['options'] = $val['arrayofkeyval'];
  7083. }
  7084. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7085. $type = 'link';
  7086. $param['options'] = array($reg[1] . ':' . $reg[2] => $reg[1] . ':' . $reg[2]);
  7087. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7088. $param['options'] = array($reg[1] . ':' . $reg[2] . ':' . $reg[3] . ':' . $reg[4] => 'N');
  7089. $type = 'sellist';
  7090. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7091. $param['options'] = array($reg[1] . ':' . $reg[2] . ':' . $reg[3] => 'N');
  7092. $type = 'sellist';
  7093. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  7094. $param['options'] = array($reg[1] . ':' . $reg[2] => 'N');
  7095. $type = 'sellist';
  7096. }
  7097. //
  7098. // TEST Value
  7099. //
  7100. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  7101. $validate = new Validate($this->db, $langs);
  7102. // little trick : to perform tests with good performances sort tests by quick to low
  7103. //
  7104. // COMMON TESTS
  7105. //
  7106. // Required test and empty value
  7107. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  7108. $this->setFieldError($fieldKey, $validate->error);
  7109. return false;
  7110. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  7111. // if no value sent and the field is not mandatory, no need to perform tests
  7112. return true;
  7113. }
  7114. // MAX Size test
  7115. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  7116. $this->setFieldError($fieldKey, $validate->error);
  7117. return false;
  7118. }
  7119. // MIN Size test
  7120. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  7121. $this->setFieldError($fieldKey, $validate->error);
  7122. return false;
  7123. }
  7124. //
  7125. // TESTS for TYPE
  7126. //
  7127. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  7128. if (!$validate->isTimestamp($fieldValue)) {
  7129. $this->setFieldError($fieldKey, $validate->error);
  7130. return false;
  7131. } else {
  7132. return true;
  7133. }
  7134. } elseif ($type == 'duration') {
  7135. if (!$validate->isDuration($fieldValue)) {
  7136. $this->setFieldError($fieldKey, $validate->error);
  7137. return false;
  7138. } else {
  7139. return true;
  7140. }
  7141. } elseif (in_array($type, array('double', 'real', 'price'))) {
  7142. // is numeric
  7143. if (!$validate->isNumeric($fieldValue)) {
  7144. $this->setFieldError($fieldKey, $validate->error);
  7145. return false;
  7146. } else {
  7147. return true;
  7148. }
  7149. } elseif ($type == 'boolean') {
  7150. if (!$validate->isBool($fieldValue)) {
  7151. $this->setFieldError($fieldKey, $validate->error);
  7152. return false;
  7153. } else {
  7154. return true;
  7155. }
  7156. } elseif ($type == 'mail') {
  7157. if (!$validate->isEmail($fieldValue)) {
  7158. $this->setFieldError($fieldKey, $validate->error);
  7159. return false;
  7160. }
  7161. } elseif ($type == 'url') {
  7162. if (!$validate->isUrl($fieldValue)) {
  7163. $this->setFieldError($fieldKey, $validate->error);
  7164. return false;
  7165. } else {
  7166. return true;
  7167. }
  7168. } elseif ($type == 'phone') {
  7169. if (!$validate->isPhone($fieldValue)) {
  7170. $this->setFieldError($fieldKey, $validate->error);
  7171. return false;
  7172. } else {
  7173. return true;
  7174. }
  7175. } elseif ($type == 'select' || $type == 'radio') {
  7176. if (!isset($param['options'][$fieldValue])) {
  7177. $this->error = $langs->trans('RequireValidValue');
  7178. return false;
  7179. } else {
  7180. return true;
  7181. }
  7182. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  7183. $param_list = array_keys($param['options']);
  7184. $InfoFieldList = explode(":", $param_list[0]);
  7185. $value_arr = explode(',', $fieldValue);
  7186. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  7187. $selectkey = "rowid";
  7188. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  7189. $selectkey = $InfoFieldList[2];
  7190. }
  7191. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  7192. $this->setFieldError($fieldKey, $validate->error);
  7193. return false;
  7194. } else {
  7195. return true;
  7196. }
  7197. } elseif ($type == 'link') {
  7198. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  7199. $InfoFieldList = explode(":", $param_list[0]);
  7200. $classname = $InfoFieldList[0];
  7201. $classpath = $InfoFieldList[1];
  7202. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  7203. $this->setFieldError($fieldKey, $validate->error);
  7204. return false;
  7205. } else {
  7206. return true;
  7207. }
  7208. }
  7209. // if no test failled all is ok
  7210. return true;
  7211. }
  7212. /**
  7213. * Function to show lines of extrafields with output datas.
  7214. * 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
  7215. *
  7216. * @param Extrafields $extrafields Extrafield Object
  7217. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  7218. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  7219. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  7220. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  7221. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  7222. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  7223. * @return string String with html content to show
  7224. */
  7225. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  7226. {
  7227. global $db, $conf, $langs, $action, $form, $hookmanager;
  7228. if (!is_object($form)) {
  7229. $form = new Form($db);
  7230. }
  7231. if (!is_object($extrafields)) {
  7232. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  7233. return 'Bad parameter extrafields for showOptionals';
  7234. }
  7235. if (!is_array($extrafields->attributes[$this->table_element])) {
  7236. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  7237. }
  7238. $out = '';
  7239. $parameters = array('mode' => $mode, 'params' => $params, 'keysuffix' => $keysuffix, 'keyprefix' => $keyprefix, 'display_type' => $display_type);
  7240. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  7241. if (empty($reshook)) {
  7242. if (is_array($extrafields->attributes[$this->table_element]) && key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
  7243. $out .= "\n";
  7244. $out .= '<!-- commonobject:showOptionals --> ';
  7245. $out .= "\n";
  7246. $nbofextrafieldsshown = 0;
  7247. $extrafields_collapse_num = '';
  7248. $e = 0; // var to manage the modulo (odd/even)
  7249. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  7250. // Show only the key field in params
  7251. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  7252. continue;
  7253. }
  7254. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  7255. $enabled = 1;
  7256. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  7257. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
  7258. }
  7259. if (empty($enabled)) {
  7260. continue;
  7261. }
  7262. $visibility = 1;
  7263. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  7264. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
  7265. }
  7266. $perms = 1;
  7267. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  7268. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
  7269. }
  7270. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7271. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7272. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7273. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7274. } elseif ($mode == 'view' && empty($visibility)) {
  7275. continue;
  7276. }
  7277. if (empty($perms)) {
  7278. continue;
  7279. }
  7280. // Load language if required
  7281. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7282. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7283. }
  7284. $colspan = 0;
  7285. if (is_array($params) && count($params) > 0 && $display_type == 'card') {
  7286. if (array_key_exists('cols', $params)) {
  7287. $colspan = $params['cols'];
  7288. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7289. $reg = array();
  7290. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7291. $colspan = $reg[1];
  7292. } else {
  7293. $colspan = $params['colspan'];
  7294. }
  7295. }
  7296. }
  7297. $colspan = intval($colspan);
  7298. switch ($mode) {
  7299. case "view":
  7300. $value = ((!empty($this->array_options) && array_key_exists("options_" . $key . $keysuffix, $this->array_options)) ? $this->array_options["options_" . $key . $keysuffix] : null); // Value may be cleaned or formated later
  7301. break;
  7302. case "create":
  7303. case "edit":
  7304. // We get the value of property found with GETPOST so it takes into account:
  7305. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7306. $check = 'alphanohtml';
  7307. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7308. $check = 'restricthtml';
  7309. }
  7310. $getposttemp = GETPOST($keyprefix . 'options_' . $key . $keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7311. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7312. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix . 'options_' . $key . $keysuffix)) {
  7313. if (is_array($getposttemp)) {
  7314. // $getposttemp is an array but following code expects a comma separated string
  7315. $value = implode(",", $getposttemp);
  7316. } else {
  7317. $value = $getposttemp;
  7318. }
  7319. } else {
  7320. $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.
  7321. }
  7322. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7323. break;
  7324. }
  7325. $nbofextrafieldsshown++;
  7326. // Output value of the current field
  7327. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7328. $extrafields_collapse_num = '';
  7329. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7330. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7331. $extrafield_param_list = array_keys($extrafield_param['options']);
  7332. if (count($extrafield_param_list) > 0) {
  7333. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7334. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7335. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7336. }
  7337. }
  7338. }
  7339. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7340. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7341. } elseif ($key == 'discount_start_minute' || $key == 'discount_to_hour' || $key == 'discount_to_minute') {
  7342. } elseif (($key == 'assigned_device' || $key == 'unique_identifier') && $this->isRollerDevice()) {
  7343. } else {
  7344. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7345. $csstyle = '';
  7346. if (is_array($params) && count($params) > 0) {
  7347. if (array_key_exists('class', $params)) {
  7348. $class .= $params['class'] . ' ';
  7349. }
  7350. if (array_key_exists('style', $params)) {
  7351. $csstyle = $params['style'];
  7352. }
  7353. }
  7354. // add html5 elements
  7355. $domData = ' data-element="extrafield"';
  7356. $domData .= ' data-targetelement="' . $this->element . '"';
  7357. $domData .= ' data-targetid="' . $this->id . '"';
  7358. $html_id = (empty($this->id) ? '' : 'extrarow-' . $this->element . '_' . $key . '_' . $this->id);
  7359. if ($display_type == 'card') {
  7360. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7361. $colspan = 0;
  7362. }
  7363. if ($action == 'selectlines') {
  7364. $colspan++;
  7365. }
  7366. }
  7367. // Convert date into timestamp format (value in memory must be a timestamp)
  7368. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7369. $datenotinstring = null;
  7370. if (array_key_exists('options_' . $key, $this->array_options)) {
  7371. $datenotinstring = $this->array_options['options_' . $key];
  7372. if (!is_numeric($this->array_options['options_' . $key])) { // For backward compatibility
  7373. $datenotinstring = $this->db->jdate($datenotinstring);
  7374. }
  7375. }
  7376. $datekey = $keyprefix . 'options_' . $key . $keysuffix;
  7377. $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey . 'month', 'int', 3), GETPOST($datekey . 'day', 'int', 3), GETPOST($datekey . 'year', 'int', 3)) : $datenotinstring;
  7378. }
  7379. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7380. $datenotinstring = null;
  7381. if (array_key_exists('options_' . $key, $this->array_options)) {
  7382. $datenotinstring = $this->array_options['options_' . $key];
  7383. if (!is_numeric($this->array_options['options_' . $key])) { // For backward compatibility
  7384. $datenotinstring = $this->db->jdate($datenotinstring);
  7385. }
  7386. }
  7387. $timekey = $keyprefix . 'options_' . $key . $keysuffix;
  7388. $value = (GETPOSTISSET($timekey)) ? dol_mktime(GETPOST($timekey . 'hour', 'int', 3), GETPOST($timekey . 'min', 'int', 3), GETPOST($timekey . 'sec', 'int', 3), GETPOST($timekey . 'month', 'int', 3), GETPOST($timekey . 'day', 'int', 3), GETPOST($timekey . 'year', 'int', 3), 'tzuserrel') : $datenotinstring;
  7389. }
  7390. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7391. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7392. if (GETPOSTISSET($keyprefix . 'options_' . $key . $keysuffix) || $value) {
  7393. $value = price2num($value);
  7394. } elseif (isset($this->array_options['options_' . $key])) {
  7395. $value = $this->array_options['options_' . $key];
  7396. }
  7397. }
  7398. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7399. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
  7400. if ($action == 'create') {
  7401. $value = (GETPOSTISSET($keyprefix . 'options_' . $key . $keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7402. }
  7403. }
  7404. $labeltoshow = $langs->trans($label);
  7405. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7406. if ($display_type == 'card') {
  7407. $out .= '<tr ' . ($html_id ? 'id="' . $html_id . '" ' : '') . $csstyle . ' class="field_options_' . $key . ' ' . $class . $this->element . '_extras_' . $key . ' trextrafields_collapse' . $extrafields_collapse_num . (!empty($this->id) ? '_' . $this->id : '') . '" ' . $domData . ' >';
  7408. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
  7409. $out .= '<td></td>';
  7410. }
  7411. $out .= '<td class="' . (empty($params['tdclass']) ? 'titlefieldcreate' : $params['tdclass']) . ' wordbreak';
  7412. } elseif ($display_type == 'line') {
  7413. $out .= '<div ' . ($html_id ? 'id="' . $html_id . '" ' : '') . $csstyle . ' class="fieldline_options_' . $key . ' ' . $class . $this->element . '_extras_' . $key . ' trextrafields_collapse' . $extrafields_collapse_num . (!empty($this->id) ? '_' . $this->id : '') . '" ' . $domData . ' >';
  7414. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  7415. }
  7416. //$out .= "titlefield";
  7417. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7418. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7419. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7420. if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
  7421. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7422. $out .= ' fieldrequired';
  7423. }
  7424. }
  7425. $out .= '">';
  7426. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7427. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7428. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7429. } else {
  7430. $out .= $labeltoshow;
  7431. }
  7432. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7433. $out .= '&nbsp;<span style="color: red">*</span>';
  7434. }
  7435. } else {
  7436. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7437. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7438. } else {
  7439. $out .= $labeltoshow;
  7440. }
  7441. }
  7442. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7443. $html_id = !empty($this->id) ? $this->element . '_extras_' . $key . '_' . $this->id : '';
  7444. if ($display_type == 'card') {
  7445. // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one
  7446. $out .= '<td ' . ($html_id ? 'id="' . $html_id . '" ' : '') . ' class="valuefieldcreate ' . $this->element . '_extras_' . $key . '" ' . ($colspan ? ' colspan="' . $colspan . '"' : '') . '>';
  7447. } elseif ($display_type == 'line') {
  7448. $out .= '<div ' . ($html_id ? 'id="' . $html_id . '" ' : '') . ' style="display: inline-block" class="valuefieldcreate ' . $this->element . '_extras_' . $key . ' extra_inline_' . $extrafields->attributes[$this->table_element]['type'][$key] . '">';
  7449. }
  7450. switch ($mode) {
  7451. case "view":
  7452. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7453. break;
  7454. case "create":
  7455. if ($key == 'discount_start_hour') {
  7456. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7457. $out .= $extrafields->showInputField('discount_start_minute', $this->array_options['options_discount_start_minute'], '', $keysuffix, '', 0, $this->id, $this->table_element);
  7458. $out .= ' - ';
  7459. $out .= $extrafields->showInputField('discount_to_hour', $this->array_options['options_discount_to_hour'], '', $keysuffix, '', 0, $this->id, $this->table_element);
  7460. $out .= $extrafields->showInputField('discount_to_minute', $this->array_options['options_discount_to_minute'], '', $keysuffix, '', 0, $this->id, $this->table_element);
  7461. } elseif ($key == 'assigned_device' || $key == 'unique_identifier') {
  7462. $entrepotObj = new Entrepot($this->db);
  7463. $entrepotObj->fetch($_REQUEST['inventory_id']);
  7464. if ($entrepotObj->array_options['options_entrepot_type'] == 2) {
  7465. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7466. }
  7467. } else {
  7468. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7469. }
  7470. break;
  7471. case "edit":
  7472. if ($key == 'discount_start_hour') {
  7473. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7474. $out .= $extrafields->showInputField('discount_start_minute', $this->array_options['options_discount_start_minute'], '', $keysuffix, '', 0, $this->id, $this->table_element);
  7475. $out .= ' - ';
  7476. $out .= $extrafields->showInputField('discount_to_hour', $this->array_options['options_discount_to_hour'], '', $keysuffix, '', 0, $this->id, $this->table_element);
  7477. $out .= $extrafields->showInputField('discount_to_minute', $this->array_options['options_discount_to_minute'], '', $keysuffix, '', 0, $this->id, $this->table_element);
  7478. } elseif ($key == 'assigned_device' || $key == 'unique_identifier') {
  7479. $entrepotObj = new Entrepot($this->db);
  7480. $entrepotObj->fetch($_REQUEST['inventory_id']);
  7481. if ($entrepotObj->array_options['options_entrepot_type'] == 2) {
  7482. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7483. }
  7484. } elseif ($key == 'participants') {
  7485. $out .= $value;
  7486. } else {
  7487. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7488. }
  7489. break;
  7490. }
  7491. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7492. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7493. $out .= ($display_type == 'card' ? '</tr>' : '</div>');
  7494. } else {
  7495. $out .= ($display_type == 'card' ? '</tr>' : '</div>');
  7496. }
  7497. $e++;
  7498. }
  7499. }
  7500. $out .= "\n";
  7501. // Add code to manage list depending on others
  7502. if (!empty($conf->use_javascript_ajax)) {
  7503. $out .= $this->getJSListDependancies();
  7504. }
  7505. $out .= '<!-- commonobject:showOptionals end --> ' . "\n";
  7506. if (empty($nbofextrafieldsshown)) {
  7507. $out = '';
  7508. }
  7509. }
  7510. }
  7511. $out .= $hookmanager->resPrint;
  7512. return $out;
  7513. }
  7514. private function isRollerDevice()
  7515. {
  7516. $entrepotObj = new Entrepot($this->db);
  7517. $entrepotObj->fetch($_REQUEST['inventory_id']);
  7518. if ($entrepotObj->array_options['options_entrepot_type'] == 1) {
  7519. return true;
  7520. } else {
  7521. return false;
  7522. }
  7523. }
  7524. /**
  7525. * @param string $type Type for prefix
  7526. * @return string Javacript code to manage dependency
  7527. */
  7528. public function getJSListDependancies($type = '_extra')
  7529. {
  7530. $out = '
  7531. <script>
  7532. jQuery(document).ready(function() {
  7533. function showOptions' . $type . '(child_list, parent_list, orig_select)
  7534. {
  7535. var val = $("select[name=\""+parent_list+"\"]").val();
  7536. var parentVal = parent_list + ":" + val;
  7537. if(typeof val == "string"){
  7538. if(val != "") {
  7539. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7540. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7541. $("select[name=\""+child_list+"\"]").append(options);
  7542. } else {
  7543. var options = orig_select.find("option[parent]").clone();
  7544. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7545. $("select[name=\""+child_list+"\"]").append(options);
  7546. }
  7547. } else if(val > 0) {
  7548. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7549. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7550. $("select[name=\""+child_list+"\"]").append(options);
  7551. } else {
  7552. var options = orig_select.find("option[parent]").clone();
  7553. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7554. $("select[name=\""+child_list+"\"]").append(options);
  7555. }
  7556. }
  7557. function setListDependencies' . $type . '() {
  7558. jQuery("select option[parent]").parent().each(function() {
  7559. var orig_select = {};
  7560. var child_list = $(this).attr("name");
  7561. orig_select[child_list] = $(this).clone();
  7562. var parent = $(this).find("option[parent]:first").attr("parent");
  7563. var infos = parent.split(":");
  7564. var parent_list = infos[0];
  7565. //Hide daughters lists
  7566. if ($("#"+child_list).val() == 0 && ($("#"+parent_list).val() == 0 || $("#"+parent_list).val() == undefined)){
  7567. $("#"+child_list).hide();
  7568. //Show mother lists
  7569. } else if ($("#"+parent_list).val() != 0){
  7570. $("#"+parent_list).show();
  7571. }
  7572. //Show the child list if the parent list value is selected
  7573. $("select[name=\""+parent_list+"\"]").click(function() {
  7574. if ($(this).val() != 0){
  7575. $("#"+child_list).show()
  7576. }
  7577. });
  7578. //When we change parent list
  7579. $("select[name=\""+parent_list+"\"]").change(function() {
  7580. showOptions' . $type . '(child_list, parent_list, orig_select[child_list]);
  7581. //Select the value 0 on child list after a change on the parent list
  7582. $("#"+child_list).val(0).trigger("change");
  7583. //Hide child lists if the parent value is set to 0
  7584. if ($(this).val() == 0){
  7585. $("#"+child_list).hide();
  7586. }
  7587. });
  7588. });
  7589. }
  7590. setListDependencies' . $type . '();
  7591. });
  7592. </script>' . "\n";
  7593. return $out;
  7594. }
  7595. /**
  7596. * Returns the rights used for this class
  7597. * @return stdClass
  7598. */
  7599. public function getRights()
  7600. {
  7601. global $user;
  7602. $element = $this->element;
  7603. if ($element == 'facturerec') {
  7604. $element = 'facture';
  7605. } elseif ($element == 'invoice_supplier_rec') {
  7606. return $user->rights->fournisseur->facture;
  7607. } elseif ($element == 'evaluation') {
  7608. return $user->rights->hrm->evaluation;
  7609. }
  7610. return $user->rights->{$element};
  7611. }
  7612. /**
  7613. * Function used to replace a thirdparty id with another one.
  7614. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7615. * Column name fk_soc MUST be used to identify thirdparties
  7616. *
  7617. * @param DoliDB $db Database handler
  7618. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7619. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7620. * @param string[] $tables Tables that need to be changed
  7621. * @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)
  7622. * @return bool True if success, False if error
  7623. */
  7624. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7625. {
  7626. foreach ($tables as $table) {
  7627. $sql = 'UPDATE ' . $db->prefix() . $table . ' SET fk_soc = ' . ((int) $dest_id) . ' WHERE fk_soc = ' . ((int) $origin_id);
  7628. if (!$db->query($sql)) {
  7629. if ($ignoreerrors) {
  7630. return true; // TODO Not enough. If there is A-B on kept thirdparty and B-C on old one, we must get A-B-C after merge. Not A-B.
  7631. }
  7632. //$this->errors = $db->lasterror();
  7633. return false;
  7634. }
  7635. }
  7636. return true;
  7637. }
  7638. /**
  7639. * Function used to replace a product id with another one.
  7640. * This function is meant to be called from replaceProduct with the appropriate tables
  7641. * Column name fk_product MUST be used to identify products
  7642. *
  7643. * @param DoliDB $db Database handler
  7644. * @param int $origin_id Old product id (the product to delete)
  7645. * @param int $dest_id New product id (the product that will received element of the other)
  7646. * @param string[] $tables Tables that need to be changed
  7647. * @param int $ignoreerrors Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old product may already exists on new one)
  7648. * @return bool True if success, False if error
  7649. */
  7650. public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7651. {
  7652. foreach ($tables as $table) {
  7653. $sql = 'UPDATE ' . MAIN_DB_PREFIX . $table . ' SET fk_product = ' . ((int) $dest_id) . ' WHERE fk_product = ' . ((int) $origin_id);
  7654. if (!$db->query($sql)) {
  7655. if ($ignoreerrors) {
  7656. return true; // TODO Not enough. If there is A-B on kept product and B-C on old one, we must get A-B-C after merge. Not A-B.
  7657. }
  7658. //$this->errors = $db->lasterror();
  7659. return false;
  7660. }
  7661. }
  7662. return true;
  7663. }
  7664. /**
  7665. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7666. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7667. * elseif calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7668. * elseif calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7669. * else set min buy price as buy price
  7670. *
  7671. * @param float $unitPrice Product unit price
  7672. * @param float $discountPercent Line discount percent
  7673. * @param int $fk_product Product id
  7674. * @return float <0 if KO, buyprice if OK
  7675. */
  7676. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7677. {
  7678. global $conf;
  7679. $buyPrice = 0;
  7680. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7681. // When ForceBuyingPriceIfNull is set
  7682. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7683. } else {
  7684. // Get cost price for margin calculation
  7685. if (!empty($fk_product) && $fk_product > 0) {
  7686. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7687. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  7688. $product = new Product($this->db);
  7689. $result = $product->fetch($fk_product);
  7690. if ($result <= 0) {
  7691. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7692. return -1;
  7693. }
  7694. if ($product->cost_price > 0) {
  7695. $buyPrice = $product->cost_price;
  7696. } elseif ($product->pmp > 0) {
  7697. $buyPrice = $product->pmp;
  7698. }
  7699. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7700. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  7701. $product = new Product($this->db);
  7702. $result = $product->fetch($fk_product);
  7703. if ($result <= 0) {
  7704. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7705. return -1;
  7706. }
  7707. if ($product->pmp > 0) {
  7708. $buyPrice = $product->pmp;
  7709. }
  7710. }
  7711. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7712. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
  7713. $productFournisseur = new ProductFournisseur($this->db);
  7714. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7715. $buyPrice = $productFournisseur->fourn_unitprice;
  7716. } elseif ($result < 0) {
  7717. $this->errors[] = $productFournisseur->error;
  7718. return -2;
  7719. }
  7720. }
  7721. }
  7722. }
  7723. return $buyPrice;
  7724. }
  7725. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7726. /**
  7727. * Show photos of an object (nbmax maximum), into several columns
  7728. *
  7729. * @param string $modulepart 'product', 'ticket', ...
  7730. * @param string $sdir Directory to scan (full absolute path)
  7731. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7732. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7733. * @param int $nbbyrow Number of image per line or -1 to use div separator or 0 to use no separator. Used only if size=1 or 'small'.
  7734. * @param int $showfilename 1=Show filename
  7735. * @param int $showaction 1=Show icon with action links (resize, delete)
  7736. * @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.
  7737. * @param int $maxWidth Max width of original image when size='small'
  7738. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7739. * @param int $notitle Do not add title tag on image
  7740. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7741. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7742. */
  7743. 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)
  7744. {
  7745. // phpcs:enable
  7746. global $conf, $user, $langs;
  7747. include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  7748. include_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php';
  7749. $sortfield = 'position_name';
  7750. $sortorder = 'asc';
  7751. $dir = $sdir . '/';
  7752. $pdir = '/';
  7753. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7754. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7755. // For backward compatibility
  7756. if ($modulepart == 'product') {
  7757. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  7758. $dir = $sdir . '/' . get_exdir($this->id, 2, 0, 0, $this, $modulepart) . $this->id . "/photos/";
  7759. $pdir = '/' . get_exdir($this->id, 2, 0, 0, $this, $modulepart) . $this->id . "/photos/";
  7760. }
  7761. }
  7762. // Defined relative dir to DOL_DATA_ROOT
  7763. $relativedir = '';
  7764. if ($dir) {
  7765. $relativedir = preg_replace('/^' . preg_quote(DOL_DATA_ROOT, '/') . '/', '', $dir);
  7766. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7767. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7768. }
  7769. $dirthumb = $dir . 'thumbs/';
  7770. $pdirthumb = $pdir . 'thumbs/';
  7771. $return = '<!-- Photo -->' . "\n";
  7772. $nbphoto = 0;
  7773. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1);
  7774. /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatiblity, we scan also old dirs
  7775. {
  7776. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7777. $filearray=array_merge($filearray, $filearrayold);
  7778. }*/
  7779. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7780. if (count($filearray)) {
  7781. if ($sortfield && $sortorder) {
  7782. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7783. }
  7784. foreach ($filearray as $key => $val) {
  7785. $photo = '';
  7786. $file = $val['name'];
  7787. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7788. if (image_format_supported($file) >= 0) {
  7789. $nbphoto++;
  7790. $photo = $file;
  7791. $viewfilename = $file;
  7792. if ($size == 1 || $size == 'small') { // Format vignette
  7793. // Find name of thumb file
  7794. $photo_vignette = basename(getImageFileNameForSize($dir . $file, '_small'));
  7795. if (!dol_is_file($dirthumb . $photo_vignette)) {
  7796. // The thumb does not exists, so we will use the original file
  7797. $dirthumb = $dir;
  7798. $pdirthumb = $pdir;
  7799. $photo_vignette = basename($file);
  7800. }
  7801. // Get filesize of original file
  7802. $imgarray = dol_getImageSize($dir . $photo);
  7803. if ($nbbyrow > 0) {
  7804. if ($nbphoto == 1) {
  7805. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7806. }
  7807. if ($nbphoto % $nbbyrow == 1) {
  7808. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7809. }
  7810. $return .= '<td style="width: ' . ceil(100 / $nbbyrow) . '%" class="photo">';
  7811. } elseif ($nbbyrow < 0) {
  7812. $return .= '<div class="inline-block">';
  7813. }
  7814. $return .= "\n";
  7815. $relativefile = preg_replace('/^\//', '', $pdir . $photo);
  7816. if (empty($nolink)) {
  7817. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity=' . $this->entity);
  7818. if ($urladvanced) {
  7819. $return .= '<a href="' . $urladvanced . '">';
  7820. } else {
  7821. $return .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $this->entity . '&file=' . urlencode($pdir . $photo) . '" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7822. }
  7823. }
  7824. // Show image (width height=$maxHeight)
  7825. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7826. $alt = $langs->transnoentitiesnoconv('File') . ': ' . $relativefile;
  7827. $alt .= ' - ' . $langs->transnoentitiesnoconv('Size') . ': ' . $imgarray['width'] . 'x' . $imgarray['height'];
  7828. if ($notitle) {
  7829. $alt = '';
  7830. }
  7831. $addphotorefcss = 1;
  7832. if ($usesharelink) {
  7833. if ($val['share']) {
  7834. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7835. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7836. $return .= '<img class="photo photowithmargin' . ($addphotorefcss ? ' photoref' : '') . '"' . ($maxHeight ? ' height="' . $maxHeight . '"' : '') . ' src="' . DOL_URL_ROOT . '/viewimage.php?hashp=' . urlencode($val['share']) . '" title="' . dol_escape_htmltag($alt) . '">';
  7837. } else {
  7838. $return .= '<!-- Show original file -->';
  7839. $return .= '<img class="photo photowithmargin' . ($addphotorefcss ? ' photoref' : '') . '" height="' . $maxHeight . '" src="' . DOL_URL_ROOT . '/viewimage.php?hashp=' . urlencode($val['share']) . '" title="' . dol_escape_htmltag($alt) . '">';
  7840. }
  7841. } else {
  7842. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7843. $return .= '<img class="photo photowithmargin' . ($addphotorefcss ? ' photoref' : '') . '" height="' . $maxHeight . '" src="' . DOL_URL_ROOT . '/public/theme/common/nophoto.png" title="' . dol_escape_htmltag($alt) . '">';
  7844. }
  7845. } else {
  7846. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7847. $return .= '<!-- Show thumb -->';
  7848. $return .= '<img class="photo photowithmargin' . ($addphotorefcss ? ' photoref' : '') . ' maxwidth150onsmartphone maxwidth200"' . ($maxHeight ? ' height="' . $maxHeight . '"' : '') . ' src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $this->entity . '&file=' . urlencode($pdirthumb . $photo_vignette) . '" title="' . dol_escape_htmltag($alt) . '">';
  7849. } else {
  7850. $return .= '<!-- Show original file -->';
  7851. $return .= '<img class="photo photowithmargin' . ($addphotorefcss ? ' photoref' : '') . '" height="' . $maxHeight . '" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $this->entity . '&file=' . urlencode($pdir . $photo) . '" title="' . dol_escape_htmltag($alt) . '">';
  7852. }
  7853. }
  7854. if (empty($nolink)) {
  7855. $return .= '</a>';
  7856. }
  7857. $return .= "\n";
  7858. if ($showfilename) {
  7859. $return .= '<br>' . $viewfilename;
  7860. }
  7861. if ($showaction) {
  7862. $return .= '<br>';
  7863. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7864. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7865. $return .= '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $this->id . '&action=addthumb&token=' . newToken() . '&file=' . urlencode($pdir . $viewfilename) . '">' . img_picto($langs->trans('GenerateThumb'), 'refresh') . '&nbsp;&nbsp;</a>';
  7866. }
  7867. // Special cas for product
  7868. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7869. // Link to resize
  7870. $return .= '<a href="' . DOL_URL_ROOT . '/core/photos_resize.php?modulepart=' . urlencode('produit|service') . '&id=' . $this->id . '&file=' . urlencode($pdir . $viewfilename) . '" title="' . dol_escape_htmltag($langs->trans("Resize")) . '">' . img_picto($langs->trans("Resize"), 'resize', '') . '</a> &nbsp; ';
  7871. // Link to delete
  7872. $return .= '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $this->id . '&action=delete&token=' . newToken() . '&file=' . urlencode($pdir . $viewfilename) . '">';
  7873. $return .= img_delete() . '</a>';
  7874. }
  7875. }
  7876. $return .= "\n";
  7877. if ($nbbyrow > 0) {
  7878. $return .= '</td>';
  7879. if (($nbphoto % $nbbyrow) == 0) {
  7880. $return .= '</tr>';
  7881. }
  7882. } elseif ($nbbyrow < 0) {
  7883. $return .= '</div>';
  7884. }
  7885. }
  7886. if (empty($size)) { // Format origine
  7887. $return .= '<img class="photo photowithmargin" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $this->entity . '&file=' . urlencode($pdir . $photo) . '">';
  7888. if ($showfilename) {
  7889. $return .= '<br>' . $viewfilename;
  7890. }
  7891. if ($showaction) {
  7892. // Special case for product
  7893. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7894. // Link to resize
  7895. $return .= '<a href="' . DOL_URL_ROOT . '/core/photos_resize.php?modulepart=' . urlencode('produit|service') . '&id=' . $this->id . '&file=' . urlencode($pdir . $viewfilename) . '" title="' . dol_escape_htmltag($langs->trans("Resize")) . '">' . img_picto($langs->trans("Resize"), 'resize', '') . '</a> &nbsp; ';
  7896. // Link to delete
  7897. $return .= '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $this->id . '&action=delete&token=' . newToken() . '&file=' . urlencode($pdir . $viewfilename) . '">';
  7898. $return .= img_delete() . '</a>';
  7899. }
  7900. }
  7901. }
  7902. // On continue ou on arrete de boucler ?
  7903. if ($nbmax && $nbphoto >= $nbmax) {
  7904. break;
  7905. }
  7906. }
  7907. }
  7908. if ($size == 1 || $size == 'small') {
  7909. if ($nbbyrow > 0) {
  7910. // Ferme tableau
  7911. while ($nbphoto % $nbbyrow) {
  7912. $return .= '<td style="width: ' . ceil(100 / $nbbyrow) . '%">&nbsp;</td>';
  7913. $nbphoto++;
  7914. }
  7915. if ($nbphoto) {
  7916. $return .= '</table>';
  7917. }
  7918. }
  7919. }
  7920. }
  7921. $this->nbphoto = $nbphoto;
  7922. return $return;
  7923. }
  7924. /**
  7925. * Function test if type is array
  7926. *
  7927. * @param array $info content informations of field
  7928. * @return bool true if array
  7929. */
  7930. protected function isArray($info)
  7931. {
  7932. if (is_array($info)) {
  7933. if (isset($info['type']) && $info['type'] == 'array') {
  7934. return true;
  7935. } else {
  7936. return false;
  7937. }
  7938. }
  7939. return false;
  7940. }
  7941. /**
  7942. * Function test if type is date
  7943. *
  7944. * @param array $info content informations of field
  7945. * @return bool true if date
  7946. */
  7947. public function isDate($info)
  7948. {
  7949. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7950. return true;
  7951. }
  7952. return false;
  7953. }
  7954. /**
  7955. * Function test if type is duration
  7956. *
  7957. * @param array $info content informations of field
  7958. * @return bool true if field of type duration
  7959. */
  7960. public function isDuration($info)
  7961. {
  7962. if (is_array($info)) {
  7963. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7964. return true;
  7965. } else {
  7966. return false;
  7967. }
  7968. } else {
  7969. return false;
  7970. }
  7971. }
  7972. /**
  7973. * Function test if type is integer
  7974. *
  7975. * @param array $info content informations of field
  7976. * @return bool true if integer
  7977. */
  7978. public function isInt($info)
  7979. {
  7980. if (is_array($info)) {
  7981. if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
  7982. return true;
  7983. } else {
  7984. return false;
  7985. }
  7986. } else {
  7987. return false;
  7988. }
  7989. }
  7990. /**
  7991. * Function test if type is float
  7992. *
  7993. * @param array $info content informations of field
  7994. * @return bool true if float
  7995. */
  7996. public function isFloat($info)
  7997. {
  7998. if (is_array($info)) {
  7999. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  8000. return true;
  8001. } else {
  8002. return false;
  8003. }
  8004. }
  8005. return false;
  8006. }
  8007. /**
  8008. * Function test if type is text
  8009. *
  8010. * @param array $info content informations of field
  8011. * @return bool true if type text
  8012. */
  8013. public function isText($info)
  8014. {
  8015. if (is_array($info)) {
  8016. if (isset($info['type']) && $info['type'] == 'text') {
  8017. return true;
  8018. } else {
  8019. return false;
  8020. }
  8021. }
  8022. return false;
  8023. }
  8024. /**
  8025. * Function test if field can be null
  8026. *
  8027. * @param array $info content informations of field
  8028. * @return bool true if it can be null
  8029. */
  8030. protected function canBeNull($info)
  8031. {
  8032. if (is_array($info)) {
  8033. if (isset($info['notnull']) && $info['notnull'] != '1') {
  8034. return true;
  8035. } else {
  8036. return false;
  8037. }
  8038. }
  8039. return true;
  8040. }
  8041. /**
  8042. * Function test if field is forced to null if zero or empty
  8043. *
  8044. * @param array $info content informations of field
  8045. * @return bool true if forced to null
  8046. */
  8047. protected function isForcedToNullIfZero($info)
  8048. {
  8049. if (is_array($info)) {
  8050. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  8051. return true;
  8052. } else {
  8053. return false;
  8054. }
  8055. }
  8056. return false;
  8057. }
  8058. /**
  8059. * Function test if is indexed
  8060. *
  8061. * @param array $info content informations of field
  8062. * @return bool
  8063. */
  8064. protected function isIndex($info)
  8065. {
  8066. if (is_array($info)) {
  8067. if (isset($info['index']) && $info['index'] == true) {
  8068. return true;
  8069. } else {
  8070. return false;
  8071. }
  8072. }
  8073. return false;
  8074. }
  8075. /**
  8076. * Function to prepare a part of the query for insert by returning an array with all properties of object.
  8077. *
  8078. * Note $this->${field} are set by the page that make the createCommon() or the updateCommon().
  8079. * $this->${field} should be a clean and string value (so date are formated for SQL insert).
  8080. *
  8081. * @return array Array with all values of each properties to update
  8082. */
  8083. protected function setSaveQuery()
  8084. {
  8085. global $conf;
  8086. $queryarray = array();
  8087. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  8088. // Depending on field type ('datetime', ...)
  8089. if ($this->isDate($info)) {
  8090. if (empty($this->{$field})) {
  8091. $queryarray[$field] = null;
  8092. } else {
  8093. $queryarray[$field] = $this->db->idate($this->{$field});
  8094. }
  8095. } elseif ($this->isDuration($info)) {
  8096. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8097. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8098. if (!isset($this->{$field})) {
  8099. if (!empty($info['default'])) {
  8100. $queryarray[$field] = $info['default'];
  8101. } else {
  8102. $queryarray[$field] = 0;
  8103. }
  8104. } else {
  8105. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8106. }
  8107. } else {
  8108. $queryarray[$field] = null;
  8109. }
  8110. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  8111. if ($field == 'entity' && is_null($this->{$field})) {
  8112. $queryarray[$field] = ((int) $conf->entity);
  8113. } else {
  8114. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8115. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8116. if (!isset($this->{$field})) {
  8117. $queryarray[$field] = 0;
  8118. } elseif ($this->isInt($info)) {
  8119. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8120. } elseif ($this->isFloat($info)) {
  8121. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8122. }
  8123. } else {
  8124. $queryarray[$field] = null;
  8125. }
  8126. }
  8127. } else {
  8128. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  8129. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  8130. $queryarray[$field] = $this->{$field};
  8131. }
  8132. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  8133. unset($queryarray[$field]);
  8134. }
  8135. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  8136. $queryarray[$field] = null; // May force 0 to null
  8137. }
  8138. }
  8139. return $queryarray;
  8140. }
  8141. /**
  8142. * Function to load data from a SQL pointer into properties of current object $this
  8143. *
  8144. * @param stdClass $obj Contain data of object from database
  8145. * @return void
  8146. */
  8147. public function setVarsFromFetchObj(&$obj)
  8148. {
  8149. global $db;
  8150. foreach ($this->fields as $field => $info) {
  8151. if ($this->isDate($info)) {
  8152. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  8153. $this->{$field} = '';
  8154. } else {
  8155. $this->{$field} = $db->jdate($obj->{$field});
  8156. }
  8157. } elseif ($this->isInt($info)) {
  8158. if ($field == 'rowid') {
  8159. $this->id = (int) $obj->{$field};
  8160. } else {
  8161. if ($this->isForcedToNullIfZero($info)) {
  8162. if (empty($obj->{$field})) {
  8163. $this->{$field} = null;
  8164. } else {
  8165. $this->{$field} = (double) $obj->{$field};
  8166. }
  8167. } else {
  8168. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8169. $this->{$field} = (int) $obj->{$field};
  8170. } else {
  8171. $this->{$field} = null;
  8172. }
  8173. }
  8174. }
  8175. } elseif ($this->isFloat($info)) {
  8176. if ($this->isForcedToNullIfZero($info)) {
  8177. if (empty($obj->{$field})) {
  8178. $this->{$field} = null;
  8179. } else {
  8180. $this->{$field} = (double) $obj->{$field};
  8181. }
  8182. } else {
  8183. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8184. $this->{$field} = (double) $obj->{$field};
  8185. } else {
  8186. $this->{$field} = null;
  8187. }
  8188. }
  8189. } else {
  8190. $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
  8191. }
  8192. }
  8193. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  8194. if (!isset($this->fields['ref']) && isset($this->id)) {
  8195. $this->ref = $this->id;
  8196. }
  8197. }
  8198. /**
  8199. * Function to concat keys of fields
  8200. *
  8201. * @param string $alias String of alias of table for fields. For example 't'. It is recommended to use '' and set alias into fields defintion.
  8202. * @return string list of alias fields
  8203. */
  8204. public function getFieldList($alias = '')
  8205. {
  8206. $keys = array_keys($this->fields);
  8207. if (!empty($alias)) {
  8208. $keys_with_alias = array();
  8209. foreach ($keys as $fieldname) {
  8210. $keys_with_alias[] = $alias . '.' . $fieldname;
  8211. }
  8212. return implode(',', $keys_with_alias);
  8213. } else {
  8214. return implode(',', $keys);
  8215. }
  8216. }
  8217. /**
  8218. * Add quote to field value if necessary
  8219. *
  8220. * @param string|int $value Value to protect
  8221. * @param array $fieldsentry Properties of field
  8222. * @return string
  8223. */
  8224. protected function quote($value, $fieldsentry)
  8225. {
  8226. if (is_null($value)) {
  8227. return 'NULL';
  8228. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  8229. return price2num("$value");
  8230. } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
  8231. return (int) $value;
  8232. } elseif ($fieldsentry['type'] == 'boolean') {
  8233. if ($value) {
  8234. return 'true';
  8235. } else {
  8236. return 'false';
  8237. }
  8238. } else {
  8239. return "'" . $this->db->escape($value) . "'";
  8240. }
  8241. }
  8242. /**
  8243. * Create object into database
  8244. *
  8245. * @param User $user User that creates
  8246. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8247. * @return int <0 if KO, Id of created object if OK
  8248. */
  8249. public function createCommon(User $user, $notrigger = false)
  8250. {
  8251. global $langs;
  8252. dol_syslog(get_class($this) . "::createCommon create", LOG_DEBUG);
  8253. $error = 0;
  8254. $now = dol_now();
  8255. $fieldvalues = $this->setSaveQuery();
  8256. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  8257. $fieldvalues['date_creation'] = $this->db->idate($now);
  8258. }
  8259. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  8260. $fieldvalues['fk_user_creat'] = $user->id;
  8261. }
  8262. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  8263. if (array_key_exists('ref', $fieldvalues)) {
  8264. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8265. }
  8266. $keys = array();
  8267. $values = array(); // Array to store string forged for SQL syntax
  8268. foreach ($fieldvalues as $k => $v) {
  8269. $keys[$k] = $k;
  8270. $value = $this->fields[$k];
  8271. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  8272. }
  8273. // Clean and check mandatory
  8274. foreach ($keys as $key) {
  8275. // If field is an implicit foreign key field (so type = 'integer:...')
  8276. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8277. $values[$key] = '';
  8278. }
  8279. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8280. $values[$key] = '';
  8281. }
  8282. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  8283. $error++;
  8284. $langs->load("errors");
  8285. dol_syslog("Mandatory field '" . $key . "' is empty and required into ->fields definition of class");
  8286. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8287. }
  8288. // If value is null and there is a default value for field
  8289. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  8290. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  8291. }
  8292. // If field is an implicit foreign key field (so type = 'integer:...')
  8293. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  8294. if (isset($this->fields[$key]['default'])) {
  8295. $values[$key] = ((int) $this->fields[$key]['default']);
  8296. } else {
  8297. $values[$key] = 'null';
  8298. }
  8299. }
  8300. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  8301. $values[$key] = 'null';
  8302. }
  8303. }
  8304. if ($error) {
  8305. return -1;
  8306. }
  8307. $this->db->begin();
  8308. if (!$error) {
  8309. $sql = "INSERT INTO " . $this->db->prefix() . $this->table_element;
  8310. $sql .= " (" . implode(", ", $keys) . ')';
  8311. $sql .= " VALUES (" . implode(", ", $values) . ")"; // $values can contains 'abc' or 123
  8312. $res = $this->db->query($sql);
  8313. if (!$res) {
  8314. $error++;
  8315. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  8316. $this->errors[] = "ErrorRefAlreadyExists";
  8317. } else {
  8318. $this->errors[] = $this->db->lasterror();
  8319. }
  8320. }
  8321. }
  8322. if (!$error) {
  8323. $this->id = $this->db->last_insert_id($this->db->prefix() . $this->table_element);
  8324. }
  8325. // If we have a field ref with a default value of (PROV)
  8326. if (!$error) {
  8327. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  8328. $sql = "UPDATE " . $this->db->prefix() . $this->table_element . " SET ref = '(PROV" . ((int) $this->id) . ")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = " . ((int) $this->id);
  8329. $resqlupdate = $this->db->query($sql);
  8330. if ($resqlupdate === false) {
  8331. $error++;
  8332. $this->errors[] = $this->db->lasterror();
  8333. } else {
  8334. $this->ref = '(PROV' . $this->id . ')';
  8335. }
  8336. }
  8337. }
  8338. // Create extrafields
  8339. if (!$error) {
  8340. $result = $this->insertExtraFields();
  8341. if ($result < 0) {
  8342. $error++;
  8343. }
  8344. }
  8345. // Create lines
  8346. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8347. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8348. for ($i = 0; $i < $num; $i++) {
  8349. $line = $this->lines[$i];
  8350. $keyforparent = $this->fk_element;
  8351. $line->$keyforparent = $this->id;
  8352. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8353. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8354. if (!is_object($line)) {
  8355. $line = (object) $line;
  8356. }
  8357. $result = $line->create($user, 1);
  8358. if ($result < 0) {
  8359. $this->error = $line->error;
  8360. $this->db->rollback();
  8361. return -1;
  8362. }
  8363. }
  8364. }
  8365. // Triggers
  8366. if (!$error && !$notrigger) {
  8367. // Call triggers
  8368. $result = $this->call_trigger(strtoupper(get_class($this)) . '_CREATE', $user);
  8369. if ($result < 0) {
  8370. $error++;
  8371. }
  8372. // End call triggers
  8373. }
  8374. // Commit or rollback
  8375. if ($error) {
  8376. $this->db->rollback();
  8377. return -1;
  8378. } else {
  8379. $this->db->commit();
  8380. return $this->id;
  8381. }
  8382. }
  8383. /**
  8384. * Load object in memory from the database
  8385. *
  8386. * @param int $id Id object
  8387. * @param string $ref Ref
  8388. * @param string $morewhere More SQL filters (' AND ...')
  8389. * @return int <0 if KO, 0 if not found, >0 if OK
  8390. */
  8391. public function fetchCommon($id, $ref = null, $morewhere = '')
  8392. {
  8393. if (empty($id) && empty($ref) && empty($morewhere)) {
  8394. return -1;
  8395. }
  8396. $fieldlist = $this->getFieldList('t');
  8397. if (empty($fieldlist)) {
  8398. return 0;
  8399. }
  8400. $sql = "SELECT " . $fieldlist;
  8401. $sql .= " FROM " . $this->db->prefix() . $this->table_element . ' as t';
  8402. if (!empty($id)) {
  8403. $sql .= ' WHERE t.rowid = ' . ((int) $id);
  8404. } elseif (!empty($ref)) {
  8405. $sql .= " WHERE t.ref = '" . $this->db->escape($ref) . "'";
  8406. } else {
  8407. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8408. }
  8409. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8410. $sql .= ' AND t.entity IN (' . getEntity($this->element) . ')';
  8411. }
  8412. if ($morewhere) {
  8413. $sql .= $morewhere;
  8414. }
  8415. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8416. $res = $this->db->query($sql);
  8417. if ($res) {
  8418. $obj = $this->db->fetch_object($res);
  8419. if ($obj) {
  8420. $this->setVarsFromFetchObj($obj);
  8421. // Retrieve all extrafield
  8422. // fetch optionals attributes and labels
  8423. $this->fetch_optionals();
  8424. return $this->id;
  8425. } else {
  8426. return 0;
  8427. }
  8428. } else {
  8429. $this->error = $this->db->lasterror();
  8430. $this->errors[] = $this->error;
  8431. return -1;
  8432. }
  8433. }
  8434. /**
  8435. * Load object in memory from the database
  8436. *
  8437. * @param string $morewhere More SQL filters (' AND ...')
  8438. * @return int <0 if KO, 0 if not found, >0 if OK
  8439. */
  8440. public function fetchLinesCommon($morewhere = '')
  8441. {
  8442. $objectlineclassname = get_class($this) . 'Line';
  8443. if (!class_exists($objectlineclassname)) {
  8444. $this->error = 'Error, class ' . $objectlineclassname . ' not found during call of fetchLinesCommon';
  8445. return -1;
  8446. }
  8447. $objectline = new $objectlineclassname($this->db);
  8448. $sql = "SELECT " . $objectline->getFieldList('l');
  8449. $sql .= " FROM " . $this->db->prefix() . $objectline->table_element . " as l";
  8450. $sql .= " WHERE l.fk_" . $this->db->escape($this->element) . " = " . ((int) $this->id);
  8451. if ($morewhere) {
  8452. $sql .= $morewhere;
  8453. }
  8454. if (isset($objectline->fields['position'])) {
  8455. $sql .= $this->db->order('position', 'ASC');
  8456. }
  8457. $resql = $this->db->query($sql);
  8458. if ($resql) {
  8459. $num_rows = $this->db->num_rows($resql);
  8460. $i = 0;
  8461. while ($i < $num_rows) {
  8462. $obj = $this->db->fetch_object($resql);
  8463. if ($obj) {
  8464. $newline = new $objectlineclassname($this->db);
  8465. $newline->setVarsFromFetchObj($obj);
  8466. $this->lines[] = $newline;
  8467. }
  8468. $i++;
  8469. }
  8470. return 1;
  8471. } else {
  8472. $this->error = $this->db->lasterror();
  8473. $this->errors[] = $this->error;
  8474. return -1;
  8475. }
  8476. }
  8477. /**
  8478. * Update object into database
  8479. *
  8480. * @param User $user User that modifies
  8481. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8482. * @return int <0 if KO, >0 if OK
  8483. */
  8484. public function updateCommon(User $user, $notrigger = false)
  8485. {
  8486. global $conf, $langs;
  8487. dol_syslog(get_class($this) . "::updateCommon update", LOG_DEBUG);
  8488. $error = 0;
  8489. $now = dol_now();
  8490. // $this->oldcopy should have been set by the caller of update
  8491. //if (empty($this->oldcopy)) {
  8492. // $this->oldcopy = dol_clone($this);
  8493. //}
  8494. $fieldvalues = $this->setSaveQuery();
  8495. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8496. $fieldvalues['date_modification'] = $this->db->idate($now);
  8497. }
  8498. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8499. $fieldvalues['fk_user_modif'] = $user->id;
  8500. }
  8501. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8502. if (array_key_exists('ref', $fieldvalues)) {
  8503. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8504. }
  8505. // Add quotes and escape on fields with type string
  8506. $keys = array();
  8507. $values = array();
  8508. $tmp = array();
  8509. foreach ($fieldvalues as $k => $v) {
  8510. $keys[$k] = $k;
  8511. $value = $this->fields[$k];
  8512. $values[$k] = $this->quote($v, $value);
  8513. $tmp[] = $k . '=' . $this->quote($v, $this->fields[$k]);
  8514. }
  8515. // Clean and check mandatory fields
  8516. foreach ($keys as $key) {
  8517. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8518. $values[$key] = ''; // This is an implicit foreign key field
  8519. }
  8520. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8521. $values[$key] = ''; // This is an explicit foreign key field
  8522. }
  8523. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8524. /*
  8525. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8526. {
  8527. $error++;
  8528. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8529. }*/
  8530. }
  8531. $sql = 'UPDATE ' . $this->db->prefix() . $this->table_element . ' SET ' . implode(', ', $tmp) . ' WHERE rowid=' . ((int) $this->id);
  8532. $this->db->begin();
  8533. if (!$error) {
  8534. $res = $this->db->query($sql);
  8535. if (!$res) {
  8536. $error++;
  8537. $this->errors[] = $this->db->lasterror();
  8538. }
  8539. }
  8540. // Update extrafield
  8541. if (!$error) {
  8542. $result = $this->insertExtraFields();
  8543. if ($result < 0) {
  8544. $error++;
  8545. }
  8546. }
  8547. // Triggers
  8548. if (!$error && !$notrigger) {
  8549. // Call triggers
  8550. $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $user);
  8551. if ($result < 0) {
  8552. $error++;
  8553. } //Do also here what you must do to rollback action if trigger fail
  8554. // End call triggers
  8555. }
  8556. // Commit or rollback
  8557. if ($error) {
  8558. $this->db->rollback();
  8559. return -1;
  8560. } else {
  8561. $this->db->commit();
  8562. return $this->id;
  8563. }
  8564. }
  8565. /**
  8566. * Delete object in database
  8567. *
  8568. * @param User $user User that deletes
  8569. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8570. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8571. * @return int <0 if KO, 0=Nothing done because object has child, >0 if OK
  8572. */
  8573. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8574. {
  8575. dol_syslog(get_class($this) . "::deleteCommon delete", LOG_DEBUG);
  8576. $error = 0;
  8577. $this->db->begin();
  8578. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8579. foreach ($this->childtables as $table) {
  8580. $sql = "DELETE FROM " . $this->db->prefix() . $table . " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  8581. $resql = $this->db->query($sql);
  8582. if (!$resql) {
  8583. $this->error = $this->db->lasterror();
  8584. $this->errors[] = $this->error;
  8585. $this->db->rollback();
  8586. return -1;
  8587. }
  8588. }
  8589. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8590. $objectisused = $this->isObjectUsed($this->id);
  8591. if (!empty($objectisused)) {
  8592. dol_syslog(get_class($this) . "::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8593. $this->error = 'ErrorRecordHasChildren';
  8594. $this->errors[] = $this->error;
  8595. $this->db->rollback();
  8596. return 0;
  8597. }
  8598. }
  8599. // Delete cascade first
  8600. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8601. foreach ($this->childtablesoncascade as $table) {
  8602. $deleteFromObject = explode(':', $table);
  8603. if (count($deleteFromObject) >= 2) {
  8604. $className = str_replace('@', '', $deleteFromObject[0]);
  8605. $filePath = $deleteFromObject[1];
  8606. $columnName = $deleteFromObject[2];
  8607. $TMoreSQL = array();
  8608. $more_sql = $deleteFromObject[3];
  8609. if (!empty($more_sql)) {
  8610. $TMoreSQL['customsql'] = $more_sql;
  8611. }
  8612. if (dol_include_once($filePath)) {
  8613. $childObject = new $className($this->db);
  8614. if (method_exists($childObject, 'deleteByParentField')) {
  8615. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8616. if ($result < 0) {
  8617. $error++;
  8618. $this->errors[] = $childObject->error;
  8619. break;
  8620. }
  8621. } else {
  8622. $error++;
  8623. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8624. break;
  8625. }
  8626. } else {
  8627. $error++;
  8628. $this->errors[] = 'Cannot include child class file ' . $filePath;
  8629. break;
  8630. }
  8631. } else {
  8632. // Delete record in child table
  8633. $sql = "DELETE FROM " . $this->db->prefix() . $table . " WHERE " . $this->fk_element . " = " . ((int) $this->id);
  8634. $resql = $this->db->query($sql);
  8635. if (!$resql) {
  8636. $error++;
  8637. $this->error = $this->db->lasterror();
  8638. $this->errors[] = $this->error;
  8639. break;
  8640. }
  8641. }
  8642. }
  8643. }
  8644. if (!$error) {
  8645. if (!$notrigger) {
  8646. // Call triggers
  8647. $result = $this->call_trigger(strtoupper(get_class($this)) . '_DELETE', $user);
  8648. if ($result < 0) {
  8649. $error++;
  8650. } // Do also here what you must do to rollback action if trigger fail
  8651. // End call triggers
  8652. }
  8653. }
  8654. // Delete llx_ecm_files
  8655. if (!$error) {
  8656. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8657. if (!$res) {
  8658. $error++;
  8659. }
  8660. }
  8661. // Delete linked object
  8662. $res = $this->deleteObjectLinked();
  8663. if ($res < 0) {
  8664. $error++;
  8665. }
  8666. if (!$error && !empty($this->isextrafieldmanaged)) {
  8667. $result = $this->deleteExtraFields();
  8668. if ($result < 0) {
  8669. $error++;
  8670. }
  8671. }
  8672. if (!$error) {
  8673. $sql = 'DELETE FROM ' . $this->db->prefix() . $this->table_element . ' WHERE rowid=' . ((int) $this->id);
  8674. $resql = $this->db->query($sql);
  8675. if (!$resql) {
  8676. $error++;
  8677. $this->errors[] = $this->db->lasterror();
  8678. }
  8679. }
  8680. // Commit or rollback
  8681. if ($error) {
  8682. $this->db->rollback();
  8683. return -1;
  8684. } else {
  8685. $this->db->commit();
  8686. return 1;
  8687. }
  8688. }
  8689. /**
  8690. * Delete all child object from a parent ID
  8691. *
  8692. * @param int $parentId Parent Id
  8693. * @param string $parentField Name of Foreign key parent column
  8694. * @param array $filter an array filter
  8695. * @param string $filtermode AND or OR
  8696. * @return int <0 if KO, >0 if OK
  8697. * @throws Exception
  8698. */
  8699. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8700. {
  8701. global $user;
  8702. $error = 0;
  8703. $deleted = 0;
  8704. if (!empty($parentId) && !empty($parentField)) {
  8705. $this->db->begin();
  8706. $sql = "SELECT rowid FROM " . $this->db->prefix() . $this->table_element;
  8707. $sql .= " WHERE " . $parentField . " = " . (int) $parentId;
  8708. // Manage filters
  8709. $sqlwhere = array();
  8710. if (count($filter) > 0) {
  8711. foreach ($filter as $key => $value) {
  8712. if ($key == 'customsql') {
  8713. $sqlwhere[] = $value;
  8714. } elseif (strpos($value, '%') === false) {
  8715. $sqlwhere[] = $key . " IN (" . $this->db->sanitize($this->db->escape($value)) . ")";
  8716. } else {
  8717. $sqlwhere[] = $key . " LIKE '%" . $this->db->escape($value) . "%'";
  8718. }
  8719. }
  8720. }
  8721. if (count($sqlwhere) > 0) {
  8722. $sql .= " AND (" . implode(" " . $filtermode . " ", $sqlwhere) . ")";
  8723. }
  8724. $resql = $this->db->query($sql);
  8725. if (!$resql) {
  8726. $this->errors[] = $this->db->lasterror();
  8727. $error++;
  8728. } else {
  8729. while ($obj = $this->db->fetch_object($resql)) {
  8730. $result = $this->fetch($obj->rowid);
  8731. if ($result < 0) {
  8732. $error++;
  8733. $this->errors[] = $this->error;
  8734. } else {
  8735. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8736. $result = $this->delete();
  8737. } else {
  8738. $result = $this->delete($user);
  8739. }
  8740. if ($result < 0) {
  8741. $error++;
  8742. $this->errors[] = $this->error;
  8743. } else {
  8744. $deleted++;
  8745. }
  8746. }
  8747. }
  8748. }
  8749. if (empty($error)) {
  8750. $this->db->commit();
  8751. return $deleted;
  8752. } else {
  8753. $this->error = implode(', ', $this->errors);
  8754. $this->db->rollback();
  8755. return $error * -1;
  8756. }
  8757. }
  8758. return $deleted;
  8759. }
  8760. /**
  8761. * Delete a line of object in database
  8762. *
  8763. * @param User $user User that delete
  8764. * @param int $idline Id of line to delete
  8765. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8766. * @return int >0 if OK, <0 if KO
  8767. */
  8768. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8769. {
  8770. global $conf;
  8771. $error = 0;
  8772. $tmpforobjectclass = get_class($this);
  8773. $tmpforobjectlineclass = ucfirst($tmpforobjectclass) . 'Line';
  8774. $this->db->begin();
  8775. // Call trigger
  8776. $result = $this->call_trigger('LINE' . strtoupper($tmpforobjectclass) . '_DELETE', $user);
  8777. if ($result < 0) {
  8778. $error++;
  8779. }
  8780. // End call triggers
  8781. if (empty($error)) {
  8782. $sql = "DELETE FROM " . $this->db->prefix() . $this->table_element_line;
  8783. $sql .= " WHERE rowid = " . ((int) $idline);
  8784. $resql = $this->db->query($sql);
  8785. if (!$resql) {
  8786. $this->error = "Error " . $this->db->lasterror();
  8787. $error++;
  8788. }
  8789. }
  8790. if (empty($error)) {
  8791. // Remove extrafields
  8792. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8793. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8794. $tmpobjectline->id = $idline;
  8795. $result = $tmpobjectline->deleteExtraFields();
  8796. if ($result < 0) {
  8797. $error++;
  8798. $this->error = "Error " . get_class($this) . "::deleteLineCommon deleteExtraFields error -4 " . $tmpobjectline->error;
  8799. }
  8800. }
  8801. }
  8802. if (empty($error)) {
  8803. $this->db->commit();
  8804. return 1;
  8805. } else {
  8806. dol_syslog(get_class($this) . "::deleteLineCommon ERROR:" . $this->error, LOG_ERR);
  8807. $this->db->rollback();
  8808. return -1;
  8809. }
  8810. }
  8811. /**
  8812. * Set to a status
  8813. *
  8814. * @param User $user Object user that modify
  8815. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8816. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8817. * @param string $triggercode Trigger code to use
  8818. * @return int <0 if KO, >0 if OK
  8819. */
  8820. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8821. {
  8822. $error = 0;
  8823. $this->db->begin();
  8824. $statusfield = 'status';
  8825. if ($this->element == 'don' || $this->element == 'donation') {
  8826. $statusfield = 'fk_statut';
  8827. }
  8828. $sql = "UPDATE " . $this->db->prefix() . $this->table_element;
  8829. $sql .= " SET " . $statusfield . " = " . ((int) $status);
  8830. $sql .= " WHERE rowid = " . ((int) $this->id);
  8831. if ($this->db->query($sql)) {
  8832. if (!$error) {
  8833. $this->oldcopy = clone $this;
  8834. }
  8835. if (!$error && !$notrigger) {
  8836. // Call trigger
  8837. $result = $this->call_trigger($triggercode, $user);
  8838. if ($result < 0) {
  8839. $error++;
  8840. }
  8841. }
  8842. if (!$error) {
  8843. $this->status = $status;
  8844. $this->db->commit();
  8845. return 1;
  8846. } else {
  8847. $this->db->rollback();
  8848. return -1;
  8849. }
  8850. } else {
  8851. $this->error = $this->db->error();
  8852. $this->db->rollback();
  8853. return -1;
  8854. }
  8855. }
  8856. /**
  8857. * Initialise object with example values
  8858. * Id must be 0 if object instance is a specimen
  8859. *
  8860. * @return int
  8861. */
  8862. public function initAsSpecimenCommon()
  8863. {
  8864. global $user;
  8865. $this->id = 0;
  8866. $this->specimen = 1;
  8867. $fields = array(
  8868. 'label' => 'This is label',
  8869. 'ref' => 'ABCD1234',
  8870. 'description' => 'This is a description',
  8871. 'qty' => 123.12,
  8872. 'note_public' => 'Public note',
  8873. 'note_private' => 'Private note',
  8874. 'date_creation' => (dol_now() - 3600 * 48),
  8875. 'date_modification' => (dol_now() - 3600 * 24),
  8876. 'fk_user_creat' => $user->id,
  8877. 'fk_user_modif' => $user->id,
  8878. 'date' => dol_now(),
  8879. );
  8880. foreach ($fields as $key => $value) {
  8881. if (array_key_exists($key, $this->fields)) {
  8882. $this->{$key} = $value;
  8883. }
  8884. }
  8885. return 1;
  8886. }
  8887. /* Part for comments */
  8888. /**
  8889. * Load comments linked with current task
  8890. * @return boolean 1 if ok
  8891. */
  8892. public function fetchComments()
  8893. {
  8894. require_once DOL_DOCUMENT_ROOT . '/core/class/comment.class.php';
  8895. $comment = new Comment($this->db);
  8896. $result = $comment->fetchAllFor($this->element, $this->id);
  8897. if ($result < 0) {
  8898. $this->errors = array_merge($this->errors, $comment->errors);
  8899. return -1;
  8900. } else {
  8901. $this->comments = $comment->comments;
  8902. }
  8903. return count($this->comments);
  8904. }
  8905. /**
  8906. * Return nb comments already posted
  8907. *
  8908. * @return int
  8909. */
  8910. public function getNbComments()
  8911. {
  8912. return count($this->comments);
  8913. }
  8914. /**
  8915. * Trim object parameters
  8916. *
  8917. * @param string[] $parameters array of parameters to trim
  8918. * @return void
  8919. */
  8920. public function trimParameters($parameters)
  8921. {
  8922. if (!is_array($parameters)) {
  8923. return;
  8924. }
  8925. foreach ($parameters as $parameter) {
  8926. if (isset($this->$parameter)) {
  8927. $this->$parameter = trim($this->$parameter);
  8928. }
  8929. }
  8930. }
  8931. /* Part for categories/tags */
  8932. /**
  8933. * Sets object to given categories.
  8934. *
  8935. * Deletes object from existing categories not supplied.
  8936. * Adds it to non existing supplied categories.
  8937. * Existing categories are left untouch.
  8938. *
  8939. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8940. * @return int Array of category objects or < 0 if KO
  8941. */
  8942. public function getCategoriesCommon($type_categ)
  8943. {
  8944. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  8945. // Get current categories
  8946. $c = new Categorie($this->db);
  8947. $existing = $c->containing($this->id, $type_categ, 'id');
  8948. return $existing;
  8949. }
  8950. /**
  8951. * Sets object to given categories.
  8952. *
  8953. * Adds it to non existing supplied categories.
  8954. * Deletes object from existing categories not supplied (if remove_existing==true).
  8955. * Existing categories are left untouch.
  8956. *
  8957. * @param int[]|int $categories Category ID or array of Categories IDs
  8958. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8959. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8960. * @return int <0 if KO, >0 if OK
  8961. */
  8962. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8963. {
  8964. // Handle single category
  8965. if (!is_array($categories)) {
  8966. $categories = array($categories);
  8967. }
  8968. dol_syslog(get_class($this) . "::setCategoriesCommon Oject Id:" . $this->id . ' type_categ:' . $type_categ . ' nb tag add:' . count($categories), LOG_DEBUG);
  8969. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  8970. if (empty($type_categ)) {
  8971. dol_syslog(__METHOD__ . ': Type ' . $type_categ . 'is an unknown category type. Done nothing.', LOG_ERR);
  8972. return -1;
  8973. }
  8974. // Get current categories
  8975. $c = new Categorie($this->db);
  8976. $existing = $c->containing($this->id, $type_categ, 'id');
  8977. if ($remove_existing) {
  8978. // Diff
  8979. if (is_array($existing)) {
  8980. $to_del = array_diff($existing, $categories);
  8981. $to_add = array_diff($categories, $existing);
  8982. } else {
  8983. $to_del = array(); // Nothing to delete
  8984. $to_add = $categories;
  8985. }
  8986. } else {
  8987. $to_del = array(); // Nothing to delete
  8988. $to_add = array_diff($categories, $existing);
  8989. }
  8990. $error = 0;
  8991. $ok = 0;
  8992. // Process
  8993. foreach ($to_del as $del) {
  8994. if ($c->fetch($del) > 0) {
  8995. $result = $c->del_type($this, $type_categ);
  8996. if ($result < 0) {
  8997. $error++;
  8998. $this->error = $c->error;
  8999. $this->errors = $c->errors;
  9000. break;
  9001. } else {
  9002. $ok += $result;
  9003. }
  9004. }
  9005. }
  9006. foreach ($to_add as $add) {
  9007. if ($c->fetch($add) > 0) {
  9008. $result = $c->add_type($this, $type_categ);
  9009. if ($result < 0) {
  9010. $error++;
  9011. $this->error = $c->error;
  9012. $this->errors = $c->errors;
  9013. break;
  9014. } else {
  9015. $ok += $result;
  9016. }
  9017. }
  9018. }
  9019. return $error ? (-1 * $error) : $ok;
  9020. }
  9021. /**
  9022. * Copy related categories to another object
  9023. *
  9024. * @param int $fromId Id object source
  9025. * @param int $toId Id object cible
  9026. * @param string $type Type of category ('product', ...)
  9027. * @return int < 0 if error, > 0 if ok
  9028. */
  9029. public function cloneCategories($fromId, $toId, $type = '')
  9030. {
  9031. $this->db->begin();
  9032. if (empty($type)) {
  9033. $type = $this->table_element;
  9034. }
  9035. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  9036. $categorystatic = new Categorie($this->db);
  9037. $sql = "INSERT INTO " . $this->db->prefix() . "categorie_" . (empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]) . " (fk_categorie, fk_product)";
  9038. $sql .= " SELECT fk_categorie, $toId FROM " . $this->db->prefix() . "categorie_" . (empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  9039. $sql .= " WHERE fk_product = " . ((int) $fromId);
  9040. if (!$this->db->query($sql)) {
  9041. $this->error = $this->db->lasterror();
  9042. $this->db->rollback();
  9043. return -1;
  9044. }
  9045. $this->db->commit();
  9046. return 1;
  9047. }
  9048. /**
  9049. * Delete related files of object in database
  9050. *
  9051. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  9052. * @return bool True if OK, False if KO
  9053. */
  9054. public function deleteEcmFiles($mode = 0)
  9055. {
  9056. global $conf;
  9057. $this->db->begin();
  9058. // Delete in database with mode 0
  9059. if ($mode == 0) {
  9060. switch ($this->element) {
  9061. case 'propal':
  9062. $element = 'propale';
  9063. break;
  9064. case 'product':
  9065. $element = 'produit';
  9066. break;
  9067. case 'order_supplier':
  9068. $element = 'fournisseur/commande';
  9069. break;
  9070. case 'invoice_supplier':
  9071. $element = 'fournisseur/facture/' . get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  9072. break;
  9073. case 'shipping':
  9074. $element = 'expedition/sending';
  9075. break;
  9076. default:
  9077. $element = $this->element;
  9078. }
  9079. // Delete ecm_files extrafields
  9080. $sql = "DELETE FROM " . $this->db->prefix() . "ecm_files_extrafields WHERE fk_object IN (";
  9081. $sql .= " SELECT rowid FROM " . $this->db->prefix() . "ecm_files WHERE filename LIKE '" . $this->db->escape($this->ref) . "%'";
  9082. $sql .= " AND filepath = '" . $this->db->escape($element) . "/" . $this->db->escape($this->ref) . "' AND entity = " . ((int) $conf->entity); // No need of getEntity here
  9083. $sql .= ")";
  9084. if (!$this->db->query($sql)) {
  9085. $this->error = $this->db->lasterror();
  9086. $this->db->rollback();
  9087. return false;
  9088. }
  9089. // Delete ecm_files
  9090. $sql = "DELETE FROM " . $this->db->prefix() . "ecm_files";
  9091. $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%'";
  9092. $sql .= " AND filepath = '" . $this->db->escape($element) . "/" . $this->db->escape($this->ref) . "' AND entity = " . ((int) $conf->entity); // No need of getEntity here
  9093. if (!$this->db->query($sql)) {
  9094. $this->error = $this->db->lasterror();
  9095. $this->db->rollback();
  9096. return false;
  9097. }
  9098. }
  9099. // Delete in database with mode 1
  9100. if ($mode == 1) {
  9101. $sql = 'DELETE FROM ' . $this->db->prefix() . "ecm_files_extrafields";
  9102. $sql .= " WHERE fk_object IN (SELECT rowid FROM " . $this->db->prefix() . "ecm_files WHERE src_object_type = '" . $this->db->escape($this->table_element . (empty($this->module) ? "" : "@" . $this->module)) . "' AND src_object_id = " . ((int) $this->id) . ")";
  9103. $resql = $this->db->query($sql);
  9104. if (!$resql) {
  9105. $this->error = $this->db->lasterror();
  9106. $this->db->rollback();
  9107. return false;
  9108. }
  9109. $sql = 'DELETE FROM ' . $this->db->prefix() . "ecm_files";
  9110. $sql .= " WHERE src_object_type = '" . $this->db->escape($this->table_element . (empty($this->module) ? "" : "@" . $this->module)) . "' AND src_object_id = " . ((int) $this->id);
  9111. $resql = $this->db->query($sql);
  9112. if (!$resql) {
  9113. $this->error = $this->db->lasterror();
  9114. $this->db->rollback();
  9115. return false;
  9116. }
  9117. }
  9118. $this->db->commit();
  9119. return true;
  9120. }
  9121. }