commonobject.class.php 353 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164
  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. protected $labelStatus;
  492. protected $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 (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)
  778. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
  779. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  780. $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
  781. } else {
  782. $out .= ($outdone ? ' - ' : '').$this->state;
  783. }
  784. $outdone++;
  785. }
  786. if ($outdone) {
  787. $out = '<div class="address inline-block">'.$out.'</div>';
  788. }
  789. 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)) {
  790. $out .= ($outdone ? '<br>' : '');
  791. }
  792. if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  793. $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  794. $outdone++;
  795. }
  796. if (!empty($this->phone_pro)) {
  797. $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  798. $outdone++;
  799. }
  800. if (!empty($this->phone_mobile)) {
  801. $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  802. $outdone++;
  803. }
  804. if (!empty($this->phone_perso)) {
  805. $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso"));
  806. $outdone++;
  807. }
  808. if (!empty($this->office_phone)) {
  809. $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro"));
  810. $outdone++;
  811. }
  812. if (!empty($this->user_mobile)) {
  813. $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile"));
  814. $outdone++;
  815. }
  816. if (!empty($this->fax)) {
  817. $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  818. $outdone++;
  819. }
  820. if (!empty($this->office_fax)) {
  821. $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax"));
  822. $outdone++;
  823. }
  824. if ($out) {
  825. $out .= '<div style="clear: both;"></div>';
  826. }
  827. $outdone = 0;
  828. if (!empty($this->email)) {
  829. $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
  830. $outdone++;
  831. }
  832. if (!empty($this->url)) {
  833. //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
  834. $out .= dol_print_url($this->url, '_blank', 0, 1);
  835. $outdone++;
  836. }
  837. if (isModEnabled('socialnetworks')) {
  838. $outsocialnetwork = '';
  839. if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
  840. $socialnetworksdict = getArrayOfSocialNetworks();
  841. foreach ($this->socialnetworks as $key => $value) {
  842. if ($value) {
  843. $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
  844. }
  845. $outdone++;
  846. }
  847. } else { // Old code to remove
  848. if (!empty($this->skype)) {
  849. $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
  850. }
  851. $outdone++;
  852. if (!empty($this->jabberid)) {
  853. $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
  854. }
  855. $outdone++;
  856. if (!empty($this->twitter)) {
  857. $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
  858. }
  859. $outdone++;
  860. if (!empty($this->facebook)) {
  861. $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
  862. }
  863. $outdone++;
  864. if (!empty($this->linkedin)) {
  865. $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
  866. }
  867. $outdone++;
  868. }
  869. if ($outsocialnetwork) {
  870. $out .= '<div style="clear: both;">'.$outsocialnetwork.'</div>';
  871. }
  872. }
  873. if ($out) {
  874. return '<!-- BEGIN part to show address block -->'."\n".$out.'<!-- END Part to show address block -->'."\n";
  875. } else {
  876. return '';
  877. }
  878. }
  879. /**
  880. * Return the link of last main doc file for direct public download.
  881. *
  882. * @param string $modulepart Module related to document
  883. * @param int $initsharekey Init the share key if it was not yet defined
  884. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  885. * @return string Link or empty string if there is no download link
  886. */
  887. public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
  888. {
  889. global $user, $dolibarr_main_url_root;
  890. if (empty($this->last_main_doc)) {
  891. return ''; // No way to known which document name to use
  892. }
  893. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  894. $ecmfile = new EcmFiles($this->db);
  895. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  896. if ($result < 0) {
  897. $this->error = $ecmfile->error;
  898. $this->errors = $ecmfile->errors;
  899. return -1;
  900. }
  901. if (empty($ecmfile->id)) {
  902. // Add entry into index
  903. if ($initsharekey) {
  904. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  905. // 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
  906. /*
  907. $ecmfile->filepath = $rel_dir;
  908. $ecmfile->filename = $filename;
  909. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  910. $ecmfile->fullpath_orig = '';
  911. $ecmfile->gen_or_uploaded = 'generated';
  912. $ecmfile->description = ''; // indexed content
  913. $ecmfile->keywords = ''; // keyword content
  914. $ecmfile->share = getRandomPassword(true);
  915. $result = $ecmfile->create($user);
  916. if ($result < 0)
  917. {
  918. $this->error = $ecmfile->error;
  919. $this->errors = $ecmfile->errors;
  920. }
  921. */
  922. } else {
  923. return '';
  924. }
  925. } elseif (empty($ecmfile->share)) {
  926. // Add entry into index
  927. if ($initsharekey) {
  928. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  929. $ecmfile->share = getRandomPassword(true);
  930. $ecmfile->update($user);
  931. } else {
  932. return '';
  933. }
  934. }
  935. // Define $urlwithroot
  936. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  937. // This is to use external domain name found into config file
  938. //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
  939. //else
  940. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
  941. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  942. $forcedownload = 0;
  943. $paramlink = '';
  944. //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  945. //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  946. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  947. if (!empty($ecmfile->share)) {
  948. $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
  949. }
  950. if ($forcedownload) {
  951. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  952. }
  953. if ($relativelink) {
  954. $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
  955. } else {
  956. $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  957. }
  958. // Here $ecmfile->share is defined
  959. return $linktoreturn;
  960. }
  961. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  962. /**
  963. * Add a link between element $this->element and a contact
  964. *
  965. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  966. * @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
  967. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  968. * @param int $notrigger Disable all triggers
  969. * @return int <0 if KO, 0 if already added, >0 if OK
  970. */
  971. public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
  972. {
  973. // phpcs:enable
  974. global $user, $langs;
  975. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  976. // Check parameters
  977. if ($fk_socpeople <= 0) {
  978. $langs->load("errors");
  979. $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
  980. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  981. return -1;
  982. }
  983. if (!$type_contact) {
  984. $langs->load("errors");
  985. $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
  986. dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
  987. return -2;
  988. }
  989. $id_type_contact = 0;
  990. if (is_numeric($type_contact)) {
  991. $id_type_contact = $type_contact;
  992. } else {
  993. // We look for id type_contact
  994. $sql = "SELECT tc.rowid";
  995. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  996. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  997. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  998. $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  999. //print $sql;
  1000. $resql = $this->db->query($sql);
  1001. if ($resql) {
  1002. $obj = $this->db->fetch_object($resql);
  1003. if ($obj) {
  1004. $id_type_contact = $obj->rowid;
  1005. }
  1006. }
  1007. }
  1008. if ($id_type_contact == 0) {
  1009. $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
  1010. 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");
  1011. return -3;
  1012. }
  1013. $datecreate = dol_now();
  1014. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  1015. $TListeContacts = $this->liste_contact(-1, $source);
  1016. $already_added = false;
  1017. if (is_array($TListeContacts) && !empty($TListeContacts)) {
  1018. foreach ($TListeContacts as $array_contact) {
  1019. if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  1020. $already_added = true;
  1021. break;
  1022. }
  1023. }
  1024. }
  1025. if (!$already_added) {
  1026. $this->db->begin();
  1027. // Insert into database
  1028. $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
  1029. $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  1030. $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
  1031. $sql .= "'".$this->db->idate($datecreate)."'";
  1032. $sql .= ", 4, ".((int) $id_type_contact);
  1033. $sql .= ")";
  1034. $resql = $this->db->query($sql);
  1035. if ($resql) {
  1036. if (!$notrigger) {
  1037. $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  1038. if ($result < 0) {
  1039. $this->db->rollback();
  1040. return -1;
  1041. }
  1042. }
  1043. $this->db->commit();
  1044. return 1;
  1045. } else {
  1046. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1047. $this->error = $this->db->errno();
  1048. $this->db->rollback();
  1049. return -2;
  1050. } else {
  1051. $this->error = $this->db->lasterror();
  1052. $this->db->rollback();
  1053. return -1;
  1054. }
  1055. }
  1056. } else {
  1057. return 0;
  1058. }
  1059. }
  1060. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1061. /**
  1062. * Copy contact from one element to current
  1063. *
  1064. * @param CommonObject $objFrom Source element
  1065. * @param string $source Nature of contact ('internal' or 'external')
  1066. * @return int >0 if OK, <0 if KO
  1067. */
  1068. public function copy_linked_contact($objFrom, $source = 'internal')
  1069. {
  1070. // phpcs:enable
  1071. $contacts = $objFrom->liste_contact(-1, $source);
  1072. foreach ($contacts as $contact) {
  1073. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
  1074. return -1;
  1075. }
  1076. }
  1077. return 1;
  1078. }
  1079. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1080. /**
  1081. * Update a link to contact line
  1082. *
  1083. * @param int $rowid Id of line contact-element
  1084. * @param int $statut New status of link
  1085. * @param int $type_contact_id Id of contact type (not modified if 0)
  1086. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  1087. * @return int <0 if KO, >= 0 if OK
  1088. */
  1089. public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
  1090. {
  1091. // phpcs:enable
  1092. // Insert into database
  1093. $sql = "UPDATE ".$this->db->prefix()."element_contact set";
  1094. $sql .= " statut = ".$statut;
  1095. if ($type_contact_id) {
  1096. $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
  1097. }
  1098. if ($fk_socpeople) {
  1099. $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
  1100. }
  1101. $sql .= " where rowid = ".((int) $rowid);
  1102. $resql = $this->db->query($sql);
  1103. if ($resql) {
  1104. return 0;
  1105. } else {
  1106. $this->error = $this->db->lasterror();
  1107. return -1;
  1108. }
  1109. }
  1110. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1111. /**
  1112. * Delete a link to contact line
  1113. *
  1114. * @param int $rowid Id of contact link line to delete
  1115. * @param int $notrigger Disable all triggers
  1116. * @return int >0 if OK, <0 if KO
  1117. */
  1118. public function delete_contact($rowid, $notrigger = 0)
  1119. {
  1120. // phpcs:enable
  1121. global $user;
  1122. $this->db->begin();
  1123. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1124. $sql .= " WHERE rowid = ".((int) $rowid);
  1125. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  1126. if ($this->db->query($sql)) {
  1127. if (!$notrigger) {
  1128. $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  1129. if ($result < 0) {
  1130. $this->db->rollback();
  1131. return -1;
  1132. }
  1133. }
  1134. $this->db->commit();
  1135. return 1;
  1136. } else {
  1137. $this->error = $this->db->lasterror();
  1138. $this->db->rollback();
  1139. return -1;
  1140. }
  1141. }
  1142. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1143. /**
  1144. * Delete all links between an object $this and all its contacts in llx_element_contact
  1145. *
  1146. * @param string $source '' or 'internal' or 'external'
  1147. * @param string $code Type of contact (code or id)
  1148. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1149. */
  1150. public function delete_linked_contact($source = '', $code = '')
  1151. {
  1152. // phpcs:enable
  1153. $listId = '';
  1154. $temp = array();
  1155. $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
  1156. if (!empty($typeContact)) {
  1157. foreach ($typeContact as $key => $value) {
  1158. array_push($temp, $key);
  1159. }
  1160. $listId = implode(",", $temp);
  1161. }
  1162. // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
  1163. // any type or record instead of only the ones of the current object. So we do nothing in such a case.
  1164. if (empty($listId)) {
  1165. return 0;
  1166. }
  1167. $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
  1168. $sql .= " WHERE element_id = ".((int) $this->id);
  1169. $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
  1170. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  1171. if ($this->db->query($sql)) {
  1172. return 1;
  1173. } else {
  1174. $this->error = $this->db->lasterror();
  1175. return -1;
  1176. }
  1177. }
  1178. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1179. /**
  1180. * Get array of all contacts for an object
  1181. *
  1182. * @param int $statusoflink Status of links to get (-1=all). Not used.
  1183. * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user)
  1184. * @param int $list 0:Returned array contains all properties, 1:Return array contains just id
  1185. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  1186. * @param int $status Status of user or company
  1187. * @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.
  1188. * @return array|int Array of contacts, -1 if error
  1189. */
  1190. public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
  1191. {
  1192. // phpcs:enable
  1193. global $langs;
  1194. $tab = array();
  1195. $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
  1196. if ($source == 'internal') {
  1197. $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  1198. }
  1199. if ($source == 'external' || $source == 'thirdparty') {
  1200. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  1201. }
  1202. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  1203. $sql .= ", tc.source, tc.element, tc.code, tc.libelle";
  1204. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
  1205. $sql .= ", ".$this->db->prefix()."element_contact ec";
  1206. if ($source == 'internal') { // internal contact (user)
  1207. $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
  1208. }
  1209. if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
  1210. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
  1211. }
  1212. $sql .= " WHERE ec.element_id = ".((int) $this->id);
  1213. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1214. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1215. if ($code) {
  1216. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1217. }
  1218. if ($source == 'internal') {
  1219. $sql .= " AND tc.source = 'internal'";
  1220. if ($status >= 0) {
  1221. $sql .= " AND t.statut = ".((int) $status);
  1222. }
  1223. }
  1224. if ($source == 'external' || $source == 'thirdparty') {
  1225. $sql .= " AND tc.source = 'external'";
  1226. if ($status >= 0) {
  1227. $sql .= " AND t.statut = ".((int) $status); // t is llx_socpeople
  1228. }
  1229. }
  1230. $sql .= " AND tc.active = 1";
  1231. if ($statusoflink >= 0) {
  1232. $sql .= " AND ec.statut = ".((int) $statusoflink);
  1233. }
  1234. $sql .= " ORDER BY t.lastname ASC";
  1235. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  1236. $resql = $this->db->query($sql);
  1237. if ($resql) {
  1238. $num = $this->db->num_rows($resql);
  1239. $i = 0;
  1240. while ($i < $num) {
  1241. $obj = $this->db->fetch_object($resql);
  1242. if (!$list) {
  1243. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1244. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1245. $tab[$i] = array(
  1246. 'source' => $obj->source,
  1247. 'socid' => $obj->socid,
  1248. 'id' => $obj->id,
  1249. 'nom' => $obj->lastname, // For backward compatibility
  1250. 'civility' => $obj->civility,
  1251. 'lastname' => $obj->lastname,
  1252. 'firstname' => $obj->firstname,
  1253. 'email'=>$obj->email,
  1254. 'login'=> (empty($obj->login) ? '' : $obj->login),
  1255. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  1256. 'statuscontact' => $obj->statuscontact,
  1257. 'rowid' => $obj->rowid,
  1258. 'code' => $obj->code,
  1259. 'libelle' => $libelle_type,
  1260. 'status' => $obj->statuslink,
  1261. 'fk_c_type_contact' => $obj->fk_c_type_contact
  1262. );
  1263. } else {
  1264. $tab[$i] = $obj->id;
  1265. }
  1266. $i++;
  1267. }
  1268. return $tab;
  1269. } else {
  1270. $this->error = $this->db->lasterror();
  1271. dol_print_error($this->db);
  1272. return -1;
  1273. }
  1274. }
  1275. /**
  1276. * Update status of a contact linked to object
  1277. *
  1278. * @param int $rowid Id of link between object and contact
  1279. * @return int <0 if KO, >=0 if OK
  1280. */
  1281. public function swapContactStatus($rowid)
  1282. {
  1283. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  1284. $sql .= " tc.code, tc.libelle";
  1285. $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
  1286. $sql .= " WHERE ec.rowid =".((int) $rowid);
  1287. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1288. $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
  1289. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  1290. $resql = $this->db->query($sql);
  1291. if ($resql) {
  1292. $obj = $this->db->fetch_object($resql);
  1293. $newstatut = ($obj->statut == 4) ? 5 : 4;
  1294. $result = $this->update_contact($rowid, $newstatut);
  1295. $this->db->free($resql);
  1296. return $result;
  1297. } else {
  1298. $this->error = $this->db->error();
  1299. dol_print_error($this->db);
  1300. return -1;
  1301. }
  1302. }
  1303. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1304. /**
  1305. * Return array with list of possible values for type of contacts
  1306. *
  1307. * @param string $source 'internal', 'external' or 'all'
  1308. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  1309. * @param int $option 0=Return array id->label, 1=Return array code->label
  1310. * @param int $activeonly 0=all status of contact, 1=only the active
  1311. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1312. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1313. */
  1314. public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
  1315. {
  1316. // phpcs:enable
  1317. global $langs;
  1318. if (empty($order)) {
  1319. $order = 'position';
  1320. }
  1321. if ($order == 'position') {
  1322. $order .= ',code';
  1323. }
  1324. $tab = array();
  1325. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  1326. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1327. $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
  1328. if ($activeonly == 1) {
  1329. $sql .= " AND tc.active=1"; // only the active types
  1330. }
  1331. if (!empty($source) && $source != 'all') {
  1332. $sql .= " AND tc.source='".$this->db->escape($source)."'";
  1333. }
  1334. if (!empty($code)) {
  1335. $sql .= " AND tc.code='".$this->db->escape($code)."'";
  1336. }
  1337. $sql .= $this->db->order($order, 'ASC');
  1338. //print "sql=".$sql;
  1339. $resql = $this->db->query($sql);
  1340. if ($resql) {
  1341. $num = $this->db->num_rows($resql);
  1342. $i = 0;
  1343. while ($i < $num) {
  1344. $obj = $this->db->fetch_object($resql);
  1345. $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
  1346. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1347. if (empty($option)) {
  1348. $tab[$obj->rowid] = $libelle_type;
  1349. } else {
  1350. $tab[$obj->code] = $libelle_type;
  1351. }
  1352. $i++;
  1353. }
  1354. return $tab;
  1355. } else {
  1356. $this->error = $this->db->lasterror();
  1357. //dol_print_error($this->db);
  1358. return null;
  1359. }
  1360. }
  1361. /**
  1362. * Return array with list of possible values for type of contacts
  1363. *
  1364. * @param string $source 'internal', 'external' or 'all'
  1365. * @param int $option 0=Return array id->label, 1=Return array code->label
  1366. * @param int $activeonly 0=all status of contact, 1=only the active
  1367. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  1368. * @param string $element Filter on 1 element type
  1369. * @param string $excludeelement Exclude 1 element type. Example: 'agenda'
  1370. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  1371. */
  1372. public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
  1373. {
  1374. global $langs, $conf;
  1375. $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
  1376. $tab = array();
  1377. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element";
  1378. $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
  1379. $sqlWhere = array();
  1380. if (!empty($element)) {
  1381. $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
  1382. }
  1383. if (!empty($excludeelement)) {
  1384. $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
  1385. }
  1386. if ($activeonly == 1) {
  1387. $sqlWhere[] = " tc.active=1"; // only the active types
  1388. }
  1389. if (!empty($source) && $source != 'all') {
  1390. $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
  1391. }
  1392. if (!empty($code)) {
  1393. $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
  1394. }
  1395. if (count($sqlWhere) > 0) {
  1396. $sql .= " WHERE ".implode(' AND ', $sqlWhere);
  1397. }
  1398. $sql .= $this->db->order('tc.element, tc.position', 'ASC');
  1399. dol_syslog(__METHOD__, LOG_DEBUG);
  1400. $resql = $this->db->query($sql);
  1401. if ($resql) {
  1402. $num = $this->db->num_rows($resql);
  1403. if ($num > 0) {
  1404. $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
  1405. while ($obj = $this->db->fetch_object($resql)) {
  1406. $modulename = $obj->element;
  1407. if (strpos($obj->element, 'project') !== false) {
  1408. $modulename = 'projet';
  1409. } elseif ($obj->element == 'contrat') {
  1410. $element = 'contract';
  1411. } elseif ($obj->element == 'action') {
  1412. $modulename = 'agenda';
  1413. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1414. $modulename = 'fournisseur';
  1415. } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
  1416. $modulename = 'fournisseur';
  1417. }
  1418. if (!empty($conf->{$modulename}->enabled)) {
  1419. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1420. $tmpelement = $obj->element;
  1421. $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
  1422. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
  1423. if (empty($option)) {
  1424. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1425. } else {
  1426. $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
  1427. }
  1428. }
  1429. }
  1430. }
  1431. return $tab;
  1432. } else {
  1433. $this->error = $this->db->lasterror();
  1434. return null;
  1435. }
  1436. }
  1437. /**
  1438. * Return id of contacts for a source and a contact code.
  1439. * Example: contact client de facturation ('external', 'BILLING')
  1440. * Example: contact client de livraison ('external', 'SHIPPING')
  1441. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1442. *
  1443. * @param string $source 'external' or 'internal'
  1444. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1445. * @param int $status limited to a certain status
  1446. * @return array List of id for such contacts
  1447. */
  1448. public function getIdContact($source, $code, $status = 0)
  1449. {
  1450. global $conf;
  1451. $result = array();
  1452. $i = 0;
  1453. //cas particulier pour les expeditions
  1454. if ($this->element == 'shipping' && $this->origin_id != 0) {
  1455. $id = $this->origin_id;
  1456. $element = 'commande';
  1457. } elseif ($this->element == 'reception' && $this->origin_id != 0) {
  1458. $id = $this->origin_id;
  1459. $element = 'order_supplier';
  1460. } else {
  1461. $id = $this->id;
  1462. $element = $this->element;
  1463. }
  1464. $sql = "SELECT ec.fk_socpeople";
  1465. $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
  1466. if ($source == 'internal') {
  1467. $sql .= " ".$this->db->prefix()."user as c,";
  1468. }
  1469. if ($source == 'external') {
  1470. $sql .= " ".$this->db->prefix()."socpeople as c,";
  1471. }
  1472. $sql .= " ".$this->db->prefix()."c_type_contact as tc";
  1473. $sql .= " WHERE ec.element_id = ".((int) $id);
  1474. $sql .= " AND ec.fk_socpeople = c.rowid";
  1475. if ($source == 'internal') {
  1476. $sql .= " AND c.entity IN (".getEntity('user').")";
  1477. }
  1478. if ($source == 'external') {
  1479. $sql .= " AND c.entity IN (".getEntity('societe').")";
  1480. }
  1481. $sql .= " AND ec.fk_c_type_contact = tc.rowid";
  1482. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1483. $sql .= " AND tc.source = '".$this->db->escape($source)."'";
  1484. if ($code) {
  1485. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  1486. }
  1487. $sql .= " AND tc.active = 1";
  1488. if ($status) {
  1489. $sql .= " AND ec.statut = ".((int) $status);
  1490. }
  1491. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1492. $resql = $this->db->query($sql);
  1493. if ($resql) {
  1494. while ($obj = $this->db->fetch_object($resql)) {
  1495. $result[$i] = $obj->fk_socpeople;
  1496. $i++;
  1497. }
  1498. } else {
  1499. $this->error = $this->db->error();
  1500. return null;
  1501. }
  1502. return $result;
  1503. }
  1504. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1505. /**
  1506. * Load object contact with id=$this->contact_id into $this->contact
  1507. *
  1508. * @param int $contactid Id du contact. Use this->contact_id if empty.
  1509. * @return int <0 if KO, >0 if OK
  1510. */
  1511. public function fetch_contact($contactid = null)
  1512. {
  1513. // phpcs:enable
  1514. if (empty($contactid)) {
  1515. $contactid = $this->contact_id;
  1516. }
  1517. if (empty($contactid)) {
  1518. return 0;
  1519. }
  1520. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1521. $contact = new Contact($this->db);
  1522. $result = $contact->fetch($contactid);
  1523. $this->contact = $contact;
  1524. return $result;
  1525. }
  1526. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1527. /**
  1528. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1529. *
  1530. * @param int $force_thirdparty_id Force thirdparty id
  1531. * @return int <0 if KO, >0 if OK
  1532. */
  1533. public function fetch_thirdparty($force_thirdparty_id = 0)
  1534. {
  1535. // phpcs:enable
  1536. global $conf;
  1537. if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
  1538. return 0;
  1539. }
  1540. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1541. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
  1542. if ($force_thirdparty_id) {
  1543. $idtofetch = $force_thirdparty_id;
  1544. }
  1545. if ($idtofetch) {
  1546. $thirdparty = new Societe($this->db);
  1547. $result = $thirdparty->fetch($idtofetch);
  1548. if ($result<0) {
  1549. $this->errors=array_merge($this->errors, $thirdparty->errors);
  1550. }
  1551. $this->thirdparty = $thirdparty;
  1552. // Use first price level if level not defined for third party
  1553. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1554. $this->thirdparty->price_level = 1;
  1555. }
  1556. return $result;
  1557. } else {
  1558. return -1;
  1559. }
  1560. }
  1561. /**
  1562. * Looks for an object with ref matching the wildcard provided
  1563. * It does only work when $this->table_ref_field is set
  1564. *
  1565. * @param string $ref Wildcard
  1566. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1567. */
  1568. public function fetchOneLike($ref)
  1569. {
  1570. if (!$this->table_ref_field) {
  1571. return 0;
  1572. }
  1573. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element." WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."' LIMIT 1";
  1574. $query = $this->db->query($sql);
  1575. if (!$this->db->num_rows($query)) {
  1576. return 0;
  1577. }
  1578. $result = $this->db->fetch_object($query);
  1579. return $this->fetch($result->rowid);
  1580. }
  1581. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1582. /**
  1583. * Load data for barcode into properties ->barcode_type*
  1584. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1585. * if it is not defined, ->element must be defined to know default barcode type.
  1586. *
  1587. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1588. */
  1589. public function fetch_barcode()
  1590. {
  1591. // phpcs:enable
  1592. global $conf;
  1593. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1594. $idtype = $this->barcode_type;
  1595. 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
  1596. if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
  1597. $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1598. } elseif ($this->element == 'societe') {
  1599. $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1600. } else {
  1601. dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1602. }
  1603. }
  1604. if ($idtype > 0) {
  1605. 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
  1606. $sql = "SELECT rowid, code, libelle as label, coder";
  1607. $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
  1608. $sql .= " WHERE rowid = ".((int) $idtype);
  1609. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1610. $resql = $this->db->query($sql);
  1611. if ($resql) {
  1612. $obj = $this->db->fetch_object($resql);
  1613. $this->barcode_type = $obj->rowid;
  1614. $this->barcode_type_code = $obj->code;
  1615. $this->barcode_type_label = $obj->label;
  1616. $this->barcode_type_coder = $obj->coder;
  1617. return 1;
  1618. } else {
  1619. dol_print_error($this->db);
  1620. return -1;
  1621. }
  1622. }
  1623. }
  1624. return 0;
  1625. }
  1626. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1627. /**
  1628. * Load the project with id $this->fk_project into this->project
  1629. *
  1630. * @return int <0 if KO, >=0 if OK
  1631. */
  1632. public function fetch_project()
  1633. {
  1634. // phpcs:enable
  1635. return $this->fetch_projet();
  1636. }
  1637. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1638. /**
  1639. * Load the project with id $this->fk_project into this->project
  1640. *
  1641. * @return int <0 if KO, >=0 if OK
  1642. */
  1643. public function fetch_projet()
  1644. {
  1645. // phpcs:enable
  1646. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1647. if (empty($this->fk_project) && !empty($this->fk_projet)) {
  1648. $this->fk_project = $this->fk_projet; // For backward compatibility
  1649. }
  1650. if (empty($this->fk_project)) {
  1651. return 0;
  1652. }
  1653. $project = new Project($this->db);
  1654. $result = $project->fetch($this->fk_project);
  1655. $this->projet = $project; // deprecated
  1656. $this->project = $project;
  1657. return $result;
  1658. }
  1659. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1660. /**
  1661. * Load the product with id $this->fk_product into this->product
  1662. *
  1663. * @return int <0 if KO, >=0 if OK
  1664. */
  1665. public function fetch_product()
  1666. {
  1667. // phpcs:enable
  1668. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1669. if (empty($this->fk_product)) {
  1670. return 0;
  1671. }
  1672. $product = new Product($this->db);
  1673. $result = $product->fetch($this->fk_product);
  1674. $this->product = $product;
  1675. return $result;
  1676. }
  1677. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1678. /**
  1679. * Load the user with id $userid into this->user
  1680. *
  1681. * @param int $userid Id du contact
  1682. * @return int <0 if KO, >0 if OK
  1683. */
  1684. public function fetch_user($userid)
  1685. {
  1686. // phpcs:enable
  1687. $user = new User($this->db);
  1688. $result = $user->fetch($userid);
  1689. $this->user = $user;
  1690. return $result;
  1691. }
  1692. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1693. /**
  1694. * Read linked origin object
  1695. *
  1696. * @return void
  1697. */
  1698. public function fetch_origin()
  1699. {
  1700. // phpcs:enable
  1701. if ($this->origin == 'shipping') {
  1702. $this->origin = 'expedition';
  1703. }
  1704. if ($this->origin == 'delivery') {
  1705. $this->origin = 'livraison';
  1706. }
  1707. if ($this->origin == 'order_supplier') {
  1708. $this->origin = 'commandeFournisseur';
  1709. }
  1710. $origin = $this->origin;
  1711. $classname = ucfirst($origin);
  1712. $this->$origin = new $classname($this->db);
  1713. $this->$origin->fetch($this->origin_id);
  1714. }
  1715. /**
  1716. * Load object from specific field
  1717. *
  1718. * @param string $table Table element or element line
  1719. * @param string $field Field selected
  1720. * @param string $key Import key
  1721. * @param string $element Element name
  1722. * @return int <0 if KO, >0 if OK
  1723. */
  1724. public function fetchObjectFrom($table, $field, $key, $element = null)
  1725. {
  1726. global $conf;
  1727. $result = false;
  1728. $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
  1729. $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
  1730. if (!empty($element)) {
  1731. $sql .= " AND entity IN (".getEntity($element).")";
  1732. } else {
  1733. $sql .= " AND entity = ".((int) $conf->entity);
  1734. }
  1735. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1736. $resql = $this->db->query($sql);
  1737. if ($resql) {
  1738. $row = $this->db->fetch_row($resql);
  1739. // Test for avoid error -1
  1740. if ($row[0] > 0) {
  1741. $result = $this->fetch($row[0]);
  1742. }
  1743. }
  1744. return $result;
  1745. }
  1746. /**
  1747. * Getter generic. Load value from a specific field
  1748. *
  1749. * @param string $table Table of element or element line
  1750. * @param int $id Element id
  1751. * @param string $field Field selected
  1752. * @return int <0 if KO, >0 if OK
  1753. */
  1754. public function getValueFrom($table, $id, $field)
  1755. {
  1756. $result = false;
  1757. if (!empty($id) && !empty($field) && !empty($table)) {
  1758. $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
  1759. $sql .= " WHERE rowid = ".((int) $id);
  1760. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1761. $resql = $this->db->query($sql);
  1762. if ($resql) {
  1763. $row = $this->db->fetch_row($resql);
  1764. $result = $row[0];
  1765. }
  1766. }
  1767. return $result;
  1768. }
  1769. /**
  1770. * Setter generic. Update a specific field into database.
  1771. * Warning: Trigger is run only if param trigkey is provided.
  1772. *
  1773. * @param string $field Field to update
  1774. * @param mixed $value New value
  1775. * @param string $table To force other table element or element line (should not be used)
  1776. * @param int $id To force other object id (should not be used)
  1777. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1778. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1779. * @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'
  1780. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1781. * @param string $fk_user_field Name of field to save user id making change
  1782. * @return int <0 if KO, >0 if OK
  1783. * @see updateExtraField()
  1784. */
  1785. public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
  1786. {
  1787. global $user, $langs, $conf;
  1788. if (empty($table)) {
  1789. $table = $this->table_element;
  1790. }
  1791. if (empty($id)) {
  1792. $id = $this->id;
  1793. }
  1794. if (empty($format)) {
  1795. $format = 'text';
  1796. }
  1797. if (empty($id_field)) {
  1798. $id_field = 'rowid';
  1799. }
  1800. $error = 0;
  1801. $this->db->begin();
  1802. // Special case
  1803. if ($table == 'product' && $field == 'note_private') {
  1804. $field = 'note';
  1805. }
  1806. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  1807. $fk_user_field = 'fk_user_mod';
  1808. }
  1809. $sql = "UPDATE ".$this->db->prefix().$table." SET ";
  1810. if ($format == 'text') {
  1811. $sql .= $field." = '".$this->db->escape($value)."'";
  1812. } elseif ($format == 'int') {
  1813. $sql .= $field." = ".((int) $value);
  1814. } elseif ($format == 'date') {
  1815. $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1816. }
  1817. if ($fk_user_field) {
  1818. if (!empty($fuser) && is_object($fuser)) {
  1819. $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
  1820. } elseif (empty($fuser) || $fuser != 'none') {
  1821. $sql .= ", ".$fk_user_field." = ".((int) $user->id);
  1822. }
  1823. }
  1824. $sql .= " WHERE ".$id_field." = ".((int) $id);
  1825. dol_syslog(__METHOD__."", LOG_DEBUG);
  1826. $resql = $this->db->query($sql);
  1827. if ($resql) {
  1828. if ($trigkey) {
  1829. // call trigger with updated object values
  1830. if (method_exists($this, 'fetch')) {
  1831. $result = $this->fetch($id);
  1832. } else {
  1833. $result = $this->fetchCommon($id);
  1834. }
  1835. if ($result >= 0) {
  1836. $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1837. }
  1838. if ($result < 0) {
  1839. $error++;
  1840. }
  1841. }
  1842. if (!$error) {
  1843. if (property_exists($this, $field)) {
  1844. $this->$field = $value;
  1845. }
  1846. $this->db->commit();
  1847. return 1;
  1848. } else {
  1849. $this->db->rollback();
  1850. return -2;
  1851. }
  1852. } else {
  1853. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1854. $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
  1855. } else {
  1856. $this->error = $this->db->lasterror();
  1857. }
  1858. $this->db->rollback();
  1859. return -1;
  1860. }
  1861. }
  1862. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1863. /**
  1864. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1865. *
  1866. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')". Do not allow user input data here.
  1867. * @param string $fieldid Name of field to use for the select MAX and MIN
  1868. * @param int $nodbprefix Do not include DB prefix to forge table name
  1869. * @return int <0 if KO, >0 if OK
  1870. */
  1871. public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
  1872. {
  1873. // phpcs:enable
  1874. global $conf, $user;
  1875. if (!$this->table_element) {
  1876. dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1877. return -1;
  1878. }
  1879. if ($fieldid == 'none') {
  1880. return 1;
  1881. }
  1882. // For backward compatibility
  1883. if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
  1884. $fieldid = 'titre';
  1885. }
  1886. // Security on socid
  1887. $socid = 0;
  1888. if ($user->socid > 0) {
  1889. $socid = $user->socid;
  1890. }
  1891. // this->ismultientitymanaged contains
  1892. // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  1893. $aliastablesociete = 's';
  1894. if ($this->element == 'societe') {
  1895. $aliastablesociete = 'te'; // te as table_element
  1896. }
  1897. $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
  1898. $sql = "SELECT MAX(te.".$fieldid.")";
  1899. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1900. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1901. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1902. }
  1903. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1904. $tmparray = explode('@', $this->ismultientitymanaged);
  1905. $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
  1906. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1907. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1908. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1909. $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
  1910. }
  1911. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1912. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1913. }
  1914. $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)
  1915. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1916. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1917. }
  1918. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1919. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1920. }
  1921. if (!empty($filter)) {
  1922. if (!preg_match('/^\s*AND/i', $filter)) {
  1923. $sql .= " AND "; // For backward compatibility
  1924. }
  1925. $sql .= $filter;
  1926. }
  1927. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1928. $tmparray = explode('@', $this->ismultientitymanaged);
  1929. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1930. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1931. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1932. }
  1933. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1934. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1935. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1936. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  1937. } else {
  1938. $sql .= " AND ug.fk_user = te.rowid";
  1939. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  1940. }
  1941. } else {
  1942. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  1943. }
  1944. }
  1945. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  1946. $tmparray = explode('@', $this->ismultientitymanaged);
  1947. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  1948. }
  1949. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  1950. $sql .= ' AND te.fk_soc = '.((int) $socid);
  1951. }
  1952. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  1953. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  1954. }
  1955. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  1956. $sql .= ' AND te.rowid = '.((int) $socid);
  1957. }
  1958. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1959. $result = $this->db->query($sql);
  1960. if (!$result) {
  1961. $this->error = $this->db->lasterror();
  1962. return -1;
  1963. }
  1964. $row = $this->db->fetch_row($result);
  1965. $this->ref_previous = $row[0];
  1966. $sql = "SELECT MIN(te.".$fieldid.")";
  1967. $sql .= " FROM ".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te";
  1968. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1969. $sql .= ",".$this->db->prefix()."usergroup_user as ug";
  1970. }
  1971. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1972. $tmparray = explode('@', $this->ismultientitymanaged);
  1973. $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
  1974. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1975. $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
  1976. } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1977. $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
  1978. }
  1979. if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
  1980. $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
  1981. }
  1982. $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)
  1983. if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
  1984. $sql .= " AND sc.fk_user = ".((int) $user->id);
  1985. }
  1986. if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
  1987. $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
  1988. }
  1989. if (!empty($filter)) {
  1990. if (!preg_match('/^\s*AND/i', $filter)) {
  1991. $sql .= " AND "; // For backward compatibility
  1992. }
  1993. $sql .= $filter;
  1994. }
  1995. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
  1996. $tmparray = explode('@', $this->ismultientitymanaged);
  1997. $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
  1998. } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
  1999. $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  2000. }
  2001. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  2002. if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  2003. if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  2004. $sql .= " AND te.entity IS NOT NULL"; // Show all users
  2005. } else {
  2006. $sql .= " AND ug.fk_user = te.rowid";
  2007. $sql .= " AND ug.entity IN (".getEntity('usergroup').")";
  2008. }
  2009. } else {
  2010. $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
  2011. }
  2012. }
  2013. if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
  2014. $tmparray = explode('@', $this->ismultientitymanaged);
  2015. $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
  2016. }
  2017. if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
  2018. $sql .= ' AND te.fk_soc = '.((int) $socid);
  2019. }
  2020. if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
  2021. $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
  2022. }
  2023. if ($restrictiononfksoc && $socid && $this->element == 'societe') {
  2024. $sql .= ' AND te.rowid = '.((int) $socid);
  2025. }
  2026. //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  2027. // 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
  2028. $result = $this->db->query($sql);
  2029. if (!$result) {
  2030. $this->error = $this->db->lasterror();
  2031. return -2;
  2032. }
  2033. $row = $this->db->fetch_row($result);
  2034. $this->ref_next = $row[0];
  2035. return 1;
  2036. }
  2037. /**
  2038. * Return list of id of contacts of object
  2039. *
  2040. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  2041. * @return array Array of id of contacts (if source=external or internal)
  2042. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  2043. */
  2044. public function getListContactId($source = 'external')
  2045. {
  2046. $contactAlreadySelected = array();
  2047. $tab = $this->liste_contact(-1, $source);
  2048. $num = count($tab);
  2049. $i = 0;
  2050. while ($i < $num) {
  2051. if ($source == 'thirdparty') {
  2052. $contactAlreadySelected[$i] = $tab[$i]['socid'];
  2053. } else {
  2054. $contactAlreadySelected[$i] = $tab[$i]['id'];
  2055. }
  2056. $i++;
  2057. }
  2058. return $contactAlreadySelected;
  2059. }
  2060. /**
  2061. * Link element with a project
  2062. *
  2063. * @param int $projectid Project id to link element to
  2064. * @param int $notrigger Disable the trigger
  2065. * @return int <0 if KO, >0 if OK
  2066. */
  2067. public function setProject($projectid, $notrigger = 0)
  2068. {
  2069. global $user;
  2070. $error = 0;
  2071. if (!$this->table_element) {
  2072. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
  2073. return -1;
  2074. }
  2075. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2076. if (!empty($this->fields['fk_project'])) { // Common case
  2077. if ($projectid) {
  2078. $sql .= " SET fk_project = ".((int) $projectid);
  2079. } else {
  2080. $sql .= " SET fk_project = NULL";
  2081. }
  2082. $sql .= ' WHERE rowid = '.((int) $this->id);
  2083. } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
  2084. if ($projectid) {
  2085. $sql .= " SET fk_project = ".((int) $projectid);
  2086. } else {
  2087. $sql .= " SET fk_project = NULL";
  2088. }
  2089. $sql .= ' WHERE id = '.((int) $this->id);
  2090. } else // Special case for old architecture objects
  2091. {
  2092. if ($projectid) {
  2093. $sql .= ' SET fk_projet = '.((int) $projectid);
  2094. } else {
  2095. $sql .= ' SET fk_projet = NULL';
  2096. }
  2097. $sql .= " WHERE rowid = ".((int) $this->id);
  2098. }
  2099. $this->db->begin();
  2100. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  2101. if ($this->db->query($sql)) {
  2102. $this->fk_project = ((int) $projectid);
  2103. } else {
  2104. dol_print_error($this->db);
  2105. $error++;
  2106. }
  2107. // Triggers
  2108. if (!$error && !$notrigger) {
  2109. // Call triggers
  2110. $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
  2111. if ($result < 0) {
  2112. $error++;
  2113. } //Do also here what you must do to rollback action if trigger fail
  2114. // End call triggers
  2115. }
  2116. // Commit or rollback
  2117. if ($error) {
  2118. $this->db->rollback();
  2119. return -1;
  2120. } else {
  2121. $this->db->commit();
  2122. return 1;
  2123. }
  2124. }
  2125. /**
  2126. * Change the payments methods
  2127. *
  2128. * @param int $id Id of new payment method
  2129. * @return int >0 if OK, <0 if KO
  2130. */
  2131. public function setPaymentMethods($id)
  2132. {
  2133. global $user;
  2134. $error = 0; $notrigger = 0;
  2135. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  2136. if ($this->statut >= 0 || $this->element == 'societe') {
  2137. // TODO uniformize field name
  2138. $fieldname = 'fk_mode_reglement';
  2139. if ($this->element == 'societe') {
  2140. $fieldname = 'mode_reglement';
  2141. }
  2142. if (get_class($this) == 'Fournisseur') {
  2143. $fieldname = 'mode_reglement_supplier';
  2144. }
  2145. if (get_class($this) == 'Tva') {
  2146. $fieldname = 'fk_typepayment';
  2147. }
  2148. if (get_class($this) == 'Salary') {
  2149. $fieldname = 'fk_typepayment';
  2150. }
  2151. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2152. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2153. $sql .= ' WHERE rowid='.((int) $this->id);
  2154. if ($this->db->query($sql)) {
  2155. $this->mode_reglement_id = $id;
  2156. // for supplier
  2157. if (get_class($this) == 'Fournisseur') {
  2158. $this->mode_reglement_supplier_id = $id;
  2159. }
  2160. // Triggers
  2161. if (!$error && !$notrigger) {
  2162. // Call triggers
  2163. if (get_class($this) == 'Commande') {
  2164. $result = $this->call_trigger('ORDER_MODIFY', $user);
  2165. } else {
  2166. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  2167. }
  2168. if ($result < 0) {
  2169. $error++;
  2170. }
  2171. // End call triggers
  2172. }
  2173. return 1;
  2174. } else {
  2175. dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
  2176. $this->error = $this->db->error();
  2177. return -1;
  2178. }
  2179. } else {
  2180. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  2181. $this->error = 'Status of the object is incompatible '.$this->statut;
  2182. return -2;
  2183. }
  2184. }
  2185. /**
  2186. * Change the multicurrency code
  2187. *
  2188. * @param string $code multicurrency code
  2189. * @return int >0 if OK, <0 if KO
  2190. */
  2191. public function setMulticurrencyCode($code)
  2192. {
  2193. dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
  2194. if ($this->statut >= 0 || $this->element == 'societe') {
  2195. $fieldname = 'multicurrency_code';
  2196. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2197. $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
  2198. $sql .= ' WHERE rowid='.((int) $this->id);
  2199. if ($this->db->query($sql)) {
  2200. $this->multicurrency_code = $code;
  2201. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  2202. if ($rate) {
  2203. $this->setMulticurrencyRate($rate, 2);
  2204. }
  2205. return 1;
  2206. } else {
  2207. dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
  2208. $this->error = $this->db->error();
  2209. return -1;
  2210. }
  2211. } else {
  2212. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  2213. $this->error = 'Status of the object is incompatible '.$this->statut;
  2214. return -2;
  2215. }
  2216. }
  2217. /**
  2218. * Change the multicurrency rate
  2219. *
  2220. * @param double $rate multicurrency rate
  2221. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency will be recalculated
  2222. * @return int >0 if OK, <0 if KO
  2223. */
  2224. public function setMulticurrencyRate($rate, $mode = 1)
  2225. {
  2226. dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
  2227. if ($this->statut >= 0 || $this->element == 'societe') {
  2228. $fieldname = 'multicurrency_tx';
  2229. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2230. $sql .= " SET ".$fieldname." = ".((float) $rate);
  2231. $sql .= ' WHERE rowid='.((int) $this->id);
  2232. if ($this->db->query($sql)) {
  2233. $this->multicurrency_tx = $rate;
  2234. // Update line price
  2235. if (!empty($this->lines)) {
  2236. foreach ($this->lines as &$line) {
  2237. // Amounts in company currency will be recalculated
  2238. if ($mode == 1) {
  2239. $line->subprice = 0;
  2240. }
  2241. // Amounts in foreign currency will be recalculated
  2242. if ($mode == 2) {
  2243. $line->multicurrency_subprice = 0;
  2244. }
  2245. switch ($this->element) {
  2246. case 'propal':
  2247. $this->updateline(
  2248. $line->id,
  2249. $line->subprice,
  2250. $line->qty,
  2251. $line->remise_percent,
  2252. $line->tva_tx,
  2253. $line->localtax1_tx,
  2254. $line->localtax2_tx,
  2255. ($line->description ? $line->description : $line->desc),
  2256. 'HT',
  2257. $line->info_bits,
  2258. $line->special_code,
  2259. $line->fk_parent_line,
  2260. $line->skip_update_total,
  2261. $line->fk_fournprice,
  2262. $line->pa_ht,
  2263. $line->label,
  2264. $line->product_type,
  2265. $line->date_start,
  2266. $line->date_end,
  2267. $line->array_options,
  2268. $line->fk_unit,
  2269. $line->multicurrency_subprice
  2270. );
  2271. break;
  2272. case 'commande':
  2273. $this->updateline(
  2274. $line->id,
  2275. ($line->description ? $line->description : $line->desc),
  2276. $line->subprice,
  2277. $line->qty,
  2278. $line->remise_percent,
  2279. $line->tva_tx,
  2280. $line->localtax1_tx,
  2281. $line->localtax2_tx,
  2282. 'HT',
  2283. $line->info_bits,
  2284. $line->date_start,
  2285. $line->date_end,
  2286. $line->product_type,
  2287. $line->fk_parent_line,
  2288. $line->skip_update_total,
  2289. $line->fk_fournprice,
  2290. $line->pa_ht,
  2291. $line->label,
  2292. $line->special_code,
  2293. $line->array_options,
  2294. $line->fk_unit,
  2295. $line->multicurrency_subprice
  2296. );
  2297. break;
  2298. case 'facture':
  2299. $this->updateline(
  2300. $line->id,
  2301. ($line->description ? $line->description : $line->desc),
  2302. $line->subprice,
  2303. $line->qty,
  2304. $line->remise_percent,
  2305. $line->date_start,
  2306. $line->date_end,
  2307. $line->tva_tx,
  2308. $line->localtax1_tx,
  2309. $line->localtax2_tx,
  2310. 'HT',
  2311. $line->info_bits,
  2312. $line->product_type,
  2313. $line->fk_parent_line,
  2314. $line->skip_update_total,
  2315. $line->fk_fournprice,
  2316. $line->pa_ht,
  2317. $line->label,
  2318. $line->special_code,
  2319. $line->array_options,
  2320. $line->situation_percent,
  2321. $line->fk_unit,
  2322. $line->multicurrency_subprice
  2323. );
  2324. break;
  2325. case 'supplier_proposal':
  2326. $this->updateline(
  2327. $line->id,
  2328. $line->subprice,
  2329. $line->qty,
  2330. $line->remise_percent,
  2331. $line->tva_tx,
  2332. $line->localtax1_tx,
  2333. $line->localtax2_tx,
  2334. ($line->description ? $line->description : $line->desc),
  2335. 'HT',
  2336. $line->info_bits,
  2337. $line->special_code,
  2338. $line->fk_parent_line,
  2339. $line->skip_update_total,
  2340. $line->fk_fournprice,
  2341. $line->pa_ht,
  2342. $line->label,
  2343. $line->product_type,
  2344. $line->array_options,
  2345. $line->ref_fourn,
  2346. $line->multicurrency_subprice
  2347. );
  2348. break;
  2349. case 'order_supplier':
  2350. $this->updateline(
  2351. $line->id,
  2352. ($line->description ? $line->description : $line->desc),
  2353. $line->subprice,
  2354. $line->qty,
  2355. $line->remise_percent,
  2356. $line->tva_tx,
  2357. $line->localtax1_tx,
  2358. $line->localtax2_tx,
  2359. 'HT',
  2360. $line->info_bits,
  2361. $line->product_type,
  2362. false,
  2363. $line->date_start,
  2364. $line->date_end,
  2365. $line->array_options,
  2366. $line->fk_unit,
  2367. $line->multicurrency_subprice,
  2368. $line->ref_supplier
  2369. );
  2370. break;
  2371. case 'invoice_supplier':
  2372. $this->updateline(
  2373. $line->id,
  2374. ($line->description ? $line->description : $line->desc),
  2375. $line->subprice,
  2376. $line->tva_tx,
  2377. $line->localtax1_tx,
  2378. $line->localtax2_tx,
  2379. $line->qty,
  2380. 0,
  2381. 'HT',
  2382. $line->info_bits,
  2383. $line->product_type,
  2384. $line->remise_percent,
  2385. false,
  2386. $line->date_start,
  2387. $line->date_end,
  2388. $line->array_options,
  2389. $line->fk_unit,
  2390. $line->multicurrency_subprice,
  2391. $line->ref_supplier
  2392. );
  2393. break;
  2394. default:
  2395. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  2396. break;
  2397. }
  2398. }
  2399. }
  2400. return 1;
  2401. } else {
  2402. dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
  2403. $this->error = $this->db->error();
  2404. return -1;
  2405. }
  2406. } else {
  2407. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  2408. $this->error = 'Status of the object is incompatible '.$this->statut;
  2409. return -2;
  2410. }
  2411. }
  2412. /**
  2413. * Change the payments terms
  2414. *
  2415. * @param int $id Id of new payment terms
  2416. * @param string $deposit_percent % of deposit if needed by payment terms
  2417. * @return int >0 if OK, <0 if KO
  2418. */
  2419. public function setPaymentTerms($id, $deposit_percent = null)
  2420. {
  2421. dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
  2422. if ($this->statut >= 0 || $this->element == 'societe') {
  2423. // TODO uniformize field name
  2424. $fieldname = 'fk_cond_reglement';
  2425. if ($this->element == 'societe') {
  2426. $fieldname = 'cond_reglement';
  2427. }
  2428. if (get_class($this) == 'Fournisseur') {
  2429. $fieldname = 'cond_reglement_supplier';
  2430. }
  2431. if (empty($deposit_percent) || $deposit_percent < 0) {
  2432. $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
  2433. }
  2434. if ($deposit_percent > 100) {
  2435. $deposit_percent = 100;
  2436. }
  2437. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2438. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2439. if (in_array($this->table_element, array('propal', 'commande'))) {
  2440. $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
  2441. }
  2442. $sql .= ' WHERE rowid='.((int) $this->id);
  2443. if ($this->db->query($sql)) {
  2444. $this->cond_reglement_id = $id;
  2445. // for supplier
  2446. if (get_class($this) == 'Fournisseur') {
  2447. $this->cond_reglement_supplier_id = $id;
  2448. }
  2449. $this->cond_reglement = $id; // for compatibility
  2450. $this->deposit_percent = $deposit_percent;
  2451. return 1;
  2452. } else {
  2453. dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
  2454. $this->error = $this->db->error();
  2455. return -1;
  2456. }
  2457. } else {
  2458. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  2459. $this->error = 'Status of the object is incompatible '.$this->statut;
  2460. return -2;
  2461. }
  2462. }
  2463. /**
  2464. * Change the transport mode methods
  2465. *
  2466. * @param int $id Id of transport mode
  2467. * @return int >0 if OK, <0 if KO
  2468. */
  2469. public function setTransportMode($id)
  2470. {
  2471. dol_syslog(get_class($this).'::setTransportMode('.$id.')');
  2472. if ($this->statut >= 0 || $this->element == 'societe') {
  2473. $fieldname = 'fk_transport_mode';
  2474. if ($this->element == 'societe') {
  2475. $fieldname = 'transport_mode';
  2476. }
  2477. if (get_class($this) == 'Fournisseur') {
  2478. $fieldname = 'transport_mode_supplier';
  2479. }
  2480. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2481. $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
  2482. $sql .= ' WHERE rowid='.((int) $this->id);
  2483. if ($this->db->query($sql)) {
  2484. $this->transport_mode_id = $id;
  2485. // for supplier
  2486. if (get_class($this) == 'Fournisseur') {
  2487. $this->transport_mode_supplier_id = $id;
  2488. }
  2489. return 1;
  2490. } else {
  2491. dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
  2492. $this->error = $this->db->error();
  2493. return -1;
  2494. }
  2495. } else {
  2496. dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
  2497. $this->error = 'Status of the object is incompatible '.$this->statut;
  2498. return -2;
  2499. }
  2500. }
  2501. /**
  2502. * Change the retained warranty payments terms
  2503. *
  2504. * @param int $id Id of new payment terms
  2505. * @return int >0 if OK, <0 if KO
  2506. */
  2507. public function setRetainedWarrantyPaymentTerms($id)
  2508. {
  2509. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
  2510. if ($this->statut >= 0 || $this->element == 'societe') {
  2511. $fieldname = 'retained_warranty_fk_cond_reglement';
  2512. $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
  2513. $sql .= " SET ".$fieldname." = ".((int) $id);
  2514. $sql .= ' WHERE rowid='.((int) $this->id);
  2515. if ($this->db->query($sql)) {
  2516. $this->retained_warranty_fk_cond_reglement = $id;
  2517. return 1;
  2518. } else {
  2519. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
  2520. $this->error = $this->db->error();
  2521. return -1;
  2522. }
  2523. } else {
  2524. dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
  2525. $this->error = 'Status of the object is incompatible '.$this->statut;
  2526. return -2;
  2527. }
  2528. }
  2529. /**
  2530. * Define delivery address
  2531. * @deprecated
  2532. *
  2533. * @param int $id Address id
  2534. * @return int <0 si ko, >0 si ok
  2535. */
  2536. public function setDeliveryAddress($id)
  2537. {
  2538. $fieldname = 'fk_delivery_address';
  2539. if ($this->element == 'delivery' || $this->element == 'shipping') {
  2540. $fieldname = 'fk_address';
  2541. }
  2542. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
  2543. $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
  2544. if ($this->db->query($sql)) {
  2545. $this->fk_delivery_address = $id;
  2546. return 1;
  2547. } else {
  2548. $this->error = $this->db->error();
  2549. dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
  2550. return -1;
  2551. }
  2552. }
  2553. /**
  2554. * Change the shipping method
  2555. *
  2556. * @param int $shipping_method_id Id of shipping method
  2557. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2558. * @param User $userused Object user
  2559. *
  2560. * @return int 1 if OK, 0 if KO
  2561. */
  2562. public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
  2563. {
  2564. global $user;
  2565. if (empty($userused)) {
  2566. $userused = $user;
  2567. }
  2568. $error = 0;
  2569. if (!$this->table_element) {
  2570. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
  2571. return -1;
  2572. }
  2573. $this->db->begin();
  2574. if ($shipping_method_id < 0) {
  2575. $shipping_method_id = 'NULL';
  2576. }
  2577. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  2578. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2579. $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
  2580. $sql .= " WHERE rowid=".((int) $this->id);
  2581. $resql = $this->db->query($sql);
  2582. if (!$resql) {
  2583. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  2584. $this->error = $this->db->lasterror();
  2585. $error++;
  2586. } else {
  2587. if (!$notrigger) {
  2588. // Call trigger
  2589. $this->context = array('shippingmethodupdate'=>1);
  2590. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2591. if ($result < 0) {
  2592. $error++;
  2593. }
  2594. // End call trigger
  2595. }
  2596. }
  2597. if ($error) {
  2598. $this->db->rollback();
  2599. return -1;
  2600. } else {
  2601. $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
  2602. $this->db->commit();
  2603. return 1;
  2604. }
  2605. }
  2606. /**
  2607. * Change the warehouse
  2608. *
  2609. * @param int $warehouse_id Id of warehouse
  2610. * @return int 1 if OK, 0 if KO
  2611. */
  2612. public function setWarehouse($warehouse_id)
  2613. {
  2614. if (!$this->table_element) {
  2615. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
  2616. return -1;
  2617. }
  2618. if ($warehouse_id < 0) {
  2619. $warehouse_id = 'NULL';
  2620. }
  2621. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  2622. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2623. $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
  2624. $sql .= " WHERE rowid=".((int) $this->id);
  2625. if ($this->db->query($sql)) {
  2626. $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
  2627. return 1;
  2628. } else {
  2629. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  2630. $this->error = $this->db->error();
  2631. return 0;
  2632. }
  2633. }
  2634. /**
  2635. * Set last model used by doc generator
  2636. *
  2637. * @param User $user User object that make change
  2638. * @param string $modelpdf Modele name
  2639. * @return int <0 if KO, >0 if OK
  2640. */
  2641. public function setDocModel($user, $modelpdf)
  2642. {
  2643. if (!$this->table_element) {
  2644. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
  2645. return -1;
  2646. }
  2647. $newmodelpdf = dol_trunc($modelpdf, 255);
  2648. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2649. $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  2650. $sql .= " WHERE rowid = ".((int) $this->id);
  2651. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  2652. $resql = $this->db->query($sql);
  2653. if ($resql) {
  2654. $this->model_pdf = $modelpdf;
  2655. $this->modelpdf = $modelpdf; // For bakward compatibility
  2656. return 1;
  2657. } else {
  2658. dol_print_error($this->db);
  2659. return 0;
  2660. }
  2661. }
  2662. /**
  2663. * Change the bank account
  2664. *
  2665. * @param int $fk_account Id of bank account
  2666. * @param bool $notrigger false=launch triggers after, true=disable triggers
  2667. * @param User $userused Object user
  2668. * @return int 1 if OK, 0 if KO
  2669. */
  2670. public function setBankAccount($fk_account, $notrigger = false, $userused = null)
  2671. {
  2672. global $user;
  2673. if (empty($userused)) {
  2674. $userused = $user;
  2675. }
  2676. $error = 0;
  2677. if (!$this->table_element) {
  2678. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
  2679. return -1;
  2680. }
  2681. $this->db->begin();
  2682. if ($fk_account < 0) {
  2683. $fk_account = 'NULL';
  2684. }
  2685. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  2686. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  2687. $sql .= " SET fk_account = ".((int) $fk_account);
  2688. $sql .= " WHERE rowid=".((int) $this->id);
  2689. $resql = $this->db->query($sql);
  2690. if (!$resql) {
  2691. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  2692. $this->error = $this->db->lasterror();
  2693. $error++;
  2694. } else {
  2695. if (!$notrigger) {
  2696. // Call trigger
  2697. $this->context = array('bankaccountupdate'=>1);
  2698. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
  2699. if ($result < 0) {
  2700. $error++;
  2701. }
  2702. // End call trigger
  2703. }
  2704. }
  2705. if ($error) {
  2706. $this->db->rollback();
  2707. return -1;
  2708. } else {
  2709. $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
  2710. $this->db->commit();
  2711. return 1;
  2712. }
  2713. }
  2714. // TODO: Move line related operations to CommonObjectLine?
  2715. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2716. /**
  2717. * Save a new position (field rang) for details lines.
  2718. * You can choose to set position for lines with already a position or lines without any position defined.
  2719. *
  2720. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  2721. * @param string $rowidorder ASC or DESC
  2722. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2723. * @return int <0 if KO, >0 if OK
  2724. */
  2725. public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
  2726. {
  2727. // phpcs:enable
  2728. if (!$this->table_element_line) {
  2729. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
  2730. return -1;
  2731. }
  2732. if (!$this->fk_element) {
  2733. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
  2734. return -1;
  2735. }
  2736. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2737. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2738. $fieldposition = 'position';
  2739. }
  2740. // Count number of lines to reorder (according to choice $renum)
  2741. $nl = 0;
  2742. $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
  2743. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2744. if (!$renum) {
  2745. $sql .= " AND " . $fieldposition . " = 0";
  2746. }
  2747. if ($renum) {
  2748. $sql .= " AND " . $fieldposition . " <> 0";
  2749. }
  2750. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  2751. $resql = $this->db->query($sql);
  2752. if ($resql) {
  2753. $row = $this->db->fetch_row($resql);
  2754. $nl = $row[0];
  2755. } else {
  2756. dol_print_error($this->db);
  2757. }
  2758. if ($nl > 0) {
  2759. // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
  2760. $rows = array();
  2761. // We first search all lines that are parent lines (for multilevel details lines)
  2762. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2763. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2764. if ($fk_parent_line) {
  2765. $sql .= ' AND fk_parent_line IS NULL';
  2766. }
  2767. $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
  2768. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  2769. $resql = $this->db->query($sql);
  2770. if ($resql) {
  2771. $i = 0;
  2772. $num = $this->db->num_rows($resql);
  2773. while ($i < $num) {
  2774. $row = $this->db->fetch_row($resql);
  2775. $rows[] = $row[0]; // Add parent line into array rows
  2776. $childrens = $this->getChildrenOfLine($row[0]);
  2777. if (!empty($childrens)) {
  2778. foreach ($childrens as $child) {
  2779. array_push($rows, $child);
  2780. }
  2781. }
  2782. $i++;
  2783. }
  2784. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2785. if (!empty($rows)) {
  2786. foreach ($rows as $key => $row) {
  2787. $this->updateRangOfLine($row, ($key + 1));
  2788. }
  2789. }
  2790. } else {
  2791. dol_print_error($this->db);
  2792. }
  2793. }
  2794. return 1;
  2795. }
  2796. /**
  2797. * Get children of line
  2798. *
  2799. * @param int $id Id of parent line
  2800. * @param int $includealltree 0 = 1st level child, 1 = All level child
  2801. * @return array Array with list of children lines id
  2802. */
  2803. public function getChildrenOfLine($id, $includealltree = 0)
  2804. {
  2805. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2806. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2807. $fieldposition = 'position';
  2808. }
  2809. $rows = array();
  2810. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2811. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2812. $sql .= ' AND fk_parent_line = '.((int) $id);
  2813. $sql .= " ORDER BY " . $fieldposition . " ASC";
  2814. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
  2815. $resql = $this->db->query($sql);
  2816. if ($resql) {
  2817. if ($this->db->num_rows($resql) > 0) {
  2818. while ($row = $this->db->fetch_row($resql)) {
  2819. $rows[] = $row[0];
  2820. if (!empty($includealltree)) {
  2821. $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
  2822. }
  2823. }
  2824. }
  2825. }
  2826. return $rows;
  2827. }
  2828. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2829. /**
  2830. * Update a line to have a lower rank
  2831. *
  2832. * @param int $rowid Id of line
  2833. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2834. * @return void
  2835. */
  2836. public function line_up($rowid, $fk_parent_line = true)
  2837. {
  2838. // phpcs:enable
  2839. $this->line_order(false, 'ASC', $fk_parent_line);
  2840. // Get rang of line
  2841. $rang = $this->getRangOfLine($rowid);
  2842. // Update position of line
  2843. $this->updateLineUp($rowid, $rang);
  2844. }
  2845. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2846. /**
  2847. * Update a line to have a higher rank
  2848. *
  2849. * @param int $rowid Id of line
  2850. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2851. * @return void
  2852. */
  2853. public function line_down($rowid, $fk_parent_line = true)
  2854. {
  2855. // phpcs:enable
  2856. $this->line_order(false, 'ASC', $fk_parent_line);
  2857. // Get rang of line
  2858. $rang = $this->getRangOfLine($rowid);
  2859. // Get max value for rang
  2860. $max = $this->line_max();
  2861. // Update position of line
  2862. $this->updateLineDown($rowid, $rang, $max);
  2863. }
  2864. /**
  2865. * Update position of line (rang)
  2866. *
  2867. * @param int $rowid Id of line
  2868. * @param int $rang Position
  2869. * @return int <0 if KO, >0 if OK
  2870. */
  2871. public function updateRangOfLine($rowid, $rang)
  2872. {
  2873. global $hookmanager;
  2874. $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
  2875. if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2876. $fieldposition = 'position';
  2877. }
  2878. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2879. $sql .= ' WHERE rowid = '.((int) $rowid);
  2880. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2881. if (!$this->db->query($sql)) {
  2882. dol_print_error($this->db);
  2883. return -1;
  2884. } else {
  2885. $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
  2886. $action='';
  2887. $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
  2888. return 1;
  2889. }
  2890. }
  2891. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2892. /**
  2893. * Update position of line with ajax (rang)
  2894. *
  2895. * @param array $rows Array of rows
  2896. * @return void
  2897. */
  2898. public function line_ajaxorder($rows)
  2899. {
  2900. // phpcs:enable
  2901. $num = count($rows);
  2902. for ($i = 0; $i < $num; $i++) {
  2903. $this->updateRangOfLine($rows[$i], ($i + 1));
  2904. }
  2905. }
  2906. /**
  2907. * Update position of line up (rang)
  2908. *
  2909. * @param int $rowid Id of line
  2910. * @param int $rang Position
  2911. * @return void
  2912. */
  2913. public function updateLineUp($rowid, $rang)
  2914. {
  2915. if ($rang > 1) {
  2916. $fieldposition = 'rang';
  2917. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2918. $fieldposition = 'position';
  2919. }
  2920. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2921. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2922. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
  2923. if ($this->db->query($sql)) {
  2924. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
  2925. $sql .= ' WHERE rowid = '.((int) $rowid);
  2926. if (!$this->db->query($sql)) {
  2927. dol_print_error($this->db);
  2928. }
  2929. } else {
  2930. dol_print_error($this->db);
  2931. }
  2932. }
  2933. }
  2934. /**
  2935. * Update position of line down (rang)
  2936. *
  2937. * @param int $rowid Id of line
  2938. * @param int $rang Position
  2939. * @param int $max Max
  2940. * @return void
  2941. */
  2942. public function updateLineDown($rowid, $rang, $max)
  2943. {
  2944. if ($rang < $max) {
  2945. $fieldposition = 'rang';
  2946. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2947. $fieldposition = 'position';
  2948. }
  2949. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
  2950. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2951. $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
  2952. if ($this->db->query($sql)) {
  2953. $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
  2954. $sql .= ' WHERE rowid = '.((int) $rowid);
  2955. if (!$this->db->query($sql)) {
  2956. dol_print_error($this->db);
  2957. }
  2958. } else {
  2959. dol_print_error($this->db);
  2960. }
  2961. }
  2962. }
  2963. /**
  2964. * Get position of line (rang)
  2965. *
  2966. * @param int $rowid Id of line
  2967. * @return int Value of rang in table of lines
  2968. */
  2969. public function getRangOfLine($rowid)
  2970. {
  2971. $fieldposition = 'rang';
  2972. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2973. $fieldposition = 'position';
  2974. }
  2975. $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
  2976. $sql .= " WHERE rowid = ".((int) $rowid);
  2977. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2978. $resql = $this->db->query($sql);
  2979. if ($resql) {
  2980. $row = $this->db->fetch_row($resql);
  2981. return $row[0];
  2982. }
  2983. }
  2984. /**
  2985. * Get rowid of the line relative to its position
  2986. *
  2987. * @param int $rang Rang value
  2988. * @return int Rowid of the line
  2989. */
  2990. public function getIdOfLine($rang)
  2991. {
  2992. $fieldposition = 'rang';
  2993. if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
  2994. $fieldposition = 'position';
  2995. }
  2996. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
  2997. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  2998. $sql .= " AND " . $fieldposition . " = ".((int) $rang);
  2999. $resql = $this->db->query($sql);
  3000. if ($resql) {
  3001. $row = $this->db->fetch_row($resql);
  3002. return $row[0];
  3003. }
  3004. }
  3005. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3006. /**
  3007. * Get max value used for position of line (rang)
  3008. *
  3009. * @param int $fk_parent_line Parent line id
  3010. * @return int Max value of rang in table of lines
  3011. */
  3012. public function line_max($fk_parent_line = 0)
  3013. {
  3014. // phpcs:enable
  3015. $positionfield = 'rang';
  3016. if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
  3017. $positionfield = 'position';
  3018. }
  3019. // Search the last rang with fk_parent_line
  3020. if ($fk_parent_line) {
  3021. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  3022. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3023. $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
  3024. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3025. $resql = $this->db->query($sql);
  3026. if ($resql) {
  3027. $row = $this->db->fetch_row($resql);
  3028. if (!empty($row[0])) {
  3029. return $row[0];
  3030. } else {
  3031. return $this->getRangOfLine($fk_parent_line);
  3032. }
  3033. }
  3034. } else {
  3035. // If not, search the last rang of element
  3036. $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
  3037. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3038. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  3039. $resql = $this->db->query($sql);
  3040. if ($resql) {
  3041. $row = $this->db->fetch_row($resql);
  3042. return $row[0];
  3043. }
  3044. }
  3045. }
  3046. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3047. /**
  3048. * Update external ref of element
  3049. *
  3050. * @param string $ref_ext Update field ref_ext
  3051. * @return int <0 if KO, >0 if OK
  3052. */
  3053. public function update_ref_ext($ref_ext)
  3054. {
  3055. // phpcs:enable
  3056. if (!$this->table_element) {
  3057. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  3058. return -1;
  3059. }
  3060. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3061. $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  3062. $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
  3063. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  3064. if ($this->db->query($sql)) {
  3065. $this->ref_ext = $ref_ext;
  3066. return 1;
  3067. } else {
  3068. $this->error = $this->db->error();
  3069. return -1;
  3070. }
  3071. }
  3072. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3073. /**
  3074. * Update note of element
  3075. *
  3076. * @param string $note New value for note
  3077. * @param string $suffix '', '_public' or '_private'
  3078. * @return int <0 if KO, >0 if OK
  3079. */
  3080. public function update_note($note, $suffix = '')
  3081. {
  3082. // phpcs:enable
  3083. global $user;
  3084. if (!$this->table_element) {
  3085. $this->error = 'update_note was called on objet with property table_element not defined';
  3086. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  3087. return -1;
  3088. }
  3089. if (!in_array($suffix, array('', '_public', '_private'))) {
  3090. $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  3091. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  3092. return -2;
  3093. }
  3094. $newsuffix = $suffix;
  3095. // Special cas
  3096. if ($this->table_element == 'product' && $newsuffix == '_private') {
  3097. $newsuffix = '';
  3098. }
  3099. if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
  3100. $fieldusermod = "fk_user_mod";
  3101. } elseif ($this->table_element == 'ecm_files') {
  3102. $fieldusermod = "fk_user_m";
  3103. } else {
  3104. $fieldusermod = "fk_user_modif";
  3105. }
  3106. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  3107. $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
  3108. $sql .= ", ".$fieldusermod." = ".((int) $user->id);
  3109. $sql .= " WHERE rowid = ".((int) $this->id);
  3110. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  3111. if ($this->db->query($sql)) {
  3112. if ($suffix == '_public') {
  3113. $this->note_public = $note;
  3114. } elseif ($suffix == '_private') {
  3115. $this->note_private = $note;
  3116. } else {
  3117. $this->note = $note; // deprecated
  3118. $this->note_private = $note;
  3119. }
  3120. return 1;
  3121. } else {
  3122. $this->error = $this->db->lasterror();
  3123. return -1;
  3124. }
  3125. }
  3126. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3127. /**
  3128. * Update public note (kept for backward compatibility)
  3129. *
  3130. * @param string $note New value for note
  3131. * @return int <0 if KO, >0 if OK
  3132. * @deprecated
  3133. * @see update_note()
  3134. */
  3135. public function update_note_public($note)
  3136. {
  3137. // phpcs:enable
  3138. return $this->update_note($note, '_public');
  3139. }
  3140. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3141. /**
  3142. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  3143. * Must be called at end of methods addline or updateline.
  3144. *
  3145. * @param int $exclspec >0 = Exclude special product (product_type=9)
  3146. * @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
  3147. * @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.
  3148. * @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).
  3149. * @return int <0 if KO, >0 if OK
  3150. */
  3151. public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
  3152. {
  3153. // phpcs:enable
  3154. global $conf, $hookmanager, $action;
  3155. $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
  3156. $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3157. if ($reshook > 0) {
  3158. return 1; // replacement code
  3159. } elseif ($reshook < 0) {
  3160. return -1; // failure
  3161. } // reshook = 0 => execute normal code
  3162. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  3163. $MODULE = "";
  3164. if ($this->element == 'propal') {
  3165. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  3166. } elseif ($this->element == 'commande' || $this->element == 'order') {
  3167. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  3168. } elseif ($this->element == 'facture' || $this->element == 'invoice') {
  3169. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  3170. } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
  3171. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  3172. } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
  3173. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  3174. } elseif ($this->element == 'supplier_proposal') {
  3175. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  3176. }
  3177. if (!empty($MODULE)) {
  3178. if (!empty($conf->global->$MODULE)) {
  3179. $modsactivated = explode(',', $conf->global->$MODULE);
  3180. foreach ($modsactivated as $mod) {
  3181. if (isModEnabled($mod)) {
  3182. return 1; // update was disabled by specific setup
  3183. }
  3184. }
  3185. }
  3186. }
  3187. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3188. $forcedroundingmode = $roundingadjust;
  3189. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
  3190. $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
  3191. } elseif ($forcedroundingmode == 'auto') {
  3192. $forcedroundingmode = '0';
  3193. }
  3194. $error = 0;
  3195. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  3196. // Define constants to find lines to sum (field name int the table_element_line not into table_element)
  3197. $fieldtva = 'total_tva';
  3198. $fieldlocaltax1 = 'total_localtax1';
  3199. $fieldlocaltax2 = 'total_localtax2';
  3200. $fieldup = 'subprice';
  3201. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  3202. $fieldtva = 'tva';
  3203. $fieldup = 'pu_ht';
  3204. }
  3205. if ($this->element == 'invoice_supplier_rec') {
  3206. $fieldup = 'pu_ht';
  3207. }
  3208. if ($this->element == 'expensereport') {
  3209. $fieldup = 'value_unit';
  3210. }
  3211. $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,";
  3212. $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  3213. if ($this->table_element_line == 'facturedet') {
  3214. $sql .= ', situation_percent';
  3215. }
  3216. $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  3217. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  3218. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  3219. if ($exclspec) {
  3220. $product_field = 'product_type';
  3221. if ($this->table_element_line == 'contratdet') {
  3222. $product_field = ''; // contratdet table has no product_type field
  3223. }
  3224. if ($product_field) {
  3225. $sql .= " AND ".$product_field." <> 9";
  3226. }
  3227. }
  3228. $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
  3229. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3230. $resql = $this->db->query($sql);
  3231. if ($resql) {
  3232. $this->total_ht = 0;
  3233. $this->total_tva = 0;
  3234. $this->total_localtax1 = 0;
  3235. $this->total_localtax2 = 0;
  3236. $this->total_ttc = 0;
  3237. $total_ht_by_vats = array();
  3238. $total_tva_by_vats = array();
  3239. $total_ttc_by_vats = array();
  3240. $this->multicurrency_total_ht = 0;
  3241. $this->multicurrency_total_tva = 0;
  3242. $this->multicurrency_total_ttc = 0;
  3243. $num = $this->db->num_rows($resql);
  3244. $i = 0;
  3245. while ($i < $num) {
  3246. $obj = $this->db->fetch_object($resql);
  3247. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  3248. $parameters = array('fk_element' => $obj->rowid);
  3249. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3250. 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'
  3251. // This part of code is to fix data. We should not call it too often.
  3252. $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
  3253. $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);
  3254. $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.
  3255. $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
  3256. //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
  3257. //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
  3258. if ($diff_on_current_total) {
  3259. // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
  3260. $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);
  3261. 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);
  3262. $resqlfix = $this->db->query($sqlfix);
  3263. if (!$resqlfix) {
  3264. dol_print_error($this->db, 'Failed to update line');
  3265. }
  3266. $obj->total_tva = $tmpcal[1];
  3267. $obj->total_ttc = $tmpcal[2];
  3268. } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
  3269. // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
  3270. // we ask to force the use of rounding on line (like done on calculation) so we force update of line
  3271. $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);
  3272. 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);
  3273. $resqlfix = $this->db->query($sqlfix);
  3274. if (!$resqlfix) {
  3275. dol_print_error($this->db, 'Failed to update line');
  3276. }
  3277. $obj->total_tva = $tmpcal[1];
  3278. $obj->total_ttc = $tmpcal[2];
  3279. }
  3280. }
  3281. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  3282. $this->total_tva += $obj->total_tva;
  3283. $this->total_localtax1 += $obj->total_localtax1;
  3284. $this->total_localtax2 += $obj->total_localtax2;
  3285. $this->total_ttc += $obj->total_ttc;
  3286. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  3287. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  3288. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  3289. if (!isset($total_ht_by_vats[$obj->vatrate])) {
  3290. $total_ht_by_vats[$obj->vatrate] = 0;
  3291. }
  3292. if (!isset($total_tva_by_vats[$obj->vatrate])) {
  3293. $total_tva_by_vats[$obj->vatrate] = 0;
  3294. }
  3295. if (!isset($total_ttc_by_vats[$obj->vatrate])) {
  3296. $total_ttc_by_vats[$obj->vatrate] = 0;
  3297. }
  3298. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  3299. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  3300. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  3301. if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  3302. $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  3303. $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
  3304. //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";
  3305. if ($diff) {
  3306. if (abs($diff) > 0.1) {
  3307. $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.';
  3308. dol_syslog($errmsg, LOG_WARNING);
  3309. dol_print_error('', $errmsg);
  3310. exit;
  3311. }
  3312. $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);
  3313. 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);
  3314. $resqlfix = $this->db->query($sqlfix);
  3315. if (!$resqlfix) {
  3316. dol_print_error($this->db, 'Failed to update line');
  3317. }
  3318. $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
  3319. $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
  3320. $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
  3321. $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
  3322. }
  3323. }
  3324. $i++;
  3325. }
  3326. // Add revenue stamp to total
  3327. $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
  3328. $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
  3329. // Situations totals
  3330. if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
  3331. $prev_sits = $this->get_prev_sits();
  3332. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  3333. $this->total_ht -= $sit->total_ht;
  3334. $this->total_tva -= $sit->total_tva;
  3335. $this->total_localtax1 -= $sit->total_localtax1;
  3336. $this->total_localtax2 -= $sit->total_localtax2;
  3337. $this->total_ttc -= $sit->total_ttc;
  3338. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  3339. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  3340. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  3341. }
  3342. }
  3343. // Clean total
  3344. $this->total_ht = (float) price2num($this->total_ht);
  3345. $this->total_tva = (float) price2num($this->total_tva);
  3346. $this->total_localtax1 = (float) price2num($this->total_localtax1);
  3347. $this->total_localtax2 = (float) price2num($this->total_localtax2);
  3348. $this->total_ttc = (float) price2num($this->total_ttc);
  3349. $this->db->free($resql);
  3350. // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
  3351. $fieldht = 'total_ht';
  3352. $fieldtva = 'tva';
  3353. $fieldlocaltax1 = 'localtax1';
  3354. $fieldlocaltax2 = 'localtax2';
  3355. $fieldttc = 'total_ttc';
  3356. // Specific code for backward compatibility with old field names
  3357. if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
  3358. $fieldtva = 'total_tva';
  3359. }
  3360. if (empty($nodatabaseupdate)) {
  3361. $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
  3362. $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
  3363. $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
  3364. $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
  3365. $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
  3366. $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
  3367. $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
  3368. $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
  3369. $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
  3370. $sql .= " WHERE rowid = ".((int) $this->id);
  3371. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  3372. $resql = $this->db->query($sql);
  3373. if (!$resql) {
  3374. $error++;
  3375. $this->error = $this->db->lasterror();
  3376. $this->errors[] = $this->db->lasterror();
  3377. }
  3378. }
  3379. if (!$error) {
  3380. return 1;
  3381. } else {
  3382. return -1;
  3383. }
  3384. } else {
  3385. dol_print_error($this->db, 'Bad request in update_price');
  3386. return -1;
  3387. }
  3388. }
  3389. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3390. /**
  3391. * Add an object link into llx_element_element.
  3392. *
  3393. * @param string $origin Linked element type
  3394. * @param int $origin_id Linked element id
  3395. * @param User $f_user User that create
  3396. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  3397. * @return int <=0 if KO, >0 if OK
  3398. * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked()
  3399. */
  3400. public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
  3401. {
  3402. // phpcs:enable
  3403. global $user, $hookmanager, $action;
  3404. $origin = (!empty($origin) ? $origin : $this->origin);
  3405. $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
  3406. $f_user = isset($f_user) ? $f_user : $user;
  3407. // Special case
  3408. if ($origin == 'order') {
  3409. $origin = 'commande';
  3410. }
  3411. if ($origin == 'invoice') {
  3412. $origin = 'facture';
  3413. }
  3414. if ($origin == 'invoice_template') {
  3415. $origin = 'facturerec';
  3416. }
  3417. if ($origin == 'supplierorder') {
  3418. $origin = 'order_supplier';
  3419. }
  3420. // 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.
  3421. // 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.
  3422. $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
  3423. // Add module part to target type if object has $module property and isn't in core modules.
  3424. $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
  3425. $parameters = array('targettype'=>$targettype);
  3426. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3427. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3428. if ($reshook > 0) {
  3429. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3430. }
  3431. $this->db->begin();
  3432. $error = 0;
  3433. $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
  3434. $sql .= "fk_source";
  3435. $sql .= ", sourcetype";
  3436. $sql .= ", fk_target";
  3437. $sql .= ", targettype";
  3438. $sql .= ") VALUES (";
  3439. $sql .= ((int) $origin_id);
  3440. $sql .= ", '" . $this->db->escape($origin) . "'";
  3441. $sql .= ", " . ((int) $this->id);
  3442. $sql .= ", '" . $this->db->escape($targettype) . "'";
  3443. $sql .= ")";
  3444. dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
  3445. if ($this->db->query($sql)) {
  3446. if (!$notrigger) {
  3447. // Call trigger
  3448. $this->context['link_origin'] = $origin;
  3449. $this->context['link_origin_id'] = $origin_id;
  3450. $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
  3451. if ($result < 0) {
  3452. $error++;
  3453. }
  3454. // End call triggers
  3455. }
  3456. } else {
  3457. $this->error = $this->db->lasterror();
  3458. $error++;
  3459. }
  3460. if (!$error) {
  3461. $this->db->commit();
  3462. return 1;
  3463. } else {
  3464. $this->db->rollback();
  3465. return 0;
  3466. }
  3467. }
  3468. /**
  3469. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  3470. * this->linkedObjectsIds array +
  3471. * this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
  3472. * Possible usage for parameters:
  3473. * - all parameters empty -> we look all link to current object (current object can be source or target)
  3474. * - source id+type -> will get list of targets linked to source
  3475. * - target id+type -> will get list of sources linked to target
  3476. * - source id+type + target type -> will get list of targets of the type linked to source
  3477. * - target id+type + source type -> will get list of sources of the type linked to target
  3478. *
  3479. * @param int $sourceid Object source id (if not defined, id of object)
  3480. * @param string $sourcetype Object source type (if not defined, element name of object)
  3481. * @param int $targetid Object target id (if not defined, id of object)
  3482. * @param string $targettype Object target type (if not defined, element name of object)
  3483. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  3484. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  3485. * @param string $orderby SQL 'ORDER BY' clause
  3486. * @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.
  3487. * @return int <0 if KO, >0 if OK
  3488. * @see add_object_linked(), updateObjectLinked(), deleteObjectLinked()
  3489. */
  3490. public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
  3491. {
  3492. global $conf, $hookmanager, $action;
  3493. // Important for pdf generation time reduction
  3494. // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
  3495. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3496. return 1;
  3497. }
  3498. $this->linkedObjectsIds = array();
  3499. $this->linkedObjects = array();
  3500. $justsource = false;
  3501. $justtarget = false;
  3502. $withtargettype = false;
  3503. $withsourcetype = false;
  3504. $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
  3505. // Hook for explicitly set the targettype if it must be differtent than $this->element
  3506. $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3507. if ($reshook > 0) {
  3508. if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
  3509. if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
  3510. if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
  3511. if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
  3512. }
  3513. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
  3514. $justsource = true; // the source (id and type) is a search criteria
  3515. if (!empty($targettype)) {
  3516. $withtargettype = true;
  3517. }
  3518. }
  3519. if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
  3520. $justtarget = true; // the target (id and type) is a search criteria
  3521. if (!empty($sourcetype)) {
  3522. $withsourcetype = true;
  3523. }
  3524. }
  3525. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3526. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3527. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3528. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3529. /*if (empty($sourceid) && empty($targetid))
  3530. {
  3531. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  3532. return -1;
  3533. }*/
  3534. // Links between objects are stored in table element_element
  3535. $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
  3536. $sql .= " FROM ".$this->db->prefix()."element_element";
  3537. $sql .= " WHERE ";
  3538. if ($justsource || $justtarget) {
  3539. if ($justsource) {
  3540. $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3541. if ($withtargettype) {
  3542. $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
  3543. }
  3544. } elseif ($justtarget) {
  3545. $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
  3546. if ($withsourcetype) {
  3547. $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
  3548. }
  3549. }
  3550. } else {
  3551. $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
  3552. $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
  3553. if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
  3554. $this->linkedObjectsFullLoaded[$this->id] = true;
  3555. }
  3556. }
  3557. $sql .= " ORDER BY ".$orderby;
  3558. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  3559. $resql = $this->db->query($sql);
  3560. if ($resql) {
  3561. $num = $this->db->num_rows($resql);
  3562. $i = 0;
  3563. while ($i < $num) {
  3564. $obj = $this->db->fetch_object($resql);
  3565. if ($justsource || $justtarget) {
  3566. if ($justsource) {
  3567. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3568. } elseif ($justtarget) {
  3569. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3570. }
  3571. } else {
  3572. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
  3573. $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
  3574. }
  3575. if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
  3576. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
  3577. }
  3578. }
  3579. $i++;
  3580. }
  3581. if (!empty($this->linkedObjectsIds)) {
  3582. $tmparray = $this->linkedObjectsIds;
  3583. foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  3584. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  3585. $module = $element = $subelement = $objecttype;
  3586. $regs = array();
  3587. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  3588. && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  3589. $module = $element = $regs[1];
  3590. $subelement = $regs[2];
  3591. }
  3592. $classpath = $element.'/class';
  3593. // To work with non standard classpath or module name
  3594. if ($objecttype == 'facture') {
  3595. $classpath = 'compta/facture/class';
  3596. } elseif ($objecttype == 'facturerec') {
  3597. $classpath = 'compta/facture/class';
  3598. $module = 'facture';
  3599. } elseif ($objecttype == 'propal') {
  3600. $classpath = 'comm/propal/class';
  3601. } elseif ($objecttype == 'supplier_proposal') {
  3602. $classpath = 'supplier_proposal/class';
  3603. } elseif ($objecttype == 'shipping') {
  3604. $classpath = 'expedition/class';
  3605. $subelement = 'expedition';
  3606. $module = 'expedition_bon';
  3607. } elseif ($objecttype == 'delivery') {
  3608. $classpath = 'delivery/class';
  3609. $subelement = 'delivery';
  3610. $module = 'delivery_note';
  3611. } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  3612. $classpath = 'fourn/class';
  3613. $module = 'fournisseur';
  3614. } elseif ($objecttype == 'fichinter') {
  3615. $classpath = 'fichinter/class';
  3616. $subelement = 'fichinter';
  3617. $module = 'ficheinter';
  3618. } elseif ($objecttype == 'subscription') {
  3619. $classpath = 'adherents/class';
  3620. $module = 'adherent';
  3621. } elseif ($objecttype == 'contact') {
  3622. $module = 'societe';
  3623. }
  3624. // Set classfile
  3625. $classfile = strtolower($subelement);
  3626. $classname = ucfirst($subelement);
  3627. if ($objecttype == 'order') {
  3628. $classfile = 'commande';
  3629. $classname = 'Commande';
  3630. } elseif ($objecttype == 'invoice_supplier') {
  3631. $classfile = 'fournisseur.facture';
  3632. $classname = 'FactureFournisseur';
  3633. } elseif ($objecttype == 'order_supplier') {
  3634. $classfile = 'fournisseur.commande';
  3635. $classname = 'CommandeFournisseur';
  3636. } elseif ($objecttype == 'supplier_proposal') {
  3637. $classfile = 'supplier_proposal';
  3638. $classname = 'SupplierProposal';
  3639. } elseif ($objecttype == 'facturerec') {
  3640. $classfile = 'facture-rec';
  3641. $classname = 'FactureRec';
  3642. } elseif ($objecttype == 'subscription') {
  3643. $classfile = 'subscription';
  3644. $classname = 'Subscription';
  3645. } elseif ($objecttype == 'project' || $objecttype == 'projet') {
  3646. $classpath = 'projet/class';
  3647. $classfile = 'project';
  3648. $classname = 'Project';
  3649. } elseif ($objecttype == 'conferenceorboothattendee') {
  3650. $classpath = 'eventorganization/class';
  3651. $classfile = 'conferenceorboothattendee';
  3652. $classname = 'ConferenceOrBoothAttendee';
  3653. $module = 'eventorganization';
  3654. } elseif ($objecttype == 'conferenceorbooth') {
  3655. $classpath = 'eventorganization/class';
  3656. $classfile = 'conferenceorbooth';
  3657. $classname = 'ConferenceOrBooth';
  3658. $module = 'eventorganization';
  3659. } elseif ($objecttype == 'mo') {
  3660. $classpath = 'mrp/class';
  3661. $classfile = 'mo';
  3662. $classname = 'Mo';
  3663. $module = 'mrp';
  3664. }
  3665. // Here $module, $classfile and $classname are set, we can use them.
  3666. if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
  3667. if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
  3668. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  3669. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  3670. if (class_exists($classname)) {
  3671. foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
  3672. $object = new $classname($this->db);
  3673. $ret = $object->fetch($objectid);
  3674. if ($ret >= 0) {
  3675. $this->linkedObjects[$objecttype][$i] = $object;
  3676. }
  3677. }
  3678. }
  3679. }
  3680. } else {
  3681. unset($this->linkedObjectsIds[$objecttype]);
  3682. }
  3683. }
  3684. }
  3685. return 1;
  3686. } else {
  3687. dol_print_error($this->db);
  3688. return -1;
  3689. }
  3690. }
  3691. /**
  3692. * Clear the cache saying that all linked object were already loaded. So next fetchObjectLinked will reload all links.
  3693. *
  3694. * @return int <0 if KO, >0 if OK
  3695. * @see fetchObjectLinked()
  3696. */
  3697. public function clearObjectLinkedCache()
  3698. {
  3699. if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
  3700. unset($this->linkedObjectsFullLoaded[$this->id]);
  3701. }
  3702. return 1;
  3703. }
  3704. /**
  3705. * Update object linked of a current object
  3706. *
  3707. * @param int $sourceid Object source id
  3708. * @param string $sourcetype Object source type
  3709. * @param int $targetid Object target id
  3710. * @param string $targettype Object target type
  3711. * @param User $f_user User that create
  3712. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3713. * @return int >0 if OK, <0 if KO
  3714. * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked()
  3715. */
  3716. public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
  3717. {
  3718. global $user;
  3719. $updatesource = false;
  3720. $updatetarget = false;
  3721. $f_user = isset($f_user) ? $f_user : $user;
  3722. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3723. $updatesource = true;
  3724. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3725. $updatetarget = true;
  3726. }
  3727. $this->db->begin();
  3728. $error = 0;
  3729. $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
  3730. if ($updatesource) {
  3731. $sql .= "fk_source = " . ((int) $sourceid);
  3732. $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3733. $sql .= " WHERE fk_target = " . ((int) $this->id);
  3734. $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
  3735. } elseif ($updatetarget) {
  3736. $sql .= "fk_target = " . ((int) $targetid);
  3737. $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
  3738. $sql .= " WHERE fk_source = " . ((int) $this->id);
  3739. $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3740. }
  3741. dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
  3742. if ($this->db->query($sql)) {
  3743. if (!$notrigger) {
  3744. // Call trigger
  3745. $this->context['link_source_id'] = $sourceid;
  3746. $this->context['link_source_type'] = $sourcetype;
  3747. $this->context['link_target_id'] = $targetid;
  3748. $this->context['link_target_type'] = $targettype;
  3749. $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
  3750. if ($result < 0) {
  3751. $error++;
  3752. }
  3753. // End call triggers
  3754. }
  3755. } else {
  3756. $this->error = $this->db->lasterror();
  3757. $error++;
  3758. }
  3759. if (!$error) {
  3760. $this->db->commit();
  3761. return 1;
  3762. } else {
  3763. $this->db->rollback();
  3764. return -1;
  3765. }
  3766. }
  3767. /**
  3768. * Delete all links between an object $this
  3769. *
  3770. * @param int $sourceid Object source id
  3771. * @param string $sourcetype Object source type
  3772. * @param int $targetid Object target id
  3773. * @param string $targettype Object target type
  3774. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  3775. * @param User $f_user User that create
  3776. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3777. * @return int >0 if OK, <0 if KO
  3778. * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked()
  3779. */
  3780. public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
  3781. {
  3782. global $user;
  3783. $deletesource = false;
  3784. $deletetarget = false;
  3785. $f_user = isset($f_user) ? $f_user : $user;
  3786. if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
  3787. $deletesource = true;
  3788. } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
  3789. $deletetarget = true;
  3790. }
  3791. $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
  3792. $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
  3793. $targetid = (!empty($targetid) ? $targetid : $this->id);
  3794. $targettype = (!empty($targettype) ? $targettype : $this->element);
  3795. $this->db->begin();
  3796. $error = 0;
  3797. if (!$notrigger) {
  3798. // Call trigger
  3799. $this->context['link_id'] = $rowid;
  3800. $this->context['link_source_id'] = $sourceid;
  3801. $this->context['link_source_type'] = $sourcetype;
  3802. $this->context['link_target_id'] = $targetid;
  3803. $this->context['link_target_type'] = $targettype;
  3804. $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
  3805. if ($result < 0) {
  3806. $error++;
  3807. }
  3808. // End call triggers
  3809. }
  3810. if (!$error) {
  3811. $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
  3812. $sql .= " WHERE";
  3813. if ($rowid > 0) {
  3814. $sql .= " rowid = " . ((int) $rowid);
  3815. } else {
  3816. if ($deletesource) {
  3817. $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
  3818. $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
  3819. } elseif ($deletetarget) {
  3820. $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
  3821. $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
  3822. } else {
  3823. $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
  3824. $sql .= " OR";
  3825. $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
  3826. }
  3827. }
  3828. dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
  3829. if (!$this->db->query($sql)) {
  3830. $this->error = $this->db->lasterror();
  3831. $this->errors[] = $this->error;
  3832. $error++;
  3833. }
  3834. }
  3835. if (!$error) {
  3836. $this->db->commit();
  3837. return 1;
  3838. } else {
  3839. $this->db->rollback();
  3840. return 0;
  3841. }
  3842. }
  3843. /**
  3844. * Function used to get an array with all items linked to an object id in association table
  3845. *
  3846. * @param int $fk_object_where id of object we need to get linked items
  3847. * @param string $field_select name of field we need to get a list
  3848. * @param string $field_where name of field of object we need to get linked items
  3849. * @param string $table_element name of association table
  3850. * @return array Array of record
  3851. */
  3852. public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
  3853. {
  3854. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3855. return -1;
  3856. }
  3857. global $db;
  3858. $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3859. $resql = $db->query($sql);
  3860. $TRes = array();
  3861. if (!empty($resql)) {
  3862. while ($res = $db->fetch_object($resql)) {
  3863. $TRes[] = $res->{$field_select};
  3864. }
  3865. }
  3866. return $TRes;
  3867. }
  3868. /**
  3869. * Function used to remove all items linked to an object id in association table
  3870. *
  3871. * @param int $fk_object_where id of object we need to remove linked items
  3872. * @param string $field_where name of field of object we need to delete linked items
  3873. * @param string $table_element name of association table
  3874. * @return int <0 if KO, 0 if nothing done, >0 if OK and something done
  3875. */
  3876. public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
  3877. {
  3878. if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
  3879. return -1;
  3880. }
  3881. global $db;
  3882. $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
  3883. $resql = $db->query($sql);
  3884. if (empty($resql)) {
  3885. return 0;
  3886. }
  3887. return 1;
  3888. }
  3889. /**
  3890. * Set status of an object.
  3891. *
  3892. * @param int $status Status to set
  3893. * @param int $elementId Id of element to force (use this->id by default if null)
  3894. * @param string $elementType Type of element to force (use this->table_element by default)
  3895. * @param string $trigkey Trigger key to use for trigger. Use '' means automatic but it is not recommended and is deprecated.
  3896. * @param string $fieldstatus Name of status field in this->table_element
  3897. * @return int <0 if KO, >0 if OK
  3898. */
  3899. public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
  3900. {
  3901. global $user, $langs, $conf;
  3902. $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
  3903. $elementId = (!empty($elementId) ? $elementId : $this->id);
  3904. $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
  3905. $this->db->begin();
  3906. if ($elementTable == 'facture_rec') {
  3907. $fieldstatus = "suspended";
  3908. }
  3909. if ($elementTable == 'mailing') {
  3910. $fieldstatus = "statut";
  3911. }
  3912. if ($elementTable == 'cronjob') {
  3913. $fieldstatus = "status";
  3914. }
  3915. if ($elementTable == 'user') {
  3916. $fieldstatus = "statut";
  3917. }
  3918. if ($elementTable == 'expensereport') {
  3919. $fieldstatus = "fk_statut";
  3920. }
  3921. if ($elementTable == 'commande_fournisseur_dispatch') {
  3922. $fieldstatus = "status";
  3923. }
  3924. if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
  3925. $fieldstatus = 'status';
  3926. }
  3927. $sql = "UPDATE ".$this->db->prefix().$elementTable;
  3928. $sql .= " SET ".$fieldstatus." = ".((int) $status);
  3929. // If status = 1 = validated, update also fk_user_valid
  3930. // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
  3931. if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
  3932. $sql .= ", fk_user_valid = ".((int) $user->id);
  3933. }
  3934. if ($status == 1 && in_array($elementTable, array('expensereport'))) {
  3935. $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
  3936. }
  3937. if ($status == 1 && in_array($elementTable, array('inventory'))) {
  3938. $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
  3939. }
  3940. $sql .= " WHERE rowid = ".((int) $elementId);
  3941. $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
  3942. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  3943. $resql = $this->db->query($sql);
  3944. if ($resql) {
  3945. $error = 0;
  3946. $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
  3947. if ($nb_rows_affected > 0) {
  3948. if (empty($trigkey)) {
  3949. // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
  3950. if ($this->element == 'supplier_proposal' && $status == 2) {
  3951. $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  3952. }
  3953. if ($this->element == 'supplier_proposal' && $status == 3) {
  3954. $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  3955. }
  3956. if ($this->element == 'supplier_proposal' && $status == 4) {
  3957. $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  3958. }
  3959. if ($this->element == 'fichinter' && $status == 3) {
  3960. $trigkey = 'FICHINTER_CLASSIFY_DONE';
  3961. }
  3962. if ($this->element == 'fichinter' && $status == 2) {
  3963. $trigkey = 'FICHINTER_CLASSIFY_BILLED';
  3964. }
  3965. if ($this->element == 'fichinter' && $status == 1) {
  3966. $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
  3967. }
  3968. }
  3969. if ($trigkey) {
  3970. // Call trigger
  3971. $result = $this->call_trigger($trigkey, $user);
  3972. if ($result < 0) {
  3973. $error++;
  3974. }
  3975. // End call triggers
  3976. }
  3977. } else {
  3978. // The status was probably already good. We do nothing more, no triggers.
  3979. }
  3980. if (!$error) {
  3981. $this->db->commit();
  3982. if (empty($savElementId)) {
  3983. // If the element we update is $this (so $elementId was provided as null)
  3984. if ($fieldstatus == 'tosell') {
  3985. $this->status = $status;
  3986. } elseif ($fieldstatus == 'tobuy') {
  3987. $this->status_buy = $status;
  3988. } else {
  3989. $this->statut = $status;
  3990. $this->status = $status;
  3991. }
  3992. }
  3993. return 1;
  3994. } else {
  3995. $this->db->rollback();
  3996. dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
  3997. return -1;
  3998. }
  3999. } else {
  4000. $this->error = $this->db->lasterror();
  4001. $this->db->rollback();
  4002. return -1;
  4003. }
  4004. }
  4005. /**
  4006. * Load type of canvas of an object if it exists
  4007. *
  4008. * @param int $id Record id
  4009. * @param string $ref Record ref
  4010. * @return int <0 if KO, 0 if nothing done, >0 if OK
  4011. */
  4012. public function getCanvas($id = 0, $ref = '')
  4013. {
  4014. global $conf;
  4015. if (empty($id) && empty($ref)) {
  4016. return 0;
  4017. }
  4018. if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
  4019. return 0; // To increase speed. Not enabled by default.
  4020. }
  4021. // Clean parameters
  4022. $ref = trim($ref);
  4023. $sql = "SELECT rowid, canvas";
  4024. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  4025. $sql .= " WHERE entity IN (".getEntity($this->element).")";
  4026. if (!empty($id)) {
  4027. $sql .= " AND rowid = ".((int) $id);
  4028. }
  4029. if (!empty($ref)) {
  4030. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  4031. }
  4032. $resql = $this->db->query($sql);
  4033. if ($resql) {
  4034. $obj = $this->db->fetch_object($resql);
  4035. if ($obj) {
  4036. $this->canvas = $obj->canvas;
  4037. return 1;
  4038. } else {
  4039. return 0;
  4040. }
  4041. } else {
  4042. dol_print_error($this->db);
  4043. return -1;
  4044. }
  4045. }
  4046. /**
  4047. * Get special code of a line
  4048. *
  4049. * @param int $lineid Id of line
  4050. * @return int Special code
  4051. */
  4052. public function getSpecialCode($lineid)
  4053. {
  4054. $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
  4055. $sql .= " WHERE rowid = ".((int) $lineid);
  4056. $resql = $this->db->query($sql);
  4057. if ($resql) {
  4058. $row = $this->db->fetch_row($resql);
  4059. return $row[0];
  4060. }
  4061. }
  4062. /**
  4063. * Function to check if an object is used by others.
  4064. * Check is done into this->childtables. There is no check into llx_element_element.
  4065. *
  4066. * @param int $id Force id of object
  4067. * @param int $entity Force entity to check
  4068. * @return int <0 if KO, 0 if not used, >0 if already used
  4069. */
  4070. public function isObjectUsed($id = 0, $entity = 0)
  4071. {
  4072. global $langs;
  4073. if (empty($id)) {
  4074. $id = $this->id;
  4075. }
  4076. // Check parameters
  4077. if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
  4078. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  4079. return -1;
  4080. }
  4081. $arraytoscan = $this->childtables;
  4082. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  4083. $tmparray = array_keys($this->childtables);
  4084. if (is_numeric($tmparray[0])) {
  4085. $arraytoscan = array_flip($this->childtables);
  4086. }
  4087. // Test if child exists
  4088. $haschild = 0;
  4089. foreach ($arraytoscan as $table => $element) {
  4090. //print $id.'-'.$table.'-'.$elementname.'<br>';
  4091. // Check if element can be deleted
  4092. $sql = "SELECT COUNT(*) as nb";
  4093. $sql.= " FROM ".$this->db->prefix().$table." as c";
  4094. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4095. $sql.= ", ".$this->db->prefix().$element['parent']." as p";
  4096. }
  4097. $sql.= " WHERE c.".$this->fk_element." = ".((int) $id);
  4098. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4099. $sql.= " AND c.".$element['parentkey']." = p.rowid";
  4100. }
  4101. if (!empty($entity)) {
  4102. if (!empty($element['parent']) && !empty($element['parentkey'])) {
  4103. $sql.= " AND p.entity = ".((int) $entity);
  4104. } else {
  4105. $sql.= " AND c.entity = ".((int) $entity);
  4106. }
  4107. }
  4108. $resql = $this->db->query($sql);
  4109. if ($resql) {
  4110. $obj = $this->db->fetch_object($resql);
  4111. if ($obj->nb > 0) {
  4112. $langs->load("errors");
  4113. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  4114. $haschild += $obj->nb;
  4115. if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
  4116. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
  4117. } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
  4118. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
  4119. } else { // new usage: $element['name']=Translation key
  4120. $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
  4121. }
  4122. break; // We found at least one, we stop here
  4123. }
  4124. } else {
  4125. $this->errors[] = $this->db->lasterror();
  4126. return -1;
  4127. }
  4128. }
  4129. if ($haschild > 0) {
  4130. $this->errors[] = "ErrorRecordHasChildren";
  4131. return $haschild;
  4132. } else {
  4133. return 0;
  4134. }
  4135. }
  4136. /**
  4137. * Function to say how many lines object contains
  4138. *
  4139. * @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
  4140. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  4141. */
  4142. public function hasProductsOrServices($predefined = -1)
  4143. {
  4144. $nb = 0;
  4145. foreach ($this->lines as $key => $val) {
  4146. $qualified = 0;
  4147. if ($predefined == -1) {
  4148. $qualified = 1;
  4149. }
  4150. if ($predefined == 1 && $val->fk_product > 0) {
  4151. $qualified = 1;
  4152. }
  4153. if ($predefined == 0 && $val->fk_product <= 0) {
  4154. $qualified = 1;
  4155. }
  4156. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
  4157. $qualified = 1;
  4158. }
  4159. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
  4160. $qualified = 1;
  4161. }
  4162. if ($qualified) {
  4163. $nb++;
  4164. }
  4165. }
  4166. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  4167. return $nb;
  4168. }
  4169. /**
  4170. * Function that returns the total amount HT of discounts applied for all lines.
  4171. *
  4172. * @return float|string Total amout of discount
  4173. */
  4174. public function getTotalDiscount()
  4175. {
  4176. if (!empty($this->table_element_line) ) {
  4177. $total_discount = 0.00;
  4178. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  4179. $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
  4180. $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
  4181. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  4182. $resql = $this->db->query($sql);
  4183. if ($resql) {
  4184. $num = $this->db->num_rows($resql);
  4185. $i = 0;
  4186. while ($i < $num) {
  4187. $obj = $this->db->fetch_object($resql);
  4188. $pu_ht = $obj->pu_ht;
  4189. $qty = $obj->qty;
  4190. $total_ht = $obj->total_ht;
  4191. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  4192. $total_discount += $total_discount_line;
  4193. $i++;
  4194. }
  4195. }
  4196. //print $total_discount; exit;
  4197. return price2num($total_discount);
  4198. }
  4199. return null;
  4200. }
  4201. /**
  4202. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  4203. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  4204. *
  4205. * @return array array('weight'=>...,'volume'=>...)
  4206. */
  4207. public function getTotalWeightVolume()
  4208. {
  4209. $totalWeight = 0;
  4210. $totalVolume = 0;
  4211. // defined for shipment only
  4212. $totalOrdered = '';
  4213. // defined for shipment only
  4214. $totalToShip = '';
  4215. foreach ($this->lines as $line) {
  4216. if (isset($line->qty_asked)) {
  4217. if (empty($totalOrdered)) {
  4218. $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
  4219. }
  4220. $totalOrdered += $line->qty_asked; // defined for shipment only
  4221. }
  4222. if (isset($line->qty_shipped)) {
  4223. if (empty($totalToShip)) {
  4224. $totalToShip = 0; // Avoid warning because $totalToShip is ''
  4225. }
  4226. $totalToShip += $line->qty_shipped; // defined for shipment only
  4227. } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
  4228. if (empty($totalToShip)) {
  4229. $totalToShip = 0;
  4230. }
  4231. $totalToShip += $line->qty; // defined for reception only
  4232. }
  4233. // Define qty, weight, volume, weight_units, volume_units
  4234. if ($this->element == 'shipping') {
  4235. // for shipments
  4236. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  4237. } else {
  4238. $qty = $line->qty ? $line->qty : 0;
  4239. }
  4240. $weight = !empty($line->weight) ? $line->weight : 0;
  4241. ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
  4242. $volume = !empty($line->volume) ? $line->volume : 0;
  4243. ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
  4244. $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
  4245. ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
  4246. $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
  4247. ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
  4248. $weightUnit = 0;
  4249. $volumeUnit = 0;
  4250. if (!empty($weight_units)) {
  4251. $weightUnit = $weight_units;
  4252. }
  4253. if (!empty($volume_units)) {
  4254. $volumeUnit = $volume_units;
  4255. }
  4256. if (empty($totalWeight)) {
  4257. $totalWeight = 0; // Avoid warning because $totalWeight is ''
  4258. }
  4259. if (empty($totalVolume)) {
  4260. $totalVolume = 0; // Avoid warning because $totalVolume is ''
  4261. }
  4262. //var_dump($line->volume_units);
  4263. if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4264. $trueWeightUnit = pow(10, $weightUnit);
  4265. $totalWeight += $weight * $qty * $trueWeightUnit;
  4266. } else {
  4267. if ($weight_units == 99) {
  4268. // conversion 1 Pound = 0.45359237 KG
  4269. $trueWeightUnit = 0.45359237;
  4270. $totalWeight += $weight * $qty * $trueWeightUnit;
  4271. } elseif ($weight_units == 98) {
  4272. // conversion 1 Ounce = 0.0283495 KG
  4273. $trueWeightUnit = 0.0283495;
  4274. $totalWeight += $weight * $qty * $trueWeightUnit;
  4275. } else {
  4276. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  4277. }
  4278. }
  4279. if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  4280. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  4281. $trueVolumeUnit = pow(10, $volumeUnit);
  4282. //print $line->volume;
  4283. $totalVolume += $volume * $qty * $trueVolumeUnit;
  4284. } else {
  4285. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  4286. }
  4287. }
  4288. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  4289. }
  4290. /**
  4291. * Set extra parameters
  4292. *
  4293. * @return int <0 if KO, >0 if OK
  4294. */
  4295. public function setExtraParameters()
  4296. {
  4297. $this->db->begin();
  4298. $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
  4299. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  4300. $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  4301. $sql .= " WHERE rowid = ".((int) $this->id);
  4302. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  4303. $resql = $this->db->query($sql);
  4304. if (!$resql) {
  4305. $this->error = $this->db->lasterror();
  4306. $this->db->rollback();
  4307. return -1;
  4308. } else {
  4309. $this->db->commit();
  4310. return 1;
  4311. }
  4312. }
  4313. // --------------------
  4314. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  4315. // --------------------
  4316. /* This is to show add lines */
  4317. /**
  4318. * Show add free and predefined products/services form
  4319. *
  4320. * @param int $dateSelector 1=Show also date range input fields
  4321. * @param Societe $seller Object thirdparty who sell
  4322. * @param Societe $buyer Object thirdparty who buy
  4323. * @param string $defaulttpldir Directory where to find the template
  4324. * @return void
  4325. */
  4326. public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
  4327. {
  4328. global $conf, $user, $langs, $object, $hookmanager, $extrafields;
  4329. global $form;
  4330. // Line extrafield
  4331. if (!is_object($extrafields)) {
  4332. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4333. $extrafields = new ExtraFields($this->db);
  4334. }
  4335. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4336. // Output template part (modules that overwrite templates must declare this into descriptor)
  4337. // Use global variables + $dateSelector + $seller and $buyer
  4338. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
  4339. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4340. foreach ($dirtpls as $module => $reldir) {
  4341. if (!empty($module)) {
  4342. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  4343. } else {
  4344. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
  4345. }
  4346. if (empty($conf->file->strict_mode)) {
  4347. $res = @include $tpl;
  4348. } else {
  4349. $res = include $tpl; // for debug
  4350. }
  4351. if ($res) {
  4352. break;
  4353. }
  4354. }
  4355. }
  4356. /* This is to show array of line of details */
  4357. /**
  4358. * Return HTML table for object lines
  4359. * TODO Move this into an output class file (htmlline.class.php)
  4360. * If lines are into a template, title must also be into a template
  4361. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4362. *
  4363. * @param string $action Action code
  4364. * @param string $seller Object of seller third party
  4365. * @param string $buyer Object of buyer third party
  4366. * @param int $selected Object line selected
  4367. * @param int $dateSelector 1=Show also date range input fields
  4368. * @param string $defaulttpldir Directory where to find the template
  4369. * @return void
  4370. */
  4371. public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
  4372. {
  4373. global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
  4374. // TODO We should not use global var for this
  4375. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  4376. // Define usemargins
  4377. $usemargins = 0;
  4378. if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
  4379. $usemargins = 1;
  4380. }
  4381. $num = count($this->lines);
  4382. // Line extrafield
  4383. if (!is_object($extrafields)) {
  4384. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4385. $extrafields = new ExtraFields($this->db);
  4386. }
  4387. $extrafields->fetch_name_optionals_label($this->table_element_line);
  4388. $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
  4389. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4390. if (empty($reshook)) {
  4391. // Output template part (modules that overwrite templates must declare this into descriptor)
  4392. // Use global variables + $dateSelector + $seller and $buyer
  4393. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
  4394. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4395. foreach ($dirtpls as $module => $reldir) {
  4396. $res = 0;
  4397. if (!empty($module)) {
  4398. $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
  4399. } else {
  4400. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
  4401. }
  4402. if (file_exists($tpl)) {
  4403. if (empty($conf->file->strict_mode)) {
  4404. $res = @include $tpl;
  4405. } else {
  4406. $res = include $tpl; // for debug
  4407. }
  4408. }
  4409. if ($res) {
  4410. break;
  4411. }
  4412. }
  4413. }
  4414. $i = 0;
  4415. print "<!-- begin printObjectLines() --><tbody>\n";
  4416. foreach ($this->lines as $line) {
  4417. //Line extrafield
  4418. $line->fetch_optionals();
  4419. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
  4420. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4421. if (empty($line->fk_parent_line)) {
  4422. $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
  4423. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4424. } else {
  4425. $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);
  4426. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4427. }
  4428. }
  4429. if (empty($reshook)) {
  4430. $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
  4431. }
  4432. $i++;
  4433. }
  4434. print "</tbody><!-- end printObjectLines() -->\n";
  4435. }
  4436. /**
  4437. * Return HTML content of a detail line
  4438. * TODO Move this into an output class file (htmlline.class.php)
  4439. *
  4440. * @param string $action GET/POST action
  4441. * @param CommonObjectLine $line Selected object line to output
  4442. * @param string $var Not used
  4443. * @param int $num Number of line (0)
  4444. * @param int $i I
  4445. * @param int $dateSelector 1=Show also date range input fields
  4446. * @param string $seller Object of seller third party
  4447. * @param string $buyer Object of buyer third party
  4448. * @param int $selected Object line selected
  4449. * @param Extrafields $extrafields Object of extrafields
  4450. * @param string $defaulttpldir Directory where to find the template (deprecated)
  4451. * @return void
  4452. */
  4453. public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
  4454. {
  4455. global $conf, $langs, $user, $object, $hookmanager;
  4456. global $form;
  4457. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  4458. $object_rights = $this->getRights();
  4459. $element = $this->element;
  4460. $text = '';
  4461. $description = '';
  4462. // Line in view mode
  4463. if ($action != 'editline' || $selected != $line->id) {
  4464. // Product
  4465. if (!empty($line->fk_product) && $line->fk_product > 0) {
  4466. $product_static = new Product($this->db);
  4467. $product_static->fetch($line->fk_product);
  4468. $product_static->ref = $line->ref; //can change ref in hook
  4469. $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
  4470. $text = $product_static->getNomUrl(1);
  4471. // Define output language and label
  4472. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  4473. if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
  4474. dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  4475. return;
  4476. }
  4477. $prod = new Product($this->db);
  4478. $prod->fetch($line->fk_product);
  4479. $outputlangs = $langs;
  4480. $newlang = '';
  4481. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  4482. $newlang = GETPOST('lang_id', 'aZ09');
  4483. }
  4484. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
  4485. $newlang = $this->thirdparty->default_lang; // To use language of customer
  4486. }
  4487. if (!empty($newlang)) {
  4488. $outputlangs = new Translate("", $conf);
  4489. $outputlangs->setDefaultLang($newlang);
  4490. }
  4491. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  4492. } else {
  4493. $label = $line->product_label;
  4494. }
  4495. $text .= ' - '.(!empty($line->label) ? $line->label : $label);
  4496. $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.
  4497. }
  4498. $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
  4499. // Output template part (modules that overwrite templates must declare this into descriptor)
  4500. // Use global variables + $dateSelector + $seller and $buyer
  4501. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4502. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4503. foreach ($dirtpls as $module => $reldir) {
  4504. $res = 0;
  4505. if (!empty($module)) {
  4506. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  4507. } else {
  4508. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
  4509. }
  4510. if (file_exists($tpl)) {
  4511. if (empty($conf->file->strict_mode)) {
  4512. $res = @include $tpl;
  4513. } else {
  4514. $res = include $tpl; // for debug
  4515. }
  4516. }
  4517. if ($res) {
  4518. break;
  4519. }
  4520. }
  4521. }
  4522. // Line in update mode
  4523. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
  4524. $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  4525. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
  4526. // Output template part (modules that overwrite templates must declare this into descriptor)
  4527. // Use global variables + $dateSelector + $seller and $buyer
  4528. // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
  4529. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4530. foreach ($dirtpls as $module => $reldir) {
  4531. if (!empty($module)) {
  4532. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  4533. } else {
  4534. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
  4535. }
  4536. if (empty($conf->file->strict_mode)) {
  4537. $res = @include $tpl;
  4538. } else {
  4539. $res = include $tpl; // for debug
  4540. }
  4541. if ($res) {
  4542. break;
  4543. }
  4544. }
  4545. }
  4546. }
  4547. /* This is to show array of line of details of source object */
  4548. /**
  4549. * Return HTML table table of source object lines
  4550. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4551. * If lines are into a template, title must also be into a template
  4552. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  4553. *
  4554. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  4555. * @param array $selectedLines Array of lines id for selected lines
  4556. * @return void
  4557. */
  4558. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  4559. {
  4560. global $langs, $hookmanager, $conf, $form, $action;
  4561. print '<tr class="liste_titre">';
  4562. print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
  4563. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  4564. print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
  4565. print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
  4566. if (isModEnabled("multicurrency")) {
  4567. print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
  4568. }
  4569. print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
  4570. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4571. print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
  4572. }
  4573. print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
  4574. print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
  4575. print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  4576. print '</tr>';
  4577. $i = 0;
  4578. if (!empty($this->lines)) {
  4579. foreach ($this->lines as $line) {
  4580. $reshook = 0;
  4581. //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
  4582. if (is_object($hookmanager)) { // Old code is commented on preceding line.
  4583. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  4584. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  4585. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4586. }
  4587. if (empty($reshook)) {
  4588. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  4589. }
  4590. $i++;
  4591. }
  4592. }
  4593. }
  4594. /**
  4595. * Return HTML with a line of table array of source object lines
  4596. * TODO Move this and previous function into output html class file (htmlline.class.php).
  4597. * If lines are into a template, title must also be into a template
  4598. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  4599. *
  4600. * @param CommonObjectLine $line Line
  4601. * @param string $var Var
  4602. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  4603. * @param string $defaulttpldir Directory where to find the template
  4604. * @param array $selectedLines Array of lines id for selected lines
  4605. * @return void
  4606. */
  4607. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  4608. {
  4609. global $langs, $conf;
  4610. //var_dump($line);
  4611. if (!empty($line->date_start)) {
  4612. $date_start = $line->date_start;
  4613. } else {
  4614. $date_start = $line->date_debut_prevue;
  4615. if ($line->date_debut_reel) {
  4616. $date_start = $line->date_debut_reel;
  4617. }
  4618. }
  4619. if (!empty($line->date_end)) {
  4620. $date_end = $line->date_end;
  4621. } else {
  4622. $date_end = $line->date_fin_prevue;
  4623. if ($line->date_fin_reel) {
  4624. $date_end = $line->date_fin_reel;
  4625. }
  4626. }
  4627. $this->tpl['id'] = $line->id;
  4628. $this->tpl['label'] = '';
  4629. if (!empty($line->fk_parent_line)) {
  4630. $this->tpl['label'] .= img_picto('', 'rightarrow');
  4631. }
  4632. if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
  4633. $discount = new DiscountAbsolute($this->db);
  4634. $discount->fk_soc = $this->socid;
  4635. $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
  4636. } elseif (!empty($line->fk_product)) {
  4637. $productstatic = new Product($this->db);
  4638. $productstatic->id = $line->fk_product;
  4639. $productstatic->ref = $line->ref;
  4640. $productstatic->type = $line->fk_product_type;
  4641. if (empty($productstatic->ref)) {
  4642. $line->fetch_product();
  4643. $productstatic = $line->product;
  4644. }
  4645. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  4646. $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
  4647. // Dates
  4648. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4649. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4650. }
  4651. } else {
  4652. $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
  4653. if (!empty($line->desc)) {
  4654. $this->tpl['label'] .= $line->desc;
  4655. } else {
  4656. $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
  4657. }
  4658. // Dates
  4659. if ($line->product_type == 1 && ($date_start || $date_end)) {
  4660. $this->tpl['label'] .= get_date_range($date_start, $date_end);
  4661. }
  4662. }
  4663. if (!empty($line->desc)) {
  4664. if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
  4665. $discount = new DiscountAbsolute($this->db);
  4666. $discount->fetch($line->fk_remise_except);
  4667. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
  4668. } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
  4669. $discount = new DiscountAbsolute($this->db);
  4670. $discount->fetch($line->fk_remise_except);
  4671. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
  4672. } elseif ($line->desc == '(EXCESS RECEIVED)') {
  4673. $discount = new DiscountAbsolute($this->db);
  4674. $discount->fetch($line->fk_remise_except);
  4675. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
  4676. } elseif ($line->desc == '(EXCESS PAID)') {
  4677. $discount = new DiscountAbsolute($this->db);
  4678. $discount->fetch($line->fk_remise_except);
  4679. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
  4680. } else {
  4681. $this->tpl['description'] = dol_trunc($line->desc, 60);
  4682. }
  4683. } else {
  4684. $this->tpl['description'] = '&nbsp;';
  4685. }
  4686. // VAT Rate
  4687. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  4688. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  4689. if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
  4690. $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
  4691. }
  4692. $this->tpl['price'] = price($line->subprice);
  4693. $this->tpl['total_ht'] = price($line->total_ht);
  4694. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  4695. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  4696. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  4697. $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  4698. }
  4699. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  4700. // Is the line strike or not
  4701. $this->tpl['strike'] = 0;
  4702. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
  4703. $this->tpl['strike'] = 1;
  4704. }
  4705. // Output template part (modules that overwrite templates must declare this into descriptor)
  4706. // Use global variables + $dateSelector + $seller and $buyer
  4707. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
  4708. foreach ($dirtpls as $module => $reldir) {
  4709. if (!empty($module)) {
  4710. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  4711. } else {
  4712. $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
  4713. }
  4714. if (empty($conf->file->strict_mode)) {
  4715. $res = @include $tpl;
  4716. } else {
  4717. $res = include $tpl; // for debug
  4718. }
  4719. if ($res) {
  4720. break;
  4721. }
  4722. }
  4723. }
  4724. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4725. /**
  4726. * Add resources to the current object : add entry into llx_element_resources
  4727. * Need $this->element & $this->id
  4728. *
  4729. * @param int $resource_id Resource id
  4730. * @param string $resource_type 'resource'
  4731. * @param int $busy Busy or not
  4732. * @param int $mandatory Mandatory or not
  4733. * @return int <=0 if KO, >0 if OK
  4734. */
  4735. public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
  4736. {
  4737. // phpcs:enable
  4738. $this->db->begin();
  4739. $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
  4740. $sql .= "resource_id";
  4741. $sql .= ", resource_type";
  4742. $sql .= ", element_id";
  4743. $sql .= ", element_type";
  4744. $sql .= ", busy";
  4745. $sql .= ", mandatory";
  4746. $sql .= ") VALUES (";
  4747. $sql .= $resource_id;
  4748. $sql .= ", '".$this->db->escape($resource_type)."'";
  4749. $sql .= ", '".$this->db->escape($this->id)."'";
  4750. $sql .= ", '".$this->db->escape($this->element)."'";
  4751. $sql .= ", '".$this->db->escape($busy)."'";
  4752. $sql .= ", '".$this->db->escape($mandatory)."'";
  4753. $sql .= ")";
  4754. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  4755. if ($this->db->query($sql)) {
  4756. $this->db->commit();
  4757. return 1;
  4758. } else {
  4759. $this->error = $this->db->lasterror();
  4760. $this->db->rollback();
  4761. return 0;
  4762. }
  4763. }
  4764. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4765. /**
  4766. * Delete a link to resource line
  4767. *
  4768. * @param int $rowid Id of resource line to delete
  4769. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  4770. * @param int $notrigger Disable all triggers
  4771. * @return int >0 if OK, <0 if KO
  4772. */
  4773. public function delete_resource($rowid, $element, $notrigger = 0)
  4774. {
  4775. // phpcs:enable
  4776. global $user;
  4777. $this->db->begin();
  4778. $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
  4779. $sql .= " WHERE rowid = ".((int) $rowid);
  4780. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  4781. $resql = $this->db->query($sql);
  4782. if (!$resql) {
  4783. $this->error = $this->db->lasterror();
  4784. $this->db->rollback();
  4785. return -1;
  4786. } else {
  4787. if (!$notrigger) {
  4788. $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  4789. if ($result < 0) {
  4790. $this->db->rollback();
  4791. return -1;
  4792. }
  4793. }
  4794. $this->db->commit();
  4795. return 1;
  4796. }
  4797. }
  4798. /**
  4799. * Overwrite magic function to solve problem of cloning object that are kept as references
  4800. *
  4801. * @return void
  4802. */
  4803. public function __clone()
  4804. {
  4805. // Force a copy of this->lines, otherwise it will point to same object.
  4806. if (isset($this->lines) && is_array($this->lines)) {
  4807. $nboflines = count($this->lines);
  4808. for ($i = 0; $i < $nboflines; $i++) {
  4809. $this->lines[$i] = clone $this->lines[$i];
  4810. }
  4811. }
  4812. }
  4813. /**
  4814. * Common function for all objects extending CommonObject for generating documents
  4815. *
  4816. * @param string $modelspath Relative folder where generators are placed
  4817. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model_pdf','alpha') for example.
  4818. * @param Translate $outputlangs Output language to use
  4819. * @param int $hidedetails 1 to hide details. 0 by default
  4820. * @param int $hidedesc 1 to hide product description. 0 by default
  4821. * @param int $hideref 1 to hide product reference. 0 by default
  4822. * @param null|array $moreparams Array to provide more information
  4823. * @return int >0 if OK, <0 if KO
  4824. * @see addFileIntoDatabaseIndex()
  4825. */
  4826. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
  4827. {
  4828. global $conf, $langs, $user, $hookmanager, $action;
  4829. $srctemplatepath = '';
  4830. $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
  4831. $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4832. if (empty($reshook)) {
  4833. dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
  4834. if (empty($modele)) {
  4835. $this->error = 'BadValueForParameterModele';
  4836. return -1;
  4837. }
  4838. // Increase limit for PDF build
  4839. $err = error_reporting();
  4840. error_reporting(0);
  4841. @set_time_limit(120);
  4842. error_reporting($err);
  4843. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  4844. $tmp = explode(':', $modele, 2);
  4845. if (!empty($tmp[1])) {
  4846. $modele = $tmp[0];
  4847. $srctemplatepath = $tmp[1];
  4848. }
  4849. // Search template files
  4850. $file = '';
  4851. $classname = '';
  4852. $filefound = '';
  4853. $dirmodels = array('/');
  4854. if (is_array($conf->modules_parts['models'])) {
  4855. $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
  4856. }
  4857. foreach ($dirmodels as $reldir) {
  4858. foreach (array('doc', 'pdf') as $prefix) {
  4859. if (in_array(get_class($this), array('Adherent'))) {
  4860. // Member module use prefix_modele.class.php
  4861. $file = $prefix."_".$modele.".class.php";
  4862. } else {
  4863. // Other module use prefix_modele.modules.php
  4864. $file = $prefix."_".$modele.".modules.php";
  4865. }
  4866. // On verifie l'emplacement du modele
  4867. $file = dol_buildpath($reldir.$modelspath.$file, 0);
  4868. if (file_exists($file)) {
  4869. $filefound = $file;
  4870. $classname = $prefix.'_'.$modele;
  4871. break;
  4872. }
  4873. }
  4874. if ($filefound) {
  4875. break;
  4876. }
  4877. }
  4878. // If generator was found
  4879. if ($filefound) {
  4880. global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
  4881. require_once $file;
  4882. $obj = new $classname($this->db);
  4883. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  4884. if ($obj->type == 'odt' && empty($srctemplatepath)) {
  4885. $varfortemplatedir = $obj->scandir;
  4886. if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
  4887. $dirtoscan = $conf->global->$varfortemplatedir;
  4888. $listoffiles = array();
  4889. // Now we add first model found in directories scanned
  4890. $listofdir = explode(',', $dirtoscan);
  4891. foreach ($listofdir as $key => $tmpdir) {
  4892. $tmpdir = trim($tmpdir);
  4893. $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
  4894. if (!$tmpdir) {
  4895. unset($listofdir[$key]);
  4896. continue;
  4897. }
  4898. if (is_dir($tmpdir)) {
  4899. $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
  4900. if (count($tmpfiles)) {
  4901. $listoffiles = array_merge($listoffiles, $tmpfiles);
  4902. }
  4903. }
  4904. }
  4905. if (count($listoffiles)) {
  4906. foreach ($listoffiles as $record) {
  4907. $srctemplatepath = $record['fullname'];
  4908. break;
  4909. }
  4910. }
  4911. }
  4912. if (empty($srctemplatepath)) {
  4913. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  4914. return -1;
  4915. }
  4916. }
  4917. if ($obj->type == 'odt' && !empty($srctemplatepath)) {
  4918. if (!dol_is_file($srctemplatepath)) {
  4919. dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
  4920. $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  4921. return -1;
  4922. }
  4923. }
  4924. // We save charset_output to restore it because write_file can change it if needed for
  4925. // output format that does not support UTF8.
  4926. $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
  4927. if (in_array(get_class($this), array('Adherent'))) {
  4928. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
  4929. } else {
  4930. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4931. }
  4932. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4933. if ($resultwritefile > 0) {
  4934. $outputlangs->charset_output = $sav_charset_output;
  4935. // We delete old preview
  4936. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4937. dol_delete_preview($this);
  4938. // Index file in database
  4939. if (!empty($obj->result['fullpath'])) {
  4940. $destfull = $obj->result['fullpath'];
  4941. // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
  4942. $update_main_doc_field = 0;
  4943. if (!empty($obj->update_main_doc_field)) {
  4944. $update_main_doc_field = 1;
  4945. }
  4946. $this->indexFile($destfull, $update_main_doc_field);
  4947. } else {
  4948. 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);
  4949. }
  4950. // Success in building document. We build meta file.
  4951. dol_meta_create($this);
  4952. return 1;
  4953. } else {
  4954. $outputlangs->charset_output = $sav_charset_output;
  4955. $this->error = $obj->error;
  4956. $this->errors = $obj->errors;
  4957. dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
  4958. return -1;
  4959. }
  4960. } else {
  4961. if (!$filefound) {
  4962. $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
  4963. $this->errors[] = $this->error;
  4964. dol_syslog($this->error, LOG_ERR);
  4965. } else {
  4966. $this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $filefound);
  4967. $this->errors[] = $this->error;
  4968. dol_syslog($this->error, LOG_ERR);
  4969. }
  4970. return -1;
  4971. }
  4972. } else {
  4973. return $reshook;
  4974. }
  4975. }
  4976. /**
  4977. * Index a file into the ECM database
  4978. *
  4979. * @param string $destfull Full path of file to index
  4980. * @param int $update_main_doc_field Update field main_doc fied into the table of object.
  4981. * This param is set when called for a document generation if document generator hase
  4982. * ->update_main_doc_field set and returns ->result['fullpath'].
  4983. * @return int <0 if KO, >0 if OK
  4984. */
  4985. public function indexFile($destfull, $update_main_doc_field)
  4986. {
  4987. global $conf, $user;
  4988. $upload_dir = dirname($destfull);
  4989. $destfile = basename($destfull);
  4990. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  4991. if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
  4992. $filename = basename($destfile);
  4993. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4994. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4995. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4996. $ecmfile = new EcmFiles($this->db);
  4997. $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
  4998. // Set the public "share" key
  4999. $setsharekey = false;
  5000. if ($this->element == 'propal' || $this->element == 'proposal') {
  5001. if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
  5002. $setsharekey = true; // feature to make online signature is not set or set to on (default)
  5003. }
  5004. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  5005. $setsharekey = true;
  5006. }
  5007. }
  5008. if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
  5009. $setsharekey = true;
  5010. }
  5011. if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
  5012. $setsharekey = true;
  5013. }
  5014. if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5015. $setsharekey = true;
  5016. }
  5017. if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5018. $setsharekey = true;
  5019. }
  5020. if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
  5021. $setsharekey = true;
  5022. }
  5023. if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
  5024. $setsharekey = true;
  5025. }
  5026. if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
  5027. $setsharekey = true;
  5028. }
  5029. if ($setsharekey) {
  5030. if (empty($ecmfile->share)) { // Because object not found or share not set yet
  5031. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  5032. $ecmfile->share = getRandomPassword(true);
  5033. }
  5034. }
  5035. if ($result > 0) {
  5036. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5037. $ecmfile->fullpath_orig = '';
  5038. $ecmfile->gen_or_uploaded = 'generated';
  5039. $ecmfile->description = ''; // indexed content
  5040. $ecmfile->keywords = ''; // keyword content
  5041. $result = $ecmfile->update($user);
  5042. if ($result < 0) {
  5043. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5044. return -1;
  5045. }
  5046. } else {
  5047. $ecmfile->entity = $conf->entity;
  5048. $ecmfile->filepath = $rel_dir;
  5049. $ecmfile->filename = $filename;
  5050. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  5051. $ecmfile->fullpath_orig = '';
  5052. $ecmfile->gen_or_uploaded = 'generated';
  5053. $ecmfile->description = ''; // indexed content
  5054. $ecmfile->keywords = ''; // keyword content
  5055. $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
  5056. $ecmfile->src_object_id = $this->id;
  5057. $result = $ecmfile->create($user);
  5058. if ($result < 0) {
  5059. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  5060. return -1;
  5061. }
  5062. }
  5063. /*$this->result['fullname']=$destfull;
  5064. $this->result['filepath']=$ecmfile->filepath;
  5065. $this->result['filename']=$ecmfile->filename;*/
  5066. //var_dump($obj->update_main_doc_field);exit;
  5067. if ($update_main_doc_field && !empty($this->table_element)) {
  5068. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
  5069. $sql .= " WHERE rowid = ".((int) $this->id);
  5070. $resql = $this->db->query($sql);
  5071. if (!$resql) {
  5072. dol_print_error($this->db);
  5073. return -1;
  5074. } else {
  5075. $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
  5076. }
  5077. }
  5078. }
  5079. return 1;
  5080. }
  5081. /**
  5082. * Build thumb
  5083. * @todo Move this into files.lib.php
  5084. *
  5085. * @param string $file Path file in UTF8 to original file to create thumbs from.
  5086. * @return void
  5087. */
  5088. public function addThumbs($file)
  5089. {
  5090. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  5091. require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  5092. $file_osencoded = dol_osencode($file);
  5093. if (file_exists($file_osencoded)) {
  5094. // Create small thumbs for company (Ratio is near 16/9)
  5095. // Used on logon for example
  5096. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  5097. // Create mini thumbs for company (Ratio is near 16/9)
  5098. // Used on menu or for setup page for example
  5099. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  5100. }
  5101. }
  5102. /* Functions common to commonobject and commonobjectline */
  5103. /* For default values */
  5104. /**
  5105. * Return the default value to use for a field when showing the create form of object.
  5106. * Return values in this order:
  5107. * 1) If parameter is available into POST, we return it first.
  5108. * 2) If not but an alternate value was provided as parameter of function, we return it.
  5109. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  5110. * 4) Return value found into database (TODO No yet implemented)
  5111. *
  5112. * @param string $fieldname Name of field
  5113. * @param string $alternatevalue Alternate value to use
  5114. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  5115. **/
  5116. public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
  5117. {
  5118. global $conf, $_POST;
  5119. // If param here has been posted, we use this value first.
  5120. if (GETPOSTISSET($fieldname)) {
  5121. return GETPOST($fieldname, 'alphanohtml', 3);
  5122. }
  5123. if (isset($alternatevalue)) {
  5124. return $alternatevalue;
  5125. }
  5126. $newelement = $this->element;
  5127. if ($newelement == 'facture') {
  5128. $newelement = 'invoice';
  5129. }
  5130. if ($newelement == 'commande') {
  5131. $newelement = 'order';
  5132. }
  5133. if (empty($newelement)) {
  5134. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  5135. return '';
  5136. }
  5137. $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
  5138. //var_dump($keyforfieldname);
  5139. if (isset($conf->global->$keyforfieldname)) {
  5140. return $conf->global->$keyforfieldname;
  5141. }
  5142. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  5143. }
  5144. /* For triggers */
  5145. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5146. /**
  5147. * Call trigger based on this instance.
  5148. * Some context information may also be provided into array property this->context.
  5149. * NB: Error from trigger are stacked in interface->errors
  5150. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  5151. *
  5152. * @param string $triggerName trigger's name to execute
  5153. * @param User $user Object user
  5154. * @return int Result of run_triggers
  5155. */
  5156. public function call_trigger($triggerName, $user)
  5157. {
  5158. // phpcs:enable
  5159. global $langs, $conf;
  5160. if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
  5161. dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
  5162. exit;
  5163. }
  5164. if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
  5165. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  5166. $langs = new Translate('', $conf);
  5167. }
  5168. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  5169. $interface = new Interfaces($this->db);
  5170. $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
  5171. if ($result < 0) {
  5172. if (!empty($this->errors)) {
  5173. $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.
  5174. } else {
  5175. $this->errors = $interface->errors;
  5176. }
  5177. }
  5178. return $result;
  5179. }
  5180. /* Functions for data in other language */
  5181. /**
  5182. * Function to get alternative languages of a data into $this->array_languages
  5183. * This method is NOT called by method fetch of objects but must be called separately.
  5184. *
  5185. * @return int <0 if error, 0 if no values of alternative languages to find nor found, 1 if a value was found and loaded
  5186. * @see fetch_optionnals()
  5187. */
  5188. public function fetchValuesForExtraLanguages()
  5189. {
  5190. // To avoid SQL errors. Probably not the better solution though
  5191. if (!$this->element) {
  5192. return 0;
  5193. }
  5194. if (!($this->id > 0)) {
  5195. return 0;
  5196. }
  5197. if (is_array($this->array_languages)) {
  5198. return 1;
  5199. }
  5200. $this->array_languages = array();
  5201. $element = $this->element;
  5202. if ($element == 'categorie') {
  5203. $element = 'categories'; // For compatibility
  5204. }
  5205. // Request to get translation values for object
  5206. $sql = "SELECT rowid, property, lang , value";
  5207. $sql .= " FROM ".$this->db->prefix()."object_lang";
  5208. $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
  5209. $sql .= " AND fk_object = ".((int) $this->id);
  5210. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5211. $resql = $this->db->query($sql);
  5212. if ($resql) {
  5213. $numrows = $this->db->num_rows($resql);
  5214. if ($numrows) {
  5215. $i = 0;
  5216. while ($i < $numrows) {
  5217. $obj = $this->db->fetch_object($resql);
  5218. $key = $obj->property;
  5219. $value = $obj->value;
  5220. $codelang = $obj->lang;
  5221. $type = $this->fields[$key]['type'];
  5222. // we can add this attribute to object
  5223. if (preg_match('/date/', $type)) {
  5224. $this->array_languages[$key][$codelang] = $this->db->jdate($value);
  5225. } else {
  5226. $this->array_languages[$key][$codelang] = $value;
  5227. }
  5228. $i++;
  5229. }
  5230. }
  5231. $this->db->free($resql);
  5232. if ($numrows) {
  5233. return $numrows;
  5234. } else {
  5235. return 0;
  5236. }
  5237. } else {
  5238. dol_print_error($this->db);
  5239. return -1;
  5240. }
  5241. }
  5242. /**
  5243. * Fill array_options property of object by extrafields value (using for data sent by forms)
  5244. *
  5245. * @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.
  5246. * @return int 1 if array_options set, 0 if no value, -1 if error (field required missing for example)
  5247. */
  5248. public function setValuesForExtraLanguages($onlykey = '')
  5249. {
  5250. global $_POST, $langs;
  5251. // Get extra fields
  5252. foreach ($_POST as $postfieldkey => $postfieldvalue) {
  5253. $tmparray = explode('-', $postfieldkey);
  5254. if ($tmparray[0] != 'field') {
  5255. continue;
  5256. }
  5257. $element = $tmparray[1];
  5258. $key = $tmparray[2];
  5259. $codelang = $tmparray[3];
  5260. //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
  5261. if (!empty($onlykey) && $key != $onlykey) {
  5262. continue;
  5263. }
  5264. if ($element != $this->element) {
  5265. continue;
  5266. }
  5267. $key_type = $this->fields[$key]['type'];
  5268. $enabled = 1;
  5269. if (isset($this->fields[$key]['enabled'])) {
  5270. $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
  5271. }
  5272. /*$perms = 1;
  5273. if (isset($this->fields[$key]['perms']))
  5274. {
  5275. $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
  5276. }*/
  5277. if (empty($enabled)) {
  5278. continue;
  5279. }
  5280. //if (empty($perms)) continue;
  5281. if (in_array($key_type, array('date'))) {
  5282. // Clean parameters
  5283. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5284. $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month", 'int'), GETPOST($postfieldkey."day", 'int'), GETPOST($postfieldkey."year", 'int'));
  5285. } elseif (in_array($key_type, array('datetime'))) {
  5286. // Clean parameters
  5287. // TODO GMT date in memory must be GMT so we should add gm=true in parameters
  5288. $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'));
  5289. } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
  5290. $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
  5291. if (!empty($value_arr)) {
  5292. $value_key = implode(',', $value_arr);
  5293. } else {
  5294. $value_key = '';
  5295. }
  5296. } elseif (in_array($key_type, array('price', 'double'))) {
  5297. $value_arr = GETPOST($postfieldkey, 'alpha');
  5298. $value_key = price2num($value_arr);
  5299. } else {
  5300. $value_key = GETPOST($postfieldkey);
  5301. if (in_array($key_type, array('link')) && $value_key == '-1') {
  5302. $value_key = '';
  5303. }
  5304. }
  5305. $this->array_languages[$key][$codelang] = $value_key;
  5306. /*if ($nofillrequired) {
  5307. $langs->load('errors');
  5308. setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
  5309. return -1;
  5310. }*/
  5311. }
  5312. return 1;
  5313. }
  5314. /* Functions for extrafields */
  5315. /**
  5316. * Function to make a fetch but set environment to avoid to load computed values before.
  5317. *
  5318. * @param int $id ID of object
  5319. * @return int >0 if OK, 0 if not found, <0 if KO
  5320. */
  5321. public function fetchNoCompute($id)
  5322. {
  5323. global $conf;
  5324. $savDisableCompute = $conf->disable_compute;
  5325. $conf->disable_compute = 1;
  5326. $ret = $this->fetch($id);
  5327. $conf->disable_compute = $savDisableCompute;
  5328. return $ret;
  5329. }
  5330. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5331. /**
  5332. * Function to get extra fields of an object into $this->array_options
  5333. * This method is in most cases called by method fetch of objects but you can call it separately.
  5334. *
  5335. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  5336. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  5337. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  5338. * @see fetchValuesForExtraLanguages()
  5339. */
  5340. public function fetch_optionals($rowid = null, $optionsArray = null)
  5341. {
  5342. // phpcs:enable
  5343. global $conf, $extrafields;
  5344. if (empty($rowid)) {
  5345. $rowid = $this->id;
  5346. }
  5347. if (empty($rowid) && isset($this->rowid)) {
  5348. $rowid = $this->rowid; // deprecated
  5349. }
  5350. // To avoid SQL errors. Probably not the better solution though
  5351. if (!$this->table_element) {
  5352. return 0;
  5353. }
  5354. $this->array_options = array();
  5355. if (!is_array($optionsArray)) {
  5356. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  5357. if (!isset($extrafields) || !is_object($extrafields)) {
  5358. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5359. $extrafields = new ExtraFields($this->db);
  5360. }
  5361. // Load array of extrafields for elementype = $this->table_element
  5362. if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
  5363. $extrafields->fetch_name_optionals_label($this->table_element);
  5364. }
  5365. $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
  5366. } else {
  5367. global $extrafields;
  5368. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  5369. }
  5370. $table_element = $this->table_element;
  5371. if ($table_element == 'categorie') {
  5372. $table_element = 'categories'; // For compatibility
  5373. }
  5374. // Request to get complementary values
  5375. if (is_array($optionsArray) && count($optionsArray) > 0) {
  5376. $sql = "SELECT rowid";
  5377. foreach ($optionsArray as $name => $label) {
  5378. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
  5379. $sql .= ", ".$name;
  5380. }
  5381. }
  5382. $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
  5383. $sql .= " WHERE fk_object = ".((int) $rowid);
  5384. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  5385. $resql = $this->db->query($sql);
  5386. if ($resql) {
  5387. $numrows = $this->db->num_rows($resql);
  5388. if ($numrows) {
  5389. $tab = $this->db->fetch_array($resql);
  5390. foreach ($tab as $key => $value) {
  5391. // 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)
  5392. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
  5393. // we can add this attribute to object
  5394. if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
  5395. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  5396. $this->array_options["options_".$key] = $this->db->jdate($value);
  5397. } else {
  5398. $this->array_options["options_".$key] = $value;
  5399. }
  5400. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  5401. }
  5402. }
  5403. }
  5404. // If field is a computed field, value must become result of compute (regardless of whether a row exists
  5405. // in the element's extrafields table)
  5406. if (is_array($extrafields->attributes[$this->table_element]['label'])) {
  5407. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
  5408. if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
  5409. //var_dump($conf->disable_compute);
  5410. if (empty($conf->disable_compute)) {
  5411. global $objectoffield; // We set a global variable to $objectoffield so
  5412. $objectoffield = $this; // we can use it inside computed formula
  5413. $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
  5414. }
  5415. }
  5416. }
  5417. }
  5418. $this->db->free($resql);
  5419. if ($numrows) {
  5420. return $numrows;
  5421. } else {
  5422. return 0;
  5423. }
  5424. } else {
  5425. $this->errors[]=$this->db->lasterror;
  5426. return -1;
  5427. }
  5428. }
  5429. return 0;
  5430. }
  5431. /**
  5432. * Delete all extra fields values for the current object.
  5433. *
  5434. * @return int <0 if KO, >0 if OK
  5435. * @see deleteExtraLanguages(), insertExtraField(), updateExtraField(), setValueFrom()
  5436. */
  5437. public function deleteExtraFields()
  5438. {
  5439. global $conf;
  5440. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5441. return 0;
  5442. }
  5443. $this->db->begin();
  5444. $table_element = $this->table_element;
  5445. if ($table_element == 'categorie') {
  5446. $table_element = 'categories'; // For compatibility
  5447. }
  5448. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  5449. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5450. $resql = $this->db->query($sql_del);
  5451. if (!$resql) {
  5452. $this->error = $this->db->lasterror();
  5453. $this->db->rollback();
  5454. return -1;
  5455. } else {
  5456. $this->db->commit();
  5457. return 1;
  5458. }
  5459. }
  5460. /**
  5461. * Add/Update all extra fields values for the current object.
  5462. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5463. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5464. *
  5465. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5466. * @param User $userused Object user
  5467. * @return int -1=error, O=did nothing, 1=OK
  5468. * @see insertExtraLanguages(), updateExtraField(), deleteExtraField(), setValueFrom()
  5469. */
  5470. public function insertExtraFields($trigger = '', $userused = null)
  5471. {
  5472. global $conf, $langs, $user;
  5473. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5474. return 0;
  5475. }
  5476. if (empty($userused)) {
  5477. $userused = $user;
  5478. }
  5479. $error = 0;
  5480. if (!empty($this->array_options)) {
  5481. // Check parameters
  5482. $langs->load('admin');
  5483. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5484. $extrafields = new ExtraFields($this->db);
  5485. $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
  5486. // Eliminate copied source object extra fields that do not exist in target object
  5487. $new_array_options = array();
  5488. foreach ($this->array_options as $key => $value) {
  5489. if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
  5490. $new_array_options[$key] = $value;
  5491. } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
  5492. $new_array_options['options_'.$key] = $value;
  5493. }
  5494. }
  5495. foreach ($new_array_options as $key => $value) {
  5496. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5497. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  5498. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  5499. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  5500. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  5501. $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
  5502. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
  5503. // If we clone, we have to clean unique extrafields to prevent duplicates.
  5504. // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
  5505. if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
  5506. $new_array_options[$key] = null;
  5507. }
  5508. // Similar code than into insertExtraFields
  5509. if ($attributeRequired) {
  5510. $mandatorypb = false;
  5511. if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
  5512. $mandatorypb = true;
  5513. }
  5514. if ($this->array_options[$key] === '') {
  5515. $mandatorypb = true;
  5516. }
  5517. if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
  5518. $mandatorypb = true;
  5519. }
  5520. if ($mandatorypb) {
  5521. $langs->load("errors");
  5522. dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
  5523. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5524. return -1;
  5525. }
  5526. }
  5527. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5528. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5529. if (!empty($attrfieldcomputed)) {
  5530. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5531. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5532. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5533. $new_array_options[$key] = $value;
  5534. } else {
  5535. $new_array_options[$key] = null;
  5536. }
  5537. }
  5538. switch ($attributeType) {
  5539. case 'int':
  5540. if (!is_numeric($value) && $value != '') {
  5541. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5542. return -1;
  5543. } elseif ($value == '') {
  5544. $new_array_options[$key] = null;
  5545. }
  5546. break;
  5547. case 'price':
  5548. case 'double':
  5549. $value = price2num($value);
  5550. if (!is_numeric($value) && $value != '') {
  5551. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5552. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5553. return -1;
  5554. } elseif ($value == '') {
  5555. $value = null;
  5556. }
  5557. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5558. $new_array_options[$key] = $value;
  5559. break;
  5560. /*case 'select': // Not required, we chosed value='0' for undefined values
  5561. if ($value=='-1')
  5562. {
  5563. $this->array_options[$key] = null;
  5564. }
  5565. break;*/
  5566. case 'password':
  5567. $algo = '';
  5568. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
  5569. // If there is an encryption choice, we use it to crypt data before insert
  5570. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  5571. $algo = reset($tmparrays);
  5572. if ($algo != '') {
  5573. //global $action; // $action may be 'create', 'update', 'update_extras'...
  5574. //var_dump($action);
  5575. //var_dump($this->oldcopy);exit;
  5576. 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
  5577. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  5578. 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.
  5579. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5580. } else {
  5581. // var_dump($algo);
  5582. $newvalue = dol_hash($this->array_options[$key], $algo);
  5583. $new_array_options[$key] = $newvalue;
  5584. }
  5585. } else {
  5586. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  5587. }
  5588. }
  5589. } else // Common usage
  5590. {
  5591. $new_array_options[$key] = $this->array_options[$key];
  5592. }
  5593. break;
  5594. case 'date':
  5595. case 'datetime':
  5596. // If data is a string instead of a timestamp, we convert it
  5597. if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
  5598. $this->array_options[$key] = strtotime($this->array_options[$key]);
  5599. }
  5600. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  5601. break;
  5602. case 'link':
  5603. $param_list = array_keys($attributeParam['options']);
  5604. // 0 : ObjectName
  5605. // 1 : classPath
  5606. $InfoFieldList = explode(":", $param_list[0]);
  5607. dol_include_once($InfoFieldList[1]);
  5608. if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
  5609. if ($value == '-1') { // -1 is key for no defined in combo list of objects
  5610. $new_array_options[$key] = '';
  5611. } elseif ($value) {
  5612. $object = new $InfoFieldList[0]($this->db);
  5613. if (is_numeric($value)) {
  5614. $res = $object->fetch($value); // Common case
  5615. } else {
  5616. $res = $object->fetch('', $value); // For compatibility
  5617. }
  5618. if ($res > 0) {
  5619. $new_array_options[$key] = $object->id;
  5620. } else {
  5621. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5622. return -1;
  5623. }
  5624. }
  5625. } else {
  5626. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5627. }
  5628. break;
  5629. }
  5630. }
  5631. $this->db->begin();
  5632. $table_element = $this->table_element;
  5633. if ($table_element == 'categorie') {
  5634. $table_element = 'categories'; // For compatibility
  5635. }
  5636. dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
  5637. $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5638. $this->db->query($sql_del);
  5639. $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
  5640. foreach ($new_array_options as $key => $value) {
  5641. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5642. // Add field of attribut
  5643. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
  5644. $sql .= ",".$attributeKey;
  5645. }
  5646. }
  5647. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5648. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5649. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5650. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5651. $sql .= ",".$tmpkey;
  5652. }
  5653. }
  5654. }
  5655. $sql .= ") VALUES (".$this->id;
  5656. foreach ($new_array_options as $key => $value) {
  5657. $attributeKey = substr($key, 8); // Remove 'options_' prefix
  5658. // Add field of attribute
  5659. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
  5660. if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
  5661. $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
  5662. } else {
  5663. $sql .= ",null";
  5664. }
  5665. }
  5666. }
  5667. // We must insert a default value for fields for other entities that are mandatory to avoid not null error
  5668. if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
  5669. foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
  5670. if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
  5671. if (in_array($tmpval, array('int', 'double', 'price'))) {
  5672. $sql .= ", 0";
  5673. } else {
  5674. $sql .= ", ''";
  5675. }
  5676. }
  5677. }
  5678. }
  5679. $sql .= ")";
  5680. $resql = $this->db->query($sql);
  5681. if (!$resql) {
  5682. $this->error = $this->db->lasterror();
  5683. $error++;
  5684. }
  5685. if (!$error && $trigger) {
  5686. // Call trigger
  5687. $this->context = array('extrafieldaddupdate'=>1);
  5688. $result = $this->call_trigger($trigger, $userused);
  5689. if ($result < 0) {
  5690. $error++;
  5691. }
  5692. // End call trigger
  5693. }
  5694. if ($error) {
  5695. $this->db->rollback();
  5696. return -1;
  5697. } else {
  5698. $this->db->commit();
  5699. return 1;
  5700. }
  5701. } else {
  5702. return 0;
  5703. }
  5704. }
  5705. /**
  5706. * Add/Update all extra fields values for the current object.
  5707. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5708. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  5709. *
  5710. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5711. * @param User $userused Object user
  5712. * @return int -1=error, O=did nothing, 1=OK
  5713. * @see insertExtraFields(), updateExtraField(), setValueFrom()
  5714. */
  5715. public function insertExtraLanguages($trigger = '', $userused = null)
  5716. {
  5717. global $conf, $langs, $user;
  5718. if (empty($userused)) {
  5719. $userused = $user;
  5720. }
  5721. $error = 0;
  5722. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  5723. return 0; // For avoid conflicts if trigger used
  5724. }
  5725. if (is_array($this->array_languages)) {
  5726. $new_array_languages = $this->array_languages;
  5727. foreach ($new_array_languages as $key => $value) {
  5728. $attributeKey = $key;
  5729. $attributeType = $this->fields[$attributeKey]['type'];
  5730. $attributeLabel = $this->fields[$attributeKey]['label'];
  5731. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5732. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5733. switch ($attributeType) {
  5734. case 'int':
  5735. if (!is_numeric($value) && $value != '') {
  5736. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5737. return -1;
  5738. } elseif ($value == '') {
  5739. $new_array_languages[$key] = null;
  5740. }
  5741. break;
  5742. case 'double':
  5743. $value = price2num($value);
  5744. if (!is_numeric($value) && $value != '') {
  5745. dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5746. $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
  5747. return -1;
  5748. } elseif ($value == '') {
  5749. $new_array_languages[$key] = null;
  5750. }
  5751. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5752. $new_array_languages[$key] = $value;
  5753. break;
  5754. /*case 'select': // Not required, we chosed value='0' for undefined values
  5755. if ($value=='-1')
  5756. {
  5757. $this->array_options[$key] = null;
  5758. }
  5759. break;*/
  5760. }
  5761. }
  5762. $this->db->begin();
  5763. $table_element = $this->table_element;
  5764. if ($table_element == 'categorie') {
  5765. $table_element = 'categories'; // For compatibility
  5766. }
  5767. dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
  5768. foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
  5769. foreach ($langcodearray as $langcode => $value) {
  5770. $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
  5771. $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
  5772. $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
  5773. $this->db->query($sql_del);
  5774. if ($value !== '') {
  5775. $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
  5776. $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
  5777. $sql .= ")";
  5778. $resql = $this->db->query($sql);
  5779. if (!$resql) {
  5780. $this->error = $this->db->lasterror();
  5781. $error++;
  5782. break;
  5783. }
  5784. }
  5785. }
  5786. }
  5787. if (!$error && $trigger) {
  5788. // Call trigger
  5789. $this->context = array('extralanguagesaddupdate'=>1);
  5790. $result = $this->call_trigger($trigger, $userused);
  5791. if ($result < 0) {
  5792. $error++;
  5793. }
  5794. // End call trigger
  5795. }
  5796. if ($error) {
  5797. $this->db->rollback();
  5798. return -1;
  5799. } else {
  5800. $this->db->commit();
  5801. return 1;
  5802. }
  5803. } else {
  5804. return 0;
  5805. }
  5806. }
  5807. /**
  5808. * Update 1 extra field value for the current object. Keep other fields unchanged.
  5809. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5810. *
  5811. * @param string $key Key of the extrafield to update (without starting 'options_')
  5812. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5813. * @param User $userused Object user
  5814. * @return int -1=error, O=did nothing, 1=OK
  5815. * @see updateExtraLanguages(), insertExtraFields(), deleteExtraFields(), setValueFrom()
  5816. */
  5817. public function updateExtraField($key, $trigger = null, $userused = null)
  5818. {
  5819. global $conf, $langs, $user;
  5820. if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  5821. return 0;
  5822. }
  5823. if (empty($userused)) {
  5824. $userused = $user;
  5825. }
  5826. $error = 0;
  5827. if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
  5828. // Check parameters
  5829. $langs->load('admin');
  5830. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  5831. $extrafields = new ExtraFields($this->db);
  5832. $extrafields->fetch_name_optionals_label($this->table_element);
  5833. $value = $this->array_options["options_".$key];
  5834. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  5835. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  5836. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  5837. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  5838. $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
  5839. // Similar code than into insertExtraFields
  5840. if ($attributeRequired) {
  5841. $mandatorypb = false;
  5842. if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
  5843. $mandatorypb = true;
  5844. }
  5845. if ($this->array_options["options_".$key] === '') {
  5846. $mandatorypb = true;
  5847. }
  5848. if ($mandatorypb) {
  5849. $langs->load("errors");
  5850. dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
  5851. $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
  5852. return -1;
  5853. }
  5854. }
  5855. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  5856. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  5857. if (!empty($attrfieldcomputed)) {
  5858. if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
  5859. $value = dol_eval($attrfieldcomputed, 1, 0, '');
  5860. dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG);
  5861. $this->array_options["options_".$key] = $value;
  5862. } else {
  5863. $this->array_options["options_".$key] = null;
  5864. }
  5865. }
  5866. switch ($attributeType) {
  5867. case 'int':
  5868. if (!is_numeric($value) && $value != '') {
  5869. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5870. return -1;
  5871. } elseif ($value === '') {
  5872. $this->array_options["options_".$key] = null;
  5873. }
  5874. break;
  5875. case 'double':
  5876. $value = price2num($value);
  5877. if (!is_numeric($value) && $value != '') {
  5878. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  5879. $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  5880. return -1;
  5881. } elseif ($value === '') {
  5882. $value = null;
  5883. }
  5884. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  5885. $this->array_options["options_".$key] = $value;
  5886. break;
  5887. /*case 'select': // Not required, we chosed value='0' for undefined values
  5888. if ($value=='-1')
  5889. {
  5890. $this->array_options[$key] = null;
  5891. }
  5892. break;*/
  5893. case 'price':
  5894. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  5895. break;
  5896. case 'date':
  5897. case 'datetime':
  5898. if (empty($this->array_options["options_".$key])) {
  5899. $this->array_options["options_".$key] = null;
  5900. } else {
  5901. $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
  5902. }
  5903. break;
  5904. case 'boolean':
  5905. if (empty($this->array_options["options_".$key])) {
  5906. $this->array_options["options_".$key] = null;
  5907. }
  5908. break;
  5909. /*
  5910. case 'link':
  5911. $param_list = array_keys($attributeParam['options']);
  5912. // 0 : ObjectName
  5913. // 1 : classPath
  5914. $InfoFieldList = explode(":", $param_list[0]);
  5915. dol_include_once($InfoFieldList[1]);
  5916. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  5917. {
  5918. if ($value == '-1') // -1 is key for no defined in combo list of objects
  5919. {
  5920. $new_array_options[$key] = '';
  5921. } elseif ($value) {
  5922. $object = new $InfoFieldList[0]($this->db);
  5923. if (is_numeric($value)) $res = $object->fetch($value); // Common case
  5924. else $res = $object->fetch('', $value); // For compatibility
  5925. if ($res > 0) $new_array_options[$key] = $object->id;
  5926. else {
  5927. $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
  5928. $this->db->rollback();
  5929. return -1;
  5930. }
  5931. }
  5932. } else {
  5933. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5934. }
  5935. break;
  5936. */
  5937. }
  5938. $this->db->begin();
  5939. $linealreadyfound = 0;
  5940. // 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)
  5941. $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object = ".((int) $this->id);
  5942. $resql = $this->db->query($sql);
  5943. if ($resql) {
  5944. $tmpobj = $this->db->fetch_object($resql);
  5945. if ($tmpobj) {
  5946. $linealreadyfound = $tmpobj->nb;
  5947. }
  5948. }
  5949. if ($linealreadyfound) {
  5950. if ($this->array_options["options_".$key] === null) {
  5951. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null";
  5952. } else {
  5953. $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'";
  5954. }
  5955. $sql .= " WHERE fk_object = ".((int) $this->id);
  5956. } else {
  5957. $result = $this->insertExtraFields('', $user);
  5958. if ($result < 0) {
  5959. $error++;
  5960. }
  5961. }
  5962. $resql = $this->db->query($sql);
  5963. if (!$resql) {
  5964. $error++;
  5965. $this->error = $this->db->lasterror();
  5966. }
  5967. if (!$error && $trigger) {
  5968. // Call trigger
  5969. $this->context = array('extrafieldupdate'=>1);
  5970. $result = $this->call_trigger($trigger, $userused);
  5971. if ($result < 0) {
  5972. $error++;
  5973. }
  5974. // End call trigger
  5975. }
  5976. if ($error) {
  5977. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  5978. $this->db->rollback();
  5979. return -1;
  5980. } else {
  5981. $this->db->commit();
  5982. return 1;
  5983. }
  5984. } else {
  5985. return 0;
  5986. }
  5987. }
  5988. /**
  5989. * Update an extra language value for the current object.
  5990. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  5991. *
  5992. * @param string $key Key of the extrafield (without starting 'options_')
  5993. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  5994. * @param User $userused Object user
  5995. * @return int -1=error, O=did nothing, 1=OK
  5996. * @see updateExtraFields(), insertExtraLanguages()
  5997. */
  5998. public function updateExtraLanguages($key, $trigger = null, $userused = null)
  5999. {
  6000. global $conf, $langs, $user;
  6001. if (empty($userused)) {
  6002. $userused = $user;
  6003. }
  6004. $error = 0;
  6005. if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
  6006. return 0; // For avoid conflicts if trigger used
  6007. }
  6008. return 0;
  6009. }
  6010. /**
  6011. * Return HTML string to put an input field into a page
  6012. * Code very similar with showInputField of extra fields
  6013. *
  6014. * @param array $val Array of properties for field to show (used only if ->fields not defined)
  6015. * @param string $key Key of attribute
  6016. * @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)
  6017. * @param string $moreparam To add more parameters on html input tag
  6018. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6019. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6020. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  6021. * @param int $nonewbutton Force to not show the new button on field that are links to object
  6022. * @return string
  6023. */
  6024. public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
  6025. {
  6026. global $conf, $langs, $form;
  6027. if (!is_object($form)) {
  6028. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6029. $form = new Form($this->db);
  6030. }
  6031. if (!empty($this->fields)) {
  6032. $val = $this->fields[$key];
  6033. }
  6034. // Validation tests and output
  6035. $fieldValidationErrorMsg = '';
  6036. $validationClass = '';
  6037. $fieldValidationErrorMsg = $this->getFieldError($key);
  6038. if (!empty($fieldValidationErrorMsg)) {
  6039. $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
  6040. } else {
  6041. $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
  6042. }
  6043. $out = '';
  6044. $type = '';
  6045. $isDependList = 0;
  6046. $param = array();
  6047. $param['options'] = array();
  6048. $reg = array();
  6049. $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
  6050. // Because we work on extrafields
  6051. if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6052. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6053. $type = 'link';
  6054. } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6055. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6056. $type = 'link';
  6057. } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
  6058. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6059. $type = 'link';
  6060. } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6061. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
  6062. $type = 'sellist';
  6063. } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6064. $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6065. $type = 'sellist';
  6066. } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
  6067. $param['options'] = array($reg[2].':'.$reg[3] => 'N');
  6068. $type = 'sellist';
  6069. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6070. $param['options'] = array($reg[1] => 'N');
  6071. $type = 'chkbxlst';
  6072. } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
  6073. $param['options'] = array();
  6074. $type = 'varchar';
  6075. $size = $reg[1];
  6076. } elseif (preg_match('/varchar/', $val['type'])) {
  6077. $param['options'] = array();
  6078. $type = 'varchar';
  6079. } else {
  6080. $param['options'] = array();
  6081. $type = $this->fields[$key]['type'];
  6082. }
  6083. // Special case that force options and type ($type can be integer, varchar, ...)
  6084. if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
  6085. $param['options'] = $this->fields[$key]['arrayofkeyval'];
  6086. $type = 'select';
  6087. }
  6088. $label = $this->fields[$key]['label'];
  6089. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  6090. $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
  6091. $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
  6092. $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
  6093. $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
  6094. $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
  6095. $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
  6096. $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
  6097. $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
  6098. $objectid = $this->id;
  6099. if ($computed) {
  6100. if (!preg_match('/^search_/', $keyprefix)) {
  6101. return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  6102. } else {
  6103. return '';
  6104. }
  6105. }
  6106. // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
  6107. if (empty($morecss) && !empty($val['css'])) {
  6108. $morecss = $val['css'];
  6109. } elseif (empty($morecss)) {
  6110. if ($type == 'date') {
  6111. $morecss = 'minwidth100imp';
  6112. } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
  6113. $morecss = 'minwidth200imp';
  6114. } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6115. $morecss = 'maxwidth75';
  6116. } elseif ($type == 'url') {
  6117. $morecss = 'minwidth400';
  6118. } elseif ($type == 'boolean') {
  6119. $morecss = '';
  6120. } else {
  6121. if (round($size) < 12) {
  6122. $morecss = 'minwidth100';
  6123. } elseif (round($size) <= 48) {
  6124. $morecss = 'minwidth200';
  6125. } else {
  6126. $morecss = 'minwidth400';
  6127. }
  6128. }
  6129. }
  6130. // Add validation state class
  6131. if (!empty($validationClass)) {
  6132. $morecss.= $validationClass;
  6133. }
  6134. if (in_array($type, array('date'))) {
  6135. $tmp = explode(',', $size);
  6136. $newsize = $tmp[0];
  6137. $showtime = 0;
  6138. // Do not show current date when field not required (see selectDate() method)
  6139. if (!$required && $value == '') {
  6140. $value = '-1';
  6141. }
  6142. // TODO Must also support $moreparam
  6143. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  6144. } elseif (in_array($type, array('datetime'))) {
  6145. $tmp = explode(',', $size);
  6146. $newsize = $tmp[0];
  6147. $showtime = 1;
  6148. // Do not show current date when field not required (see selectDate() method)
  6149. if (!$required && $value == '') $value = '-1';
  6150. // TODO Must also support $moreparam
  6151. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
  6152. } elseif (in_array($type, array('duration'))) {
  6153. $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
  6154. } elseif (in_array($type, array('int', 'integer'))) {
  6155. $tmp = explode(',', $size);
  6156. $newsize = $tmp[0];
  6157. $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' : '').'>';
  6158. } elseif (in_array($type, array('real'))) {
  6159. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6160. } elseif (preg_match('/varchar/', $type)) {
  6161. $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' : '').'>';
  6162. } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
  6163. $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
  6164. } elseif (preg_match('/^text/', $type)) {
  6165. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6166. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6167. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
  6168. $out = $doleditor->Create(1);
  6169. } else {
  6170. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6171. }
  6172. } elseif (preg_match('/^html/', $type)) {
  6173. if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
  6174. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  6175. $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
  6176. $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
  6177. } else {
  6178. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
  6179. }
  6180. } elseif ($type == 'boolean') {
  6181. $checked = '';
  6182. if (!empty($value)) {
  6183. $checked = ' checked value="1" ';
  6184. } else {
  6185. $checked = ' value="1" ';
  6186. }
  6187. $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
  6188. } elseif ($type == 'price') {
  6189. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6190. $value = price($value);
  6191. }
  6192. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
  6193. } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
  6194. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  6195. $value = price($value);
  6196. }
  6197. $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
  6198. } elseif ($type == 'select') {
  6199. $out = '';
  6200. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6201. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6202. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6203. }
  6204. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6205. if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
  6206. $out .= '<option value="0">&nbsp;</option>';
  6207. }
  6208. foreach ($param['options'] as $keyb => $valb) {
  6209. if ((string) $keyb == '') {
  6210. continue;
  6211. }
  6212. if (strpos($valb, "|") !== false) {
  6213. list($valb, $parent) = explode('|', $valb);
  6214. }
  6215. $out .= '<option value="'.$keyb.'"';
  6216. $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
  6217. $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
  6218. $out .= '>'.$valb.'</option>';
  6219. }
  6220. $out .= '</select>';
  6221. } elseif ($type == 'sellist') {
  6222. $out = '';
  6223. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
  6224. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6225. $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  6226. }
  6227. $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
  6228. if (is_array($param['options'])) {
  6229. $param_list = array_keys($param['options']);
  6230. $InfoFieldList = explode(":", $param_list[0]);
  6231. $parentName = '';
  6232. $parentField = '';
  6233. // 0 : tableName
  6234. // 1 : label field name
  6235. // 2 : key fields name (if differ of rowid)
  6236. // 3 : key field parent (for dependent lists)
  6237. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6238. // 5 : id category type
  6239. // 6 : ids categories list separated by comma for category root
  6240. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6241. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6242. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6243. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6244. } else {
  6245. $keyList = $InfoFieldList[2].' as rowid';
  6246. }
  6247. }
  6248. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6249. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6250. $keyList .= ', '.$parentField;
  6251. }
  6252. $filter_categorie = false;
  6253. if (count($InfoFieldList) > 5) {
  6254. if ($InfoFieldList[0] == 'categorie') {
  6255. $filter_categorie = true;
  6256. }
  6257. }
  6258. if ($filter_categorie === false) {
  6259. $fields_label = explode('|', $InfoFieldList[1]);
  6260. if (is_array($fields_label)) {
  6261. $keyList .= ', ';
  6262. $keyList .= implode(', ', $fields_label);
  6263. }
  6264. $sqlwhere = '';
  6265. $sql = "SELECT " . $keyList;
  6266. $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
  6267. if (!empty($InfoFieldList[4])) {
  6268. // can use SELECT request
  6269. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6270. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6271. }
  6272. // current object id can be use into filter
  6273. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6274. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6275. } else {
  6276. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6277. }
  6278. //We have to join on extrafield table
  6279. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6280. $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra";
  6281. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6282. } else {
  6283. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6284. }
  6285. } else {
  6286. $sqlwhere .= ' WHERE 1=1';
  6287. }
  6288. // Some tables may have field, some other not. For the moment we disable it.
  6289. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6290. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6291. }
  6292. $sql .= $sqlwhere;
  6293. //print $sql;
  6294. $sql .= ' ORDER BY ' . implode(', ', $fields_label);
  6295. dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
  6296. $resql = $this->db->query($sql);
  6297. if ($resql) {
  6298. $out .= '<option value="0">&nbsp;</option>';
  6299. $num = $this->db->num_rows($resql);
  6300. $i = 0;
  6301. while ($i < $num) {
  6302. $labeltoshow = '';
  6303. $obj = $this->db->fetch_object($resql);
  6304. // Several field into label (eq table:code|libelle:rowid)
  6305. $notrans = false;
  6306. $fields_label = explode('|', $InfoFieldList[1]);
  6307. if (count($fields_label) > 1) {
  6308. $notrans = true;
  6309. foreach ($fields_label as $field_toshow) {
  6310. $labeltoshow .= $obj->$field_toshow . ' ';
  6311. }
  6312. } else {
  6313. $labeltoshow = $obj->{$InfoFieldList[1]};
  6314. }
  6315. $labeltoshow = dol_trunc($labeltoshow, 45);
  6316. if ($value == $obj->rowid) {
  6317. foreach ($fields_label as $field_toshow) {
  6318. $translabel = $langs->trans($obj->$field_toshow);
  6319. if ($translabel != $obj->$field_toshow) {
  6320. $labeltoshow = dol_trunc($translabel) . ' ';
  6321. } else {
  6322. $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
  6323. }
  6324. }
  6325. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6326. } else {
  6327. if (!$notrans) {
  6328. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6329. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6330. $labeltoshow = dol_trunc($translabel, 18);
  6331. } else {
  6332. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
  6333. }
  6334. }
  6335. if (empty($labeltoshow)) {
  6336. $labeltoshow = '(not defined)';
  6337. }
  6338. if ($value == $obj->rowid) {
  6339. $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
  6340. }
  6341. if (!empty($InfoFieldList[3]) && $parentField) {
  6342. $parent = $parentName . ':' . $obj->{$parentField};
  6343. $isDependList = 1;
  6344. }
  6345. $out .= '<option value="' . $obj->rowid . '"';
  6346. $out .= ($value == $obj->rowid ? ' selected' : '');
  6347. $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
  6348. $out .= '>' . $labeltoshow . '</option>';
  6349. }
  6350. $i++;
  6351. }
  6352. $this->db->free($resql);
  6353. } else {
  6354. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6355. }
  6356. } else {
  6357. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6358. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6359. $out .= '<option value="0">&nbsp;</option>';
  6360. foreach ($data as $data_key => $data_value) {
  6361. $out .= '<option value="' . $data_key . '"';
  6362. $out .= ($value == $data_key ? ' selected' : '');
  6363. $out .= '>' . $data_value . '</option>';
  6364. }
  6365. }
  6366. }
  6367. $out .= '</select>';
  6368. } elseif ($type == 'checkbox') {
  6369. $value_arr = explode(',', $value);
  6370. $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
  6371. } elseif ($type == 'radio') {
  6372. $out = '';
  6373. foreach ($param['options'] as $keyopt => $valopt) {
  6374. $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
  6375. $out .= ' value="'.$keyopt.'"';
  6376. $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  6377. $out .= ($value == $keyopt ? 'checked' : '');
  6378. $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
  6379. }
  6380. } elseif ($type == 'chkbxlst') {
  6381. if (is_array($value)) {
  6382. $value_arr = $value;
  6383. } else {
  6384. $value_arr = explode(',', $value);
  6385. }
  6386. if (is_array($param['options'])) {
  6387. $param_list = array_keys($param['options']);
  6388. $InfoFieldList = explode(":", $param_list[0]);
  6389. $parentName = '';
  6390. $parentField = '';
  6391. // 0 : tableName
  6392. // 1 : label field name
  6393. // 2 : key fields name (if differ of rowid)
  6394. // 3 : key field parent (for dependent lists)
  6395. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  6396. // 5 : id category type
  6397. // 6 : ids categories list separated by comma for category root
  6398. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
  6399. if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
  6400. list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  6401. $keyList .= ', '.$parentField;
  6402. }
  6403. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6404. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  6405. $keyList = 'main.'.$InfoFieldList[2].' as rowid';
  6406. } else {
  6407. $keyList = $InfoFieldList[2].' as rowid';
  6408. }
  6409. }
  6410. $filter_categorie = false;
  6411. if (count($InfoFieldList) > 5) {
  6412. if ($InfoFieldList[0] == 'categorie') {
  6413. $filter_categorie = true;
  6414. }
  6415. }
  6416. if ($filter_categorie === false) {
  6417. $fields_label = explode('|', $InfoFieldList[1]);
  6418. if (is_array($fields_label)) {
  6419. $keyList .= ', ';
  6420. $keyList .= implode(', ', $fields_label);
  6421. }
  6422. $sqlwhere = '';
  6423. $sql = "SELECT " . $keyList;
  6424. $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
  6425. if (!empty($InfoFieldList[4])) {
  6426. // can use SELECT request
  6427. if (strpos($InfoFieldList[4], '$SEL$') !== false) {
  6428. $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
  6429. }
  6430. // current object id can be use into filter
  6431. if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
  6432. $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
  6433. } else {
  6434. $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
  6435. }
  6436. // We have to join on extrafield table
  6437. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6438. $sql .= ' as main, ' . $this->db->prefix() . $InfoFieldList[0] . '_extrafields as extra';
  6439. $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
  6440. } else {
  6441. $sqlwhere .= " WHERE " . $InfoFieldList[4];
  6442. }
  6443. } else {
  6444. $sqlwhere .= ' WHERE 1=1';
  6445. }
  6446. // Some tables may have field, some other not. For the moment we disable it.
  6447. if (in_array($InfoFieldList[0], array('tablewithentity'))) {
  6448. $sqlwhere .= " AND entity = " . ((int) $conf->entity);
  6449. }
  6450. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  6451. // print $sql;
  6452. $sql .= $sqlwhere;
  6453. dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
  6454. $resql = $this->db->query($sql);
  6455. if ($resql) {
  6456. $num = $this->db->num_rows($resql);
  6457. $i = 0;
  6458. $data = array();
  6459. while ($i < $num) {
  6460. $labeltoshow = '';
  6461. $obj = $this->db->fetch_object($resql);
  6462. $notrans = false;
  6463. // Several field into label (eq table:code|libelle:rowid)
  6464. $fields_label = explode('|', $InfoFieldList[1]);
  6465. if (count($fields_label) > 1) {
  6466. $notrans = true;
  6467. foreach ($fields_label as $field_toshow) {
  6468. $labeltoshow .= $obj->$field_toshow . ' ';
  6469. }
  6470. } else {
  6471. $labeltoshow = $obj->{$InfoFieldList[1]};
  6472. }
  6473. $labeltoshow = dol_trunc($labeltoshow, 45);
  6474. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6475. foreach ($fields_label as $field_toshow) {
  6476. $translabel = $langs->trans($obj->$field_toshow);
  6477. if ($translabel != $obj->$field_toshow) {
  6478. $labeltoshow = dol_trunc($translabel, 18) . ' ';
  6479. } else {
  6480. $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
  6481. }
  6482. }
  6483. $data[$obj->rowid] = $labeltoshow;
  6484. } else {
  6485. if (!$notrans) {
  6486. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6487. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6488. $labeltoshow = dol_trunc($translabel, 18);
  6489. } else {
  6490. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  6491. }
  6492. }
  6493. if (empty($labeltoshow)) {
  6494. $labeltoshow = '(not defined)';
  6495. }
  6496. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6497. $data[$obj->rowid] = $labeltoshow;
  6498. }
  6499. if (!empty($InfoFieldList[3]) && $parentField) {
  6500. $parent = $parentName . ':' . $obj->{$parentField};
  6501. $isDependList = 1;
  6502. }
  6503. $data[$obj->rowid] = $labeltoshow;
  6504. }
  6505. $i++;
  6506. }
  6507. $this->db->free($resql);
  6508. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6509. } else {
  6510. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  6511. }
  6512. } else {
  6513. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6514. $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
  6515. $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
  6516. }
  6517. }
  6518. } elseif ($type == 'link') {
  6519. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
  6520. $param_list_array = explode(':', $param_list[0]);
  6521. $showempty = (($required && $default != '') ? 0 : 1);
  6522. if (!preg_match('/search_/', $keyprefix)) {
  6523. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6524. if (!empty($this->fields[$key]['picto'])) {
  6525. $morecss .= ' widthcentpercentminusxx';
  6526. } else {
  6527. $morecss .= ' widthcentpercentminusx';
  6528. }
  6529. } else {
  6530. if (!empty($this->fields[$key]['picto'])) {
  6531. $morecss .= ' widthcentpercentminusx';
  6532. }
  6533. }
  6534. }
  6535. $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
  6536. if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
  6537. 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".
  6538. list($class, $classfile) = explode(':', $param_list[0]);
  6539. if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
  6540. $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
  6541. } else {
  6542. $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
  6543. }
  6544. $paramforthenewlink = '';
  6545. $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
  6546. $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
  6547. $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
  6548. $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
  6549. $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
  6550. // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
  6551. $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>';
  6552. }
  6553. }
  6554. } elseif ($type == 'password') {
  6555. // If prefix is 'search_', field is used as a filter, we use a common text field.
  6556. $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
  6557. } elseif ($type == 'array') {
  6558. $newval = $val;
  6559. $newval['type'] = 'varchar(256)';
  6560. $out = '';
  6561. if (!empty($value)) {
  6562. foreach ($value as $option) {
  6563. $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6564. $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
  6565. }
  6566. }
  6567. $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  6568. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  6569. $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
  6570. if (!empty($conf->use_javascript_ajax)) {
  6571. $out .= '
  6572. <script>
  6573. $(document).ready(function() {
  6574. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  6575. $("'.dol_escape_js($newInput).'").insertBefore(this);
  6576. });
  6577. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  6578. $(this).parent().remove();
  6579. });
  6580. });
  6581. </script>';
  6582. }
  6583. }
  6584. if (!empty($hidden)) {
  6585. $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  6586. }
  6587. if ($isDependList==1) {
  6588. $out .= $this->getJSListDependancies('_common');
  6589. }
  6590. /* Add comments
  6591. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  6592. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  6593. */
  6594. // Display error message for field
  6595. if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
  6596. $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
  6597. }
  6598. return $out;
  6599. }
  6600. /**
  6601. * Return HTML string to show a field into a page
  6602. * Code very similar with showOutputField of extra fields
  6603. *
  6604. * @param array $val Array of properties of field to show
  6605. * @param string $key Key of attribute
  6606. * @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)
  6607. * @param string $moreparam To add more parametes on html input tag
  6608. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  6609. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  6610. * @param mixed $morecss Value for css to define size. May also be a numeric.
  6611. * @return string
  6612. */
  6613. public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
  6614. {
  6615. global $conf, $langs, $form;
  6616. if (!is_object($form)) {
  6617. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  6618. $form = new Form($this->db);
  6619. }
  6620. $objectid = $this->id; // Not used ???
  6621. $label = empty($val['label']) ? '' : $val['label'];
  6622. $type = empty($val['type']) ? '' : $val['type'];
  6623. $size = empty($val['css']) ? '' : $val['css'];
  6624. $reg = array();
  6625. // Convert var to be able to share same code than showOutputField of extrafields
  6626. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  6627. $type = 'varchar'; // convert varchar(xx) int varchar
  6628. $size = $reg[1];
  6629. } elseif (preg_match('/varchar/', $type)) {
  6630. $type = 'varchar'; // convert varchar(xx) int varchar
  6631. }
  6632. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6633. $type = 'select';
  6634. }
  6635. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6636. $type = 'link';
  6637. }
  6638. $default = empty($val['default']) ? '' : $val['default'];
  6639. $computed = empty($val['computed']) ? '' : $val['computed'];
  6640. $unique = empty($val['unique']) ? '' : $val['unique'];
  6641. $required = empty($val['required']) ? '' : $val['required'];
  6642. $param = array();
  6643. $param['options'] = array();
  6644. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  6645. $param['options'] = $val['arrayofkeyval'];
  6646. }
  6647. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  6648. $type = 'link';
  6649. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  6650. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6651. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  6652. $type = 'sellist';
  6653. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  6654. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  6655. $type = 'sellist';
  6656. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  6657. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  6658. $type = 'sellist';
  6659. } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
  6660. $param['options'] = array($reg[1] => 'N');
  6661. $type = 'chkbxlst';
  6662. }
  6663. $langfile = empty($val['langfile']) ? '' : $val['langfile'];
  6664. $list = (empty($val['list']) ? '' : $val['list']);
  6665. $help = (empty($val['help']) ? '' : $val['help']);
  6666. $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)
  6667. if ($hidden) {
  6668. return '';
  6669. }
  6670. // If field is a computed field, value must become result of compute
  6671. if ($computed) {
  6672. // Make the eval of compute string
  6673. //var_dump($computed);
  6674. $value = dol_eval($computed, 1, 0, '');
  6675. }
  6676. if (empty($morecss)) {
  6677. if ($type == 'date') {
  6678. $morecss = 'minwidth100imp';
  6679. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6680. $morecss = 'minwidth200imp';
  6681. } elseif (in_array($type, array('int', 'double', 'price'))) {
  6682. $morecss = 'maxwidth75';
  6683. } elseif ($type == 'url') {
  6684. $morecss = 'minwidth400';
  6685. } elseif ($type == 'boolean') {
  6686. $morecss = '';
  6687. } else {
  6688. if (is_numeric($size) && round($size) < 12) {
  6689. $morecss = 'minwidth100';
  6690. } elseif (is_numeric($size) && round($size) <= 48) {
  6691. $morecss = 'minwidth200';
  6692. } else {
  6693. $morecss = 'minwidth400';
  6694. }
  6695. }
  6696. }
  6697. // Format output value differently according to properties of field
  6698. if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
  6699. 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.
  6700. $value = $this->getNomUrl(1, '', 0, '', 1);
  6701. }
  6702. } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
  6703. $value = $this->getLibStatut(3);
  6704. } elseif ($type == 'date') {
  6705. if (!empty($value)) {
  6706. $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
  6707. } else {
  6708. $value = '';
  6709. }
  6710. } elseif ($type == 'datetime' || $type == 'timestamp') {
  6711. if (!empty($value)) {
  6712. $value = date('Y-m-d H:i:s', $value);
  6713. //$value = dol_print_date($value, 'dayhour', 'tzuserrel');
  6714. } else {
  6715. $value = '';
  6716. }
  6717. } elseif ($type == 'duration') {
  6718. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6719. if (!is_null($value) && $value !== '') {
  6720. $value = convertSecondToTime($value, 'allhourmin');
  6721. }
  6722. } elseif ($type == 'double' || $type == 'real') {
  6723. if (!is_null($value) && $value !== '') {
  6724. $value = price($value);
  6725. }
  6726. } elseif ($type == 'boolean') {
  6727. $checked = '';
  6728. if (!empty($value)) {
  6729. $checked = ' checked ';
  6730. }
  6731. $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
  6732. } elseif ($type == 'mail' || $type == 'email') {
  6733. $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
  6734. } elseif ($type == 'url') {
  6735. $value = dol_print_url($value, '_blank', 32, 1);
  6736. } elseif ($type == 'phone') {
  6737. $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
  6738. } elseif ($type == 'ip') {
  6739. $value = dol_print_ip($value, 0);
  6740. } elseif ($type == 'price') {
  6741. if (!is_null($value) && $value !== '') {
  6742. $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
  6743. }
  6744. } elseif ($type == 'select') {
  6745. $value = isset($param['options'][$value])?$param['options'][$value]:'';
  6746. } elseif ($type == 'sellist') {
  6747. $param_list = array_keys($param['options']);
  6748. $InfoFieldList = explode(":", $param_list[0]);
  6749. $selectkey = "rowid";
  6750. $keyList = 'rowid';
  6751. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  6752. $selectkey = $InfoFieldList[2];
  6753. $keyList = $InfoFieldList[2].' as rowid';
  6754. }
  6755. $fields_label = explode('|', $InfoFieldList[1]);
  6756. if (is_array($fields_label)) {
  6757. $keyList .= ', ';
  6758. $keyList .= implode(', ', $fields_label);
  6759. }
  6760. $filter_categorie = false;
  6761. if (count($InfoFieldList) > 5) {
  6762. if ($InfoFieldList[0] == 'categorie') {
  6763. $filter_categorie = true;
  6764. }
  6765. }
  6766. $sql = "SELECT ".$keyList;
  6767. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6768. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6769. $sql .= ' as main';
  6770. }
  6771. if ($selectkey == 'rowid' && empty($value)) {
  6772. $sql .= " WHERE ".$selectkey." = 0";
  6773. } elseif ($selectkey == 'rowid') {
  6774. $sql .= " WHERE ".$selectkey." = ".((int) $value);
  6775. } else {
  6776. $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
  6777. }
  6778. //$sql.= ' AND entity = '.$conf->entity;
  6779. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  6780. $resql = $this->db->query($sql);
  6781. if ($resql) {
  6782. if ($filter_categorie === false) {
  6783. $value = ''; // value was used, so now we reste it to use it to build final output
  6784. $numrows = $this->db->num_rows($resql);
  6785. if ($numrows) {
  6786. $obj = $this->db->fetch_object($resql);
  6787. // Several field into label (eq table:code|libelle:rowid)
  6788. $fields_label = explode('|', $InfoFieldList[1]);
  6789. if (is_array($fields_label) && count($fields_label) > 1) {
  6790. foreach ($fields_label as $field_toshow) {
  6791. $translabel = '';
  6792. if (!empty($obj->$field_toshow)) {
  6793. $translabel = $langs->trans($obj->$field_toshow);
  6794. }
  6795. if ($translabel != $field_toshow) {
  6796. $value .= dol_trunc($translabel, 18) . ' ';
  6797. } else {
  6798. $value .= $obj->$field_toshow . ' ';
  6799. }
  6800. }
  6801. } else {
  6802. $translabel = '';
  6803. if (!empty($obj->{$InfoFieldList[1]})) {
  6804. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6805. }
  6806. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6807. $value = dol_trunc($translabel, 18);
  6808. } else {
  6809. $value = $obj->{$InfoFieldList[1]};
  6810. }
  6811. }
  6812. }
  6813. } else {
  6814. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6815. $toprint = array();
  6816. $obj = $this->db->fetch_object($resql);
  6817. $c = new Categorie($this->db);
  6818. $c->fetch($obj->rowid);
  6819. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  6820. foreach ($ways as $way) {
  6821. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  6822. }
  6823. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6824. }
  6825. } else {
  6826. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6827. }
  6828. } elseif ($type == 'radio') {
  6829. $value = $param['options'][$value];
  6830. } elseif ($type == 'checkbox') {
  6831. $value_arr = explode(',', $value);
  6832. $value = '';
  6833. if (is_array($value_arr) && count($value_arr) > 0) {
  6834. $toprint = array();
  6835. foreach ($value_arr as $keyval => $valueval) {
  6836. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">'.$param['options'][$valueval].'</li>';
  6837. }
  6838. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6839. }
  6840. } elseif ($type == 'chkbxlst') {
  6841. $value_arr = explode(',', $value);
  6842. $param_list = array_keys($param['options']);
  6843. $InfoFieldList = explode(":", $param_list[0]);
  6844. $selectkey = "rowid";
  6845. $keyList = 'rowid';
  6846. if (count($InfoFieldList) >= 3) {
  6847. $selectkey = $InfoFieldList[2];
  6848. $keyList = $InfoFieldList[2].' as rowid';
  6849. }
  6850. $fields_label = explode('|', $InfoFieldList[1]);
  6851. if (is_array($fields_label)) {
  6852. $keyList .= ', ';
  6853. $keyList .= implode(', ', $fields_label);
  6854. }
  6855. $filter_categorie = false;
  6856. if (count($InfoFieldList) > 5) {
  6857. if ($InfoFieldList[0] == 'categorie') {
  6858. $filter_categorie = true;
  6859. }
  6860. }
  6861. $sql = "SELECT ".$keyList;
  6862. $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
  6863. if (strpos($InfoFieldList[4], 'extra') !== false) {
  6864. $sql .= ' as main';
  6865. }
  6866. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  6867. // $sql.= ' AND entity = '.$conf->entity;
  6868. dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
  6869. $resql = $this->db->query($sql);
  6870. if ($resql) {
  6871. if ($filter_categorie === false) {
  6872. $value = ''; // value was used, so now we reste it to use it to build final output
  6873. $toprint = array();
  6874. while ($obj = $this->db->fetch_object($resql)) {
  6875. // Several field into label (eq table:code|libelle:rowid)
  6876. $fields_label = explode('|', $InfoFieldList[1]);
  6877. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6878. if (is_array($fields_label) && count($fields_label) > 1) {
  6879. foreach ($fields_label as $field_toshow) {
  6880. $translabel = '';
  6881. if (!empty($obj->$field_toshow)) {
  6882. $translabel = $langs->trans($obj->$field_toshow);
  6883. }
  6884. if ($translabel != $field_toshow) {
  6885. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  6886. } else {
  6887. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
  6888. }
  6889. }
  6890. } else {
  6891. $translabel = '';
  6892. if (!empty($obj->{$InfoFieldList[1]})) {
  6893. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  6894. }
  6895. if ($translabel != $obj->{$InfoFieldList[1]}) {
  6896. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
  6897. } else {
  6898. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
  6899. }
  6900. }
  6901. }
  6902. }
  6903. } else {
  6904. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  6905. $toprint = array();
  6906. while ($obj = $this->db->fetch_object($resql)) {
  6907. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  6908. $c = new Categorie($this->db);
  6909. $c->fetch($obj->rowid);
  6910. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
  6911. foreach ($ways as $way) {
  6912. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
  6913. }
  6914. }
  6915. }
  6916. }
  6917. $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6918. } else {
  6919. dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  6920. }
  6921. } elseif ($type == 'link') {
  6922. $out = '';
  6923. // only if something to display (perf)
  6924. if ($value) {
  6925. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  6926. $InfoFieldList = explode(":", $param_list[0]);
  6927. $classname = $InfoFieldList[0];
  6928. $classpath = $InfoFieldList[1];
  6929. $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  6930. $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
  6931. if (!empty($classpath)) {
  6932. dol_include_once($InfoFieldList[1]);
  6933. if ($classname && class_exists($classname)) {
  6934. $object = new $classname($this->db);
  6935. if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
  6936. $result = $object->fetch($value, '', '', '', 0, 1, 1);
  6937. } else {
  6938. $result = $object->fetch($value);
  6939. }
  6940. if ($result > 0) {
  6941. if ($object->element === 'product') {
  6942. $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
  6943. if (isset($val['get_name_url_params'])) {
  6944. $get_name_url_params = explode(':', $val['get_name_url_params']);
  6945. if (!empty($get_name_url_params)) {
  6946. $param_num_max = count($get_name_url_param_arr) - 1;
  6947. foreach ($get_name_url_params as $param_num => $param_value) {
  6948. if ($param_num > $param_num_max) {
  6949. break;
  6950. }
  6951. $get_name_url_param_arr[$param_num] = $param_value;
  6952. }
  6953. }
  6954. }
  6955. /**
  6956. * @var Product $object
  6957. */
  6958. $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]);
  6959. } else {
  6960. $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
  6961. }
  6962. } else {
  6963. $value = '';
  6964. }
  6965. }
  6966. } else {
  6967. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  6968. return 'Error bad setup of extrafield';
  6969. }
  6970. } else {
  6971. $value = '';
  6972. }
  6973. } elseif ($type == 'password') {
  6974. $value = preg_replace('/./i', '*', $value);
  6975. } elseif ($type == 'array') {
  6976. $value = implode('<br>', $value);
  6977. } else { // text|html|varchar
  6978. $value = dol_htmlentitiesbr($value);
  6979. }
  6980. //print $type.'-'.$size.'-'.$value;
  6981. $out = $value;
  6982. return $out;
  6983. }
  6984. /**
  6985. * clear validation message result for a field
  6986. *
  6987. * @param string $fieldKey Key of attribute to clear
  6988. * @return null
  6989. */
  6990. public function clearFieldError($fieldKey)
  6991. {
  6992. $this->error = '';
  6993. unset($this->validateFieldsErrors[$fieldKey]);
  6994. }
  6995. /**
  6996. * set validation error message a field
  6997. *
  6998. * @param string $fieldKey Key of attribute
  6999. * @param string $msg the field error message
  7000. * @return null
  7001. */
  7002. public function setFieldError($fieldKey, $msg = '')
  7003. {
  7004. global $langs;
  7005. if (empty($msg)) { $msg = $langs->trans("UnknowError"); }
  7006. $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
  7007. }
  7008. /**
  7009. * get field error message
  7010. *
  7011. * @param string $fieldKey Key of attribute
  7012. * @return string Error message of validation ('' if no error)
  7013. */
  7014. public function getFieldError($fieldKey)
  7015. {
  7016. if (!empty($this->validateFieldsErrors[$fieldKey])) {
  7017. return $this->validateFieldsErrors[$fieldKey];
  7018. }
  7019. return '';
  7020. }
  7021. /**
  7022. * Return validation test result for a field
  7023. *
  7024. * @param array $val Array of properties of field to show
  7025. * @param string $fieldKey Key of attribute
  7026. * @param string $fieldValue value of attribute
  7027. * @return bool return false if fail true on success, see $this->error for error message
  7028. */
  7029. public function validateField($val, $fieldKey, $fieldValue)
  7030. {
  7031. global $langs;
  7032. if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
  7033. $this->clearFieldError($fieldKey);
  7034. if (!isset($val[$fieldKey])) {
  7035. $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
  7036. return false;
  7037. }
  7038. $param = array();
  7039. $param['options'] = array();
  7040. $type = $val[$fieldKey]['type'];
  7041. $required = false;
  7042. if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
  7043. // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  7044. $required = true;
  7045. }
  7046. $maxSize = 0;
  7047. $minSize = 0;
  7048. //
  7049. // PREPARE Elements
  7050. //
  7051. // Convert var to be able to share same code than showOutputField of extrafields
  7052. if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
  7053. $type = 'varchar'; // convert varchar(xx) int varchar
  7054. $maxSize = $reg[1];
  7055. } elseif (preg_match('/varchar/', $type)) {
  7056. $type = 'varchar'; // convert varchar(xx) int varchar
  7057. }
  7058. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7059. $type = 'select';
  7060. }
  7061. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7062. $type = 'link';
  7063. }
  7064. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  7065. $param['options'] = $val['arrayofkeyval'];
  7066. }
  7067. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
  7068. $type = 'link';
  7069. $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  7070. } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7071. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
  7072. $type = 'sellist';
  7073. } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
  7074. $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
  7075. $type = 'sellist';
  7076. } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
  7077. $param['options'] = array($reg[1].':'.$reg[2] => 'N');
  7078. $type = 'sellist';
  7079. }
  7080. //
  7081. // TEST Value
  7082. //
  7083. // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
  7084. $validate = new Validate($this->db, $langs);
  7085. // little trick : to perform tests with good performances sort tests by quick to low
  7086. //
  7087. // COMMON TESTS
  7088. //
  7089. // Required test and empty value
  7090. if ($required && !$validate->isNotEmptyString($fieldValue)) {
  7091. $this->setFieldError($fieldKey, $validate->error);
  7092. return false;
  7093. } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
  7094. // if no value sent and the field is not mandatory, no need to perform tests
  7095. return true;
  7096. }
  7097. // MAX Size test
  7098. if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
  7099. $this->setFieldError($fieldKey, $validate->error);
  7100. return false;
  7101. }
  7102. // MIN Size test
  7103. if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
  7104. $this->setFieldError($fieldKey, $validate->error);
  7105. return false;
  7106. }
  7107. //
  7108. // TESTS for TYPE
  7109. //
  7110. if (in_array($type, array('date', 'datetime', 'timestamp'))) {
  7111. if (!$validate->isTimestamp($fieldValue)) {
  7112. $this->setFieldError($fieldKey, $validate->error);
  7113. return false;
  7114. } else { return true; }
  7115. } elseif ($type == 'duration') {
  7116. if (!$validate->isDuration($fieldValue)) {
  7117. $this->setFieldError($fieldKey, $validate->error);
  7118. return false;
  7119. } else { return true; }
  7120. } elseif (in_array($type, array('double', 'real', 'price'))) {
  7121. // is numeric
  7122. if (!$validate->isNumeric($fieldValue)) {
  7123. $this->setFieldError($fieldKey, $validate->error);
  7124. return false;
  7125. } else { return true; }
  7126. } elseif ($type == 'boolean') {
  7127. if (!$validate->isBool($fieldValue)) {
  7128. $this->setFieldError($fieldKey, $validate->error);
  7129. return false;
  7130. } else { return true; }
  7131. } elseif ($type == 'mail') {
  7132. if (!$validate->isEmail($fieldValue)) {
  7133. $this->setFieldError($fieldKey, $validate->error);
  7134. return false;
  7135. }
  7136. } elseif ($type == 'url') {
  7137. if (!$validate->isUrl($fieldValue)) {
  7138. $this->setFieldError($fieldKey, $validate->error);
  7139. return false;
  7140. } else { return true; }
  7141. } elseif ($type == 'phone') {
  7142. if (!$validate->isPhone($fieldValue)) {
  7143. $this->setFieldError($fieldKey, $validate->error);
  7144. return false;
  7145. } else { return true; }
  7146. } elseif ($type == 'select' || $type == 'radio') {
  7147. if (!isset($param['options'][$fieldValue])) {
  7148. $this->error = $langs->trans('RequireValidValue');
  7149. return false;
  7150. } else { return true; }
  7151. } elseif ($type == 'sellist' || $type == 'chkbxlst') {
  7152. $param_list = array_keys($param['options']);
  7153. $InfoFieldList = explode(":", $param_list[0]);
  7154. $value_arr = explode(',', $fieldValue);
  7155. $value_arr = array_map(array($this->db, 'escape'), $value_arr);
  7156. $selectkey = "rowid";
  7157. if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
  7158. $selectkey = $InfoFieldList[2];
  7159. }
  7160. if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
  7161. $this->setFieldError($fieldKey, $validate->error);
  7162. return false;
  7163. } else { return true; }
  7164. } elseif ($type == 'link') {
  7165. $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
  7166. $InfoFieldList = explode(":", $param_list[0]);
  7167. $classname = $InfoFieldList[0];
  7168. $classpath = $InfoFieldList[1];
  7169. if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
  7170. $this->setFieldError($fieldKey, $validate->error);
  7171. return false;
  7172. } else { return true; }
  7173. }
  7174. // if no test failled all is ok
  7175. return true;
  7176. }
  7177. /**
  7178. * Function to show lines of extrafields with output datas.
  7179. * 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
  7180. *
  7181. * @param Extrafields $extrafields Extrafield Object
  7182. * @param string $mode Show output ('view') or input ('create' or 'edit') for extrafield
  7183. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  7184. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  7185. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  7186. * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example.
  7187. * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...)
  7188. * @return string String with html content to show
  7189. */
  7190. public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
  7191. {
  7192. global $db, $conf, $langs, $action, $form, $hookmanager;
  7193. if (!is_object($form)) {
  7194. $form = new Form($db);
  7195. }
  7196. if (!is_object($extrafields)) {
  7197. dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
  7198. return 'Bad parameter extrafields for showOptionals';
  7199. }
  7200. if (!is_array($extrafields->attributes[$this->table_element])) {
  7201. dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
  7202. }
  7203. $out = '';
  7204. $parameters = array('mode'=>$mode, 'params'=>$params, 'keysuffix'=>$keysuffix, 'keyprefix'=>$keyprefix, 'display_type'=>$display_type);
  7205. $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
  7206. if (empty($reshook)) {
  7207. 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) {
  7208. $out .= "\n";
  7209. $out .= '<!-- commonobject:showOptionals --> ';
  7210. $out .= "\n";
  7211. $nbofextrafieldsshown = 0;
  7212. $extrafields_collapse_num = '';
  7213. $e = 0; // var to manage the modulo (odd/even)
  7214. foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
  7215. // Show only the key field in params
  7216. if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
  7217. continue;
  7218. }
  7219. // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
  7220. $enabled = 1;
  7221. if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
  7222. $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
  7223. }
  7224. if (empty($enabled)) {
  7225. continue;
  7226. }
  7227. $visibility = 1;
  7228. if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
  7229. $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
  7230. }
  7231. $perms = 1;
  7232. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
  7233. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
  7234. }
  7235. if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
  7236. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  7237. } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
  7238. continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
  7239. } elseif ($mode == 'view' && empty($visibility)) {
  7240. continue;
  7241. }
  7242. if (empty($perms)) {
  7243. continue;
  7244. }
  7245. // Load language if required
  7246. if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
  7247. $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  7248. }
  7249. $colspan = 0;
  7250. if (is_array($params) && count($params) > 0 && $display_type=='card') {
  7251. if (array_key_exists('cols', $params)) {
  7252. $colspan = $params['cols'];
  7253. } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
  7254. $reg = array();
  7255. if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
  7256. $colspan = $reg[1];
  7257. } else {
  7258. $colspan = $params['colspan'];
  7259. }
  7260. }
  7261. }
  7262. $colspan = intval($colspan);
  7263. switch ($mode) {
  7264. case "view":
  7265. $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
  7266. break;
  7267. case "create":
  7268. case "edit":
  7269. // We get the value of property found with GETPOST so it takes into account:
  7270. // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
  7271. $check = 'alphanohtml';
  7272. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
  7273. $check = 'restricthtml';
  7274. }
  7275. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
  7276. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  7277. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
  7278. if (is_array($getposttemp)) {
  7279. // $getposttemp is an array but following code expects a comma separated string
  7280. $value = implode(",", $getposttemp);
  7281. } else {
  7282. $value = $getposttemp;
  7283. }
  7284. } else {
  7285. $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.
  7286. }
  7287. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  7288. break;
  7289. }
  7290. $nbofextrafieldsshown++;
  7291. // Output value of the current field
  7292. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
  7293. $extrafields_collapse_num = '';
  7294. $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
  7295. if (!empty($extrafield_param) && is_array($extrafield_param)) {
  7296. $extrafield_param_list = array_keys($extrafield_param['options']);
  7297. if (count($extrafield_param_list) > 0) {
  7298. $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
  7299. if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
  7300. $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
  7301. }
  7302. }
  7303. }
  7304. // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
  7305. $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
  7306. } else {
  7307. $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  7308. $csstyle = '';
  7309. if (is_array($params) && count($params) > 0) {
  7310. if (array_key_exists('class', $params)) {
  7311. $class .= $params['class'].' ';
  7312. }
  7313. if (array_key_exists('style', $params)) {
  7314. $csstyle = $params['style'];
  7315. }
  7316. }
  7317. // add html5 elements
  7318. $domData = ' data-element="extrafield"';
  7319. $domData .= ' data-targetelement="'.$this->element.'"';
  7320. $domData .= ' data-targetid="'.$this->id.'"';
  7321. $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
  7322. if ($display_type=='card') {
  7323. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
  7324. $colspan = 0;
  7325. }
  7326. if ($action == 'selectlines') {
  7327. $colspan++;
  7328. }
  7329. }
  7330. // Convert date into timestamp format (value in memory must be a timestamp)
  7331. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
  7332. $datenotinstring = null;
  7333. if (array_key_exists('options_'.$key, $this->array_options)) {
  7334. $datenotinstring = $this->array_options['options_'.$key];
  7335. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7336. $datenotinstring = $this->db->jdate($datenotinstring);
  7337. }
  7338. }
  7339. $datekey = $keyprefix.'options_'.$key.$keysuffix;
  7340. $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
  7341. }
  7342. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
  7343. $datenotinstring = null;
  7344. if (array_key_exists('options_'.$key, $this->array_options)) {
  7345. $datenotinstring = $this->array_options['options_'.$key];
  7346. if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
  7347. $datenotinstring = $this->db->jdate($datenotinstring);
  7348. }
  7349. }
  7350. $timekey = $keyprefix.'options_'.$key.$keysuffix;
  7351. $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;
  7352. }
  7353. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  7354. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
  7355. if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
  7356. $value = price2num($value);
  7357. } elseif (isset($this->array_options['options_'.$key])) {
  7358. $value = $this->array_options['options_'.$key];
  7359. }
  7360. }
  7361. // HTML, text, select, integer and varchar: take into account default value in database if in create mode
  7362. if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
  7363. if ($action == 'create') {
  7364. $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
  7365. }
  7366. }
  7367. $labeltoshow = $langs->trans($label);
  7368. $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
  7369. if ($display_type == 'card') {
  7370. $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.' >';
  7371. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
  7372. $out .= '<td></td>';
  7373. }
  7374. $out .= '<td class="'.(empty($params['tdclass']) ? 'titlefieldcreate' : $params['tdclass']).' wordbreak';
  7375. } elseif ($display_type == 'line') {
  7376. $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.' >';
  7377. $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
  7378. }
  7379. //$out .= "titlefield";
  7380. //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
  7381. // BUG #11554 : For public page, use red dot for required fields, instead of bold label
  7382. $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
  7383. if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
  7384. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7385. $out .= ' fieldrequired';
  7386. }
  7387. }
  7388. $out .= '">';
  7389. if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
  7390. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7391. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7392. } else {
  7393. $out .= $labeltoshow;
  7394. }
  7395. if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
  7396. $out .= '&nbsp;<span style="color: red">*</span>';
  7397. }
  7398. } else {
  7399. if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
  7400. $out .= $form->textwithpicto($labeltoshow, $helptoshow);
  7401. } else {
  7402. $out .= $labeltoshow;
  7403. }
  7404. }
  7405. $out .= ($display_type == 'card' ? '</td>' : '</div>');
  7406. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  7407. if ($display_type == 'card') {
  7408. // 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
  7409. $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
  7410. } elseif ($display_type == 'line') {
  7411. $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].'">';
  7412. }
  7413. switch ($mode) {
  7414. case "view":
  7415. $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
  7416. break;
  7417. case "create":
  7418. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7419. break;
  7420. case "edit":
  7421. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
  7422. break;
  7423. }
  7424. $out .= ($display_type=='card' ? '</td>' : '</div>');
  7425. if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
  7426. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7427. } else {
  7428. $out .= ($display_type=='card' ? '</tr>' : '</div>');
  7429. }
  7430. $e++;
  7431. }
  7432. }
  7433. $out .= "\n";
  7434. // Add code to manage list depending on others
  7435. if (!empty($conf->use_javascript_ajax)) {
  7436. $out .= $this->getJSListDependancies();
  7437. }
  7438. $out .= '<!-- commonobject:showOptionals end --> '."\n";
  7439. if (empty($nbofextrafieldsshown)) {
  7440. $out = '';
  7441. }
  7442. }
  7443. }
  7444. $out .= $hookmanager->resPrint;
  7445. return $out;
  7446. }
  7447. /**
  7448. * @param string $type Type for prefix
  7449. * @return string Javacript code to manage dependency
  7450. */
  7451. public function getJSListDependancies($type = '_extra')
  7452. {
  7453. $out = '
  7454. <script>
  7455. jQuery(document).ready(function() {
  7456. function showOptions'.$type.'(child_list, parent_list, orig_select)
  7457. {
  7458. var val = $("select[name=\""+parent_list+"\"]").val();
  7459. var parentVal = parent_list + ":" + val;
  7460. if(typeof val == "string"){
  7461. if(val != "") {
  7462. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7463. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7464. $("select[name=\""+child_list+"\"]").append(options);
  7465. } else {
  7466. var options = orig_select.find("option[parent]").clone();
  7467. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7468. $("select[name=\""+child_list+"\"]").append(options);
  7469. }
  7470. } else if(val > 0) {
  7471. var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
  7472. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7473. $("select[name=\""+child_list+"\"]").append(options);
  7474. } else {
  7475. var options = orig_select.find("option[parent]").clone();
  7476. $("select[name=\""+child_list+"\"] option[parent]").remove();
  7477. $("select[name=\""+child_list+"\"]").append(options);
  7478. }
  7479. }
  7480. function setListDependencies'.$type.'() {
  7481. jQuery("select option[parent]").parent().each(function() {
  7482. var orig_select = {};
  7483. var child_list = $(this).attr("name");
  7484. orig_select[child_list] = $(this).clone();
  7485. var parent = $(this).find("option[parent]:first").attr("parent");
  7486. var infos = parent.split(":");
  7487. var parent_list = infos[0];
  7488. //Hide daughters lists
  7489. if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
  7490. $("#"+child_list).hide();
  7491. //Show mother lists
  7492. } else if ($("#"+parent_list).val() != 0){
  7493. $("#"+parent_list).show();
  7494. }
  7495. //Show the child list if the parent list value is selected
  7496. $("select[name=\""+parent_list+"\"]").click(function() {
  7497. if ($(this).val() != 0){
  7498. $("#"+child_list).show()
  7499. }
  7500. });
  7501. //When we change parent list
  7502. $("select[name=\""+parent_list+"\"]").change(function() {
  7503. showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
  7504. //Select the value 0 on child list after a change on the parent list
  7505. $("#"+child_list).val(0).trigger("change");
  7506. //Hide child lists if the parent value is set to 0
  7507. if ($(this).val() == 0){
  7508. $("#"+child_list).hide();
  7509. }
  7510. });
  7511. });
  7512. }
  7513. setListDependencies'.$type.'();
  7514. });
  7515. </script>'."\n";
  7516. return $out;
  7517. }
  7518. /**
  7519. * Returns the rights used for this class
  7520. * @return stdClass
  7521. */
  7522. public function getRights()
  7523. {
  7524. global $user;
  7525. $element = $this->element;
  7526. if ($element == 'facturerec') {
  7527. $element = 'facture';
  7528. } elseif ($element == 'invoice_supplier_rec') {
  7529. return $user->rights->fournisseur->facture;
  7530. } elseif ($element == 'evaluation') {
  7531. return $user->rights->hrm->evaluation;
  7532. }
  7533. return $user->rights->{$element};
  7534. }
  7535. /**
  7536. * Function used to replace a thirdparty id with another one.
  7537. * This function is meant to be called from replaceThirdparty with the appropriate tables
  7538. * Column name fk_soc MUST be used to identify thirdparties
  7539. *
  7540. * @param DoliDB $db Database handler
  7541. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  7542. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  7543. * @param string[] $tables Tables that need to be changed
  7544. * @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)
  7545. * @return bool True if success, False if error
  7546. */
  7547. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7548. {
  7549. foreach ($tables as $table) {
  7550. $sql = 'UPDATE '.$db->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
  7551. if (!$db->query($sql)) {
  7552. if ($ignoreerrors) {
  7553. 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.
  7554. }
  7555. //$this->errors = $db->lasterror();
  7556. return false;
  7557. }
  7558. }
  7559. return true;
  7560. }
  7561. /**
  7562. * Function used to replace a product id with another one.
  7563. * This function is meant to be called from replaceProduct with the appropriate tables
  7564. * Column name fk_product MUST be used to identify products
  7565. *
  7566. * @param DoliDB $db Database handler
  7567. * @param int $origin_id Old product id (the product to delete)
  7568. * @param int $dest_id New product id (the product that will received element of the other)
  7569. * @param string[] $tables Tables that need to be changed
  7570. * @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)
  7571. * @return bool True if success, False if error
  7572. */
  7573. public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
  7574. {
  7575. foreach ($tables as $table) {
  7576. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
  7577. if (!$db->query($sql)) {
  7578. if ($ignoreerrors) {
  7579. 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.
  7580. }
  7581. //$this->errors = $db->lasterror();
  7582. return false;
  7583. }
  7584. }
  7585. return true;
  7586. }
  7587. /**
  7588. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  7589. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  7590. * elseif calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  7591. * elseif calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  7592. * else set min buy price as buy price
  7593. *
  7594. * @param float $unitPrice Product unit price
  7595. * @param float $discountPercent Line discount percent
  7596. * @param int $fk_product Product id
  7597. * @return float <0 if KO, buyprice if OK
  7598. */
  7599. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  7600. {
  7601. global $conf;
  7602. $buyPrice = 0;
  7603. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
  7604. // When ForceBuyingPriceIfNull is set
  7605. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  7606. } else {
  7607. // Get cost price for margin calculation
  7608. if (!empty($fk_product) && $fk_product > 0) {
  7609. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
  7610. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7611. $product = new Product($this->db);
  7612. $result = $product->fetch($fk_product);
  7613. if ($result <= 0) {
  7614. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7615. return -1;
  7616. }
  7617. if ($product->cost_price > 0) {
  7618. $buyPrice = $product->cost_price;
  7619. } elseif ($product->pmp > 0) {
  7620. $buyPrice = $product->pmp;
  7621. }
  7622. } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
  7623. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  7624. $product = new Product($this->db);
  7625. $result = $product->fetch($fk_product);
  7626. if ($result <= 0) {
  7627. $this->errors[] = 'ErrorProductIdDoesNotExists';
  7628. return -1;
  7629. }
  7630. if ($product->pmp > 0) {
  7631. $buyPrice = $product->pmp;
  7632. }
  7633. }
  7634. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
  7635. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  7636. $productFournisseur = new ProductFournisseur($this->db);
  7637. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
  7638. $buyPrice = $productFournisseur->fourn_unitprice;
  7639. } elseif ($result < 0) {
  7640. $this->errors[] = $productFournisseur->error;
  7641. return -2;
  7642. }
  7643. }
  7644. }
  7645. }
  7646. return $buyPrice;
  7647. }
  7648. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7649. /**
  7650. * Show photos of an object (nbmax maximum), into several columns
  7651. *
  7652. * @param string $modulepart 'product', 'ticket', ...
  7653. * @param string $sdir Directory to scan (full absolute path)
  7654. * @param int $size 0=original size, 1='small' use thumbnail if possible
  7655. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  7656. * @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'.
  7657. * @param int $showfilename 1=Show filename
  7658. * @param int $showaction 1=Show icon with action links (resize, delete)
  7659. * @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.
  7660. * @param int $maxWidth Max width of original image when size='small'
  7661. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  7662. * @param int $notitle Do not add title tag on image
  7663. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  7664. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  7665. */
  7666. 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)
  7667. {
  7668. // phpcs:enable
  7669. global $conf, $user, $langs;
  7670. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7671. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  7672. $sortfield = 'position_name';
  7673. $sortorder = 'asc';
  7674. $dir = $sdir.'/';
  7675. $pdir = '/';
  7676. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7677. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
  7678. // For backward compatibility
  7679. if ($modulepart == 'product') {
  7680. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  7681. $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7682. $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
  7683. }
  7684. }
  7685. // Defined relative dir to DOL_DATA_ROOT
  7686. $relativedir = '';
  7687. if ($dir) {
  7688. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
  7689. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  7690. $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
  7691. }
  7692. $dirthumb = $dir.'thumbs/';
  7693. $pdirthumb = $pdir.'thumbs/';
  7694. $return = '<!-- Photo -->'."\n";
  7695. $nbphoto = 0;
  7696. $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  7697. /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatiblity, we scan also old dirs
  7698. {
  7699. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  7700. $filearray=array_merge($filearray, $filearrayold);
  7701. }*/
  7702. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  7703. if (count($filearray)) {
  7704. if ($sortfield && $sortorder) {
  7705. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  7706. }
  7707. foreach ($filearray as $key => $val) {
  7708. $photo = '';
  7709. $file = $val['name'];
  7710. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  7711. if (image_format_supported($file) >= 0) {
  7712. $nbphoto++;
  7713. $photo = $file;
  7714. $viewfilename = $file;
  7715. if ($size == 1 || $size == 'small') { // Format vignette
  7716. // Find name of thumb file
  7717. $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
  7718. if (!dol_is_file($dirthumb.$photo_vignette)) {
  7719. // The thumb does not exists, so we will use the original file
  7720. $dirthumb = $dir;
  7721. $pdirthumb = $pdir;
  7722. $photo_vignette = basename($file);
  7723. }
  7724. // Get filesize of original file
  7725. $imgarray = dol_getImageSize($dir.$photo);
  7726. if ($nbbyrow > 0) {
  7727. if ($nbphoto == 1) {
  7728. $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
  7729. }
  7730. if ($nbphoto % $nbbyrow == 1) {
  7731. $return .= '<tr class="center valignmiddle" style="border: 1px">';
  7732. }
  7733. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">';
  7734. } elseif ($nbbyrow < 0) {
  7735. $return .= '<div class="inline-block">';
  7736. }
  7737. $return .= "\n";
  7738. $relativefile = preg_replace('/^\//', '', $pdir.$photo);
  7739. if (empty($nolink)) {
  7740. $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  7741. if ($urladvanced) {
  7742. $return .= '<a href="'.$urladvanced.'">';
  7743. } else {
  7744. $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  7745. }
  7746. }
  7747. // Show image (width height=$maxHeight)
  7748. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  7749. $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
  7750. $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  7751. if ($notitle) {
  7752. $alt = '';
  7753. }
  7754. $addphotorefcss = 1;
  7755. if ($usesharelink) {
  7756. if ($val['share']) {
  7757. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7758. $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
  7759. $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).'">';
  7760. } else {
  7761. $return .= '<!-- Show original file -->';
  7762. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  7763. }
  7764. } else {
  7765. $return .= '<!-- Show nophoto file (because file is not shared) -->';
  7766. $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' photoref' : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  7767. }
  7768. } else {
  7769. if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
  7770. $return .= '<!-- Show thumb -->';
  7771. $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).'">';
  7772. } else {
  7773. $return .= '<!-- Show original file -->';
  7774. $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).'">';
  7775. }
  7776. }
  7777. if (empty($nolink)) {
  7778. $return .= '</a>';
  7779. }
  7780. $return .= "\n";
  7781. if ($showfilename) {
  7782. $return .= '<br>'.$viewfilename;
  7783. }
  7784. if ($showaction) {
  7785. $return .= '<br>';
  7786. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  7787. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
  7788. $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>';
  7789. }
  7790. // Special cas for product
  7791. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7792. // Link to resize
  7793. $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; ';
  7794. // Link to delete
  7795. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7796. $return .= img_delete().'</a>';
  7797. }
  7798. }
  7799. $return .= "\n";
  7800. if ($nbbyrow > 0) {
  7801. $return .= '</td>';
  7802. if (($nbphoto % $nbbyrow) == 0) {
  7803. $return .= '</tr>';
  7804. }
  7805. } elseif ($nbbyrow < 0) {
  7806. $return .= '</div>';
  7807. }
  7808. }
  7809. if (empty($size)) { // Format origine
  7810. $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  7811. if ($showfilename) {
  7812. $return .= '<br>'.$viewfilename;
  7813. }
  7814. if ($showaction) {
  7815. // Special case for product
  7816. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
  7817. // Link to resize
  7818. $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; ';
  7819. // Link to delete
  7820. $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
  7821. $return .= img_delete().'</a>';
  7822. }
  7823. }
  7824. }
  7825. // On continue ou on arrete de boucler ?
  7826. if ($nbmax && $nbphoto >= $nbmax) {
  7827. break;
  7828. }
  7829. }
  7830. }
  7831. if ($size == 1 || $size == 'small') {
  7832. if ($nbbyrow > 0) {
  7833. // Ferme tableau
  7834. while ($nbphoto % $nbbyrow) {
  7835. $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
  7836. $nbphoto++;
  7837. }
  7838. if ($nbphoto) {
  7839. $return .= '</table>';
  7840. }
  7841. }
  7842. }
  7843. }
  7844. $this->nbphoto = $nbphoto;
  7845. return $return;
  7846. }
  7847. /**
  7848. * Function test if type is array
  7849. *
  7850. * @param array $info content informations of field
  7851. * @return bool true if array
  7852. */
  7853. protected function isArray($info)
  7854. {
  7855. if (is_array($info)) {
  7856. if (isset($info['type']) && $info['type'] == 'array') {
  7857. return true;
  7858. } else {
  7859. return false;
  7860. }
  7861. }
  7862. return false;
  7863. }
  7864. /**
  7865. * Function test if type is date
  7866. *
  7867. * @param array $info content informations of field
  7868. * @return bool true if date
  7869. */
  7870. public function isDate($info)
  7871. {
  7872. if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
  7873. return true;
  7874. }
  7875. return false;
  7876. }
  7877. /**
  7878. * Function test if type is duration
  7879. *
  7880. * @param array $info content informations of field
  7881. * @return bool true if field of type duration
  7882. */
  7883. public function isDuration($info)
  7884. {
  7885. if (is_array($info)) {
  7886. if (isset($info['type']) && ($info['type'] == 'duration')) {
  7887. return true;
  7888. } else {
  7889. return false;
  7890. }
  7891. } else {
  7892. return false;
  7893. }
  7894. }
  7895. /**
  7896. * Function test if type is integer
  7897. *
  7898. * @param array $info content informations of field
  7899. * @return bool true if integer
  7900. */
  7901. public function isInt($info)
  7902. {
  7903. if (is_array($info)) {
  7904. if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
  7905. return true;
  7906. } else {
  7907. return false;
  7908. }
  7909. } else {
  7910. return false;
  7911. }
  7912. }
  7913. /**
  7914. * Function test if type is float
  7915. *
  7916. * @param array $info content informations of field
  7917. * @return bool true if float
  7918. */
  7919. public function isFloat($info)
  7920. {
  7921. if (is_array($info)) {
  7922. if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
  7923. return true;
  7924. } else {
  7925. return false;
  7926. }
  7927. }
  7928. return false;
  7929. }
  7930. /**
  7931. * Function test if type is text
  7932. *
  7933. * @param array $info content informations of field
  7934. * @return bool true if type text
  7935. */
  7936. public function isText($info)
  7937. {
  7938. if (is_array($info)) {
  7939. if (isset($info['type']) && $info['type'] == 'text') {
  7940. return true;
  7941. } else {
  7942. return false;
  7943. }
  7944. }
  7945. return false;
  7946. }
  7947. /**
  7948. * Function test if field can be null
  7949. *
  7950. * @param array $info content informations of field
  7951. * @return bool true if it can be null
  7952. */
  7953. protected function canBeNull($info)
  7954. {
  7955. if (is_array($info)) {
  7956. if (isset($info['notnull']) && $info['notnull'] != '1') {
  7957. return true;
  7958. } else {
  7959. return false;
  7960. }
  7961. }
  7962. return true;
  7963. }
  7964. /**
  7965. * Function test if field is forced to null if zero or empty
  7966. *
  7967. * @param array $info content informations of field
  7968. * @return bool true if forced to null
  7969. */
  7970. protected function isForcedToNullIfZero($info)
  7971. {
  7972. if (is_array($info)) {
  7973. if (isset($info['notnull']) && $info['notnull'] == '-1') {
  7974. return true;
  7975. } else {
  7976. return false;
  7977. }
  7978. }
  7979. return false;
  7980. }
  7981. /**
  7982. * Function test if is indexed
  7983. *
  7984. * @param array $info content informations of field
  7985. * @return bool
  7986. */
  7987. protected function isIndex($info)
  7988. {
  7989. if (is_array($info)) {
  7990. if (isset($info['index']) && $info['index'] == true) {
  7991. return true;
  7992. } else {
  7993. return false;
  7994. }
  7995. }
  7996. return false;
  7997. }
  7998. /**
  7999. * Function to prepare a part of the query for insert by returning an array with all properties of object.
  8000. *
  8001. * Note $this->${field} are set by the page that make the createCommon() or the updateCommon().
  8002. * $this->${field} should be a clean and string value (so date are formated for SQL insert).
  8003. *
  8004. * @return array Array with all values of each properties to update
  8005. */
  8006. protected function setSaveQuery()
  8007. {
  8008. global $conf;
  8009. $queryarray = array();
  8010. foreach ($this->fields as $field => $info) { // Loop on definition of fields
  8011. // Depending on field type ('datetime', ...)
  8012. if ($this->isDate($info)) {
  8013. if (empty($this->{$field})) {
  8014. $queryarray[$field] = null;
  8015. } else {
  8016. $queryarray[$field] = $this->db->idate($this->{$field});
  8017. }
  8018. } elseif ($this->isDuration($info)) {
  8019. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8020. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8021. if (!isset($this->{$field})) {
  8022. if (!empty($info['default'])) {
  8023. $queryarray[$field] = $info['default'];
  8024. } else {
  8025. $queryarray[$field] = 0;
  8026. }
  8027. } else {
  8028. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8029. }
  8030. } else {
  8031. $queryarray[$field] = null;
  8032. }
  8033. } elseif ($this->isInt($info) || $this->isFloat($info)) {
  8034. if ($field == 'entity' && is_null($this->{$field})) {
  8035. $queryarray[$field] = ((int) $conf->entity);
  8036. } else {
  8037. // $this->{$field} may be null, '', 0, '0', 123, '123'
  8038. if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
  8039. if (!isset($this->{$field})) {
  8040. $queryarray[$field] = 0;
  8041. } elseif ($this->isInt($info)) {
  8042. $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8043. } elseif ($this->isFloat($info)) {
  8044. $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
  8045. }
  8046. } else {
  8047. $queryarray[$field] = null;
  8048. }
  8049. }
  8050. } else {
  8051. // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
  8052. // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
  8053. $queryarray[$field] = $this->{$field};
  8054. }
  8055. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
  8056. unset($queryarray[$field]);
  8057. }
  8058. if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
  8059. $queryarray[$field] = null; // May force 0 to null
  8060. }
  8061. }
  8062. return $queryarray;
  8063. }
  8064. /**
  8065. * Function to load data from a SQL pointer into properties of current object $this
  8066. *
  8067. * @param stdClass $obj Contain data of object from database
  8068. * @return void
  8069. */
  8070. public function setVarsFromFetchObj(&$obj)
  8071. {
  8072. global $db;
  8073. foreach ($this->fields as $field => $info) {
  8074. if ($this->isDate($info)) {
  8075. if (is_null($obj->{$field}) || $obj->{$field} === '' || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
  8076. $this->{$field} = '';
  8077. } else {
  8078. $this->{$field} = $db->jdate($obj->{$field});
  8079. }
  8080. } elseif ($this->isInt($info)) {
  8081. if ($field == 'rowid') {
  8082. $this->id = (int) $obj->{$field};
  8083. } else {
  8084. if ($this->isForcedToNullIfZero($info)) {
  8085. if (empty($obj->{$field})) {
  8086. $this->{$field} = null;
  8087. } else {
  8088. $this->{$field} = (double) $obj->{$field};
  8089. }
  8090. } else {
  8091. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8092. $this->{$field} = (int) $obj->{$field};
  8093. } else {
  8094. $this->{$field} = null;
  8095. }
  8096. }
  8097. }
  8098. } elseif ($this->isFloat($info)) {
  8099. if ($this->isForcedToNullIfZero($info)) {
  8100. if (empty($obj->{$field})) {
  8101. $this->{$field} = null;
  8102. } else {
  8103. $this->{$field} = (double) $obj->{$field};
  8104. }
  8105. } else {
  8106. if (!is_null($obj->{$field}) || (isset($info['notnull']) && $info['notnull'] == 1)) {
  8107. $this->{$field} = (double) $obj->{$field};
  8108. } else {
  8109. $this->{$field} = null;
  8110. }
  8111. }
  8112. } else {
  8113. $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
  8114. }
  8115. }
  8116. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  8117. if (!isset($this->fields['ref']) && isset($this->id)) {
  8118. $this->ref = $this->id;
  8119. }
  8120. }
  8121. /**
  8122. * Function to concat keys of fields
  8123. *
  8124. * @param string $alias String of alias of table for fields. For example 't'. It is recommended to use '' and set alias into fields defintion.
  8125. * @return string list of alias fields
  8126. */
  8127. public function getFieldList($alias = '')
  8128. {
  8129. $keys = array_keys($this->fields);
  8130. if (!empty($alias)) {
  8131. $keys_with_alias = array();
  8132. foreach ($keys as $fieldname) {
  8133. $keys_with_alias[] = $alias . '.' . $fieldname;
  8134. }
  8135. return implode(',', $keys_with_alias);
  8136. } else {
  8137. return implode(',', $keys);
  8138. }
  8139. }
  8140. /**
  8141. * Add quote to field value if necessary
  8142. *
  8143. * @param string|int $value Value to protect
  8144. * @param array $fieldsentry Properties of field
  8145. * @return string
  8146. */
  8147. protected function quote($value, $fieldsentry)
  8148. {
  8149. if (is_null($value)) {
  8150. return 'NULL';
  8151. } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
  8152. return price2num("$value");
  8153. } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
  8154. return (int) $value;
  8155. } elseif ($fieldsentry['type'] == 'boolean') {
  8156. if ($value) {
  8157. return 'true';
  8158. } else {
  8159. return 'false';
  8160. }
  8161. } else {
  8162. return "'".$this->db->escape($value)."'";
  8163. }
  8164. }
  8165. /**
  8166. * Create object into database
  8167. *
  8168. * @param User $user User that creates
  8169. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8170. * @return int <0 if KO, Id of created object if OK
  8171. */
  8172. public function createCommon(User $user, $notrigger = false)
  8173. {
  8174. global $langs;
  8175. dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
  8176. $error = 0;
  8177. $now = dol_now();
  8178. $fieldvalues = $this->setSaveQuery();
  8179. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
  8180. $fieldvalues['date_creation'] = $this->db->idate($now);
  8181. }
  8182. if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
  8183. $fieldvalues['fk_user_creat'] = $user->id;
  8184. }
  8185. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  8186. if (array_key_exists('ref', $fieldvalues)) {
  8187. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8188. }
  8189. $keys = array();
  8190. $values = array(); // Array to store string forged for SQL syntax
  8191. foreach ($fieldvalues as $k => $v) {
  8192. $keys[$k] = $k;
  8193. $value = $this->fields[$k];
  8194. $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
  8195. }
  8196. // Clean and check mandatory
  8197. foreach ($keys as $key) {
  8198. // If field is an implicit foreign key field (so type = 'integer:...')
  8199. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8200. $values[$key] = '';
  8201. }
  8202. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8203. $values[$key] = '';
  8204. }
  8205. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && is_null($this->fields[$key]['default'])) {
  8206. $error++;
  8207. $langs->load("errors");
  8208. dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
  8209. $this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8210. }
  8211. // If value is null and there is a default value for field
  8212. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($this->fields[$key]['default'])) {
  8213. $values[$key] = $this->quote($this->fields[$key]['default'], $this->fields[$key]);
  8214. }
  8215. // If field is an implicit foreign key field (so type = 'integer:...')
  8216. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
  8217. if (isset($this->fields[$key]['default'])) {
  8218. $values[$key] = ((int) $this->fields[$key]['default']);
  8219. } else {
  8220. $values[$key] = 'null';
  8221. }
  8222. }
  8223. if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
  8224. $values[$key] = 'null';
  8225. }
  8226. }
  8227. if ($error) {
  8228. return -1;
  8229. }
  8230. $this->db->begin();
  8231. if (!$error) {
  8232. $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
  8233. $sql .= " (".implode(", ", $keys).')';
  8234. $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
  8235. $res = $this->db->query($sql);
  8236. if (!$res) {
  8237. $error++;
  8238. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  8239. $this->errors[] = "ErrorRefAlreadyExists";
  8240. } else {
  8241. $this->errors[] = $this->db->lasterror();
  8242. }
  8243. }
  8244. }
  8245. if (!$error) {
  8246. $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
  8247. }
  8248. // If we have a field ref with a default value of (PROV)
  8249. if (!$error) {
  8250. if (key_exists('ref', $this->fields) && $this->fields['ref']['notnull'] > 0 && key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
  8251. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
  8252. $resqlupdate = $this->db->query($sql);
  8253. if ($resqlupdate === false) {
  8254. $error++;
  8255. $this->errors[] = $this->db->lasterror();
  8256. } else {
  8257. $this->ref = '(PROV'.$this->id.')';
  8258. }
  8259. }
  8260. }
  8261. // Create extrafields
  8262. if (!$error) {
  8263. $result = $this->insertExtraFields();
  8264. if ($result < 0) {
  8265. $error++;
  8266. }
  8267. }
  8268. // Create lines
  8269. if (!empty($this->table_element_line) && !empty($this->fk_element)) {
  8270. $num = (is_array($this->lines) ? count($this->lines) : 0);
  8271. for ($i = 0; $i < $num; $i++) {
  8272. $line = $this->lines[$i];
  8273. $keyforparent = $this->fk_element;
  8274. $line->$keyforparent = $this->id;
  8275. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  8276. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  8277. if (!is_object($line)) {
  8278. $line = (object) $line;
  8279. }
  8280. $result = $line->create($user, 1);
  8281. if ($result < 0) {
  8282. $this->error = $line->error;
  8283. $this->db->rollback();
  8284. return -1;
  8285. }
  8286. }
  8287. }
  8288. // Triggers
  8289. if (!$error && !$notrigger) {
  8290. // Call triggers
  8291. $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
  8292. if ($result < 0) {
  8293. $error++;
  8294. }
  8295. // End call triggers
  8296. }
  8297. // Commit or rollback
  8298. if ($error) {
  8299. $this->db->rollback();
  8300. return -1;
  8301. } else {
  8302. $this->db->commit();
  8303. return $this->id;
  8304. }
  8305. }
  8306. /**
  8307. * Load object in memory from the database
  8308. *
  8309. * @param int $id Id object
  8310. * @param string $ref Ref
  8311. * @param string $morewhere More SQL filters (' AND ...')
  8312. * @return int <0 if KO, 0 if not found, >0 if OK
  8313. */
  8314. public function fetchCommon($id, $ref = null, $morewhere = '')
  8315. {
  8316. if (empty($id) && empty($ref) && empty($morewhere)) {
  8317. return -1;
  8318. }
  8319. $fieldlist = $this->getFieldList('t');
  8320. if (empty($fieldlist)) {
  8321. return 0;
  8322. }
  8323. $sql = "SELECT ".$fieldlist;
  8324. $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
  8325. if (!empty($id)) {
  8326. $sql .= ' WHERE t.rowid = '.((int) $id);
  8327. } elseif (!empty($ref)) {
  8328. $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
  8329. } else {
  8330. $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  8331. }
  8332. if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  8333. $sql .= ' AND t.entity IN ('.getEntity($this->element).')';
  8334. }
  8335. if ($morewhere) {
  8336. $sql .= $morewhere;
  8337. }
  8338. $sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
  8339. $res = $this->db->query($sql);
  8340. if ($res) {
  8341. $obj = $this->db->fetch_object($res);
  8342. if ($obj) {
  8343. $this->setVarsFromFetchObj($obj);
  8344. // Retrieve all extrafield
  8345. // fetch optionals attributes and labels
  8346. $this->fetch_optionals();
  8347. return $this->id;
  8348. } else {
  8349. return 0;
  8350. }
  8351. } else {
  8352. $this->error = $this->db->lasterror();
  8353. $this->errors[] = $this->error;
  8354. return -1;
  8355. }
  8356. }
  8357. /**
  8358. * Load object in memory from the database
  8359. *
  8360. * @param string $morewhere More SQL filters (' AND ...')
  8361. * @return int <0 if KO, 0 if not found, >0 if OK
  8362. */
  8363. public function fetchLinesCommon($morewhere = '')
  8364. {
  8365. $objectlineclassname = get_class($this).'Line';
  8366. if (!class_exists($objectlineclassname)) {
  8367. $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
  8368. return -1;
  8369. }
  8370. $objectline = new $objectlineclassname($this->db);
  8371. $sql = "SELECT ".$objectline->getFieldList('l');
  8372. $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
  8373. $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
  8374. if ($morewhere) {
  8375. $sql .= $morewhere;
  8376. }
  8377. if (isset($objectline->fields['position'])) {
  8378. $sql .= $this->db->order('position', 'ASC');
  8379. }
  8380. $resql = $this->db->query($sql);
  8381. if ($resql) {
  8382. $num_rows = $this->db->num_rows($resql);
  8383. $i = 0;
  8384. while ($i < $num_rows) {
  8385. $obj = $this->db->fetch_object($resql);
  8386. if ($obj) {
  8387. $newline = new $objectlineclassname($this->db);
  8388. $newline->setVarsFromFetchObj($obj);
  8389. $this->lines[] = $newline;
  8390. }
  8391. $i++;
  8392. }
  8393. return 1;
  8394. } else {
  8395. $this->error = $this->db->lasterror();
  8396. $this->errors[] = $this->error;
  8397. return -1;
  8398. }
  8399. }
  8400. /**
  8401. * Update object into database
  8402. *
  8403. * @param User $user User that modifies
  8404. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8405. * @return int <0 if KO, >0 if OK
  8406. */
  8407. public function updateCommon(User $user, $notrigger = false)
  8408. {
  8409. global $conf, $langs;
  8410. dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
  8411. $error = 0;
  8412. $now = dol_now();
  8413. // $this->oldcopy should have been set by the caller of update
  8414. //if (empty($this->oldcopy)) {
  8415. // $this->oldcopy = dol_clone($this);
  8416. //}
  8417. $fieldvalues = $this->setSaveQuery();
  8418. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
  8419. $fieldvalues['date_modification'] = $this->db->idate($now);
  8420. }
  8421. if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
  8422. $fieldvalues['fk_user_modif'] = $user->id;
  8423. }
  8424. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  8425. if (array_key_exists('ref', $fieldvalues)) {
  8426. $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
  8427. }
  8428. // Add quotes and escape on fields with type string
  8429. $keys = array();
  8430. $values = array();
  8431. $tmp = array();
  8432. foreach ($fieldvalues as $k => $v) {
  8433. $keys[$k] = $k;
  8434. $value = $this->fields[$k];
  8435. $values[$k] = $this->quote($v, $value);
  8436. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  8437. }
  8438. // Clean and check mandatory fields
  8439. foreach ($keys as $key) {
  8440. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
  8441. $values[$key] = ''; // This is an implicit foreign key field
  8442. }
  8443. if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
  8444. $values[$key] = ''; // This is an explicit foreign key field
  8445. }
  8446. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  8447. /*
  8448. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  8449. {
  8450. $error++;
  8451. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  8452. }*/
  8453. }
  8454. $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
  8455. $this->db->begin();
  8456. if (!$error) {
  8457. $res = $this->db->query($sql);
  8458. if (!$res) {
  8459. $error++;
  8460. $this->errors[] = $this->db->lasterror();
  8461. }
  8462. }
  8463. // Update extrafield
  8464. if (!$error) {
  8465. $result = $this->insertExtraFields();
  8466. if ($result < 0) {
  8467. $error++;
  8468. }
  8469. }
  8470. // Triggers
  8471. if (!$error && !$notrigger) {
  8472. // Call triggers
  8473. $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
  8474. if ($result < 0) {
  8475. $error++;
  8476. } //Do also here what you must do to rollback action if trigger fail
  8477. // End call triggers
  8478. }
  8479. // Commit or rollback
  8480. if ($error) {
  8481. $this->db->rollback();
  8482. return -1;
  8483. } else {
  8484. $this->db->commit();
  8485. return $this->id;
  8486. }
  8487. }
  8488. /**
  8489. * Delete object in database
  8490. *
  8491. * @param User $user User that deletes
  8492. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8493. * @param int $forcechilddeletion 0=no, 1=Force deletion of children
  8494. * @return int <0 if KO, 0=Nothing done because object has child, >0 if OK
  8495. */
  8496. public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
  8497. {
  8498. dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
  8499. $error = 0;
  8500. $this->db->begin();
  8501. if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
  8502. foreach ($this->childtables as $table) {
  8503. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8504. $resql = $this->db->query($sql);
  8505. if (!$resql) {
  8506. $this->error = $this->db->lasterror();
  8507. $this->errors[] = $this->error;
  8508. $this->db->rollback();
  8509. return -1;
  8510. }
  8511. }
  8512. } elseif (!empty($this->fk_element) && !empty($this->childtables)) { // If object has childs linked with a foreign key field, we check all child tables.
  8513. $objectisused = $this->isObjectUsed($this->id);
  8514. if (!empty($objectisused)) {
  8515. dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
  8516. $this->error = 'ErrorRecordHasChildren';
  8517. $this->errors[] = $this->error;
  8518. $this->db->rollback();
  8519. return 0;
  8520. }
  8521. }
  8522. // Delete cascade first
  8523. if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
  8524. foreach ($this->childtablesoncascade as $table) {
  8525. $deleteFromObject = explode(':', $table);
  8526. if (count($deleteFromObject) >= 2) {
  8527. $className = str_replace('@', '', $deleteFromObject[0]);
  8528. $filePath = $deleteFromObject[1];
  8529. $columnName = $deleteFromObject[2];
  8530. $TMoreSQL = array();
  8531. $more_sql = $deleteFromObject[3];
  8532. if (!empty($more_sql)) {
  8533. $TMoreSQL['customsql'] = $more_sql;
  8534. }
  8535. if (dol_include_once($filePath)) {
  8536. $childObject = new $className($this->db);
  8537. if (method_exists($childObject, 'deleteByParentField')) {
  8538. $result = $childObject->deleteByParentField($this->id, $columnName, $TMoreSQL);
  8539. if ($result < 0) {
  8540. $error++;
  8541. $this->errors[] = $childObject->error;
  8542. break;
  8543. }
  8544. } else {
  8545. $error++;
  8546. $this->errors[] = "You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
  8547. break;
  8548. }
  8549. } else {
  8550. $error++;
  8551. $this->errors[] = 'Cannot include child class file '.$filePath;
  8552. break;
  8553. }
  8554. } else {
  8555. // Delete record in child table
  8556. $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
  8557. $resql = $this->db->query($sql);
  8558. if (!$resql) {
  8559. $error++;
  8560. $this->error = $this->db->lasterror();
  8561. $this->errors[] = $this->error;
  8562. break;
  8563. }
  8564. }
  8565. }
  8566. }
  8567. if (!$error) {
  8568. if (!$notrigger) {
  8569. // Call triggers
  8570. $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  8571. if ($result < 0) {
  8572. $error++;
  8573. } // Do also here what you must do to rollback action if trigger fail
  8574. // End call triggers
  8575. }
  8576. }
  8577. // Delete llx_ecm_files
  8578. if (!$error) {
  8579. $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
  8580. if (!$res) {
  8581. $error++;
  8582. }
  8583. }
  8584. // Delete linked object
  8585. $res = $this->deleteObjectLinked();
  8586. if ($res < 0) {
  8587. $error++;
  8588. }
  8589. if (!$error && !empty($this->isextrafieldmanaged)) {
  8590. $result = $this->deleteExtraFields();
  8591. if ($result < 0) {
  8592. $error++;
  8593. }
  8594. }
  8595. if (!$error) {
  8596. $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
  8597. $resql = $this->db->query($sql);
  8598. if (!$resql) {
  8599. $error++;
  8600. $this->errors[] = $this->db->lasterror();
  8601. }
  8602. }
  8603. // Commit or rollback
  8604. if ($error) {
  8605. $this->db->rollback();
  8606. return -1;
  8607. } else {
  8608. $this->db->commit();
  8609. return 1;
  8610. }
  8611. }
  8612. /**
  8613. * Delete all child object from a parent ID
  8614. *
  8615. * @param int $parentId Parent Id
  8616. * @param string $parentField Name of Foreign key parent column
  8617. * @param array $filter an array filter
  8618. * @param string $filtermode AND or OR
  8619. * @return int <0 if KO, >0 if OK
  8620. * @throws Exception
  8621. */
  8622. public function deleteByParentField($parentId = 0, $parentField = '', $filter = array(), $filtermode = "AND")
  8623. {
  8624. global $user;
  8625. $error = 0;
  8626. $deleted = 0;
  8627. if (!empty($parentId) && !empty($parentField)) {
  8628. $this->db->begin();
  8629. $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
  8630. $sql .= " WHERE ".$parentField." = ".(int) $parentId;
  8631. // Manage filters
  8632. $sqlwhere = array();
  8633. if (count($filter) > 0) {
  8634. foreach ($filter as $key => $value) {
  8635. if ($key == 'customsql') {
  8636. $sqlwhere[] = $value;
  8637. } elseif (strpos($value, '%') === false) {
  8638. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  8639. } else {
  8640. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  8641. }
  8642. }
  8643. }
  8644. if (count($sqlwhere) > 0) {
  8645. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  8646. }
  8647. $resql = $this->db->query($sql);
  8648. if (!$resql) {
  8649. $this->errors[] = $this->db->lasterror();
  8650. $error++;
  8651. } else {
  8652. while ($obj = $this->db->fetch_object($resql)) {
  8653. $result = $this->fetch($obj->rowid);
  8654. if ($result < 0) {
  8655. $error++;
  8656. $this->errors[] = $this->error;
  8657. } else {
  8658. if (get_class($this) == 'Contact') { // TODO special code because delete() for contact has not been standardized like other delete.
  8659. $result = $this->delete();
  8660. } else {
  8661. $result = $this->delete($user);
  8662. }
  8663. if ($result < 0) {
  8664. $error++;
  8665. $this->errors[] = $this->error;
  8666. } else {
  8667. $deleted++;
  8668. }
  8669. }
  8670. }
  8671. }
  8672. if (empty($error)) {
  8673. $this->db->commit();
  8674. return $deleted;
  8675. } else {
  8676. $this->error = implode(', ', $this->errors);
  8677. $this->db->rollback();
  8678. return $error * -1;
  8679. }
  8680. }
  8681. return $deleted;
  8682. }
  8683. /**
  8684. * Delete a line of object in database
  8685. *
  8686. * @param User $user User that delete
  8687. * @param int $idline Id of line to delete
  8688. * @param bool $notrigger false=launch triggers after, true=disable triggers
  8689. * @return int >0 if OK, <0 if KO
  8690. */
  8691. public function deleteLineCommon(User $user, $idline, $notrigger = false)
  8692. {
  8693. global $conf;
  8694. $error = 0;
  8695. $tmpforobjectclass = get_class($this);
  8696. $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
  8697. $this->db->begin();
  8698. // Call trigger
  8699. $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
  8700. if ($result < 0) {
  8701. $error++;
  8702. }
  8703. // End call triggers
  8704. if (empty($error)) {
  8705. $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
  8706. $sql .= " WHERE rowid = ".((int) $idline);
  8707. $resql = $this->db->query($sql);
  8708. if (!$resql) {
  8709. $this->error = "Error ".$this->db->lasterror();
  8710. $error++;
  8711. }
  8712. }
  8713. if (empty($error)) {
  8714. // Remove extrafields
  8715. $tmpobjectline = new $tmpforobjectlineclass($this->db);
  8716. if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
  8717. $tmpobjectline->id = $idline;
  8718. $result = $tmpobjectline->deleteExtraFields();
  8719. if ($result < 0) {
  8720. $error++;
  8721. $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
  8722. }
  8723. }
  8724. }
  8725. if (empty($error)) {
  8726. $this->db->commit();
  8727. return 1;
  8728. } else {
  8729. dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
  8730. $this->db->rollback();
  8731. return -1;
  8732. }
  8733. }
  8734. /**
  8735. * Set to a status
  8736. *
  8737. * @param User $user Object user that modify
  8738. * @param int $status New status to set (often a constant like self::STATUS_XXX)
  8739. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  8740. * @param string $triggercode Trigger code to use
  8741. * @return int <0 if KO, >0 if OK
  8742. */
  8743. public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
  8744. {
  8745. $error = 0;
  8746. $this->db->begin();
  8747. $statusfield = 'status';
  8748. if ($this->element == 'don' || $this->element == 'donation') {
  8749. $statusfield = 'fk_statut';
  8750. }
  8751. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  8752. $sql .= " SET ".$statusfield." = ".((int) $status);
  8753. $sql .= " WHERE rowid = ".((int) $this->id);
  8754. if ($this->db->query($sql)) {
  8755. if (!$error) {
  8756. $this->oldcopy = clone $this;
  8757. }
  8758. if (!$error && !$notrigger) {
  8759. // Call trigger
  8760. $result = $this->call_trigger($triggercode, $user);
  8761. if ($result < 0) {
  8762. $error++;
  8763. }
  8764. }
  8765. if (!$error) {
  8766. $this->status = $status;
  8767. $this->db->commit();
  8768. return 1;
  8769. } else {
  8770. $this->db->rollback();
  8771. return -1;
  8772. }
  8773. } else {
  8774. $this->error = $this->db->error();
  8775. $this->db->rollback();
  8776. return -1;
  8777. }
  8778. }
  8779. /**
  8780. * Initialise object with example values
  8781. * Id must be 0 if object instance is a specimen
  8782. *
  8783. * @return int
  8784. */
  8785. public function initAsSpecimenCommon()
  8786. {
  8787. global $user;
  8788. $this->id = 0;
  8789. $this->specimen = 1;
  8790. $fields = array(
  8791. 'label' => 'This is label',
  8792. 'ref' => 'ABCD1234',
  8793. 'description' => 'This is a description',
  8794. 'qty' => 123.12,
  8795. 'note_public' => 'Public note',
  8796. 'note_private' => 'Private note',
  8797. 'date_creation' => (dol_now() - 3600 * 48),
  8798. 'date_modification' => (dol_now() - 3600 * 24),
  8799. 'fk_user_creat' => $user->id,
  8800. 'fk_user_modif' => $user->id,
  8801. 'date' => dol_now(),
  8802. );
  8803. foreach ($fields as $key => $value) {
  8804. if (array_key_exists($key, $this->fields)) {
  8805. $this->{$key} = $value;
  8806. }
  8807. }
  8808. return 1;
  8809. }
  8810. /* Part for comments */
  8811. /**
  8812. * Load comments linked with current task
  8813. * @return boolean 1 if ok
  8814. */
  8815. public function fetchComments()
  8816. {
  8817. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  8818. $comment = new Comment($this->db);
  8819. $result = $comment->fetchAllFor($this->element, $this->id);
  8820. if ($result < 0) {
  8821. $this->errors = array_merge($this->errors, $comment->errors);
  8822. return -1;
  8823. } else {
  8824. $this->comments = $comment->comments;
  8825. }
  8826. return count($this->comments);
  8827. }
  8828. /**
  8829. * Return nb comments already posted
  8830. *
  8831. * @return int
  8832. */
  8833. public function getNbComments()
  8834. {
  8835. return count($this->comments);
  8836. }
  8837. /**
  8838. * Trim object parameters
  8839. *
  8840. * @param string[] $parameters array of parameters to trim
  8841. * @return void
  8842. */
  8843. public function trimParameters($parameters)
  8844. {
  8845. if (!is_array($parameters)) {
  8846. return;
  8847. }
  8848. foreach ($parameters as $parameter) {
  8849. if (isset($this->$parameter)) {
  8850. $this->$parameter = trim($this->$parameter);
  8851. }
  8852. }
  8853. }
  8854. /* Part for categories/tags */
  8855. /**
  8856. * Sets object to given categories.
  8857. *
  8858. * Deletes object from existing categories not supplied.
  8859. * Adds it to non existing supplied categories.
  8860. * Existing categories are left untouch.
  8861. *
  8862. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...)
  8863. * @return int Array of category objects or < 0 if KO
  8864. */
  8865. public function getCategoriesCommon($type_categ)
  8866. {
  8867. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8868. // Get current categories
  8869. $c = new Categorie($this->db);
  8870. $existing = $c->containing($this->id, $type_categ, 'id');
  8871. return $existing;
  8872. }
  8873. /**
  8874. * Sets object to given categories.
  8875. *
  8876. * Adds it to non existing supplied categories.
  8877. * Deletes object from existing categories not supplied (if remove_existing==true).
  8878. * Existing categories are left untouch.
  8879. *
  8880. * @param int[]|int $categories Category ID or array of Categories IDs
  8881. * @param string $type_categ Category type ('customer', 'supplier', 'website_page', ...) definied into const class Categorie type
  8882. * @param boolean $remove_existing True: Remove existings categories from Object if not supplies by $categories, False: let them
  8883. * @return int <0 if KO, >0 if OK
  8884. */
  8885. public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
  8886. {
  8887. // Handle single category
  8888. if (!is_array($categories)) {
  8889. $categories = array($categories);
  8890. }
  8891. dol_syslog(get_class($this)."::setCategoriesCommon Oject Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
  8892. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8893. if (empty($type_categ)) {
  8894. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
  8895. return -1;
  8896. }
  8897. // Get current categories
  8898. $c = new Categorie($this->db);
  8899. $existing = $c->containing($this->id, $type_categ, 'id');
  8900. if ($remove_existing) {
  8901. // Diff
  8902. if (is_array($existing)) {
  8903. $to_del = array_diff($existing, $categories);
  8904. $to_add = array_diff($categories, $existing);
  8905. } else {
  8906. $to_del = array(); // Nothing to delete
  8907. $to_add = $categories;
  8908. }
  8909. } else {
  8910. $to_del = array(); // Nothing to delete
  8911. $to_add = array_diff($categories, $existing);
  8912. }
  8913. $error = 0;
  8914. $ok = 0;
  8915. // Process
  8916. foreach ($to_del as $del) {
  8917. if ($c->fetch($del) > 0) {
  8918. $result=$c->del_type($this, $type_categ);
  8919. if ($result < 0) {
  8920. $error++;
  8921. $this->error = $c->error;
  8922. $this->errors = $c->errors;
  8923. break;
  8924. } else {
  8925. $ok += $result;
  8926. }
  8927. }
  8928. }
  8929. foreach ($to_add as $add) {
  8930. if ($c->fetch($add) > 0) {
  8931. $result = $c->add_type($this, $type_categ);
  8932. if ($result < 0) {
  8933. $error++;
  8934. $this->error = $c->error;
  8935. $this->errors = $c->errors;
  8936. break;
  8937. } else {
  8938. $ok += $result;
  8939. }
  8940. }
  8941. }
  8942. return $error ? (-1 * $error) : $ok;
  8943. }
  8944. /**
  8945. * Copy related categories to another object
  8946. *
  8947. * @param int $fromId Id object source
  8948. * @param int $toId Id object cible
  8949. * @param string $type Type of category ('product', ...)
  8950. * @return int < 0 if error, > 0 if ok
  8951. */
  8952. public function cloneCategories($fromId, $toId, $type = '')
  8953. {
  8954. $this->db->begin();
  8955. if (empty($type)) {
  8956. $type = $this->table_element;
  8957. }
  8958. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  8959. $categorystatic = new Categorie($this->db);
  8960. $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
  8961. $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
  8962. $sql .= " WHERE fk_product = ".((int) $fromId);
  8963. if (!$this->db->query($sql)) {
  8964. $this->error = $this->db->lasterror();
  8965. $this->db->rollback();
  8966. return -1;
  8967. }
  8968. $this->db->commit();
  8969. return 1;
  8970. }
  8971. /**
  8972. * Delete related files of object in database
  8973. *
  8974. * @param integer $mode 0=Use path to find record, 1=Use src_object_xxx fields (Mode 1 is recommanded for new objects)
  8975. * @return bool True if OK, False if KO
  8976. */
  8977. public function deleteEcmFiles($mode = 0)
  8978. {
  8979. global $conf;
  8980. $this->db->begin();
  8981. // Delete in database with mode 0
  8982. if ($mode == 0) {
  8983. switch ($this->element) {
  8984. case 'propal':
  8985. $element = 'propale';
  8986. break;
  8987. case 'product':
  8988. $element = 'produit';
  8989. break;
  8990. case 'order_supplier':
  8991. $element = 'fournisseur/commande';
  8992. break;
  8993. case 'invoice_supplier':
  8994. $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
  8995. break;
  8996. case 'shipping':
  8997. $element = 'expedition/sending';
  8998. break;
  8999. default:
  9000. $element = $this->element;
  9001. }
  9002. // Delete ecm_files extrafields
  9003. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
  9004. $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  9005. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  9006. $sql .= ")";
  9007. if (!$this->db->query($sql)) {
  9008. $this->error = $this->db->lasterror();
  9009. $this->db->rollback();
  9010. return false;
  9011. }
  9012. // Delete ecm_files
  9013. $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
  9014. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
  9015. $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
  9016. if (!$this->db->query($sql)) {
  9017. $this->error = $this->db->lasterror();
  9018. $this->db->rollback();
  9019. return false;
  9020. }
  9021. }
  9022. // Delete in database with mode 1
  9023. if ($mode == 1) {
  9024. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
  9025. $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).")";
  9026. $resql = $this->db->query($sql);
  9027. if (!$resql) {
  9028. $this->error = $this->db->lasterror();
  9029. $this->db->rollback();
  9030. return false;
  9031. }
  9032. $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
  9033. $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  9034. $resql = $this->db->query($sql);
  9035. if (!$resql) {
  9036. $this->error = $this->db->lasterror();
  9037. $this->db->rollback();
  9038. return false;
  9039. }
  9040. }
  9041. $this->db->commit();
  9042. return true;
  9043. }
  9044. }