html.form.class.php 422 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143
  1. <?php
  2. /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  7. * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>
  10. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
  11. * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
  12. * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
  13. * Copyright (C) 2010-2021 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  15. * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
  16. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  17. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  18. * Copyright (C) 2014-2020 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018-2022 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  21. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  22. * Copyright (C) 2018 Christophe Battarel <christophe@altairis.fr>
  23. * Copyright (C) 2018 Josep Lluis Amador <joseplluis@lliuretic.cat>
  24. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. */
  38. /**
  39. * \file htdocs/core/class/html.form.class.php
  40. * \ingroup core
  41. * \brief File of class with all html predefined components
  42. */
  43. /**
  44. * Class to manage generation of HTML components
  45. * Only common components must be here.
  46. *
  47. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  48. */
  49. class Form
  50. {
  51. /**
  52. * @var DoliDB Database handler.
  53. */
  54. public $db;
  55. /**
  56. * @var string Error code (or message)
  57. */
  58. public $error = '';
  59. /**
  60. * @var string[] Array of error strings
  61. */
  62. public $errors = array();
  63. public $num;
  64. // Cache arrays
  65. public $cache_types_paiements = array();
  66. public $cache_conditions_paiements = array();
  67. public $cache_transport_mode = array();
  68. public $cache_availability = array();
  69. public $cache_demand_reason = array();
  70. public $cache_types_fees = array();
  71. public $cache_vatrates = array();
  72. /**
  73. * Constructor
  74. *
  75. * @param DoliDB $db Database handler
  76. */
  77. public function __construct($db)
  78. {
  79. $this->db = $db;
  80. }
  81. /**
  82. * Output key field for an editable field
  83. *
  84. * @param string $text Text of label or key to translate
  85. * @param string $htmlname Name of select field ('edit' prefix will be added)
  86. * @param string $preselected Value to show/edit (not used in this function)
  87. * @param object $object Object
  88. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  89. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'checkbox:ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  90. * @param string $moreparam More param to add on a href URL.
  91. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  92. * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
  93. * @param string $paramid Key of parameter for id ('id', 'socid')
  94. * @param string $help Tooltip help
  95. * @return string HTML edit field
  96. */
  97. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  98. {
  99. global $conf, $langs;
  100. $ret = '';
  101. // TODO change for compatibility
  102. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
  103. if (!empty($perm)) {
  104. $tmp = explode(':', $typeofdata);
  105. $ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  106. if ($fieldrequired) {
  107. $ret .= '<span class="fieldrequired">';
  108. }
  109. if ($help) {
  110. $ret .= $this->textwithpicto($langs->trans($text), $help);
  111. } else {
  112. $ret .= $langs->trans($text);
  113. }
  114. if ($fieldrequired) {
  115. $ret .= '</span>';
  116. }
  117. $ret .= '</div>'."\n";
  118. } else {
  119. if ($fieldrequired) {
  120. $ret .= '<span class="fieldrequired">';
  121. }
  122. if ($help) {
  123. $ret .= $this->textwithpicto($langs->trans($text), $help);
  124. } else {
  125. $ret .= $langs->trans($text);
  126. }
  127. if ($fieldrequired) {
  128. $ret .= '</span>';
  129. }
  130. }
  131. } else {
  132. if (empty($notabletag) && $perm) {
  133. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  134. }
  135. if ($fieldrequired) {
  136. $ret .= '<span class="fieldrequired">';
  137. }
  138. if ($help) {
  139. $ret .= $this->textwithpicto($langs->trans($text), $help);
  140. } else {
  141. $ret .= $langs->trans($text);
  142. }
  143. if ($fieldrequired) {
  144. $ret .= '</span>';
  145. }
  146. if (!empty($notabletag)) {
  147. $ret .= ' ';
  148. }
  149. if (empty($notabletag) && $perm) {
  150. $ret .= '</td>';
  151. }
  152. if (empty($notabletag) && $perm) {
  153. $ret .= '<td class="right">';
  154. }
  155. if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  156. $ret .= '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&token='.newToken().'&'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  157. }
  158. if (!empty($notabletag) && $notabletag == 1) {
  159. $ret .= ' : ';
  160. }
  161. if (!empty($notabletag) && $notabletag == 3) {
  162. $ret .= ' ';
  163. }
  164. if (empty($notabletag) && $perm) {
  165. $ret .= '</td>';
  166. }
  167. if (empty($notabletag) && $perm) {
  168. $ret .= '</tr></table>';
  169. }
  170. }
  171. return $ret;
  172. }
  173. /**
  174. * Output value of a field for an editable field
  175. *
  176. * @param string $text Text of label (not used in this function)
  177. * @param string $htmlname Name of select field
  178. * @param string $value Value to show/edit
  179. * @param object $object Object
  180. * @param boolean $perm Permission to allow button to edit parameter
  181. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select;xkey:xval,ykey:yval,...')
  182. * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of numeric value). Use '' to use same than $value
  183. * @param object $extObject External object
  184. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  185. * @param string $moreparam More param to add on the form action href URL
  186. * @param int $notabletag Do no output table tags
  187. * @param string $formatfunc Call a specific function to output field in view mode (For example: 'dol_print_email')
  188. * @param string $paramid Key of parameter for id ('id', 'socid')
  189. * @param string $gm 'auto' or 'tzuser' or 'tzserver' (when $typeofdata is a date)
  190. * @return string HTML edit field
  191. */
  192. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id', $gm = 'auto')
  193. {
  194. global $conf, $langs;
  195. $ret = '';
  196. // Check parameters
  197. if (empty($typeofdata)) {
  198. return 'ErrorBadParameter';
  199. }
  200. // When option to edit inline is activated
  201. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  202. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  203. } else {
  204. $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
  205. if ($editmode) {
  206. $ret .= "\n";
  207. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  208. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  209. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  210. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  211. if (empty($notabletag)) {
  212. $ret .= '<table class="nobordernopadding centpercent">';
  213. }
  214. if (empty($notabletag)) {
  215. $ret .= '<tr><td>';
  216. }
  217. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) {
  218. $tmp = explode(':', $typeofdata);
  219. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  220. } elseif (preg_match('/^(numeric|amount|integer)/', $typeofdata)) {
  221. $tmp = explode(':', $typeofdata);
  222. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  223. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ? price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  224. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  225. $tmp = explode(':', $typeofdata);
  226. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  227. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  228. $tmp = explode(':', $typeofdata);
  229. $cols = $tmp[2];
  230. $morealt = '';
  231. if (preg_match('/%/', $cols)) {
  232. $morealt = ' style="width: '.$cols.'"';
  233. $cols = '';
  234. }
  235. $valuetoshow = ($editvalue ? $editvalue : $value);
  236. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  237. // textarea convert automatically entities chars into simple chars.
  238. // So we convert & into &amp; so a string like 'a &lt; <b>b</b><br>é<br>&lt;script&gt;alert('X');&lt;script&gt;' stay a correct html and is not converted by textarea component when wysiwig is off.
  239. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  240. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  241. $ret .= '</textarea>';
  242. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  243. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  244. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  245. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  246. } elseif (preg_match('/^select;/', $typeofdata)) {
  247. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  248. $arraylist = array();
  249. foreach ($arraydata as $val) {
  250. $tmp = explode(':', $val);
  251. $tmpkey = str_replace('|', ':', $tmp[0]);
  252. $arraylist[$tmpkey] = $tmp[1];
  253. }
  254. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  255. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  256. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  257. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  258. $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), ($tmp[2] ? $tmp[2] : ''), ($tmp[3] ? $tmp[3] : '100'), ($tmp[1] ? $tmp[1] : 'dolibarr_notes'), 'In', ($tmp[5] ? $tmp[5] : 0), (isset($tmp[8]) ? ($tmp[8] ?true:false) : true), true, ($tmp[6] ? $tmp[6] : '20'), ($tmp[7] ? $tmp[7] : '100'));
  259. $ret .= $doleditor->Create(1);
  260. }
  261. if (empty($notabletag)) {
  262. $ret .= '</td>';
  263. }
  264. if (empty($notabletag)) {
  265. $ret .= '<td class="left">';
  266. }
  267. //else $ret.='<div class="clearboth"></div>';
  268. $ret .= '<input type="submit" class="smallpaddingimp button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  269. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  270. $ret .= '<br>'."\n";
  271. }
  272. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  273. if (empty($notabletag)) {
  274. $ret .= '</td>';
  275. }
  276. if (empty($notabletag)) {
  277. $ret .= '</tr></table>'."\n";
  278. }
  279. $ret .= '</form>'."\n";
  280. } else {
  281. if (preg_match('/^(email)/', $typeofdata)) {
  282. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  283. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  284. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  285. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  286. $tmp = explode(':', $typeofdata);
  287. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  288. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  289. $ret .= dol_htmlentitiesbr($value);
  290. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  291. $ret .= dol_string_onlythesehtmltags($value);
  292. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  293. $ret .= dol_string_onlythesehtmltags($value);
  294. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  295. $ret .= '<span class="valuedate">'.dol_print_date($value, 'day', $gm).'</span>';
  296. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  297. $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour', $gm).'</span>';
  298. } elseif (preg_match('/^select;/', $typeofdata)) {
  299. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  300. $arraylist = array();
  301. foreach ($arraydata as $val) {
  302. $tmp = explode(':', $val);
  303. $arraylist[$tmp[0]] = $tmp[1];
  304. }
  305. $ret .= $arraylist[$value];
  306. if ($htmlname == 'fk_product_type') {
  307. if ($value == 0) {
  308. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  309. } else {
  310. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  311. }
  312. }
  313. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  314. $tmpcontent = dol_htmlentitiesbr($value);
  315. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  316. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  317. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  318. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  319. }
  320. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  321. // clean data from some dangerous html
  322. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  323. } else {
  324. $ret .= dol_escape_htmltag($value);
  325. }
  326. if ($formatfunc && method_exists($object, $formatfunc)) {
  327. $ret = $object->$formatfunc($ret);
  328. }
  329. }
  330. }
  331. return $ret;
  332. }
  333. /**
  334. * Output edit in place form
  335. *
  336. * @param string $fieldname Name of the field
  337. * @param object $object Object
  338. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  339. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  340. * @param string $check Same coe than $check parameter of GETPOST()
  341. * @param string $morecss More CSS
  342. * @return string HTML code for the edit of alternative language
  343. */
  344. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  345. {
  346. global $conf, $langs, $extralanguages;
  347. $result = '';
  348. // List of extra languages
  349. $arrayoflangcode = array();
  350. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  351. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  352. }
  353. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  354. if (!is_object($extralanguages)) {
  355. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  356. $extralanguages = new ExtraLanguages($this->db);
  357. }
  358. $extralanguages->fetch_name_extralanguages('societe');
  359. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  360. return ''; // No extralang field to show
  361. }
  362. $result .= '<!-- Widget for translation -->'."\n";
  363. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  364. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  365. $result .= $s;
  366. $result .= '</div>';
  367. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  368. $resultforextrlang = '';
  369. foreach ($arrayoflangcode as $langcode) {
  370. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  371. if (empty($valuetoshow)) {
  372. $object->fetchValuesForExtraLanguages();
  373. //var_dump($object->array_languages);
  374. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  375. }
  376. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  377. $resultforextrlang .= $s;
  378. // TODO Use the showInputField() method of ExtraLanguages object
  379. if ($typeofdata == 'textarea') {
  380. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  381. $resultforextrlang .= $valuetoshow;
  382. $resultforextrlang .= '</textarea>';
  383. } else {
  384. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  385. }
  386. }
  387. $result .= $resultforextrlang;
  388. $result .= '</div>';
  389. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  390. }
  391. return $result;
  392. }
  393. /**
  394. * Output edit in place form
  395. *
  396. * @param object $object Object
  397. * @param string $value Value to show/edit
  398. * @param string $htmlname DIV ID (field name)
  399. * @param int $condition Condition to edit
  400. * @param string $inputType Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:loadmethod:savemethod:buttononly')
  401. * @param string $editvalue When in edit mode, use this value as $value instead of value
  402. * @param object $extObject External object
  403. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  404. * @return string HTML edit in place
  405. */
  406. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  407. {
  408. global $conf;
  409. $out = '';
  410. // Check parameters
  411. if (preg_match('/^text/', $inputType)) {
  412. $value = dol_nl2br($value);
  413. } elseif (preg_match('/^numeric/', $inputType)) {
  414. $value = price($value);
  415. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  416. $value = dol_print_date($value, 'day');
  417. }
  418. if ($condition) {
  419. $element = false;
  420. $table_element = false;
  421. $fk_element = false;
  422. $loadmethod = false;
  423. $savemethod = false;
  424. $ext_element = false;
  425. $button_only = false;
  426. $inputOption = '';
  427. if (is_object($object)) {
  428. $element = $object->element;
  429. $table_element = $object->table_element;
  430. $fk_element = $object->id;
  431. }
  432. if (is_object($extObject)) {
  433. $ext_element = $extObject->element;
  434. }
  435. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  436. $tmp = explode(':', $inputType);
  437. $inputType = $tmp[0];
  438. if (!empty($tmp[1])) {
  439. $inputOption = $tmp[1];
  440. }
  441. if (!empty($tmp[2])) {
  442. $savemethod = $tmp[2];
  443. }
  444. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  445. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  446. $tmp = explode(':', $inputType);
  447. $inputType = $tmp[0];
  448. if (!empty($tmp[1])) {
  449. $inputOption = $tmp[1];
  450. }
  451. if (!empty($tmp[2])) {
  452. $savemethod = $tmp[2];
  453. }
  454. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  455. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  456. $tmp = explode(':', $inputType);
  457. $inputType = $tmp[0];
  458. $loadmethod = $tmp[1];
  459. if (!empty($tmp[2])) {
  460. $savemethod = $tmp[2];
  461. }
  462. if (!empty($tmp[3])) {
  463. $button_only = true;
  464. }
  465. } elseif (preg_match('/^textarea/', $inputType)) {
  466. $tmp = explode(':', $inputType);
  467. $inputType = $tmp[0];
  468. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  469. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  470. } elseif (preg_match('/^ckeditor/', $inputType)) {
  471. $tmp = explode(':', $inputType);
  472. $inputType = $tmp[0];
  473. $toolbar = $tmp[1];
  474. if (!empty($tmp[2])) {
  475. $width = $tmp[2];
  476. }
  477. if (!empty($tmp[3])) {
  478. $heigth = $tmp[3];
  479. }
  480. if (!empty($tmp[4])) {
  481. $savemethod = $tmp[4];
  482. }
  483. if (!empty($conf->fckeditor->enabled)) {
  484. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  485. } else {
  486. $inputType = 'textarea';
  487. }
  488. }
  489. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  490. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  491. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  492. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  493. if (!empty($savemethod)) {
  494. $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  495. }
  496. if (!empty($ext_element)) {
  497. $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  498. }
  499. if (!empty($custommsg)) {
  500. if (is_array($custommsg)) {
  501. if (!empty($custommsg['success'])) {
  502. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  503. }
  504. if (!empty($custommsg['error'])) {
  505. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  506. }
  507. } else {
  508. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  509. }
  510. }
  511. if ($inputType == 'textarea') {
  512. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  513. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  514. }
  515. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  516. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  517. } else {
  518. $out = $value;
  519. }
  520. return $out;
  521. }
  522. /**
  523. * Show a text and picto with tooltip on text or picto.
  524. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  525. *
  526. * @param string $text Text to show
  527. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  528. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  529. * @param int $direction -1=image is before, 0=no image, 1=image is after
  530. * @param string $img Html code for image (use img_xxx() function to get it)
  531. * @param string $extracss Add a CSS style to td tags
  532. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  533. * @param string $incbefore Include code before the text
  534. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  535. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  536. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  537. * @return string Code html du tooltip (texte+picto)
  538. * @see textwithpicto() Use thisfunction if you can.
  539. */
  540. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  541. {
  542. if ($incbefore) {
  543. $text = $incbefore.$text;
  544. }
  545. if (!$htmltext) {
  546. return $text;
  547. }
  548. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  549. $tag = 'td';
  550. if ($notabs == 2) {
  551. $tag = 'div';
  552. }
  553. if ($notabs == 3) {
  554. $tag = 'span';
  555. }
  556. // Sanitize tooltip
  557. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  558. $extrastyle = '';
  559. if ($direction < 0) {
  560. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  561. $extrastyle = 'padding: 0px; padding-left: 3px !important;';
  562. }
  563. if ($direction > 0) {
  564. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  565. $extrastyle = 'padding: 0px; padding-right: 3px !important;';
  566. }
  567. $classfortooltip = 'classfortooltip';
  568. $s = '';
  569. $textfordialog = '';
  570. if ($tooltiptrigger == '') {
  571. $htmltext = str_replace('"', '&quot;', $htmltext);
  572. } else {
  573. $classfortooltip = 'classfortooltiponclick';
  574. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  575. }
  576. if ($tooltipon == 2 || $tooltipon == 3) {
  577. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  578. if ($tooltiptrigger == '') {
  579. $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  580. } else {
  581. $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  582. }
  583. } else {
  584. $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  585. }
  586. if ($tooltipon == 1 || $tooltipon == 3) {
  587. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  588. if ($tooltiptrigger == '') {
  589. $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  590. } else {
  591. $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  592. }
  593. } else {
  594. $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  595. }
  596. if (empty($notabs)) {
  597. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  598. } elseif ($notabs == 2) {
  599. $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  600. }
  601. // Define value if value is before
  602. if ($direction < 0) {
  603. $s .= '<'.$tag.$paramfortooltipimg;
  604. if ($tag == 'td') {
  605. $s .= ' class=valigntop" width="14"';
  606. }
  607. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  608. }
  609. // Use another method to help avoid having a space in value in order to use this value with jquery
  610. // Define label
  611. if ((string) $text != '') {
  612. $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  613. }
  614. // Define value if value is after
  615. if ($direction > 0) {
  616. $s .= '<'.$tag.$paramfortooltipimg;
  617. if ($tag == 'td') {
  618. $s .= ' class="valignmiddle" width="14"';
  619. }
  620. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  621. }
  622. if (empty($notabs)) {
  623. $s .= '</tr></table>';
  624. } elseif ($notabs == 2) {
  625. $s .= '</div>';
  626. }
  627. return $s;
  628. }
  629. /**
  630. * Show a text with a picto and a tooltip on picto
  631. *
  632. * @param string $text Text to show
  633. * @param string $htmltext Content of tooltip
  634. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  635. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  636. * @param string $extracss Add a CSS style to td, div or span tag
  637. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  638. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  639. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key, clickable link is on image or on link if param $type='none' or on both if $type='xxxclickable')
  640. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  641. * @return string HTML code of text, picto, tooltip
  642. */
  643. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  644. {
  645. global $conf, $langs;
  646. $alt = '';
  647. if ($tooltiptrigger) {
  648. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  649. }
  650. //For backwards compatibility
  651. if ($type == '0') {
  652. $type = 'info';
  653. } elseif ($type == '1') {
  654. $type = 'help';
  655. }
  656. // If info or help with no javascript, show only text
  657. if (empty($conf->use_javascript_ajax)) {
  658. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  659. return $text;
  660. } else {
  661. $alt = $htmltext;
  662. $htmltext = '';
  663. }
  664. }
  665. // If info or help with smartphone, show only text (tooltip hover can't works)
  666. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  667. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  668. return $text;
  669. }
  670. }
  671. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  672. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  673. //{
  674. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  675. //}
  676. $img = '';
  677. if ($type == 'info') {
  678. $img = img_help(0, $alt);
  679. } elseif ($type == 'help') {
  680. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  681. } elseif ($type == 'helpclickable') {
  682. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  683. } elseif ($type == 'superadmin') {
  684. $img = img_picto($alt, 'redstar');
  685. } elseif ($type == 'admin') {
  686. $img = img_picto($alt, 'star');
  687. } elseif ($type == 'warning') {
  688. $img = img_warning($alt);
  689. } elseif ($type != 'none') {
  690. $img = img_picto($alt, $type); // $type can be an image path
  691. }
  692. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  693. }
  694. /**
  695. * Generate select HTML to choose massaction
  696. *
  697. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  698. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  699. * @param int $alwaysvisible 1=select button always visible
  700. * @param string $name Name for massaction
  701. * @param string $cssclass CSS class used to check for select
  702. * @return string|void Select list
  703. */
  704. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  705. {
  706. global $conf, $langs, $hookmanager;
  707. $disabled = 0;
  708. $ret = '<div class="centpercent center">';
  709. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  710. // Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks.
  711. $parameters = array();
  712. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  713. // check if there is a mass action
  714. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  715. return;
  716. }
  717. if (empty($reshook)) {
  718. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  719. foreach ($arrayofaction as $code => $label) {
  720. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  721. }
  722. }
  723. $ret .= $hookmanager->resPrint;
  724. $ret .= '</select>';
  725. if (empty($conf->dol_optimize_smallscreen)) {
  726. $ret .= ajax_combobox('.'.$name.'select');
  727. }
  728. // Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button
  729. $ret .= '<input type="submit" name="confirmmassactioninvisible" style="display: none" tabindex="-1">'; // Hidden button BEFORE so it is the one used when we submit with ENTER.
  730. $ret .= '<input type="submit" disabled name="confirmmassaction"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display: none"').' class="button smallpaddingimp'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'confirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  731. $ret .= '</div>';
  732. if (!empty($conf->use_javascript_ajax)) {
  733. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  734. <script>
  735. function initCheckForSelect(mode, name, cssclass) /* mode is 0 during init of page or click all, 1 when we click on 1 checkboxi, "name" refers to the class of the massaction button, "cssclass" to the class of the checkfor select boxes */
  736. {
  737. atleastoneselected=0;
  738. jQuery("."+cssclass).each(function( index ) {
  739. /* console.log( index + ": " + $( this ).text() ); */
  740. if ($(this).is(\':checked\')) atleastoneselected++;
  741. });
  742. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  743. if (atleastoneselected || '.$alwaysvisible.')
  744. {
  745. jQuery("."+name).show();
  746. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  747. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  748. }
  749. else
  750. {
  751. jQuery("."+name).hide();
  752. jQuery("."+name+"other").hide();
  753. }
  754. }
  755. jQuery(document).ready(function () {
  756. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  757. jQuery(".' . $cssclass.'").click(function() {
  758. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  759. });
  760. jQuery(".' . $name.'select").change(function() {
  761. var massaction = $( this ).val();
  762. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  763. if (massaction == "builddoc")
  764. {
  765. urlform = urlform + "#show_files";
  766. }
  767. $( this ).closest("form").attr("action", urlform);
  768. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  769. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  770. if ($(this).val() != \'0\')
  771. {
  772. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  773. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  774. jQuery(".' . $name.'"+massaction).show();
  775. }
  776. else
  777. {
  778. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  779. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  780. }
  781. });
  782. });
  783. </script>
  784. ';
  785. }
  786. return $ret;
  787. }
  788. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  789. /**
  790. * Return combo list of activated countries, into language of user
  791. *
  792. * @param string $selected Id or Code or Label of preselected country
  793. * @param string $htmlname Name of html select object
  794. * @param string $htmloption More html options on select object
  795. * @param integer $maxlength Max length for labels (0=no limit)
  796. * @param string $morecss More css class
  797. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  798. * @param int $showempty Show empty choice
  799. * @param int $disablefavorites 1=Disable favorites,
  800. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  801. * @param array $exclude_country_code Array of country code (iso2) to exclude
  802. * @param int $hideflags Hide flags
  803. * @return string HTML string with select
  804. */
  805. public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array(), $hideflags = 0)
  806. {
  807. // phpcs:enable
  808. global $conf, $langs, $mysoc;
  809. $langs->load("dict");
  810. $out = '';
  811. $countryArray = array();
  812. $favorite = array();
  813. $label = array();
  814. $atleastonefavorite = 0;
  815. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  816. $sql .= " FROM ".$this->db->prefix()."c_country";
  817. $sql .= " WHERE active > 0";
  818. //$sql.= " ORDER BY code ASC";
  819. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  820. $resql = $this->db->query($sql);
  821. if ($resql) {
  822. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  823. $num = $this->db->num_rows($resql);
  824. $i = 0;
  825. if ($num) {
  826. while ($i < $num) {
  827. $obj = $this->db->fetch_object($resql);
  828. $countryArray[$i]['rowid'] = $obj->rowid;
  829. $countryArray[$i]['code_iso'] = $obj->code_iso;
  830. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  831. $countryArray[$i]['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso) != "Country".$obj->code_iso ? $langs->transnoentitiesnoconv("Country".$obj->code_iso) : ($obj->label != '-' ? $obj->label : ''));
  832. $countryArray[$i]['favorite'] = $obj->favorite;
  833. $countryArray[$i]['eec'] = $obj->eec;
  834. $favorite[$i] = $obj->favorite;
  835. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  836. $i++;
  837. }
  838. if (empty($disablefavorites)) {
  839. array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  840. } else {
  841. $countryArray = dol_sort_array($countryArray, 'label');
  842. }
  843. if ($showempty) {
  844. $out .= '<option value="">&nbsp;</option>'."\n";
  845. }
  846. if ($addspecialentries) { // Add dedicated entries for groups of countries
  847. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  848. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  849. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  850. if ($mysoc->isInEEC()) {
  851. $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  852. }
  853. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  854. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  855. }
  856. foreach ($countryArray as $row) {
  857. //if (empty($showempty) && empty($row['rowid'])) continue;
  858. if (empty($row['rowid'])) {
  859. continue;
  860. }
  861. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  862. continue; // exclude some countries
  863. }
  864. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  865. $atleastonefavorite++;
  866. }
  867. if (empty($row['favorite']) && $atleastonefavorite) {
  868. $atleastonefavorite = 0;
  869. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  870. }
  871. $labeltoshow = '';
  872. if ($row['label']) {
  873. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  874. } else {
  875. $labeltoshow .= '&nbsp;';
  876. }
  877. if ($row['code_iso']) {
  878. $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
  879. if (empty($hideflags)) {
  880. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  881. $labeltoshow = $tmpflag.' '.$labeltoshow;
  882. }
  883. }
  884. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  885. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" selected data-html="'.dol_escape_htmltag($labeltoshow).'" data-eec="'.((int) $row['eec']).'">';
  886. } else {
  887. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" data-html="'.dol_escape_htmltag($labeltoshow).'" data-eec="'.((int) $row['eec']).'">';
  888. }
  889. $out .= $labeltoshow;
  890. $out .= '</option>'."\n";
  891. }
  892. }
  893. $out .= '</select>';
  894. } else {
  895. dol_print_error($this->db);
  896. }
  897. // Make select dynamic
  898. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  899. $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
  900. return $out;
  901. }
  902. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  903. /**
  904. * Return select list of incoterms
  905. *
  906. * @param string $selected Id or Code of preselected incoterm
  907. * @param string $location_incoterms Value of input location
  908. * @param string $page Defined the form action
  909. * @param string $htmlname Name of html select object
  910. * @param string $htmloption Options html on select object
  911. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  912. * @param array $events Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
  913. * @return string HTML string with select and input
  914. */
  915. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
  916. {
  917. // phpcs:enable
  918. global $conf, $langs;
  919. $langs->load("dict");
  920. $out = '';
  921. $moreattrib = '';
  922. $incotermArray = array();
  923. $sql = "SELECT rowid, code";
  924. $sql .= " FROM ".$this->db->prefix()."c_incoterms";
  925. $sql .= " WHERE active > 0";
  926. $sql .= " ORDER BY code ASC";
  927. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  928. $resql = $this->db->query($sql);
  929. if ($resql) {
  930. if ($conf->use_javascript_ajax && !$forcecombo) {
  931. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  932. $out .= ajax_combobox($htmlname, $events);
  933. }
  934. if (!empty($page)) {
  935. $out .= '<form method="post" action="'.$page.'">';
  936. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  937. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  938. }
  939. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm width75" name="'.$htmlname.'" '.$htmloption.'>';
  940. $out .= '<option value="0">&nbsp;</option>';
  941. $num = $this->db->num_rows($resql);
  942. $i = 0;
  943. if ($num) {
  944. $foundselected = false;
  945. while ($i < $num) {
  946. $obj = $this->db->fetch_object($resql);
  947. $incotermArray[$i]['rowid'] = $obj->rowid;
  948. $incotermArray[$i]['code'] = $obj->code;
  949. $i++;
  950. }
  951. foreach ($incotermArray as $row) {
  952. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  953. $out .= '<option value="'.$row['rowid'].'" selected>';
  954. } else {
  955. $out .= '<option value="'.$row['rowid'].'">';
  956. }
  957. if ($row['code']) {
  958. $out .= $row['code'];
  959. }
  960. $out .= '</option>';
  961. }
  962. }
  963. $out .= '</select>';
  964. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  965. $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT.'/core/ajax/locationincoterms.php')."\n";
  966. $moreattrib .= ' autocomplete="off"';
  967. }
  968. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="'.$location_incoterms.'">'."\n";
  969. if (!empty($page)) {
  970. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="'.$langs->trans("Modify").'"></form>';
  971. }
  972. } else {
  973. dol_print_error($this->db);
  974. }
  975. return $out;
  976. }
  977. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  978. /**
  979. * Return list of types of lines (product or service)
  980. * Example: 0=product, 1=service, 9=other (for external module)
  981. *
  982. * @param string $selected Preselected type
  983. * @param string $htmlname Name of field in html form
  984. * @param int $showempty Add an empty field
  985. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  986. * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service')
  987. * @return void
  988. */
  989. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  990. {
  991. // phpcs:enable
  992. global $langs, $conf;
  993. // If product & services are enabled or both disabled.
  994. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  995. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled))) {
  996. if (empty($hidetext)) {
  997. print $langs->trans("Type").': ';
  998. }
  999. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  1000. if ($showempty) {
  1001. print '<option value="-1"';
  1002. if ($selected == -1) {
  1003. print ' selected';
  1004. }
  1005. print '>&nbsp;</option>';
  1006. }
  1007. print '<option value="0"';
  1008. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1009. print ' selected';
  1010. }
  1011. print '>'.$langs->trans("Product");
  1012. print '<option value="1"';
  1013. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1014. print ' selected';
  1015. }
  1016. print '>'.$langs->trans("Service");
  1017. print '</select>';
  1018. print ajax_combobox('select_'.$htmlname);
  1019. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1020. }
  1021. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3) {
  1022. print $langs->trans("Service");
  1023. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  1024. }
  1025. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2) {
  1026. print $langs->trans("Product");
  1027. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  1028. }
  1029. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1030. print '<input type="hidden" name="'.$htmlname.'" value="1">'; // By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1
  1031. }
  1032. }
  1033. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1034. /**
  1035. * Load into cache cache_types_fees, array of types of fees
  1036. *
  1037. * @return int Nb of lines loaded, <0 if KO
  1038. */
  1039. public function load_cache_types_fees()
  1040. {
  1041. // phpcs:enable
  1042. global $langs;
  1043. $num = count($this->cache_types_fees);
  1044. if ($num > 0) {
  1045. return 0; // Cache already loaded
  1046. }
  1047. dol_syslog(__METHOD__, LOG_DEBUG);
  1048. $langs->load("trips");
  1049. $sql = "SELECT c.code, c.label";
  1050. $sql .= " FROM ".$this->db->prefix()."c_type_fees as c";
  1051. $sql .= " WHERE active > 0";
  1052. $resql = $this->db->query($sql);
  1053. if ($resql) {
  1054. $num = $this->db->num_rows($resql);
  1055. $i = 0;
  1056. while ($i < $num) {
  1057. $obj = $this->db->fetch_object($resql);
  1058. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1059. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1060. $this->cache_types_fees[$obj->code] = $label;
  1061. $i++;
  1062. }
  1063. asort($this->cache_types_fees);
  1064. return $num;
  1065. } else {
  1066. dol_print_error($this->db);
  1067. return -1;
  1068. }
  1069. }
  1070. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1071. /**
  1072. * Return list of types of notes
  1073. *
  1074. * @param string $selected Preselected type
  1075. * @param string $htmlname Name of field in form
  1076. * @param int $showempty Add an empty field
  1077. * @return void
  1078. */
  1079. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1080. {
  1081. // phpcs:enable
  1082. global $user, $langs;
  1083. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  1084. $this->load_cache_types_fees();
  1085. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  1086. if ($showempty) {
  1087. print '<option value="-1"';
  1088. if ($selected == -1) {
  1089. print ' selected';
  1090. }
  1091. print '>&nbsp;</option>';
  1092. }
  1093. foreach ($this->cache_types_fees as $key => $value) {
  1094. print '<option value="'.$key.'"';
  1095. if ($key == $selected) {
  1096. print ' selected';
  1097. }
  1098. print '>';
  1099. print $value;
  1100. print '</option>';
  1101. }
  1102. print '</select>';
  1103. if ($user->admin) {
  1104. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1105. }
  1106. }
  1107. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1108. /**
  1109. * Output html form to select a third party
  1110. *
  1111. * @param string $selected Preselected type
  1112. * @param string $htmlname Name of field in form
  1113. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>] are allowed here (example: 's.rowid <> x', 's.client IN (1,3)')
  1114. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1115. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1116. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1117. * @param array $events Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
  1118. * @param int $limit Maximum number of elements
  1119. * @param string $morecss Add more css styles to the SELECT component
  1120. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1121. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1122. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1123. * @param array $ajaxoptions Options for ajax_autocompleter
  1124. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1125. * @param array $excludeids Exclude IDs from the select combo
  1126. * @return string HTML string with select box for thirdparty.
  1127. */
  1128. public function select_company($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $limit = 0, $morecss = 'minwidth100', $moreparam = '', $selected_input_value = '', $hidelabel = 1, $ajaxoptions = array(), $multiple = false, $excludeids = array())
  1129. {
  1130. // phpcs:enable
  1131. global $conf, $user, $langs;
  1132. $out = '';
  1133. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1134. if (is_null($ajaxoptions)) {
  1135. $ajaxoptions = array();
  1136. }
  1137. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1138. // No immediate load of all database
  1139. $placeholder = '';
  1140. if ($selected && empty($selected_input_value)) {
  1141. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1142. $societetmp = new Societe($this->db);
  1143. $societetmp->fetch($selected);
  1144. $selected_input_value = $societetmp->name;
  1145. unset($societetmp);
  1146. }
  1147. // mode 1
  1148. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '');
  1149. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1150. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1151. if (empty($hidelabel)) {
  1152. print $langs->trans("RefOrLabel").' : ';
  1153. } elseif ($hidelabel > 1) {
  1154. $placeholder = $langs->trans("RefOrLabel");
  1155. if ($hidelabel == 2) {
  1156. $out .= img_picto($langs->trans("Search"), 'search');
  1157. }
  1158. }
  1159. $out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '').' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1160. if ($hidelabel == 3) {
  1161. $out .= img_picto($langs->trans("Search"), 'search');
  1162. }
  1163. } else {
  1164. // Immediate load of all database
  1165. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids);
  1166. }
  1167. return $out;
  1168. }
  1169. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1170. /**
  1171. * Output html form to select a third party.
  1172. * Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company.
  1173. *
  1174. * @param string $selected Preselected type
  1175. * @param string $htmlname Name of field in form
  1176. * @param string $filter Optional filters criteras (example: 's.rowid NOT IN (x)', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  1177. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1178. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1179. * @param int $forcecombo Force to use standard HTML select component without beautification
  1180. * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
  1181. * @param string $filterkey Filter on key value
  1182. * @param int $outputmode 0=HTML select string, 1=Array
  1183. * @param int $limit Limit number of answers
  1184. * @param string $morecss Add more css styles to the SELECT component
  1185. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1186. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1187. * @param array $excludeids Exclude IDs from the select combo
  1188. * @return string HTML string with
  1189. */
  1190. public function select_thirdparty_list($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $filterkey = '', $outputmode = 0, $limit = 0, $morecss = 'minwidth100', $moreparam = '', $multiple = false, $excludeids = array())
  1191. {
  1192. // phpcs:enable
  1193. global $conf, $user, $langs;
  1194. global $hookmanager;
  1195. $out = '';
  1196. $num = 0;
  1197. $outarray = array();
  1198. if ($selected === '') {
  1199. $selected = array();
  1200. } elseif (!is_array($selected)) {
  1201. $selected = array($selected);
  1202. }
  1203. // Clean $filter that may contains sql conditions so sql code
  1204. if (function_exists('testSqlAndScriptInject')) {
  1205. if (testSqlAndScriptInject($filter, 3) > 0) {
  1206. $filter = '';
  1207. }
  1208. }
  1209. // We search companies
  1210. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1211. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1212. $sql .= ", s.address, s.zip, s.town";
  1213. $sql .= ", dictp.code as country_code";
  1214. }
  1215. $sql .= " FROM ".$this->db->prefix()."societe as s";
  1216. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1217. $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as dictp ON dictp.rowid = s.fk_pays";
  1218. }
  1219. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1220. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  1221. }
  1222. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1223. if (!empty($user->socid)) {
  1224. $sql .= " AND s.rowid = ".((int) $user->socid);
  1225. }
  1226. if ($filter) {
  1227. $sql .= " AND (".$filter.")";
  1228. }
  1229. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1230. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1231. }
  1232. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1233. $sql .= " AND s.status <> 0";
  1234. }
  1235. if (!empty($excludeids)) {
  1236. $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
  1237. }
  1238. // Add where from hooks
  1239. $parameters = array();
  1240. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1241. $sql .= $hookmanager->resPrint;
  1242. // Add criteria
  1243. if ($filterkey && $filterkey != '') {
  1244. $sql .= " AND (";
  1245. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1246. // For natural search
  1247. $scrit = explode(' ', $filterkey);
  1248. $i = 0;
  1249. if (count($scrit) > 1) {
  1250. $sql .= "(";
  1251. }
  1252. foreach ($scrit as $crit) {
  1253. if ($i > 0) {
  1254. $sql .= " AND ";
  1255. }
  1256. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1257. $i++;
  1258. }
  1259. if (count($scrit) > 1) {
  1260. $sql .= ")";
  1261. }
  1262. if (!empty($conf->barcode->enabled)) {
  1263. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1264. }
  1265. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1266. $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1267. $sql .= ")";
  1268. }
  1269. $sql .= $this->db->order("nom", "ASC");
  1270. $sql .= $this->db->plimit($limit, 0);
  1271. // Build output string
  1272. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1273. $resql = $this->db->query($sql);
  1274. if ($resql) {
  1275. if (!$forcecombo) {
  1276. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1277. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1278. }
  1279. // Construct $out and $outarray
  1280. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1281. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1282. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1283. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1284. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1285. if ($showempty && !is_numeric($showempty)) {
  1286. $textifempty = $langs->trans($showempty);
  1287. } else {
  1288. $textifempty .= $langs->trans("All");
  1289. }
  1290. }
  1291. if ($showempty) {
  1292. $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
  1293. }
  1294. $num = $this->db->num_rows($resql);
  1295. $i = 0;
  1296. if ($num) {
  1297. while ($i < $num) {
  1298. $obj = $this->db->fetch_object($resql);
  1299. $label = '';
  1300. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1301. if (($obj->client) && (!empty($obj->code_client))) {
  1302. $label = $obj->code_client.' - ';
  1303. }
  1304. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1305. $label .= $obj->code_fournisseur.' - ';
  1306. }
  1307. $label .= ' '.$obj->name;
  1308. } else {
  1309. $label = $obj->name;
  1310. }
  1311. if (!empty($obj->name_alias)) {
  1312. $label .= ' ('.$obj->name_alias.')';
  1313. }
  1314. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1315. $label .= ' - '.$obj->tva_intra.'';
  1316. }
  1317. if ($showtype) {
  1318. if ($obj->client || $obj->fournisseur) {
  1319. $label .= ' (';
  1320. }
  1321. if ($obj->client == 1 || $obj->client == 3) {
  1322. $label .= $langs->trans("Customer");
  1323. }
  1324. if ($obj->client == 2 || $obj->client == 3) {
  1325. $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1326. }
  1327. if ($obj->fournisseur) {
  1328. $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1329. }
  1330. if ($obj->client || $obj->fournisseur) {
  1331. $label .= ')';
  1332. }
  1333. }
  1334. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1335. $label .= ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1336. if (!empty($obj->country_code)) {
  1337. $label .= ', '.$langs->trans('Country'.$obj->country_code);
  1338. }
  1339. }
  1340. if (empty($outputmode)) {
  1341. if (in_array($obj->rowid, $selected)) {
  1342. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1343. } else {
  1344. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1345. }
  1346. } else {
  1347. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1348. }
  1349. $i++;
  1350. if (($i % 10) == 0) {
  1351. $out .= "\n";
  1352. }
  1353. }
  1354. }
  1355. $out .= '</select>'."\n";
  1356. } else {
  1357. dol_print_error($this->db);
  1358. }
  1359. $this->result = array('nbofthirdparties'=>$num);
  1360. if ($outputmode) {
  1361. return $outarray;
  1362. }
  1363. return $out;
  1364. }
  1365. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1366. /**
  1367. * Return HTML combo list of absolute discounts
  1368. *
  1369. * @param string $selected Id remise fixe pre-selectionnee
  1370. * @param string $htmlname Nom champ formulaire
  1371. * @param string $filter Criteres optionnels de filtre
  1372. * @param int $socid Id of thirdparty
  1373. * @param int $maxvalue Max value for lines that can be selected
  1374. * @return int Return number of qualifed lines in list
  1375. */
  1376. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1377. {
  1378. // phpcs:enable
  1379. global $langs, $conf;
  1380. // On recherche les remises
  1381. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1382. $sql .= " re.description, re.fk_facture_source";
  1383. $sql .= " FROM ".$this->db->prefix()."societe_remise_except as re";
  1384. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1385. $sql .= " AND re.entity = ".$conf->entity;
  1386. if ($filter) {
  1387. $sql .= " AND ".$filter;
  1388. }
  1389. $sql .= " ORDER BY re.description ASC";
  1390. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1391. $resql = $this->db->query($sql);
  1392. if ($resql) {
  1393. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1394. $num = $this->db->num_rows($resql);
  1395. $qualifiedlines = $num;
  1396. $i = 0;
  1397. if ($num) {
  1398. print '<option value="0">&nbsp;</option>';
  1399. while ($i < $num) {
  1400. $obj = $this->db->fetch_object($resql);
  1401. $desc = dol_trunc($obj->description, 40);
  1402. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1403. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1404. }
  1405. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1406. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1407. }
  1408. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1409. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1410. }
  1411. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1412. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1413. }
  1414. $selectstring = '';
  1415. if ($selected > 0 && $selected == $obj->rowid) {
  1416. $selectstring = ' selected';
  1417. }
  1418. $disabled = '';
  1419. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1420. $qualifiedlines--;
  1421. $disabled = ' disabled';
  1422. }
  1423. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1424. $tmpfac = new Facture($this->db);
  1425. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1426. $desc = $desc.' - '.$tmpfac->ref;
  1427. }
  1428. }
  1429. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1430. $i++;
  1431. }
  1432. }
  1433. print '</select>';
  1434. print ajax_combobox('select_'.$htmlname);
  1435. return $qualifiedlines;
  1436. } else {
  1437. dol_print_error($this->db);
  1438. return -1;
  1439. }
  1440. }
  1441. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1442. /**
  1443. * Return list of all contacts (for a third party or all)
  1444. *
  1445. * @param int $socid Id ot third party or 0 for all
  1446. * @param string $selected Id contact pre-selectionne
  1447. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1448. * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
  1449. * @param string $exclude List of contacts id to exclude
  1450. * @param string $limitto Disable answers that are not id in this array list
  1451. * @param integer $showfunction Add function into label
  1452. * @param string $morecss Add more class to class style
  1453. * @param integer $showsoc Add company into label
  1454. * @param int $forcecombo Force to use combo box
  1455. * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
  1456. * @param bool $options_only Return options only (for ajax treatment)
  1457. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1458. * @param string $htmlid Html id to use instead of htmlname
  1459. * @return int <0 if KO, Nb of contact in list if OK
  1460. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1461. */
  1462. public function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
  1463. {
  1464. // phpcs:enable
  1465. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1466. return $this->num;
  1467. }
  1468. /**
  1469. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1470. * This also set the number of contacts found into $this->num
  1471. *
  1472. * @since 9.0 Add afterSelectContactOptions hook
  1473. *
  1474. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1475. * @param array|int $selected Array of ID of pre-selected contact id
  1476. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1477. * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
  1478. * @param string $exclude List of contacts id to exclude
  1479. * @param string $limitto Disable answers that are not id in this array list
  1480. * @param integer $showfunction Add function into label
  1481. * @param string $morecss Add more class to class style
  1482. * @param bool $options_only Return options only (for ajax treatment)
  1483. * @param integer $showsoc Add company into label
  1484. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1485. * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
  1486. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1487. * @param string $htmlid Html id to use instead of htmlname
  1488. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1489. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1490. * @return int|string <0 if KO, HTML with select string if OK.
  1491. */
  1492. public function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0)
  1493. {
  1494. global $conf, $langs, $hookmanager, $action;
  1495. $langs->load('companies');
  1496. if (empty($htmlid)) {
  1497. $htmlid = $htmlname;
  1498. }
  1499. $num = 0;
  1500. if ($selected === '') {
  1501. $selected = array();
  1502. } elseif (!is_array($selected)) {
  1503. $selected = array($selected);
  1504. }
  1505. $out = '';
  1506. if (!is_object($hookmanager)) {
  1507. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1508. $hookmanager = new HookManager($this->db);
  1509. }
  1510. // We search third parties
  1511. $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste, sp.email, sp.phone, sp.phone_perso, sp.phone_mobile, sp.town AS contact_town";
  1512. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1513. $sql .= ", s.nom as company, s.town AS company_town";
  1514. }
  1515. $sql .= " FROM ".$this->db->prefix()."socpeople as sp";
  1516. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1517. $sql .= " LEFT OUTER JOIN ".$this->db->prefix()."societe as s ON s.rowid=sp.fk_soc";
  1518. }
  1519. $sql .= " WHERE sp.entity IN (".getEntity('contact').")";
  1520. if ($socid > 0 || $socid == -1) {
  1521. $sql .= " AND sp.fk_soc = ".((int) $socid);
  1522. }
  1523. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1524. $sql .= " AND sp.statut <> 0";
  1525. }
  1526. // Add where from hooks
  1527. $parameters = array();
  1528. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1529. $sql .= $hookmanager->resPrint;
  1530. $sql .= " ORDER BY sp.lastname ASC";
  1531. dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
  1532. $resql = $this->db->query($sql);
  1533. if ($resql) {
  1534. $num = $this->db->num_rows($resql);
  1535. if ($htmlname != 'none' && !$options_only) {
  1536. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1537. }
  1538. if ($showempty && ! is_numeric($showempty)) {
  1539. $textforempty = $showempty;
  1540. $out .= '<option class="optiongrey" value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>'.$textforempty.'</option>';
  1541. } else {
  1542. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && ! $multiple) {
  1543. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1544. }
  1545. if ($showempty == 2) {
  1546. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1547. }
  1548. }
  1549. $i = 0;
  1550. if ($num) {
  1551. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1552. $contactstatic = new Contact($this->db);
  1553. while ($i < $num) {
  1554. $obj = $this->db->fetch_object($resql);
  1555. // Set email (or phones) and town extended infos
  1556. $extendedInfos = '';
  1557. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1558. $extendedInfos = array();
  1559. $email = trim($obj->email);
  1560. if (!empty($email)) {
  1561. $extendedInfos[] = $email;
  1562. } else {
  1563. $phone = trim($obj->phone);
  1564. $phone_perso = trim($obj->phone_perso);
  1565. $phone_mobile = trim($obj->phone_mobile);
  1566. if (!empty($phone)) {
  1567. $extendedInfos[] = $phone;
  1568. }
  1569. if (!empty($phone_perso)) {
  1570. $extendedInfos[] = $phone_perso;
  1571. }
  1572. if (!empty($phone_mobile)) {
  1573. $extendedInfos[] = $phone_mobile;
  1574. }
  1575. }
  1576. $contact_town = trim($obj->contact_town);
  1577. $company_town = trim($obj->company_town);
  1578. if (!empty($contact_town)) {
  1579. $extendedInfos[] = $contact_town;
  1580. } elseif (!empty($company_town)) {
  1581. $extendedInfos[] = $company_town;
  1582. }
  1583. $extendedInfos = implode(' - ', $extendedInfos);
  1584. if (!empty($extendedInfos)) {
  1585. $extendedInfos = ' - '.$extendedInfos;
  1586. }
  1587. }
  1588. $contactstatic->id = $obj->rowid;
  1589. $contactstatic->lastname = $obj->lastname;
  1590. $contactstatic->firstname = $obj->firstname;
  1591. if ($obj->statut == 1) {
  1592. if ($htmlname != 'none') {
  1593. $disabled = 0;
  1594. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1595. $disabled = 1;
  1596. }
  1597. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1598. $disabled = 1;
  1599. }
  1600. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1601. $out .= '<option value="'.$obj->rowid.'"';
  1602. if ($disabled) {
  1603. $out .= ' disabled';
  1604. }
  1605. $out .= ' selected>';
  1606. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1607. if ($showfunction && $obj->poste) {
  1608. $out .= ' ('.$obj->poste.')';
  1609. }
  1610. if (($showsoc > 0) && $obj->company) {
  1611. $out .= ' - ('.$obj->company.')';
  1612. }
  1613. $out .= '</option>';
  1614. } else {
  1615. $out .= '<option value="'.$obj->rowid.'"';
  1616. if ($disabled) {
  1617. $out .= ' disabled';
  1618. }
  1619. $out .= '>';
  1620. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1621. if ($showfunction && $obj->poste) {
  1622. $out .= ' ('.$obj->poste.')';
  1623. }
  1624. if (($showsoc > 0) && $obj->company) {
  1625. $out .= ' - ('.$obj->company.')';
  1626. }
  1627. $out .= '</option>';
  1628. }
  1629. } else {
  1630. if (in_array($obj->rowid, $selected)) {
  1631. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1632. if ($showfunction && $obj->poste) {
  1633. $out .= ' ('.$obj->poste.')';
  1634. }
  1635. if (($showsoc > 0) && $obj->company) {
  1636. $out .= ' - ('.$obj->company.')';
  1637. }
  1638. }
  1639. }
  1640. }
  1641. $i++;
  1642. }
  1643. } else {
  1644. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1645. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1646. $out .= $labeltoshow;
  1647. $out .= '</option>';
  1648. }
  1649. $parameters = array(
  1650. 'socid'=>$socid,
  1651. 'htmlname'=>$htmlname,
  1652. 'resql'=>$resql,
  1653. 'out'=>&$out,
  1654. 'showfunction'=>$showfunction,
  1655. 'showsoc'=>$showsoc,
  1656. );
  1657. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1658. if ($htmlname != 'none' && !$options_only) {
  1659. $out .= '</select>';
  1660. }
  1661. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1662. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1663. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1664. }
  1665. $this->num = $num;
  1666. return $out;
  1667. } else {
  1668. dol_print_error($this->db);
  1669. return -1;
  1670. }
  1671. }
  1672. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1673. /**
  1674. * Return the HTML select list of users
  1675. *
  1676. * @param string $selected Id user preselected
  1677. * @param string $htmlname Field name in form
  1678. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1679. * @param array $exclude Array list of users id to exclude
  1680. * @param int $disabled If select list must be disabled
  1681. * @param array|string $include Array list of users id to include. User '' for all users or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1682. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1683. * @param string $force_entity '0' or Ids of environment to force
  1684. * @return void
  1685. * @deprecated Use select_dolusers instead
  1686. * @see select_dolusers()
  1687. */
  1688. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1689. {
  1690. // phpcs:enable
  1691. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1692. }
  1693. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1694. /**
  1695. * Return select list of users
  1696. *
  1697. * @param string $selected User id or user object of user preselected. If 0 or < -2, we use id of current user. If -1, keep unselected (if empty is allowed)
  1698. * @param string $htmlname Field name in form
  1699. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1700. * @param array $exclude Array list of users id to exclude
  1701. * @param int $disabled If select list must be disabled
  1702. * @param array|string $include Array list of users id to include. User '' for all users or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1703. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1704. * @param string $force_entity '0' or Ids of environment to force
  1705. * @param int $maxlength Maximum length of string into list (0=no limit)
  1706. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1707. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1708. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1709. * @param string $enableonlytext If option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.
  1710. * @param string $morecss More css
  1711. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1712. * @param int $outputmode 0=HTML select string, 1=Array
  1713. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1714. * @return string HTML select string
  1715. * @see select_dolgroups()
  1716. */
  1717. public function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $noactive = 0, $outputmode = 0, $multiple = false)
  1718. {
  1719. // phpcs:enable
  1720. global $conf, $user, $langs, $hookmanager;
  1721. // If no preselected user defined, we take current user
  1722. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1723. $selected = $user->id;
  1724. }
  1725. if ($selected === '') {
  1726. $selected = array();
  1727. } elseif (!is_array($selected)) {
  1728. $selected = array($selected);
  1729. }
  1730. $excludeUsers = null;
  1731. $includeUsers = null;
  1732. // Permettre l'exclusion d'utilisateurs
  1733. if (is_array($exclude)) {
  1734. $excludeUsers = implode(",", $exclude);
  1735. }
  1736. // Permettre l'inclusion d'utilisateurs
  1737. if (is_array($include)) {
  1738. $includeUsers = implode(",", $include);
  1739. } elseif ($include == 'hierarchy') {
  1740. // Build list includeUsers to have only hierarchy
  1741. $includeUsers = implode(",", $user->getAllChildIds(0));
  1742. } elseif ($include == 'hierarchyme') {
  1743. // Build list includeUsers to have only hierarchy and current user
  1744. $includeUsers = implode(",", $user->getAllChildIds(1));
  1745. }
  1746. $out = '';
  1747. $outarray = array();
  1748. // Forge request to select users
  1749. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1750. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1751. $sql .= ", e.label";
  1752. }
  1753. $sql .= " FROM ".$this->db->prefix()."user as u";
  1754. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1755. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid = u.entity";
  1756. if ($force_entity) {
  1757. $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
  1758. } else {
  1759. $sql .= " WHERE u.entity IS NOT NULL";
  1760. }
  1761. } else {
  1762. if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1763. $sql .= " LEFT JOIN ".$this->db->prefix()."usergroup_user as ug";
  1764. $sql .= " ON ug.fk_user = u.rowid";
  1765. $sql .= " WHERE ug.entity = ".$conf->entity;
  1766. } else {
  1767. $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
  1768. }
  1769. }
  1770. if (!empty($user->socid)) {
  1771. $sql .= " AND u.fk_soc = ".((int) $user->socid);
  1772. }
  1773. if (is_array($exclude) && $excludeUsers) {
  1774. $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
  1775. }
  1776. if ($includeUsers) {
  1777. $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
  1778. }
  1779. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) {
  1780. $sql .= " AND u.statut <> 0";
  1781. }
  1782. if (!empty($morefilter)) {
  1783. $sql .= " ".$morefilter;
  1784. }
  1785. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1786. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1787. if (!empty($reshook)) {
  1788. $sql .= $hookmanager->resPrint;
  1789. }
  1790. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1791. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1792. } else {
  1793. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1794. }
  1795. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1796. $resql = $this->db->query($sql);
  1797. if ($resql) {
  1798. $num = $this->db->num_rows($resql);
  1799. $i = 0;
  1800. if ($num) {
  1801. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1802. $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1803. if ($show_empty && !$multiple) {
  1804. $textforempty = ' ';
  1805. if (!empty($conf->use_javascript_ajax)) {
  1806. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1807. }
  1808. if (!is_numeric($show_empty)) {
  1809. $textforempty = $show_empty;
  1810. }
  1811. $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  1812. }
  1813. if ($show_every) {
  1814. $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1815. }
  1816. $userstatic = new User($this->db);
  1817. while ($i < $num) {
  1818. $obj = $this->db->fetch_object($resql);
  1819. $userstatic->id = $obj->rowid;
  1820. $userstatic->lastname = $obj->lastname;
  1821. $userstatic->firstname = $obj->firstname;
  1822. $userstatic->photo = $obj->photo;
  1823. $userstatic->statut = $obj->status;
  1824. $userstatic->entity = $obj->entity;
  1825. $userstatic->admin = $obj->admin;
  1826. $disableline = '';
  1827. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1828. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1829. }
  1830. $labeltoshow = '';
  1831. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1832. $fullNameMode = 0;
  1833. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1834. $fullNameMode = 1; //Firstname+lastname
  1835. }
  1836. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1837. if (empty($obj->firstname) && empty($obj->lastname)) {
  1838. $labeltoshow .= $obj->login;
  1839. }
  1840. // Complete name with more info
  1841. $moreinfo = '';
  1842. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1843. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1844. }
  1845. if ($showstatus >= 0) {
  1846. if ($obj->status == 1 && $showstatus == 1) {
  1847. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1848. }
  1849. if ($obj->status == 0 && $showstatus == 1) {
  1850. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1851. }
  1852. }
  1853. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1854. if (!$obj->entity) {
  1855. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1856. } else {
  1857. if ($obj->entity != $conf->entity) {
  1858. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1859. }
  1860. }
  1861. }
  1862. $moreinfo .= ($moreinfo ? ')' : '');
  1863. if ($disableline && $disableline != '1') {
  1864. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1865. }
  1866. $labeltoshow .= $moreinfo;
  1867. $out .= '<option value="'.$obj->rowid.'"';
  1868. if ($disableline) {
  1869. $out .= ' disabled';
  1870. }
  1871. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1872. $out .= ' selected';
  1873. }
  1874. $out .= ' data-html="';
  1875. $outhtml = '';
  1876. // if (!empty($obj->photo)) {
  1877. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1878. // }
  1879. if ($showstatus >= 0 && $obj->status == 0) {
  1880. $outhtml .= '<strike class="opacitymediumxxx">';
  1881. }
  1882. $outhtml .= $labeltoshow;
  1883. if ($showstatus >= 0 && $obj->status == 0) {
  1884. $outhtml .= '</strike>';
  1885. }
  1886. $out .= dol_escape_htmltag($outhtml);
  1887. $out .= '">';
  1888. $out .= $labeltoshow;
  1889. $out .= '</option>';
  1890. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1891. $i++;
  1892. }
  1893. } else {
  1894. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1895. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1896. }
  1897. $out .= '</select>';
  1898. if ($num) {
  1899. // Enhance with select2
  1900. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1901. $out .= ajax_combobox($htmlname);
  1902. }
  1903. } else {
  1904. dol_print_error($this->db);
  1905. }
  1906. if ($outputmode) {
  1907. return $outarray;
  1908. }
  1909. return $out;
  1910. }
  1911. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1912. /**
  1913. * Return select list of users. Selected users are stored into session.
  1914. * List of users are provided into $_SESSION['assignedtouser'].
  1915. *
  1916. * @param string $action Value for $action
  1917. * @param string $htmlname Field name in form
  1918. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1919. * @param array $exclude Array list of users id to exclude
  1920. * @param int $disabled If select list must be disabled
  1921. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1922. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1923. * @param int $force_entity '0' or Ids of environment to force
  1924. * @param int $maxlength Maximum length of string into list (0=no limit)
  1925. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1926. * @param string $morefilter Add more filters into sql request
  1927. * @param int $showproperties Show properties of each attendees
  1928. * @param array $listofuserid Array with properties of each user
  1929. * @param array $listofcontactid Array with properties of each contact
  1930. * @param array $listofotherid Array with properties of each other contact
  1931. * @return string HTML select string
  1932. * @see select_dolgroups()
  1933. */
  1934. public function select_dolusers_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofuserid = array(), $listofcontactid = array(), $listofotherid = array())
  1935. {
  1936. // phpcs:enable
  1937. global $conf, $user, $langs;
  1938. $userstatic = new User($this->db);
  1939. $out = '';
  1940. $assignedtouser = array();
  1941. if (!empty($_SESSION['assignedtouser'])) {
  1942. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1943. }
  1944. $nbassignetouser = count($assignedtouser);
  1945. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1946. if ($nbassignetouser) {
  1947. $out .= '<ul class="attendees">';
  1948. }
  1949. $i = 0;
  1950. $ownerid = 0;
  1951. foreach ($assignedtouser as $key => $value) {
  1952. if ($value['id'] == $ownerid) {
  1953. continue;
  1954. }
  1955. $out .= '<li>';
  1956. $userstatic->fetch($value['id']);
  1957. $out .= $userstatic->getNomUrl(-1);
  1958. if ($i == 0) {
  1959. $ownerid = $value['id'];
  1960. $out .= ' ('.$langs->trans("Owner").')';
  1961. }
  1962. if ($nbassignetouser > 1 && $action != 'view') {
  1963. $out .= ' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned reposition" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
  1964. }
  1965. // Show my availability
  1966. if ($showproperties) {
  1967. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  1968. $out .= '<div class="myavailability inline-block">';
  1969. $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span> </span><input id="transparency" class="paddingrightonly" '.($action == 'view' ? 'disabled' : '').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency'] ? ' checked' : '').'><label for="transparency">'.$langs->trans("Busy").'</label>';
  1970. $out .= '</div>';
  1971. }
  1972. }
  1973. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1974. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1975. $out .= '</li>';
  1976. $i++;
  1977. }
  1978. if ($nbassignetouser) {
  1979. $out .= '</ul>';
  1980. }
  1981. // Method with no ajax
  1982. if ($action != 'view') {
  1983. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1984. $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
  1985. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  1986. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  1987. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  1988. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  1989. $out .= '});';
  1990. $out .= '})</script>';
  1991. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1992. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1993. $out .= '<br>';
  1994. }
  1995. return $out;
  1996. }
  1997. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1998. /**
  1999. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2000. *
  2001. * @param int $selected Preselected products
  2002. * @param string $htmlname Name of HTML select field (must be unique in page).
  2003. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2004. * @param int $limit Limit on number of returned lines
  2005. * @param int $price_level Level of price to show
  2006. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2007. * @param int $finished 2=all, 1=finished, 0=raw material
  2008. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2009. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2010. * @param array $ajaxoptions Options for ajax_autocompleter
  2011. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2012. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2013. * @param int $forcecombo Force to use combo box
  2014. * @param string $morecss Add more css on select
  2015. * @param int $hidepriceinlabel 1=Hide prices in label
  2016. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2017. * 'warehouseopen' = count products from open warehouses,
  2018. * 'warehouseclosed' = count products from closed warehouses,
  2019. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2020. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2021. * @param string $nooutput No print, return the output into a string
  2022. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2023. * @return void|string
  2024. */
  2025. public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 0, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = null, $nooutput = 0, $status_purchase = -1)
  2026. {
  2027. // phpcs:enable
  2028. global $langs, $conf;
  2029. $out = '';
  2030. // check parameters
  2031. $price_level = (!empty($price_level) ? $price_level : 0);
  2032. if (is_null($ajaxoptions)) {
  2033. $ajaxoptions = array();
  2034. }
  2035. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  2036. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  2037. $filtertype = '0';
  2038. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  2039. $filtertype = '1';
  2040. }
  2041. }
  2042. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2043. $placeholder = '';
  2044. if ($selected && empty($selected_input_value)) {
  2045. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2046. $producttmpselect = new Product($this->db);
  2047. $producttmpselect->fetch($selected);
  2048. $selected_input_value = $producttmpselect->ref;
  2049. unset($producttmpselect);
  2050. }
  2051. // handle case where product or service module is disabled + no filter specified
  2052. if ($filtertype == '') {
  2053. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2054. $filtertype = 1;
  2055. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2056. $filtertype = 0;
  2057. }
  2058. }
  2059. // mode=1 means customers products
  2060. $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&status_purchase='.$status_purchase.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  2061. //Price by customer
  2062. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2063. $urloption .= '&socid='.$socid;
  2064. }
  2065. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2066. if (!empty($conf->variants->enabled) && is_array($selected_combinations)) {
  2067. // Code to automatically insert with javascript the select of attributes under the select of product
  2068. // when a parent of variant has been selected.
  2069. $out .= '
  2070. <!-- script to auto show attributes select tags if a variant was selected -->
  2071. <script>
  2072. // auto show attributes fields
  2073. selected = '.json_encode($selected_combinations).';
  2074. combvalues = {};
  2075. jQuery(document).ready(function () {
  2076. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2077. if (jQuery(this).val() == \'free\') {
  2078. jQuery(\'div#attributes_box\').empty();
  2079. }
  2080. });
  2081. jQuery("input#'.$htmlname.'").change(function () {
  2082. if (!jQuery(this).val()) {
  2083. jQuery(\'div#attributes_box\').empty();
  2084. return;
  2085. }
  2086. console.log("A change has started. We get variants fields to inject html select");
  2087. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  2088. id: jQuery(this).val()
  2089. }, function (data) {
  2090. jQuery(\'div#attributes_box\').empty();
  2091. jQuery.each(data, function (key, val) {
  2092. combvalues[val.id] = val.values;
  2093. var span = jQuery(document.createElement(\'div\')).css({
  2094. \'display\': \'table-row\'
  2095. });
  2096. span.append(
  2097. jQuery(document.createElement(\'div\')).text(val.label).css({
  2098. \'font-weight\': \'bold\',
  2099. \'display\': \'table-cell\'
  2100. })
  2101. );
  2102. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2103. \'margin-left\': \'15px\',
  2104. \'white-space\': \'pre\'
  2105. }).append(
  2106. jQuery(document.createElement(\'option\')).val(\'\')
  2107. );
  2108. jQuery.each(combvalues[val.id], function (key, val) {
  2109. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2110. if (selected[val.fk_product_attribute] == val.id) {
  2111. tag.attr(\'selected\', \'selected\');
  2112. }
  2113. html.append(tag);
  2114. });
  2115. span.append(html);
  2116. jQuery(\'div#attributes_box\').append(span);
  2117. });
  2118. })
  2119. });
  2120. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  2121. });
  2122. </script>
  2123. ';
  2124. }
  2125. if (empty($hidelabel)) {
  2126. $out .= $langs->trans("RefOrLabel").' : ';
  2127. } elseif ($hidelabel > 1) {
  2128. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  2129. if ($hidelabel == 2) {
  2130. $out .= img_picto($langs->trans("Search"), 'search');
  2131. }
  2132. }
  2133. $out .= '<input type="text" class="minwidth100'.($morecss ? ' '.$morecss : '').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  2134. if ($hidelabel == 3) {
  2135. $out .= img_picto($langs->trans("Search"), 'search');
  2136. }
  2137. } else {
  2138. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2139. }
  2140. if (empty($nooutput)) {
  2141. print $out;
  2142. } else {
  2143. return $out;
  2144. }
  2145. }
  2146. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2147. /**
  2148. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2149. *
  2150. * @param int $selected Preselected BOM id
  2151. * @param string $htmlname Name of HTML select field (must be unique in page).
  2152. * @param int $limit Limit on number of returned lines
  2153. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2154. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2155. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2156. * @param string $morecss Add more css on select
  2157. * @param string $nooutput No print, return the output into a string
  2158. * @param int $forcecombo Force to use combo box
  2159. * @return void|string
  2160. */
  2161. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 1, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0)
  2162. {
  2163. // phpcs:enable
  2164. global $conf, $user, $langs, $db;
  2165. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2166. $error = 0;
  2167. $out = '';
  2168. if (!$forcecombo) {
  2169. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2170. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2171. }
  2172. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2173. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2174. $sql.= ' FROM '.MAIN_DB_PREFIX.'bom_bom as b';
  2175. $sql.= ' WHERE b.entity IN ('.getEntity('bom').')';
  2176. if (!empty($status)) $sql.= ' AND status = '. (int) $status;
  2177. if (!empty($type)) $sql.= ' AND status = '. (int) $type;
  2178. if (!empty($limit)) $sql.= 'LIMIT '. (int) $limit;
  2179. $resql = $db->query($sql);
  2180. if ($resql) {
  2181. if ($showempty) {
  2182. $out .= '<option value="-1"';
  2183. if (empty($selected)) $out .= ' selected';
  2184. $out .= '>&nbsp;</option>';
  2185. }
  2186. while ($obj = $db->fetch_object($resql)) {
  2187. $product = new Product($db);
  2188. $res = $product->fetch($obj->fk_product);
  2189. if ($obj->rowid == $selected) $out .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.' - '. $product->label .' - '.$obj->label.'</option>';
  2190. $out .= '<option value="'.$obj->rowid.'">'.$obj->ref.' - '.$product->label .' - '. $obj->label.'</option>';
  2191. }
  2192. } else {
  2193. $error++;
  2194. dol_print_error($db);
  2195. }
  2196. if (empty($nooutput)) {
  2197. print $out;
  2198. } else {
  2199. return $out;
  2200. }
  2201. }
  2202. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2203. /**
  2204. * Return list of products for a customer.
  2205. * Called by select_produits.
  2206. *
  2207. * @param int $selected Preselected product
  2208. * @param string $htmlname Name of select html
  2209. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2210. * @param int $limit Limit on number of returned lines
  2211. * @param int $price_level Level of price to show
  2212. * @param string $filterkey Filter on product
  2213. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2214. * @param int $finished Filter on finished field: 2=No filter
  2215. * @param int $outputmode 0=HTML select string, 1=Array
  2216. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2217. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2218. * @param int $forcecombo Force to use combo box
  2219. * @param string $morecss Add more css on select
  2220. * @param int $hidepriceinlabel 1=Hide prices in label
  2221. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2222. * 'warehouseopen' = count products from open warehouses,
  2223. * 'warehouseclosed' = count products from closed warehouses,
  2224. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2225. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2226. * @return array Array of keys for json
  2227. */
  2228. public function select_produits_list($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $status_purchase = -1)
  2229. {
  2230. // phpcs:enable
  2231. global $langs, $conf;
  2232. global $hookmanager;
  2233. $out = '';
  2234. $outarray = array();
  2235. // Units
  2236. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2237. $langs->load('other');
  2238. }
  2239. $warehouseStatusArray = array();
  2240. if (!empty($warehouseStatus)) {
  2241. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2242. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2243. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2244. }
  2245. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2246. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2247. }
  2248. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2249. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2250. }
  2251. }
  2252. $selectFields = " p.rowid, p.ref, p.label, p.description, p.barcode, p.fk_country, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.default_vat_code, p.duration, p.fk_price_expression";
  2253. if (count($warehouseStatusArray)) {
  2254. $selectFieldsGrouped = ", sum(".$this->db->ifsql("e.statut IS NULL", "0", "ps.reel").") as stock"; // e.statut is null if there is no record in stock
  2255. } else {
  2256. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  2257. }
  2258. $sql = "SELECT ";
  2259. $sql .= $selectFields.$selectFieldsGrouped;
  2260. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2261. //Product category
  2262. $sql .= ", (SELECT ".$this->db->prefix()."categorie_product.fk_categorie
  2263. FROM ".$this->db->prefix()."categorie_product
  2264. WHERE ".$this->db->prefix()."categorie_product.fk_product=p.rowid
  2265. LIMIT 1
  2266. ) AS categorie_product_id ";
  2267. }
  2268. //Price by customer
  2269. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2270. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2271. $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx, pcp.default_vat_code as custdefault_vat_code, pcp.ref_customer as custref';
  2272. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2273. }
  2274. // Units
  2275. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2276. $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units";
  2277. $selectFields .= ', unit_long, unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units';
  2278. }
  2279. // Multilang : we add translation
  2280. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2281. $sql .= ", pl.label as label_translated";
  2282. $sql .= ", pl.description as description_translated";
  2283. $selectFields .= ", label_translated";
  2284. $selectFields .= ", description_translated";
  2285. }
  2286. // Price by quantity
  2287. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2288. $sql .= ", (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid";
  2289. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2290. $sql .= " AND price_level = ".((int) $price_level);
  2291. }
  2292. $sql .= " ORDER BY date_price";
  2293. $sql .= " DESC LIMIT 1) as price_rowid";
  2294. $sql .= ", (SELECT pp.price_by_qty FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid"; // price_by_qty is 1 if some prices by qty exists in subtable
  2295. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2296. $sql .= " AND price_level = ".((int) $price_level);
  2297. }
  2298. $sql .= " ORDER BY date_price";
  2299. $sql .= " DESC LIMIT 1) as price_by_qty";
  2300. $selectFields .= ", price_rowid, price_by_qty";
  2301. }
  2302. $sql .= " FROM ".$this->db->prefix()."product as p";
  2303. if (count($warehouseStatusArray)) {
  2304. $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock as ps on ps.fk_product = p.rowid";
  2305. $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  2306. $sql .= ' AND e.statut IN ('.$this->db->sanitize($this->db->escape(implode(',', $warehouseStatusArray))).')'; // Return line if product is inside the selected stock. If not, an empty line will be returned so we will count 0.
  2307. }
  2308. // include search in supplier ref
  2309. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2310. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2311. }
  2312. //Price by customer
  2313. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2314. $sql .= " LEFT JOIN ".$this->db->prefix()."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
  2315. }
  2316. // Units
  2317. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2318. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2319. }
  2320. // Multilang : we add translation
  2321. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2322. $sql .= " LEFT JOIN ".$this->db->prefix()."product_lang as pl ON pl.fk_product = p.rowid ";
  2323. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2324. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  2325. $soc = new Societe($this->db);
  2326. $result = $soc->fetch($socid);
  2327. if ($result > 0 && !empty($soc->default_lang)) {
  2328. $sql .= " AND pl.lang = '".$this->db->escape($soc->default_lang)."'";
  2329. } else {
  2330. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2331. }
  2332. } else {
  2333. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2334. }
  2335. }
  2336. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2337. $sql .= " LEFT JOIN ".$this->db->prefix()."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2338. }
  2339. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  2340. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2341. $sql .= " AND pac.rowid IS NULL";
  2342. }
  2343. if ($finished == 0) {
  2344. $sql .= " AND p.finished = ".((int) $finished);
  2345. } elseif ($finished == 1) {
  2346. $sql .= " AND p.finished = ".((int) $finished);
  2347. if ($status >= 0) {
  2348. $sql .= " AND p.tosell = ".((int) $status);
  2349. }
  2350. } elseif ($status >= 0) {
  2351. $sql .= " AND p.tosell = ".((int) $status);
  2352. }
  2353. if ($status_purchase >= 0) {
  2354. $sql .= " AND p.tobuy = ".((int) $status_purchase);
  2355. }
  2356. // Filter by product type
  2357. if (strval($filtertype) != '') {
  2358. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2359. } elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2360. $sql .= " AND p.fk_product_type = 1";
  2361. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2362. $sql .= " AND p.fk_product_type = 0";
  2363. }
  2364. // Add where from hooks
  2365. $parameters = array();
  2366. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2367. $sql .= $hookmanager->resPrint;
  2368. // Add criteria on ref/label
  2369. if ($filterkey != '') {
  2370. $sql .= ' AND (';
  2371. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2372. // For natural search
  2373. $scrit = explode(' ', $filterkey);
  2374. $i = 0;
  2375. if (count($scrit) > 1) {
  2376. $sql .= "(";
  2377. }
  2378. foreach ($scrit as $crit) {
  2379. if ($i > 0) {
  2380. $sql .= " AND ";
  2381. }
  2382. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2383. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2384. $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2385. }
  2386. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && ! empty($socid)) {
  2387. $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
  2388. }
  2389. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2390. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2391. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2392. $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2393. }
  2394. }
  2395. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2396. $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2397. }
  2398. $sql .= ")";
  2399. $i++;
  2400. }
  2401. if (count($scrit) > 1) {
  2402. $sql .= ")";
  2403. }
  2404. if (!empty($conf->barcode->enabled)) {
  2405. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2406. }
  2407. $sql .= ')';
  2408. }
  2409. if (count($warehouseStatusArray)) {
  2410. $sql .= " GROUP BY ".$selectFields;
  2411. }
  2412. //Sort by category
  2413. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2414. $sql .= " ORDER BY categorie_product_id ";
  2415. //ASC OR DESC order
  2416. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2417. } else {
  2418. $sql .= $this->db->order("p.ref");
  2419. }
  2420. $sql .= $this->db->plimit($limit, 0);
  2421. // Build output string
  2422. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2423. $result = $this->db->query($sql);
  2424. if ($result) {
  2425. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2426. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2427. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2428. $num = $this->db->num_rows($result);
  2429. $events = null;
  2430. if (!$forcecombo) {
  2431. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2432. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2433. }
  2434. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2435. $textifempty = '';
  2436. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2437. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2438. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2439. if ($showempty && !is_numeric($showempty)) {
  2440. $textifempty = $langs->trans($showempty);
  2441. } else {
  2442. $textifempty .= $langs->trans("All");
  2443. }
  2444. } else {
  2445. if ($showempty && !is_numeric($showempty)) {
  2446. $textifempty = $langs->trans($showempty);
  2447. }
  2448. }
  2449. if ($showempty) {
  2450. $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
  2451. }
  2452. $i = 0;
  2453. while ($num && $i < $num) {
  2454. $opt = '';
  2455. $optJson = array();
  2456. $objp = $this->db->fetch_object($result);
  2457. if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1) { // Price by quantity will return many prices for the same product
  2458. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2459. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2460. $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
  2461. $sql .= " ORDER BY quantity ASC";
  2462. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2463. $result2 = $this->db->query($sql);
  2464. if ($result2) {
  2465. $nb_prices = $this->db->num_rows($result2);
  2466. $j = 0;
  2467. while ($nb_prices && $j < $nb_prices) {
  2468. $objp2 = $this->db->fetch_object($result2);
  2469. $objp->price_by_qty_rowid = $objp2->rowid;
  2470. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2471. $objp->price_by_qty_quantity = $objp2->quantity;
  2472. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2473. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2474. // For backward compatibility
  2475. $objp->quantity = $objp2->quantity;
  2476. $objp->price = $objp2->price;
  2477. $objp->unitprice = $objp2->unitprice;
  2478. $objp->remise_percent = $objp2->remise_percent;
  2479. $objp->remise = $objp2->remise;
  2480. //$objp->tva_tx is not overwritten by $objp2 value
  2481. //$objp->default_vat_code is not overwritten by $objp2 value
  2482. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2483. $j++;
  2484. // Add new entry
  2485. // "key" value of json key array is used by jQuery automatically as selected value
  2486. // "label" value of json key array is used by jQuery automatically as text for combo box
  2487. $out .= $opt;
  2488. array_push($outarray, $optJson);
  2489. }
  2490. }
  2491. } else {
  2492. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2493. $price_product = new Product($this->db);
  2494. $price_product->fetch($objp->rowid, '', '', 1);
  2495. $priceparser = new PriceParser($this->db);
  2496. $price_result = $priceparser->parseProduct($price_product);
  2497. if ($price_result >= 0) {
  2498. $objp->price = $price_result;
  2499. $objp->unitprice = $price_result;
  2500. //Calculate the VAT
  2501. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2502. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2503. }
  2504. }
  2505. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2506. // Add new entry
  2507. // "key" value of json key array is used by jQuery automatically as selected value
  2508. // "label" value of json key array is used by jQuery automatically as text for combo box
  2509. $out .= $opt;
  2510. array_push($outarray, $optJson);
  2511. }
  2512. $i++;
  2513. }
  2514. $out .= '</select>';
  2515. $this->db->free($result);
  2516. if (empty($outputmode)) {
  2517. return $out;
  2518. }
  2519. return $outarray;
  2520. } else {
  2521. dol_print_error($this->db);
  2522. }
  2523. }
  2524. /**
  2525. * Function to forge the string with OPTIONs of SELECT.
  2526. * This define value for &$opt and &$optJson.
  2527. * This function is called by select_produits_list().
  2528. *
  2529. * @param resource $objp Resultset of fetch
  2530. * @param string $opt Option (var used for returned value in string option format)
  2531. * @param string $optJson Option (var used for returned value in json format)
  2532. * @param int $price_level Price level
  2533. * @param string $selected Preselected value
  2534. * @param int $hidepriceinlabel Hide price in label
  2535. * @param string $filterkey Filter key to highlight
  2536. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2537. * @return void
  2538. */
  2539. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2540. {
  2541. global $langs, $conf, $user;
  2542. $outkey = '';
  2543. $outval = '';
  2544. $outref = '';
  2545. $outlabel = '';
  2546. $outlabel_translated = '';
  2547. $outdesc = '';
  2548. $outdesc_translated = '';
  2549. $outbarcode = '';
  2550. $outorigin = '';
  2551. $outtype = '';
  2552. $outprice_ht = '';
  2553. $outprice_ttc = '';
  2554. $outpricebasetype = '';
  2555. $outtva_tx = '';
  2556. $outdefault_vat_code = '';
  2557. $outqty = 1;
  2558. $outdiscount = 0;
  2559. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2560. $label = $objp->label;
  2561. if (!empty($objp->label_translated)) {
  2562. $label = $objp->label_translated;
  2563. }
  2564. if (!empty($filterkey) && $filterkey != '') {
  2565. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2566. }
  2567. $outkey = $objp->rowid;
  2568. $outref = $objp->ref;
  2569. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2570. $outlabel = $objp->label;
  2571. $outdesc = $objp->description;
  2572. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2573. $outlabel_translated = $objp->label_translated;
  2574. $outdesc_translated = $objp->description_translated;
  2575. }
  2576. $outbarcode = $objp->barcode;
  2577. $outorigin = $objp->fk_country;
  2578. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2579. $outtype = $objp->fk_product_type;
  2580. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2581. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2582. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2583. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2584. }
  2585. // Units
  2586. $outvalUnits = '';
  2587. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2588. if (!empty($objp->unit_short)) {
  2589. $outvalUnits .= ' - '.$objp->unit_short;
  2590. }
  2591. }
  2592. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2593. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2594. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2595. $outvalUnits .= ' - '.$unitToShow;
  2596. }
  2597. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2598. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2599. $outvalUnits .= ' - '.$unitToShow;
  2600. }
  2601. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2602. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2603. $outvalUnits .= ' - '.$unitToShow;
  2604. }
  2605. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2606. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2607. $outvalUnits .= ' - '.$unitToShow;
  2608. }
  2609. }
  2610. if ($outdurationvalue && $outdurationunit) {
  2611. $da = array(
  2612. 'h' => $langs->trans('Hour'),
  2613. 'd' => $langs->trans('Day'),
  2614. 'w' => $langs->trans('Week'),
  2615. 'm' => $langs->trans('Month'),
  2616. 'y' => $langs->trans('Year')
  2617. );
  2618. if (isset($da[$outdurationunit])) {
  2619. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2620. }
  2621. }
  2622. $opt = '<option value="'.$objp->rowid.'"';
  2623. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2624. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2625. $opt .= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqup="'.$objp->price_by_qty_unitprice.'" data-pbqbase="'.$objp->price_by_qty_price_base_type.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
  2626. }
  2627. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2628. if (!empty($user->rights->stock->lire)) {
  2629. if ($objp->stock > 0) {
  2630. $opt .= ' class="product_line_stock_ok"';
  2631. } elseif ($objp->stock <= 0) {
  2632. $opt .= ' class="product_line_stock_too_low"';
  2633. }
  2634. }
  2635. }
  2636. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2637. $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
  2638. $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
  2639. }
  2640. $opt .= '>';
  2641. $opt .= $objp->ref;
  2642. if (! empty($objp->custref)) {
  2643. $opt.= ' (' . $objp->custref . ')';
  2644. }
  2645. if ($outbarcode) {
  2646. $opt .= ' ('.$outbarcode.')';
  2647. }
  2648. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2649. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2650. $opt .= ' ('.getCountry($outorigin, 1).')';
  2651. }
  2652. $objRef = $objp->ref;
  2653. if (! empty($objp->custref)) {
  2654. $objRef .= ' (' . $objp->custref . ')';
  2655. }
  2656. if (!empty($filterkey) && $filterkey != '') {
  2657. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2658. }
  2659. $outval .= $objRef;
  2660. if ($outbarcode) {
  2661. $outval .= ' ('.$outbarcode.')';
  2662. }
  2663. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2664. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2665. $outval .= ' ('.getCountry($outorigin, 1).')';
  2666. }
  2667. // Units
  2668. $opt .= $outvalUnits;
  2669. $outval .= $outvalUnits;
  2670. $found = 0;
  2671. // Multiprice
  2672. // If we need a particular price level (from 1 to n)
  2673. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2674. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2675. $sql .= " FROM ".$this->db->prefix()."product_price";
  2676. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2677. $sql .= " AND entity IN (".getEntity('productprice').")";
  2678. $sql .= " AND price_level = ".((int) $price_level);
  2679. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2680. $sql .= " LIMIT 1";
  2681. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2682. $result2 = $this->db->query($sql);
  2683. if ($result2) {
  2684. $objp2 = $this->db->fetch_object($result2);
  2685. if ($objp2) {
  2686. $found = 1;
  2687. if ($objp2->price_base_type == 'HT') {
  2688. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2689. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2690. } else {
  2691. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2692. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2693. }
  2694. $outprice_ht = price($objp2->price);
  2695. $outprice_ttc = price($objp2->price_ttc);
  2696. $outpricebasetype = $objp2->price_base_type;
  2697. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2698. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2699. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2700. } else {
  2701. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2702. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2703. }
  2704. }
  2705. } else {
  2706. dol_print_error($this->db);
  2707. }
  2708. }
  2709. // Price by quantity
  2710. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2711. $found = 1;
  2712. $outqty = $objp->quantity;
  2713. $outdiscount = $objp->remise_percent;
  2714. if ($objp->quantity == 1) {
  2715. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2716. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2717. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2718. $outval .= $langs->transnoentities("Unit");
  2719. } else {
  2720. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2721. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2722. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2723. $outval .= $langs->transnoentities("Units");
  2724. }
  2725. $outprice_ht = price($objp->unitprice);
  2726. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2727. $outpricebasetype = $objp->price_base_type;
  2728. $outtva_tx = $objp->tva_tx; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
  2729. $outdefault_vat_code = $objp->default_vat_code; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
  2730. }
  2731. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2732. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2733. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2734. }
  2735. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2736. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2737. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2738. }
  2739. // Price by customer
  2740. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2741. if (!empty($objp->idprodcustprice)) {
  2742. $found = 1;
  2743. if ($objp->custprice_base_type == 'HT') {
  2744. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2745. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2746. } else {
  2747. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2748. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2749. }
  2750. $outprice_ht = price($objp->custprice);
  2751. $outprice_ttc = price($objp->custprice_ttc);
  2752. $outpricebasetype = $objp->custprice_base_type;
  2753. $outtva_tx = $objp->custtva_tx;
  2754. $outdefault_vat_code = $objp->custdefault_vat_code;
  2755. }
  2756. }
  2757. // If level no defined or multiprice not found, we used the default price
  2758. if (empty($hidepriceinlabel) && !$found) {
  2759. if ($objp->price_base_type == 'HT') {
  2760. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2761. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2762. } else {
  2763. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2764. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2765. }
  2766. $outprice_ht = price($objp->price);
  2767. $outprice_ttc = price($objp->price_ttc);
  2768. $outpricebasetype = $objp->price_base_type;
  2769. $outtva_tx = $objp->tva_tx;
  2770. $outdefault_vat_code = $objp->default_vat_code;
  2771. }
  2772. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2773. if (!empty($user->rights->stock->lire)) {
  2774. $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  2775. if ($objp->stock > 0) {
  2776. $outval .= ' - <span class="product_line_stock_ok">';
  2777. } elseif ($objp->stock <= 0) {
  2778. $outval .= ' - <span class="product_line_stock_too_low">';
  2779. }
  2780. $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
  2781. $outval .= '</span>';
  2782. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2783. $langs->load("stocks");
  2784. $tmpproduct = new Product($this->db);
  2785. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2786. $tmpproduct->load_virtual_stock();
  2787. $virtualstock = $tmpproduct->stock_theorique;
  2788. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2789. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2790. if ($virtualstock > 0) {
  2791. $outval .= '<span class="product_line_stock_ok">';
  2792. } elseif ($virtualstock <= 0) {
  2793. $outval .= '<span class="product_line_stock_too_low">';
  2794. }
  2795. $outval .= $virtualstock;
  2796. $outval .= '</span>';
  2797. unset($tmpproduct);
  2798. }
  2799. }
  2800. }
  2801. $opt .= "</option>\n";
  2802. $optJson = array(
  2803. 'key'=>$outkey,
  2804. 'value'=>$outref,
  2805. 'label'=>$outval,
  2806. 'label2'=>$outlabel,
  2807. 'desc'=>$outdesc,
  2808. 'type'=>$outtype,
  2809. 'price_ht'=>price2num($outprice_ht),
  2810. 'price_ttc'=>price2num($outprice_ttc),
  2811. 'pricebasetype'=>$outpricebasetype,
  2812. 'tva_tx'=>$outtva_tx,
  2813. 'default_vat_code'=>$outdefault_vat_code,
  2814. 'qty'=>$outqty,
  2815. 'discount'=>$outdiscount,
  2816. 'duration_value'=>$outdurationvalue,
  2817. 'duration_unit'=>$outdurationunit,
  2818. 'pbq'=>$outpbq,
  2819. 'labeltrans'=>$outlabel_translated,
  2820. 'desctrans'=>$outdesc_translated,
  2821. 'ref_customer'=>$outrefcust
  2822. );
  2823. }
  2824. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2825. /**
  2826. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2827. *
  2828. * @param int $socid Id third party
  2829. * @param string $selected Preselected product
  2830. * @param string $htmlname Name of HTML Select
  2831. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2832. * @param string $filtre For a SQL filter
  2833. * @param array $ajaxoptions Options for ajax_autocompleter
  2834. * @param int $hidelabel Hide label (0=no, 1=yes)
  2835. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2836. * @param string $morecss More CSS
  2837. * @param string $placeholder Placeholder
  2838. * @return void
  2839. */
  2840. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2841. {
  2842. // phpcs:enable
  2843. global $langs, $conf;
  2844. global $price_level, $status, $finished;
  2845. if (!isset($status)) {
  2846. $status = 1;
  2847. }
  2848. $selected_input_value = '';
  2849. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2850. if ($selected > 0) {
  2851. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2852. $producttmpselect = new Product($this->db);
  2853. $producttmpselect->fetch($selected);
  2854. $selected_input_value = $producttmpselect->ref;
  2855. unset($producttmpselect);
  2856. }
  2857. // mode=2 means suppliers products
  2858. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2859. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2860. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
  2861. } else {
  2862. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2863. }
  2864. }
  2865. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2866. /**
  2867. * Return list of suppliers products
  2868. *
  2869. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2870. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2871. * @param string $htmlname Name of HTML select
  2872. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2873. * @param string $filtre Generic filter. Data must not come from user input.
  2874. * @param string $filterkey Filter of produdts
  2875. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2876. * @param int $outputmode 0=HTML select string, 1=Array
  2877. * @param int $limit Limit of line number
  2878. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2879. * @param string $morecss Add more CSS
  2880. * @param int $showstockinlist Show stock information (slower).
  2881. * @param string $placeholder Placeholder
  2882. * @return array Array of keys for json
  2883. */
  2884. public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '', $showstockinlist = 0, $placeholder = '')
  2885. {
  2886. // phpcs:enable
  2887. global $langs, $conf, $user;
  2888. global $hookmanager;
  2889. $out = '';
  2890. $outarray = array();
  2891. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2892. $langs->load('stocks');
  2893. // Units
  2894. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2895. $langs->load('other');
  2896. }
  2897. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock,";
  2898. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2899. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  2900. $sql .= " pfp.supplier_reputation";
  2901. // if we use supplier description of the products
  2902. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2903. $sql .= " ,pfp.desc_fourn as description";
  2904. } else {
  2905. $sql .= " ,p.description";
  2906. }
  2907. // Units
  2908. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2909. $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units";
  2910. }
  2911. if (!empty($conf->barcode->enabled)) {
  2912. $sql .= ", pfp.barcode";
  2913. }
  2914. $sql .= " FROM ".$this->db->prefix()."product as p";
  2915. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2916. if ($socid > 0) {
  2917. $sql .= " AND pfp.fk_soc = ".((int) $socid);
  2918. }
  2919. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  2920. // Units
  2921. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2922. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2923. }
  2924. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2925. if ($statut != -1) {
  2926. $sql .= " AND p.tobuy = ".((int) $statut);
  2927. }
  2928. if (strval($filtertype) != '') {
  2929. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2930. }
  2931. if (!empty($filtre)) {
  2932. $sql .= " ".$filtre;
  2933. }
  2934. // Add where from hooks
  2935. $parameters = array();
  2936. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2937. $sql .= $hookmanager->resPrint;
  2938. // Add criteria on ref/label
  2939. if ($filterkey != '') {
  2940. $sql .= ' AND (';
  2941. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2942. // For natural search
  2943. $scrit = explode(' ', $filterkey);
  2944. $i = 0;
  2945. if (count($scrit) > 1) {
  2946. $sql .= "(";
  2947. }
  2948. foreach ($scrit as $crit) {
  2949. if ($i > 0) {
  2950. $sql .= " AND ";
  2951. }
  2952. $sql .= "(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2953. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2954. $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2955. }
  2956. $sql .= ")";
  2957. $i++;
  2958. }
  2959. if (count($scrit) > 1) {
  2960. $sql .= ")";
  2961. }
  2962. if (!empty($conf->barcode->enabled)) {
  2963. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2964. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2965. }
  2966. $sql .= ')';
  2967. }
  2968. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2969. $sql .= $this->db->plimit($limit, 0);
  2970. // Build output string
  2971. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2972. $result = $this->db->query($sql);
  2973. if ($result) {
  2974. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2975. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2976. $num = $this->db->num_rows($result);
  2977. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2978. $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2979. if (!$selected) {
  2980. $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2981. } else {
  2982. $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2983. }
  2984. $i = 0;
  2985. while ($i < $num) {
  2986. $objp = $this->db->fetch_object($result);
  2987. $outkey = $objp->idprodfournprice; // id in table of price
  2988. if (!$outkey && $alsoproductwithnosupplierprice) {
  2989. $outkey = 'idprod_'.$objp->rowid; // id of product
  2990. }
  2991. $outref = $objp->ref;
  2992. $outval = '';
  2993. $outbarcode = $objp->barcode;
  2994. $outqty = 1;
  2995. $outdiscount = 0;
  2996. $outtype = $objp->fk_product_type;
  2997. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2998. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2999. // Units
  3000. $outvalUnits = '';
  3001. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  3002. if (!empty($objp->unit_short)) {
  3003. $outvalUnits .= ' - '.$objp->unit_short;
  3004. }
  3005. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3006. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3007. $outvalUnits .= ' - '.$unitToShow;
  3008. }
  3009. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3010. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  3011. $outvalUnits .= ' - '.$unitToShow;
  3012. }
  3013. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3014. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3015. $outvalUnits .= ' - '.$unitToShow;
  3016. }
  3017. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3018. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3019. $outvalUnits .= ' - '.$unitToShow;
  3020. }
  3021. if ($outdurationvalue && $outdurationunit) {
  3022. $da = array(
  3023. 'h' => $langs->trans('Hour'),
  3024. 'd' => $langs->trans('Day'),
  3025. 'w' => $langs->trans('Week'),
  3026. 'm' => $langs->trans('Month'),
  3027. 'y' => $langs->trans('Year')
  3028. );
  3029. if (isset($da[$outdurationunit])) {
  3030. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  3031. }
  3032. }
  3033. }
  3034. $objRef = $objp->ref;
  3035. if ($filterkey && $filterkey != '') {
  3036. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  3037. }
  3038. $objRefFourn = $objp->ref_fourn;
  3039. if ($filterkey && $filterkey != '') {
  3040. $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3041. }
  3042. $label = $objp->label;
  3043. if ($filterkey && $filterkey != '') {
  3044. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  3045. }
  3046. $optlabel = $objp->ref;
  3047. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3048. $optlabel .= ' <span class="opacitymedium">('.$objp->ref_fourn.')</span>';
  3049. }
  3050. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3051. $optlabel .= ' ('.$outbarcode.')';
  3052. }
  3053. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3054. $outvallabel = $objRef;
  3055. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3056. $outvallabel .= ' ('.$objRefFourn.')';
  3057. }
  3058. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3059. $outvallabel .= ' ('.$outbarcode.')';
  3060. }
  3061. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3062. // Units
  3063. $optlabel .= $outvalUnits;
  3064. $outvallabel .= $outvalUnits;
  3065. if (!empty($objp->idprodfournprice)) {
  3066. $outqty = $objp->quantity;
  3067. $outdiscount = $objp->remise_percent;
  3068. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3069. $prod_supplier = new ProductFournisseur($this->db);
  3070. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3071. $prod_supplier->id = $objp->fk_product;
  3072. $prod_supplier->fourn_qty = $objp->quantity;
  3073. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3074. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3075. $priceparser = new PriceParser($this->db);
  3076. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3077. if ($price_result >= 0) {
  3078. $objp->fprice = $price_result;
  3079. if ($objp->quantity >= 1) {
  3080. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3081. }
  3082. }
  3083. }
  3084. if ($objp->quantity == 1) {
  3085. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3086. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  3087. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3088. $outvallabel .= $langs->transnoentities("Unit");
  3089. } else {
  3090. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  3091. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  3092. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3093. $outvallabel .= ' '.$langs->transnoentities("Units");
  3094. }
  3095. if ($objp->quantity > 1) {
  3096. $optlabel .= " (".price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  3097. $outvallabel .= " (".price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  3098. }
  3099. if ($objp->remise_percent >= 1) {
  3100. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  3101. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  3102. }
  3103. if ($objp->duration) {
  3104. $optlabel .= " - ".$objp->duration;
  3105. $outvallabel .= " - ".$objp->duration;
  3106. }
  3107. if (!$socid) {
  3108. $optlabel .= " - ".dol_trunc($objp->name, 8);
  3109. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  3110. }
  3111. if ($objp->supplier_reputation) {
  3112. //TODO dictionary
  3113. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  3114. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  3115. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  3116. }
  3117. } else {
  3118. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3119. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3120. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3121. } else // No supplier price defined for product, even on other suppliers
  3122. {
  3123. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3124. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3125. }
  3126. }
  3127. if (!empty($conf->stock->enabled) && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3128. $novirtualstock = ($showstockinlist == 2);
  3129. if (!empty($user->rights->stock->lire)) {
  3130. $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  3131. if ($objp->stock > 0) {
  3132. $optlabel .= ' - <span class="product_line_stock_ok">';
  3133. } elseif ($objp->stock <= 0) {
  3134. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3135. }
  3136. $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
  3137. $optlabel .= '</span>';
  3138. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3139. $langs->load("stocks");
  3140. $tmpproduct = new Product($this->db);
  3141. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3142. $tmpproduct->load_virtual_stock();
  3143. $virtualstock = $tmpproduct->stock_theorique;
  3144. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  3145. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  3146. if ($virtualstock > 0) {
  3147. $optlabel .= '<span class="product_line_stock_ok">';
  3148. } elseif ($virtualstock <= 0) {
  3149. $optlabel .= '<span class="product_line_stock_too_low">';
  3150. }
  3151. $optlabel .= $virtualstock;
  3152. $optlabel .= '</span>';
  3153. unset($tmpproduct);
  3154. }
  3155. }
  3156. }
  3157. $opt = '<option value="'.$outkey.'"';
  3158. if ($selected && $selected == $objp->idprodfournprice) {
  3159. $opt .= ' selected';
  3160. }
  3161. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3162. $opt .= ' disabled';
  3163. }
  3164. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3165. $opt .= ' data-product-id="'.$objp->rowid.'" data-price-id="'.$objp->idprodfournprice.'" data-qty="'.$objp->quantity.'" data-up="'.$objp->unitprice.'" data-discount="'.$outdiscount.'"';
  3166. }
  3167. $opt .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
  3168. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  3169. $opt .= '>';
  3170. $opt .= $optlabel;
  3171. $outval .= $outvallabel;
  3172. $opt .= "</option>\n";
  3173. // Add new entry
  3174. // "key" value of json key array is used by jQuery automatically as selected value. Example: 'type' = product or service, 'price_ht' = unit price without tax
  3175. // "label" value of json key array is used by jQuery automatically as text for combo box
  3176. $out .= $opt;
  3177. array_push(
  3178. $outarray,
  3179. array('key'=>$outkey,
  3180. 'value'=>$outref,
  3181. 'label'=>$outval,
  3182. 'qty'=>$outqty,
  3183. 'price_qty_ht'=>price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3184. 'price_unit_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3185. 'price_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3186. 'tva_tx'=>$objp->tva_tx,
  3187. 'default_vat_code'=>$objp->default_vat_code,
  3188. 'discount'=>$outdiscount,
  3189. 'type'=>$outtype,
  3190. 'duration_value'=>$outdurationvalue,
  3191. 'duration_unit'=>$outdurationunit,
  3192. 'disabled'=>(empty($objp->idprodfournprice) ? true : false),
  3193. 'description'=>$objp->description
  3194. )
  3195. );
  3196. // Exemple of var_dump $outarray
  3197. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3198. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3199. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3200. //}
  3201. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3202. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3203. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3204. $i++;
  3205. }
  3206. $out .= '</select>';
  3207. $this->db->free($result);
  3208. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  3209. $out .= ajax_combobox($htmlname);
  3210. if (empty($outputmode)) {
  3211. return $out;
  3212. }
  3213. return $outarray;
  3214. } else {
  3215. dol_print_error($this->db);
  3216. }
  3217. }
  3218. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3219. /**
  3220. * Return list of suppliers prices for a product
  3221. *
  3222. * @param int $productid Id of product
  3223. * @param string $htmlname Name of HTML field
  3224. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3225. * @return string
  3226. */
  3227. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3228. {
  3229. // phpcs:enable
  3230. global $langs, $conf;
  3231. $langs->load('stocks');
  3232. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3233. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3234. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3235. $sql .= " FROM ".$this->db->prefix()."product as p";
  3236. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3237. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  3238. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  3239. $sql .= " AND p.tobuy = 1";
  3240. $sql .= " AND s.fournisseur = 1";
  3241. $sql .= " AND p.rowid = ".((int) $productid);
  3242. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3243. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  3244. $result = $this->db->query($sql);
  3245. if ($result) {
  3246. $num = $this->db->num_rows($result);
  3247. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3248. if (!$num) {
  3249. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  3250. } else {
  3251. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3252. $form .= '<option value="0">&nbsp;</option>';
  3253. $i = 0;
  3254. while ($i < $num) {
  3255. $objp = $this->db->fetch_object($result);
  3256. $opt = '<option value="'.$objp->idprodfournprice.'"';
  3257. //if there is only one supplier, preselect it
  3258. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  3259. $opt .= ' selected';
  3260. }
  3261. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  3262. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3263. $prod_supplier = new ProductFournisseur($this->db);
  3264. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3265. $prod_supplier->id = $productid;
  3266. $prod_supplier->fourn_qty = $objp->quantity;
  3267. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3268. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3269. $priceparser = new PriceParser($this->db);
  3270. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3271. if ($price_result >= 0) {
  3272. $objp->fprice = $price_result;
  3273. if ($objp->quantity >= 1) {
  3274. $objp->unitprice = $objp->fprice / $objp->quantity;
  3275. }
  3276. }
  3277. }
  3278. if ($objp->quantity == 1) {
  3279. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3280. }
  3281. $opt .= $objp->quantity.' ';
  3282. if ($objp->quantity == 1) {
  3283. $opt .= $langs->trans("Unit");
  3284. } else {
  3285. $opt .= $langs->trans("Units");
  3286. }
  3287. if ($objp->quantity > 1) {
  3288. $opt .= " - ";
  3289. $opt .= price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit");
  3290. }
  3291. if ($objp->duration) {
  3292. $opt .= " - ".$objp->duration;
  3293. }
  3294. $opt .= "</option>\n";
  3295. $form .= $opt;
  3296. $i++;
  3297. }
  3298. }
  3299. $form .= '</select>';
  3300. $this->db->free($result);
  3301. return $form;
  3302. } else {
  3303. dol_print_error($this->db);
  3304. }
  3305. }
  3306. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3307. /**
  3308. * Return list of delivery address
  3309. *
  3310. * @param string $selected Id contact pre-selectionn
  3311. * @param int $socid Id of company
  3312. * @param string $htmlname Name of HTML field
  3313. * @param int $showempty Add an empty field
  3314. * @return integer|null
  3315. */
  3316. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3317. {
  3318. // phpcs:enable
  3319. // looking for users
  3320. $sql = "SELECT a.rowid, a.label";
  3321. $sql .= " FROM ".$this->db->prefix()."societe_address as a";
  3322. $sql .= " WHERE a.fk_soc = ".((int) $socid);
  3323. $sql .= " ORDER BY a.label ASC";
  3324. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  3325. $resql = $this->db->query($sql);
  3326. if ($resql) {
  3327. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3328. if ($showempty) {
  3329. print '<option value="0">&nbsp;</option>';
  3330. }
  3331. $num = $this->db->num_rows($resql);
  3332. $i = 0;
  3333. if ($num) {
  3334. while ($i < $num) {
  3335. $obj = $this->db->fetch_object($resql);
  3336. if ($selected && $selected == $obj->rowid) {
  3337. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  3338. } else {
  3339. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  3340. }
  3341. $i++;
  3342. }
  3343. }
  3344. print '</select>';
  3345. return $num;
  3346. } else {
  3347. dol_print_error($this->db);
  3348. }
  3349. }
  3350. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3351. /**
  3352. * Load into cache list of payment terms
  3353. *
  3354. * @return int Nb of lines loaded, <0 if KO
  3355. */
  3356. public function load_cache_conditions_paiements()
  3357. {
  3358. // phpcs:enable
  3359. global $langs;
  3360. $num = count($this->cache_conditions_paiements);
  3361. if ($num > 0) {
  3362. return 0; // Cache already loaded
  3363. }
  3364. dol_syslog(__METHOD__, LOG_DEBUG);
  3365. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3366. $sql .= " FROM ".$this->db->prefix().'c_payment_term';
  3367. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  3368. $sql .= " AND active > 0";
  3369. $sql .= " ORDER BY sortorder";
  3370. $resql = $this->db->query($sql);
  3371. if ($resql) {
  3372. $num = $this->db->num_rows($resql);
  3373. $i = 0;
  3374. while ($i < $num) {
  3375. $obj = $this->db->fetch_object($resql);
  3376. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3377. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3378. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3379. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3380. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3381. $i++;
  3382. }
  3383. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3384. return $num;
  3385. } else {
  3386. dol_print_error($this->db);
  3387. return -1;
  3388. }
  3389. }
  3390. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3391. /**
  3392. * Load int a cache property th elist of possible delivery delays.
  3393. *
  3394. * @return int Nb of lines loaded, <0 if KO
  3395. */
  3396. public function load_cache_availability()
  3397. {
  3398. // phpcs:enable
  3399. global $langs;
  3400. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3401. if ($num > 0) {
  3402. return 0; // Cache already loaded
  3403. }
  3404. dol_syslog(__METHOD__, LOG_DEBUG);
  3405. $langs->load('propal');
  3406. $sql = "SELECT rowid, code, label, position";
  3407. $sql .= " FROM ".$this->db->prefix().'c_availability';
  3408. $sql .= " WHERE active > 0";
  3409. $resql = $this->db->query($sql);
  3410. if ($resql) {
  3411. $num = $this->db->num_rows($resql);
  3412. $i = 0;
  3413. while ($i < $num) {
  3414. $obj = $this->db->fetch_object($resql);
  3415. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3416. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3417. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3418. $this->cache_availability[$obj->rowid]['label'] = $label;
  3419. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3420. $i++;
  3421. }
  3422. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3423. return $num;
  3424. } else {
  3425. dol_print_error($this->db);
  3426. return -1;
  3427. }
  3428. }
  3429. /**
  3430. * Retourne la liste des types de delais de livraison possibles
  3431. *
  3432. * @param int $selected Id du type de delais pre-selectionne
  3433. * @param string $htmlname Nom de la zone select
  3434. * @param string $filtertype To add a filter
  3435. * @param int $addempty Add empty entry
  3436. * @param string $morecss More CSS
  3437. * @return void
  3438. */
  3439. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3440. {
  3441. global $langs, $user;
  3442. $this->load_cache_availability();
  3443. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3444. print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3445. if ($addempty) {
  3446. print '<option value="0">&nbsp;</option>';
  3447. }
  3448. foreach ($this->cache_availability as $id => $arrayavailability) {
  3449. if ($selected == $id) {
  3450. print '<option value="'.$id.'" selected>';
  3451. } else {
  3452. print '<option value="'.$id.'">';
  3453. }
  3454. print dol_escape_htmltag($arrayavailability['label']);
  3455. print '</option>';
  3456. }
  3457. print '</select>';
  3458. if ($user->admin) {
  3459. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3460. }
  3461. print ajax_combobox($htmlname);
  3462. }
  3463. /**
  3464. * Load into cache cache_demand_reason, array of input reasons
  3465. *
  3466. * @return int Nb of lines loaded, <0 if KO
  3467. */
  3468. public function loadCacheInputReason()
  3469. {
  3470. global $langs;
  3471. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3472. if ($num > 0) {
  3473. return 0; // Cache already loaded
  3474. }
  3475. $sql = "SELECT rowid, code, label";
  3476. $sql .= " FROM ".$this->db->prefix().'c_input_reason';
  3477. $sql .= " WHERE active > 0";
  3478. $resql = $this->db->query($sql);
  3479. if ($resql) {
  3480. $num = $this->db->num_rows($resql);
  3481. $i = 0;
  3482. $tmparray = array();
  3483. while ($i < $num) {
  3484. $obj = $this->db->fetch_object($resql);
  3485. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3486. $label = ($obj->label != '-' ? $obj->label : '');
  3487. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
  3488. $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3489. }
  3490. if ($langs->trans($obj->code) != $obj->code) {
  3491. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3492. }
  3493. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3494. $tmparray[$obj->rowid]['code'] = $obj->code;
  3495. $tmparray[$obj->rowid]['label'] = $label;
  3496. $i++;
  3497. }
  3498. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3499. unset($tmparray);
  3500. return $num;
  3501. } else {
  3502. dol_print_error($this->db);
  3503. return -1;
  3504. }
  3505. }
  3506. /**
  3507. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3508. * List found into table c_input_reason loaded by loadCacheInputReason
  3509. *
  3510. * @param int $selected Id or code of type origin to select by default
  3511. * @param string $htmlname Nom de la zone select
  3512. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3513. * @param int $addempty Add an empty entry
  3514. * @param string $morecss Add more css to the HTML select component
  3515. * @param int $notooltip Do not show the tooltip for admin
  3516. * @return void
  3517. */
  3518. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3519. {
  3520. global $langs, $user;
  3521. $this->loadCacheInputReason();
  3522. print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3523. if ($addempty) {
  3524. print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3525. }
  3526. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3527. if ($arraydemandreason['code'] == $exclude) {
  3528. continue;
  3529. }
  3530. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3531. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3532. } else {
  3533. print '<option value="'.$arraydemandreason['id'].'">';
  3534. }
  3535. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3536. print $langs->trans($label);
  3537. print '</option>';
  3538. }
  3539. print '</select>';
  3540. if ($user->admin && empty($notooltip)) {
  3541. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3542. }
  3543. print ajax_combobox('select_'.$htmlname);
  3544. }
  3545. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3546. /**
  3547. * Charge dans cache la liste des types de paiements possibles
  3548. *
  3549. * @return int Nb of lines loaded, <0 if KO
  3550. */
  3551. public function load_cache_types_paiements()
  3552. {
  3553. // phpcs:enable
  3554. global $langs;
  3555. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3556. if ($num > 0) {
  3557. return $num; // Cache already loaded
  3558. }
  3559. dol_syslog(__METHOD__, LOG_DEBUG);
  3560. $this->cache_types_paiements = array();
  3561. $sql = "SELECT id, code, libelle as label, type, active";
  3562. $sql .= " FROM ".$this->db->prefix()."c_paiement";
  3563. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3564. $resql = $this->db->query($sql);
  3565. if ($resql) {
  3566. $num = $this->db->num_rows($resql);
  3567. $i = 0;
  3568. while ($i < $num) {
  3569. $obj = $this->db->fetch_object($resql);
  3570. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3571. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3572. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3573. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3574. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3575. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3576. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3577. $i++;
  3578. }
  3579. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3580. return $num;
  3581. } else {
  3582. dol_print_error($this->db);
  3583. return -1;
  3584. }
  3585. }
  3586. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3587. /**
  3588. * print list of payment modes.
  3589. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3590. * See instead to force the default value by the caller.
  3591. *
  3592. * @param int $selected Id of payment term to preselect by default
  3593. * @param string $htmlname Nom de la zone select
  3594. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3595. * @param int $addempty Add an empty entry
  3596. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3597. * @param string $morecss Add more CSS on select tag
  3598. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3599. * 0 : use default deposit percentage from entry
  3600. * > 0 : force deposit percentage (for example, from company object)
  3601. * @return void
  3602. */
  3603. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3604. {
  3605. // phpcs:enable
  3606. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent = -1);
  3607. }
  3608. /**
  3609. * Return list of payment modes.
  3610. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3611. * See instead to force the default value by the caller.
  3612. *
  3613. * @param int $selected Id of payment term to preselect by default
  3614. * @param string $htmlname Nom de la zone select
  3615. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3616. * @param int $addempty Add an empty entry
  3617. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3618. * @param string $morecss Add more CSS on select tag
  3619. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3620. * 0 : use default deposit percentage from entry
  3621. * > 0 : force deposit percentage (for example, from company object)
  3622. * @return string
  3623. */
  3624. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3625. {
  3626. global $langs, $user, $conf;
  3627. $out = '';
  3628. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3629. $this->load_cache_conditions_paiements();
  3630. // Set default value if not already set by caller
  3631. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3632. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3633. }
  3634. $out.= '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3635. if ($addempty) {
  3636. $out.= '<option value="0">&nbsp;</option>';
  3637. }
  3638. $selectedDepositPercent = null;
  3639. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3640. if ($filtertype <= 0 && ! empty($arrayconditions['deposit_percent'])) {
  3641. continue;
  3642. }
  3643. if ($selected == $id) {
  3644. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3645. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3646. } else {
  3647. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3648. }
  3649. $label = $arrayconditions['label'];
  3650. if (! empty($arrayconditions['deposit_percent'])) {
  3651. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3652. }
  3653. $out.= $label;
  3654. $out.= '</option>';
  3655. }
  3656. $out.= '</select>';
  3657. if ($user->admin && empty($noinfoadmin)) {
  3658. $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3659. }
  3660. $out.= ajax_combobox($htmlname);
  3661. if ($deposit_percent >= 0) {
  3662. $out .= ' <span id="'.$htmlname.'_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3663. $out .= $langs->trans('DepositPercent') . ' : ';
  3664. $out .= '<input id="'.$htmlname.'_deposit_percent" name="'.$htmlname.'_deposit_percent" class="maxwidth50" value="' . strval($deposit_percent) . '" />';
  3665. $out .= '</span>';
  3666. $out .= '
  3667. <script>
  3668. $(document).ready(function () {
  3669. $("#' . $htmlname . '").change(function () {
  3670. let $selected = $(this).find("option:selected");
  3671. let depositPercent = $selected.attr("data-deposit_percent");
  3672. if (depositPercent.length > 0) {
  3673. $("#'.$htmlname.'_deposit_percent_container").show().find("#'.$htmlname.'_deposit_percent").val(depositPercent);
  3674. } else {
  3675. $("#'.$htmlname.'_deposit_percent_container").hide();
  3676. }
  3677. return true;
  3678. });
  3679. });
  3680. </script>';
  3681. }
  3682. return $out;
  3683. }
  3684. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3685. /**
  3686. * Return list of payment methods
  3687. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3688. *
  3689. * @param string $selected Id or code or preselected payment mode
  3690. * @param string $htmlname Name of select field
  3691. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3692. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3693. * @param int $empty 1=can be empty, 0 otherwise
  3694. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3695. * @param int $maxlength Max length of label
  3696. * @param int $active Active or not, -1 = all
  3697. * @param string $morecss Add more CSS on select tag
  3698. * @param int $nooutput 1=Return string, do not send to output
  3699. * @return void
  3700. */
  3701. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3702. {
  3703. // phpcs:enable
  3704. global $langs, $user, $conf;
  3705. $out = '';
  3706. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3707. $filterarray = array();
  3708. if ($filtertype == 'CRDT') {
  3709. $filterarray = array(0, 2, 3);
  3710. } elseif ($filtertype == 'DBIT') {
  3711. $filterarray = array(1, 2, 3);
  3712. } elseif ($filtertype != '' && $filtertype != '-1') {
  3713. $filterarray = explode(',', $filtertype);
  3714. }
  3715. $this->load_cache_types_paiements();
  3716. // Set default value if not already set by caller
  3717. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3718. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3719. }
  3720. $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3721. if ($empty) {
  3722. $out .= '<option value="">&nbsp;</option>';
  3723. }
  3724. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3725. // If not good status
  3726. if ($active >= 0 && $arraytypes['active'] != $active) {
  3727. continue;
  3728. }
  3729. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3730. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3731. continue;
  3732. }
  3733. // We discard empty line if showempty is on because an empty line has already been output.
  3734. if ($empty && empty($arraytypes['code'])) {
  3735. continue;
  3736. }
  3737. if ($format == 0) {
  3738. $out .= '<option value="'.$id.'"';
  3739. } elseif ($format == 1) {
  3740. $out .= '<option value="'.$arraytypes['code'].'"';
  3741. } elseif ($format == 2) {
  3742. $out .= '<option value="'.$arraytypes['code'].'"';
  3743. } elseif ($format == 3) {
  3744. $out .= '<option value="'.$id.'"';
  3745. }
  3746. // Print attribute selected or not
  3747. if ($format == 1 || $format == 2) {
  3748. if ($selected == $arraytypes['code']) {
  3749. $out .= ' selected';
  3750. }
  3751. } else {
  3752. if ($selected == $id) {
  3753. $out .= ' selected';
  3754. }
  3755. }
  3756. $out .= '>';
  3757. if ($format == 0) {
  3758. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3759. } elseif ($format == 1) {
  3760. $value = $arraytypes['code'];
  3761. } elseif ($format == 2) {
  3762. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3763. } elseif ($format == 3) {
  3764. $value = $arraytypes['code'];
  3765. }
  3766. $out .= $value ? $value : '&nbsp;';
  3767. $out .= '</option>';
  3768. }
  3769. $out .= '</select>';
  3770. if ($user->admin && !$noadmininfo) {
  3771. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3772. }
  3773. $out .= ajax_combobox('select'.$htmlname);
  3774. if (empty($nooutput)) {
  3775. print $out;
  3776. } else {
  3777. return $out;
  3778. }
  3779. }
  3780. /**
  3781. * Selection HT or TTC
  3782. *
  3783. * @param string $selected Id pre-selectionne
  3784. * @param string $htmlname Nom de la zone select
  3785. * @param string $addjscombo Add js combo
  3786. * @return string Code of HTML select to chose tax or not
  3787. */
  3788. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3789. {
  3790. global $langs;
  3791. $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3792. $options = array(
  3793. 'HT'=>$langs->trans("HT"),
  3794. 'TTC'=>$langs->trans("TTC")
  3795. );
  3796. foreach ($options as $id => $value) {
  3797. if ($selected == $id) {
  3798. $return .= '<option value="'.$id.'" selected>'.$value;
  3799. } else {
  3800. $return .= '<option value="'.$id.'">'.$value;
  3801. }
  3802. $return .= '</option>';
  3803. }
  3804. $return .= '</select>';
  3805. if ($addjscombo) {
  3806. $return .= ajax_combobox('select_'.$htmlname);
  3807. }
  3808. return $return;
  3809. }
  3810. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3811. /**
  3812. * Load in cache list of transport mode
  3813. *
  3814. * @return int Nb of lines loaded, <0 if KO
  3815. */
  3816. public function load_cache_transport_mode()
  3817. {
  3818. // phpcs:enable
  3819. global $langs;
  3820. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  3821. if ($num > 0) {
  3822. return $num; // Cache already loaded
  3823. }
  3824. dol_syslog(__METHOD__, LOG_DEBUG);
  3825. $this->cache_transport_mode = array();
  3826. $sql = "SELECT rowid, code, label, active";
  3827. $sql .= " FROM ".$this->db->prefix()."c_transport_mode";
  3828. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3829. $resql = $this->db->query($sql);
  3830. if ($resql) {
  3831. $num = $this->db->num_rows($resql);
  3832. $i = 0;
  3833. while ($i < $num) {
  3834. $obj = $this->db->fetch_object($resql);
  3835. // If traduction exist, we use it else we take the default label
  3836. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3837. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3838. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3839. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3840. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3841. $i++;
  3842. }
  3843. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3844. return $num;
  3845. } else {
  3846. dol_print_error($this->db);
  3847. return -1;
  3848. }
  3849. }
  3850. /**
  3851. * Return list of transport mode for intracomm report
  3852. *
  3853. * @param string $selected Id of the transport mode pre-selected
  3854. * @param string $htmlname Name of the select field
  3855. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3856. * @param int $empty 1=can be empty, 0 else
  3857. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3858. * @param int $maxlength Max length of label
  3859. * @param int $active Active or not, -1 = all
  3860. * @param string $morecss Add more CSS on select tag
  3861. * @return void
  3862. */
  3863. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3864. {
  3865. global $langs, $user;
  3866. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3867. $this->load_cache_transport_mode();
  3868. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3869. if ($empty) {
  3870. print '<option value="">&nbsp;</option>';
  3871. }
  3872. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3873. // If not good status
  3874. if ($active >= 0 && $arraytypes['active'] != $active) {
  3875. continue;
  3876. }
  3877. // We discard empty line if showempty is on because an empty line has already been output.
  3878. if ($empty && empty($arraytypes['code'])) {
  3879. continue;
  3880. }
  3881. if ($format == 0) {
  3882. print '<option value="'.$id.'"';
  3883. } elseif ($format == 1) {
  3884. print '<option value="'.$arraytypes['code'].'"';
  3885. } elseif ($format == 2) {
  3886. print '<option value="'.$arraytypes['code'].'"';
  3887. } elseif ($format == 3) {
  3888. print '<option value="'.$id.'"';
  3889. }
  3890. // If text is selected, we compare with code, else with id
  3891. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  3892. print ' selected';
  3893. } elseif ($selected == $id) {
  3894. print ' selected';
  3895. }
  3896. print '>';
  3897. if ($format == 0) {
  3898. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3899. } elseif ($format == 1) {
  3900. $value = $arraytypes['code'];
  3901. } elseif ($format == 2) {
  3902. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3903. } elseif ($format == 3) {
  3904. $value = $arraytypes['code'];
  3905. }
  3906. print $value ? $value : '&nbsp;';
  3907. print '</option>';
  3908. }
  3909. print '</select>';
  3910. if ($user->admin && !$noadmininfo) {
  3911. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3912. }
  3913. }
  3914. /**
  3915. * Return a HTML select list of shipping mode
  3916. *
  3917. * @param string $selected Id shipping mode pre-selected
  3918. * @param string $htmlname Name of select zone
  3919. * @param string $filtre To filter list. This parameter must not come from input of users
  3920. * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
  3921. * @param string $moreattrib To add more attribute on select
  3922. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3923. * @param string $morecss More CSS
  3924. * @return void
  3925. */
  3926. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  3927. {
  3928. global $langs, $conf, $user;
  3929. $langs->load("admin");
  3930. $langs->load("deliveries");
  3931. $sql = "SELECT rowid, code, libelle as label";
  3932. $sql .= " FROM ".$this->db->prefix()."c_shipment_mode";
  3933. $sql .= " WHERE active > 0";
  3934. if ($filtre) {
  3935. $sql .= " AND ".$filtre;
  3936. }
  3937. $sql .= " ORDER BY libelle ASC";
  3938. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3939. $result = $this->db->query($sql);
  3940. if ($result) {
  3941. $num = $this->db->num_rows($result);
  3942. $i = 0;
  3943. if ($num) {
  3944. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3945. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3946. print '<option value="-1">&nbsp;</option>';
  3947. }
  3948. while ($i < $num) {
  3949. $obj = $this->db->fetch_object($result);
  3950. if ($selected == $obj->rowid) {
  3951. print '<option value="'.$obj->rowid.'" selected>';
  3952. } else {
  3953. print '<option value="'.$obj->rowid.'">';
  3954. }
  3955. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3956. print '</option>';
  3957. $i++;
  3958. }
  3959. print "</select>";
  3960. if ($user->admin && empty($noinfoadmin)) {
  3961. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3962. }
  3963. print ajax_combobox('select'.$htmlname);
  3964. } else {
  3965. print $langs->trans("NoShippingMethodDefined");
  3966. }
  3967. } else {
  3968. dol_print_error($this->db);
  3969. }
  3970. }
  3971. /**
  3972. * Display form to select shipping mode
  3973. *
  3974. * @param string $page Page
  3975. * @param int $selected Id of shipping mode
  3976. * @param string $htmlname Name of select html field
  3977. * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
  3978. * @return void
  3979. */
  3980. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  3981. {
  3982. global $langs;
  3983. $langs->load("deliveries");
  3984. if ($htmlname != "none") {
  3985. print '<form method="POST" action="'.$page.'">';
  3986. print '<input type="hidden" name="action" value="setshippingmethod">';
  3987. print '<input type="hidden" name="token" value="'.newToken().'">';
  3988. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3989. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3990. print '</form>';
  3991. } else {
  3992. if ($selected) {
  3993. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  3994. print $langs->trans("SendingMethod".strtoupper($code));
  3995. } else {
  3996. print "&nbsp;";
  3997. }
  3998. }
  3999. }
  4000. /**
  4001. * Creates HTML last in cycle situation invoices selector
  4002. *
  4003. * @param string $selected Preselected ID
  4004. * @param int $socid Company ID
  4005. *
  4006. * @return string HTML select
  4007. */
  4008. public function selectSituationInvoices($selected = '', $socid = 0)
  4009. {
  4010. global $langs;
  4011. $langs->load('bills');
  4012. $opt = '<option value="" selected></option>';
  4013. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4014. $sql .= ' FROM '.$this->db->prefix().'facture';
  4015. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  4016. $sql .= ' AND situation_counter >= 1';
  4017. $sql .= ' AND fk_soc = '.(int) $socid;
  4018. $sql .= ' AND type <> 2';
  4019. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4020. $resql = $this->db->query($sql);
  4021. if ($resql && $this->db->num_rows($resql) > 0) {
  4022. // Last seen cycle
  4023. $ref = 0;
  4024. while ($obj = $this->db->fetch_object($resql)) {
  4025. //Same cycle ?
  4026. if ($obj->situation_cycle_ref != $ref) {
  4027. // Just seen this cycle
  4028. $ref = $obj->situation_cycle_ref;
  4029. //not final ?
  4030. if ($obj->situation_final != 1) {
  4031. //Not prov?
  4032. if (substr($obj->ref, 1, 4) != 'PROV') {
  4033. if ($selected == $obj->rowid) {
  4034. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  4035. } else {
  4036. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  4037. }
  4038. }
  4039. }
  4040. }
  4041. }
  4042. } else {
  4043. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4044. }
  4045. if ($opt == '<option value ="" selected></option>') {
  4046. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  4047. }
  4048. return $opt;
  4049. }
  4050. /**
  4051. * Creates HTML units selector (code => label)
  4052. *
  4053. * @param string $selected Preselected Unit ID
  4054. * @param string $htmlname Select name
  4055. * @param int $showempty Add a nempty line
  4056. * @param string $unit_type Restrict to one given unit type
  4057. * @return string HTML select
  4058. */
  4059. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4060. {
  4061. global $langs;
  4062. $langs->load('products');
  4063. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  4064. $sql = "SELECT rowid, label, code FROM ".$this->db->prefix()."c_units";
  4065. $sql .= ' WHERE active > 0';
  4066. if (!empty($unit_type)) {
  4067. $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
  4068. }
  4069. $sql .= " ORDER BY sortorder";
  4070. $resql = $this->db->query($sql);
  4071. if ($resql && $this->db->num_rows($resql) > 0) {
  4072. if ($showempty) {
  4073. $return .= '<option value="none"></option>';
  4074. }
  4075. while ($res = $this->db->fetch_object($resql)) {
  4076. $unitLabel = $res->label;
  4077. if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
  4078. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  4079. }
  4080. if ($selected == $res->rowid) {
  4081. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  4082. } else {
  4083. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  4084. }
  4085. }
  4086. $return .= '</select>';
  4087. }
  4088. return $return;
  4089. }
  4090. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4091. /**
  4092. * Return a HTML select list of bank accounts
  4093. *
  4094. * @param string $selected Id account pre-selected
  4095. * @param string $htmlname Name of select zone
  4096. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4097. * @param string $filtre To filter list. This parameter must not come from input of users
  4098. * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
  4099. * @param string $moreattrib To add more attribute on select
  4100. * @param int $showcurrency Show currency in label
  4101. * @param string $morecss More CSS
  4102. * @param int $nooutput 1=Return string, do not send to output
  4103. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4104. */
  4105. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4106. {
  4107. // phpcs:enable
  4108. global $langs, $conf;
  4109. $out = '';
  4110. $langs->load("admin");
  4111. $num = 0;
  4112. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4113. $sql .= " FROM ".$this->db->prefix()."bank_account";
  4114. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  4115. if ($status != 2) {
  4116. $sql .= " AND clos = ".(int) $status;
  4117. }
  4118. if ($filtre) {
  4119. $sql .= " AND ".$filtre;
  4120. }
  4121. $sql .= " ORDER BY label";
  4122. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  4123. $result = $this->db->query($sql);
  4124. if ($result) {
  4125. $num = $this->db->num_rows($result);
  4126. $i = 0;
  4127. if ($num) {
  4128. $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4129. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4130. $out .= '<option value="-1">&nbsp;</option>';
  4131. }
  4132. while ($i < $num) {
  4133. $obj = $this->db->fetch_object($result);
  4134. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4135. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
  4136. } else {
  4137. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
  4138. }
  4139. $out .= trim($obj->label);
  4140. if ($showcurrency) {
  4141. $out .= ' ('.$obj->currency_code.')';
  4142. }
  4143. if ($status == 2 && $obj->status == 1) {
  4144. $out .= ' ('.$langs->trans("Closed").')';
  4145. }
  4146. $out .= '</option>';
  4147. $i++;
  4148. }
  4149. $out .= "</select>";
  4150. $out .= ajax_combobox('select'.$htmlname);
  4151. } else {
  4152. if ($status == 0) {
  4153. $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  4154. } else {
  4155. $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  4156. }
  4157. }
  4158. } else {
  4159. dol_print_error($this->db);
  4160. }
  4161. // Output or return
  4162. if (empty($nooutput)) {
  4163. print $out;
  4164. } else {
  4165. return $out;
  4166. }
  4167. return $num;
  4168. }
  4169. /**
  4170. * Return a HTML select list of establishment
  4171. *
  4172. * @param string $selected Id establishment pre-selected
  4173. * @param string $htmlname Name of select zone
  4174. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4175. * @param string $filtre To filter list. This parameter must not come from input of users
  4176. * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
  4177. * @param string $moreattrib To add more attribute on select
  4178. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4179. */
  4180. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4181. {
  4182. global $langs, $conf;
  4183. $langs->load("admin");
  4184. $num = 0;
  4185. $sql = "SELECT rowid, name, fk_country, status, entity";
  4186. $sql .= " FROM ".$this->db->prefix()."establishment";
  4187. $sql .= " WHERE 1=1";
  4188. if ($status != 2) {
  4189. $sql .= " AND status = ".(int) $status;
  4190. }
  4191. if ($filtre) {
  4192. $sql .= " AND ".$filtre;
  4193. }
  4194. $sql .= " ORDER BY name";
  4195. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  4196. $result = $this->db->query($sql);
  4197. if ($result) {
  4198. $num = $this->db->num_rows($result);
  4199. $i = 0;
  4200. if ($num) {
  4201. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4202. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4203. print '<option value="-1">&nbsp;</option>';
  4204. }
  4205. while ($i < $num) {
  4206. $obj = $this->db->fetch_object($result);
  4207. if ($selected == $obj->rowid) {
  4208. print '<option value="'.$obj->rowid.'" selected>';
  4209. } else {
  4210. print '<option value="'.$obj->rowid.'">';
  4211. }
  4212. print trim($obj->name);
  4213. if ($status == 2 && $obj->status == 1) {
  4214. print ' ('.$langs->trans("Closed").')';
  4215. }
  4216. print '</option>';
  4217. $i++;
  4218. }
  4219. print "</select>";
  4220. } else {
  4221. if ($status == 0) {
  4222. print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  4223. } else {
  4224. print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  4225. }
  4226. }
  4227. } else {
  4228. dol_print_error($this->db);
  4229. }
  4230. }
  4231. /**
  4232. * Display form to select bank account
  4233. *
  4234. * @param string $page Page
  4235. * @param int $selected Id of bank account
  4236. * @param string $htmlname Name of select html field
  4237. * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
  4238. * @return void
  4239. */
  4240. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4241. {
  4242. global $langs;
  4243. if ($htmlname != "none") {
  4244. print '<form method="POST" action="'.$page.'">';
  4245. print '<input type="hidden" name="action" value="setbankaccount">';
  4246. print '<input type="hidden" name="token" value="'.newToken().'">';
  4247. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4248. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4249. if ($nbaccountfound > 0) {
  4250. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4251. }
  4252. print '</form>';
  4253. } else {
  4254. $langs->load('banks');
  4255. if ($selected) {
  4256. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  4257. $bankstatic = new Account($this->db);
  4258. $result = $bankstatic->fetch($selected);
  4259. if ($result) {
  4260. print $bankstatic->getNomUrl(1);
  4261. }
  4262. } else {
  4263. print "&nbsp;";
  4264. }
  4265. }
  4266. }
  4267. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4268. /**
  4269. * Return list of categories having choosed type
  4270. *
  4271. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4272. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4273. * @param string $htmlname HTML field name
  4274. * @param int $maxlength Maximum length for labels
  4275. * @param int|string|array $markafterid Keep only or removed all categories including the leaf $markafterid in category tree (exclude) or Keep only of category is inside the leaf starting with this id.
  4276. * $markafterid can be an :
  4277. * - int (id of category)
  4278. * - string (categories ids seprated by comma)
  4279. * - array (list of categories ids)
  4280. * @param int $outputmode 0=HTML select string, 1=Array
  4281. * @param int $include [=0] Removed or 1=Keep only
  4282. * @param string $morecss More CSS
  4283. * @return string
  4284. * @see select_categories()
  4285. */
  4286. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4287. {
  4288. // phpcs:enable
  4289. global $conf, $langs;
  4290. $langs->load("categories");
  4291. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4292. // For backward compatibility
  4293. if (is_numeric($type)) {
  4294. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4295. }
  4296. if ($type === Categorie::TYPE_BANK_LINE) {
  4297. // TODO Move this into common category feature
  4298. $cate_arbo = array();
  4299. $sql = "SELECT c.label, c.rowid";
  4300. $sql .= " FROM ".$this->db->prefix()."bank_categ as c";
  4301. $sql .= " WHERE entity = ".$conf->entity;
  4302. $sql .= " ORDER BY c.label";
  4303. $result = $this->db->query($sql);
  4304. if ($result) {
  4305. $num = $this->db->num_rows($result);
  4306. $i = 0;
  4307. while ($i < $num) {
  4308. $objp = $this->db->fetch_object($result);
  4309. if ($objp) {
  4310. $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  4311. }
  4312. $i++;
  4313. }
  4314. $this->db->free($result);
  4315. } else {
  4316. dol_print_error($this->db);
  4317. }
  4318. } else {
  4319. $cat = new Categorie($this->db);
  4320. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4321. }
  4322. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  4323. $outarray = array();
  4324. if (is_array($cate_arbo)) {
  4325. if (!count($cate_arbo)) {
  4326. $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  4327. } else {
  4328. $output .= '<option value="-1">&nbsp;</option>';
  4329. foreach ($cate_arbo as $key => $value) {
  4330. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4331. $add = 'selected ';
  4332. } else {
  4333. $add = '';
  4334. }
  4335. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  4336. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4337. }
  4338. }
  4339. }
  4340. $output .= '</select>';
  4341. $output .= "\n";
  4342. if ($outputmode) {
  4343. return $outarray;
  4344. }
  4345. return $output;
  4346. }
  4347. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4348. /**
  4349. * Show a confirmation HTML form or AJAX popup
  4350. *
  4351. * @param string $page Url of page to call if confirmation is OK
  4352. * @param string $title Title
  4353. * @param string $question Question
  4354. * @param string $action Action
  4355. * @param array $formquestion An array with forms complementary inputs
  4356. * @param string $selectedchoice "" or "no" or "yes"
  4357. * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx
  4358. * @param int $height Force height of box
  4359. * @param int $width Force width of box
  4360. * @return void
  4361. * @deprecated
  4362. * @see formconfirm()
  4363. */
  4364. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4365. {
  4366. // phpcs:enable
  4367. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4368. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4369. }
  4370. /**
  4371. * Show a confirmation HTML form or AJAX popup.
  4372. * Easiest way to use this is with useajax=1.
  4373. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4374. * just after calling this method. For example:
  4375. * print '<script type="text/javascript">'."\n";
  4376. * print 'jQuery(document).ready(function() {'."\n";
  4377. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4378. * print '});'."\n";
  4379. * print '</script>'."\n";
  4380. *
  4381. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4382. * @param string $title Title
  4383. * @param string $question Question
  4384. * @param string $action Action
  4385. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>))
  4386. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', 'other' or 'onecolumn'...
  4387. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  4388. * @param int|string $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4389. * @param int|string $height Force height of box (0 = auto)
  4390. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4391. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4392. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4393. */
  4394. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0)
  4395. {
  4396. global $langs, $conf;
  4397. $more = '<!-- formconfirm before calling page='.dol_escape_htmltag($page).' -->';
  4398. $formconfirm = '';
  4399. $inputok = array();
  4400. $inputko = array();
  4401. // Clean parameters
  4402. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4403. if ($conf->browser->layout == 'phone') {
  4404. $width = '95%';
  4405. }
  4406. // Set height automatically if not defined
  4407. if (empty($height)) {
  4408. $height = 220;
  4409. if (is_array($formquestion) && count($formquestion) > 2) {
  4410. $height += ((count($formquestion) - 2) * 24);
  4411. }
  4412. }
  4413. if (is_array($formquestion) && !empty($formquestion)) {
  4414. // First add hidden fields and value
  4415. foreach ($formquestion as $key => $input) {
  4416. if (is_array($input) && !empty($input)) {
  4417. if ($input['type'] == 'hidden') {
  4418. $more .= '<input type="hidden" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  4419. }
  4420. }
  4421. }
  4422. // Now add questions
  4423. $moreonecolumn = '';
  4424. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  4425. foreach ($formquestion as $key => $input) {
  4426. if (is_array($input) && !empty($input)) {
  4427. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
  4428. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4429. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4430. if ($input['type'] == 'text') {
  4431. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="text" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4432. } elseif ($input['type'] == 'password') {
  4433. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="password" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4434. } elseif ($input['type'] == 'textarea') {
  4435. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4436. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4437. $more .= $input['value'];
  4438. $more .= '</textarea>';
  4439. $more .= '</div></div>'."\n";*/
  4440. $moreonecolumn .= '<div class="margintoponly">';
  4441. $moreonecolumn .= $input['label'].'<br>';
  4442. $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
  4443. $moreonecolumn .= $input['value'];
  4444. $moreonecolumn .= '</textarea>';
  4445. $moreonecolumn .= '</div>';
  4446. } elseif ($input['type'] == 'select') {
  4447. if (empty($morecss)) {
  4448. $morecss = 'minwidth100';
  4449. }
  4450. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4451. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4452. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4453. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4454. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4455. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4456. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4457. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4458. if (!empty($input['label'])) {
  4459. $more .= $input['label'].'</div><div class="tagtd left">';
  4460. }
  4461. $more .= $this->selectarray($input['name'], $input['values'], $input['default'], $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4462. $more .= '</div></div>'."\n";
  4463. } elseif ($input['type'] == 'checkbox') {
  4464. $more .= '<div class="tagtr">';
  4465. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  4466. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
  4467. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4468. $more .= ' checked';
  4469. }
  4470. if (is_bool($input['value']) && $input['value']) {
  4471. $more .= ' checked';
  4472. }
  4473. if (isset($input['disabled'])) {
  4474. $more .= ' disabled';
  4475. }
  4476. $more .= ' /></div>';
  4477. $more .= '</div>'."\n";
  4478. } elseif ($input['type'] == 'radio') {
  4479. $i = 0;
  4480. foreach ($input['values'] as $selkey => $selval) {
  4481. $more .= '<div class="tagtr">';
  4482. if ($i == 0) {
  4483. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4484. } else {
  4485. $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  4486. }
  4487. $more .= '<div class="tagtd'.($i == 0 ? ' tdtop' : '').'"><input type="radio" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name'].$selkey).'" name="'.dol_escape_htmltag($input['name']).'" value="'.$selkey.'"'.$moreattr;
  4488. if ($input['disabled']) {
  4489. $more .= ' disabled';
  4490. }
  4491. if (isset($input['default']) && $input['default'] === $selkey) {
  4492. $more .= ' checked="checked"';
  4493. }
  4494. $more .= ' /> ';
  4495. $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'">'.$selval.'</label>';
  4496. $more .= '</div></div>'."\n";
  4497. $i++;
  4498. }
  4499. } elseif ($input['type'] == 'date') {
  4500. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4501. $more .= '<div class="tagtd">';
  4502. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4503. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, $addnowlink);
  4504. $more .= '</div></div>'."\n";
  4505. $formquestion[] = array('name'=>$input['name'].'day');
  4506. $formquestion[] = array('name'=>$input['name'].'month');
  4507. $formquestion[] = array('name'=>$input['name'].'year');
  4508. $formquestion[] = array('name'=>$input['name'].'hour');
  4509. $formquestion[] = array('name'=>$input['name'].'min');
  4510. } elseif ($input['type'] == 'other') {
  4511. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4512. if (!empty($input['label'])) {
  4513. $more .= $input['label'].'</div><div class="tagtd">';
  4514. }
  4515. $more .= $input['value'];
  4516. $more .= '</div></div>'."\n";
  4517. } elseif ($input['type'] == 'onecolumn') {
  4518. $moreonecolumn .= '<div class="margintoponly">';
  4519. $moreonecolumn .= $input['value'];
  4520. $moreonecolumn .= '</div>'."\n";
  4521. } elseif ($input['type'] == 'hidden') {
  4522. // Do nothing more, already added by a previous loop
  4523. } elseif ($input['type'] == 'separator') {
  4524. $more .= '<br>';
  4525. } else {
  4526. $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
  4527. }
  4528. }
  4529. }
  4530. $more .= '</div>'."\n";
  4531. $more .= $moreonecolumn;
  4532. }
  4533. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4534. // Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx
  4535. // See page product/card.php for example
  4536. if (!empty($conf->dol_use_jmobile)) {
  4537. $useajax = 0;
  4538. }
  4539. if (empty($conf->use_javascript_ajax)) {
  4540. $useajax = 0;
  4541. }
  4542. if ($useajax) {
  4543. $autoOpen = true;
  4544. $dialogconfirm = 'dialog-confirm';
  4545. $button = '';
  4546. if (!is_numeric($useajax)) {
  4547. $button = $useajax;
  4548. $useajax = 1;
  4549. $autoOpen = false;
  4550. $dialogconfirm .= '-'.$button;
  4551. }
  4552. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=yes';
  4553. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=no' : '');
  4554. // Add input fields into list of fields to read during submit (inputok and inputko)
  4555. if (is_array($formquestion)) {
  4556. foreach ($formquestion as $key => $input) {
  4557. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4558. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4559. if (is_array($input) && isset($input['name'])) {
  4560. if (strpos($input['name'], ',') > 0) {
  4561. $inputok = array_merge($inputok, explode(',', $input['name']));
  4562. } else {
  4563. array_push($inputok, $input['name']);
  4564. }
  4565. }
  4566. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4567. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4568. array_push($inputko, $input['name']);
  4569. }
  4570. }
  4571. }
  4572. // Show JQuery confirm box.
  4573. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  4574. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4575. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  4576. }
  4577. if (!empty($more)) {
  4578. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  4579. }
  4580. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  4581. $formconfirm .= '</div>'."\n";
  4582. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=".$page." -->\n";
  4583. $formconfirm .= '<script type="text/javascript">'."\n";
  4584. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4585. $formconfirm .= 'jQuery(document).ready(function() {
  4586. $(function() {
  4587. $( "#'.$dialogconfirm.'" ).dialog(
  4588. {
  4589. autoOpen: '.($autoOpen ? "true" : "false").',';
  4590. if ($newselectedchoice == 'no') {
  4591. $formconfirm .= '
  4592. open: function() {
  4593. $(this).parent().find("button.ui-button:eq(2)").focus();
  4594. },';
  4595. }
  4596. $formconfirm .= '
  4597. resizable: false,
  4598. height: "'.$height.'",
  4599. width: "'.$width.'",
  4600. modal: true,
  4601. closeOnEscape: false,
  4602. buttons: {
  4603. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  4604. var options = "&token='.urlencode(newToken()).'";
  4605. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  4606. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  4607. if (inputok.length>0) {
  4608. $.each(inputok, function(i, inputname) {
  4609. var more = "";
  4610. var inputvalue;
  4611. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4612. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4613. } else {
  4614. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4615. inputvalue = $("#" + inputname + more).val();
  4616. }
  4617. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4618. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4619. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4620. });
  4621. }
  4622. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  4623. if (pageyes.length > 0) { location.href = urljump; }
  4624. $(this).dialog("close");
  4625. },
  4626. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  4627. var options = "&token='.urlencode(newToken()).'";
  4628. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  4629. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  4630. if (inputko.length>0) {
  4631. $.each(inputko, function(i, inputname) {
  4632. var more = "";
  4633. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4634. var inputvalue = $("#" + inputname + more).val();
  4635. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4636. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4637. });
  4638. }
  4639. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  4640. //alert(urljump);
  4641. if (pageno.length > 0) { location.href = urljump; }
  4642. $(this).dialog("close");
  4643. }
  4644. }
  4645. }
  4646. );
  4647. var button = "'.$button.'";
  4648. if (button.length > 0) {
  4649. $( "#" + button ).click(function() {
  4650. $("#'.$dialogconfirm.'").dialog("open");
  4651. });
  4652. }
  4653. });
  4654. });
  4655. </script>';
  4656. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4657. } else {
  4658. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  4659. if (empty($disableformtag)) {
  4660. $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  4661. }
  4662. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  4663. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  4664. $formconfirm .= '<table class="valid centpercent">'."\n";
  4665. // Line title
  4666. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4667. $formconfirm .= img_picto('', 'recent').' '.$title;
  4668. $formconfirm .= '</td></tr>'."\n";
  4669. // Line text
  4670. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4671. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  4672. }
  4673. // Line form fields
  4674. if ($more) {
  4675. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
  4676. $formconfirm .= $more;
  4677. $formconfirm .= '</td></tr>'."\n";
  4678. }
  4679. // Line with question
  4680. $formconfirm .= '<tr class="valid">';
  4681. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4682. $formconfirm .= '<td class="valid center">';
  4683. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly');
  4684. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="'.$langs->trans("Validate").'">';
  4685. $formconfirm .= '</td>';
  4686. $formconfirm .= '</tr>'."\n";
  4687. $formconfirm .= '</table>'."\n";
  4688. if (empty($disableformtag)) {
  4689. $formconfirm .= "</form>\n";
  4690. }
  4691. $formconfirm .= '<br>';
  4692. if (!empty($conf->use_javascript_ajax)) {
  4693. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4694. $formconfirm .= '<script type="text/javascript">'."\n";
  4695. $formconfirm .= '
  4696. $(document).ready(function () {
  4697. $(".confirmvalidatebutton").on("click", function() {
  4698. console.log("We click on button");
  4699. $(this).attr("disabled", "disabled");
  4700. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4701. //console.log($(this).closest("form"));
  4702. $(this).closest("form").submit();
  4703. });
  4704. });
  4705. ';
  4706. $formconfirm .= '</script>'."\n";
  4707. }
  4708. $formconfirm .= "<!-- end formconfirm -->\n";
  4709. }
  4710. return $formconfirm;
  4711. }
  4712. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4713. /**
  4714. * Show a form to select a project
  4715. *
  4716. * @param int $page Page
  4717. * @param int $socid Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
  4718. * @param int $selected Id pre-selected project
  4719. * @param string $htmlname Name of select field
  4720. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4721. * @param int $maxlength Max length
  4722. * @param int $forcefocus Force focus on field (works with javascript only)
  4723. * @param int $nooutput No print is done. String is returned.
  4724. * @return string Return html content
  4725. */
  4726. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  4727. {
  4728. // phpcs:enable
  4729. global $langs;
  4730. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4731. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4732. $out = '';
  4733. $formproject = new FormProjets($this->db);
  4734. $langs->load("project");
  4735. if ($htmlname != "none") {
  4736. $out .= "\n";
  4737. $out .= '<form method="post" action="'.$page.'">';
  4738. $out .= '<input type="hidden" name="action" value="classin">';
  4739. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4740. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  4741. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4742. $out .= '</form>';
  4743. } else {
  4744. $out .= '<span class="project_head_block">';
  4745. if ($selected) {
  4746. $projet = new Project($this->db);
  4747. $projet->fetch($selected);
  4748. $out .= $projet->getNomUrl(1, '', 1);
  4749. } else {
  4750. $out .= "&nbsp;";
  4751. }
  4752. $out .= '</span>';
  4753. }
  4754. if (empty($nooutput)) {
  4755. print $out;
  4756. return '';
  4757. }
  4758. return $out;
  4759. }
  4760. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4761. /**
  4762. * Show a form to select payment conditions
  4763. *
  4764. * @param int $page Page
  4765. * @param string $selected Id condition pre-selectionne
  4766. * @param string $htmlname Name of select html field
  4767. * @param int $addempty Add empty entry
  4768. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4769. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  4770. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  4771. * 0 : use default deposit percentage from entry
  4772. * > 0 : force deposit percentage (for example, from company object)
  4773. * @return void
  4774. */
  4775. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1)
  4776. {
  4777. // phpcs:enable
  4778. global $langs;
  4779. if ($htmlname != "none") {
  4780. print '<form method="POST" action="'.$page.'">';
  4781. print '<input type="hidden" name="action" value="setconditions">';
  4782. print '<input type="hidden" name="token" value="'.newToken().'">';
  4783. if ($type) {
  4784. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4785. }
  4786. $this->select_conditions_paiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  4787. print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4788. print '</form>';
  4789. } else {
  4790. if ($selected) {
  4791. $this->load_cache_conditions_paiements();
  4792. if (isset($this->cache_conditions_paiements[$selected])) {
  4793. $label = $this->cache_conditions_paiements[$selected]['label'];
  4794. if (! empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  4795. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  4796. }
  4797. print $label;
  4798. } else {
  4799. $langs->load('errors');
  4800. print $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4801. }
  4802. } else {
  4803. print "&nbsp;";
  4804. }
  4805. }
  4806. }
  4807. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4808. /**
  4809. * Show a form to select a delivery delay
  4810. *
  4811. * @param int $page Page
  4812. * @param string $selected Id condition pre-selectionne
  4813. * @param string $htmlname Name of select html field
  4814. * @param int $addempty Ajoute entree vide
  4815. * @return void
  4816. */
  4817. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4818. {
  4819. // phpcs:enable
  4820. global $langs;
  4821. if ($htmlname != "none") {
  4822. print '<form method="post" action="'.$page.'">';
  4823. print '<input type="hidden" name="action" value="setavailability">';
  4824. print '<input type="hidden" name="token" value="'.newToken().'">';
  4825. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4826. print '<input type="submit" name="modify" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4827. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="'.$langs->trans("Cancel").'">';
  4828. print '</form>';
  4829. } else {
  4830. if ($selected) {
  4831. $this->load_cache_availability();
  4832. print $this->cache_availability[$selected]['label'];
  4833. } else {
  4834. print "&nbsp;";
  4835. }
  4836. }
  4837. }
  4838. /**
  4839. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  4840. * List found into table c_input_reason loaded by loadCacheInputReason
  4841. *
  4842. * @param string $page Page
  4843. * @param string $selected Id condition pre-selectionne
  4844. * @param string $htmlname Name of select html field
  4845. * @param int $addempty Add empty entry
  4846. * @return void
  4847. */
  4848. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  4849. {
  4850. global $langs;
  4851. if ($htmlname != "none") {
  4852. print '<form method="post" action="'.$page.'">';
  4853. print '<input type="hidden" name="action" value="setdemandreason">';
  4854. print '<input type="hidden" name="token" value="'.newToken().'">';
  4855. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  4856. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4857. print '</form>';
  4858. } else {
  4859. if ($selected) {
  4860. $this->loadCacheInputReason();
  4861. foreach ($this->cache_demand_reason as $key => $val) {
  4862. if ($val['id'] == $selected) {
  4863. print $val['label'];
  4864. break;
  4865. }
  4866. }
  4867. } else {
  4868. print "&nbsp;";
  4869. }
  4870. }
  4871. }
  4872. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4873. /**
  4874. * Show a form + html select a date
  4875. *
  4876. * @param string $page Page
  4877. * @param string $selected Date preselected
  4878. * @param string $htmlname Html name of date input fields or 'none'
  4879. * @param int $displayhour Display hour selector
  4880. * @param int $displaymin Display minutes selector
  4881. * @param int $nooutput 1=No print output, return string
  4882. * @param string $type 'direct-debit' or 'bank-transfer'
  4883. * @return string
  4884. * @see selectDate()
  4885. */
  4886. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  4887. {
  4888. // phpcs:enable
  4889. global $langs;
  4890. $ret = '';
  4891. if ($htmlname != "none") {
  4892. $ret .= '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4893. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4894. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4895. if ($type) {
  4896. $ret .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4897. }
  4898. $ret .= '<table class="nobordernopadding">';
  4899. $ret .= '<tr><td>';
  4900. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4901. $ret .= '</td>';
  4902. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  4903. $ret .= '</tr></table></form>';
  4904. } else {
  4905. if ($displayhour) {
  4906. $ret .= dol_print_date($selected, 'dayhour');
  4907. } else {
  4908. $ret .= dol_print_date($selected, 'day');
  4909. }
  4910. }
  4911. if (empty($nooutput)) {
  4912. print $ret;
  4913. }
  4914. return $ret;
  4915. }
  4916. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4917. /**
  4918. * Show a select form to choose a user
  4919. *
  4920. * @param string $page Page
  4921. * @param string $selected Id of user preselected
  4922. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4923. * @param array $exclude List of users id to exclude
  4924. * @param array $include List of users id to include
  4925. * @return void
  4926. */
  4927. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4928. {
  4929. // phpcs:enable
  4930. global $langs;
  4931. if ($htmlname != "none") {
  4932. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4933. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4934. print '<input type="hidden" name="token" value="'.newToken().'">';
  4935. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  4936. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4937. print '</form>';
  4938. } else {
  4939. if ($selected) {
  4940. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  4941. $theuser = new User($this->db);
  4942. $theuser->fetch($selected);
  4943. print $theuser->getNomUrl(1);
  4944. } else {
  4945. print "&nbsp;";
  4946. }
  4947. }
  4948. }
  4949. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4950. /**
  4951. * Show form with payment mode
  4952. *
  4953. * @param string $page Page
  4954. * @param int $selected Id mode pre-selectionne
  4955. * @param string $htmlname Name of select html field
  4956. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  4957. * @param int $active Active or not, -1 = all
  4958. * @param int $addempty 1=Add empty entry
  4959. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4960. * @return void
  4961. */
  4962. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '')
  4963. {
  4964. // phpcs:enable
  4965. global $langs;
  4966. if ($htmlname != "none") {
  4967. print '<form method="POST" action="'.$page.'">';
  4968. print '<input type="hidden" name="action" value="setmode">';
  4969. print '<input type="hidden" name="token" value="'.newToken().'">';
  4970. if ($type) {
  4971. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4972. }
  4973. print $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  4974. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4975. print '</form>';
  4976. } else {
  4977. if ($selected) {
  4978. $this->load_cache_types_paiements();
  4979. print $this->cache_types_paiements[$selected]['label'];
  4980. } else {
  4981. print "&nbsp;";
  4982. }
  4983. }
  4984. }
  4985. /**
  4986. * Show form with transport mode
  4987. *
  4988. * @param string $page Page
  4989. * @param int $selected Id mode pre-select
  4990. * @param string $htmlname Name of select html field
  4991. * @param int $active Active or not, -1 = all
  4992. * @param int $addempty 1=Add empty entry
  4993. * @return void
  4994. */
  4995. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  4996. {
  4997. global $langs;
  4998. if ($htmlname != "none") {
  4999. print '<form method="POST" action="'.$page.'">';
  5000. print '<input type="hidden" name="action" value="settransportmode">';
  5001. print '<input type="hidden" name="token" value="'.newToken().'">';
  5002. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5003. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5004. print '</form>';
  5005. } else {
  5006. if ($selected) {
  5007. $this->load_cache_transport_mode();
  5008. print $this->cache_transport_mode[$selected]['label'];
  5009. } else {
  5010. print "&nbsp;";
  5011. }
  5012. }
  5013. }
  5014. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5015. /**
  5016. * Show form with multicurrency code
  5017. *
  5018. * @param string $page Page
  5019. * @param string $selected code pre-selectionne
  5020. * @param string $htmlname Name of select html field
  5021. * @return void
  5022. */
  5023. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5024. {
  5025. // phpcs:enable
  5026. global $langs;
  5027. if ($htmlname != "none") {
  5028. print '<form method="POST" action="'.$page.'">';
  5029. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5030. print '<input type="hidden" name="token" value="'.newToken().'">';
  5031. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5032. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5033. print '</form>';
  5034. } else {
  5035. dol_include_once('/core/lib/company.lib.php');
  5036. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5037. }
  5038. }
  5039. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5040. /**
  5041. * Show form with multicurrency rate
  5042. *
  5043. * @param string $page Page
  5044. * @param double $rate Current rate
  5045. * @param string $htmlname Name of select html field
  5046. * @param string $currency Currency code to explain the rate
  5047. * @return void
  5048. */
  5049. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5050. {
  5051. // phpcs:enable
  5052. global $langs, $mysoc, $conf;
  5053. if ($htmlname != "none") {
  5054. print '<form method="POST" action="'.$page.'">';
  5055. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5056. print '<input type="hidden" name="token" value="'.newToken().'">';
  5057. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
  5058. print '<select name="calculation_mode">';
  5059. print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
  5060. print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
  5061. print '</select> ';
  5062. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5063. print '</form>';
  5064. } else {
  5065. if (!empty($rate)) {
  5066. print price($rate, 1, $langs, 1, 0);
  5067. if ($currency && $rate != 1) {
  5068. print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  5069. }
  5070. } else {
  5071. print 1;
  5072. }
  5073. }
  5074. }
  5075. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5076. /**
  5077. * Show a select box with available absolute discounts
  5078. *
  5079. * @param string $page Page URL where form is shown
  5080. * @param int $selected Value pre-selected
  5081. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5082. * @param int $socid Third party id
  5083. * @param float $amount Total amount available
  5084. * @param string $filter SQL filter on discounts
  5085. * @param int $maxvalue Max value for lines that can be selected
  5086. * @param string $more More string to add
  5087. * @param int $hidelist 1=Hide list
  5088. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5089. * @return void
  5090. */
  5091. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5092. {
  5093. // phpcs:enable
  5094. global $conf, $langs;
  5095. if ($htmlname != "none") {
  5096. print '<form method="post" action="'.$page.'">';
  5097. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5098. print '<input type="hidden" name="token" value="'.newToken().'">';
  5099. print '<div class="inline-block">';
  5100. if (!empty($discount_type)) {
  5101. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5102. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5103. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5104. } else {
  5105. $translationKey = 'HasCreditNoteFromSupplier';
  5106. }
  5107. } else {
  5108. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5109. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5110. } else {
  5111. $translationKey = 'HasCreditNoteFromSupplier';
  5112. }
  5113. }
  5114. } else {
  5115. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5116. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5117. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5118. } else {
  5119. $translationKey = 'CompanyHasCreditNote';
  5120. }
  5121. } else {
  5122. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5123. $translationKey = 'CompanyHasAbsoluteDiscount';
  5124. } else {
  5125. $translationKey = 'CompanyHasCreditNote';
  5126. }
  5127. }
  5128. }
  5129. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5130. if (empty($hidelist)) {
  5131. print ' ';
  5132. }
  5133. print '</div>';
  5134. if (empty($hidelist)) {
  5135. print '<div class="inline-block" style="padding-right: 10px">';
  5136. $newfilter = 'discount_type='.intval($discount_type);
  5137. if (!empty($discount_type)) {
  5138. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5139. } else {
  5140. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5141. }
  5142. if ($filter) {
  5143. $newfilter .= ' AND ('.$filter.')';
  5144. }
  5145. // output the combo of discounts
  5146. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5147. if ($nbqualifiedlines > 0) {
  5148. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  5149. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5150. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5151. }
  5152. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5153. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5154. }
  5155. print '>';
  5156. }
  5157. print '</div>';
  5158. }
  5159. if ($more) {
  5160. print '<div class="inline-block">';
  5161. print $more;
  5162. print '</div>';
  5163. }
  5164. print '</form>';
  5165. } else {
  5166. if ($selected) {
  5167. print $selected;
  5168. } else {
  5169. print "0";
  5170. }
  5171. }
  5172. }
  5173. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5174. /**
  5175. * Show forms to select a contact
  5176. *
  5177. * @param string $page Page
  5178. * @param Societe $societe Filter on third party
  5179. * @param int $selected Id contact pre-selectionne
  5180. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5181. * @return void
  5182. */
  5183. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5184. {
  5185. // phpcs:enable
  5186. global $langs, $conf;
  5187. if ($htmlname != "none") {
  5188. print '<form method="post" action="'.$page.'">';
  5189. print '<input type="hidden" name="action" value="set_contact">';
  5190. print '<input type="hidden" name="token" value="'.newToken().'">';
  5191. print '<table class="nobordernopadding">';
  5192. print '<tr><td>';
  5193. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5194. $num = $this->num;
  5195. if ($num == 0) {
  5196. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5197. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  5198. }
  5199. print '</td>';
  5200. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5201. print '</tr></table></form>';
  5202. } else {
  5203. if ($selected) {
  5204. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  5205. $contact = new Contact($this->db);
  5206. $contact->fetch($selected);
  5207. print $contact->getFullName($langs);
  5208. } else {
  5209. print "&nbsp;";
  5210. }
  5211. }
  5212. }
  5213. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5214. /**
  5215. * Output html select to select thirdparty
  5216. *
  5217. * @param string $page Page
  5218. * @param string $selected Id preselected
  5219. * @param string $htmlname Name of HTML select
  5220. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5221. * @param int $showempty Add an empty field
  5222. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5223. * @param int $forcecombo Force to use combo box
  5224. * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
  5225. * @param int $nooutput No print output. Return it only.
  5226. * @param array $excludeids Exclude IDs from the select combo
  5227. * @return void|string
  5228. */
  5229. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array())
  5230. {
  5231. // phpcs:enable
  5232. global $langs;
  5233. $out = '';
  5234. if ($htmlname != "none") {
  5235. $out .= '<form method="post" action="'.$page.'">';
  5236. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5237. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5238. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5239. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5240. $out .= '</form>';
  5241. } else {
  5242. if ($selected) {
  5243. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  5244. $soc = new Societe($this->db);
  5245. $soc->fetch($selected);
  5246. $out .= $soc->getNomUrl($langs);
  5247. } else {
  5248. $out .= "&nbsp;";
  5249. }
  5250. }
  5251. if ($nooutput) {
  5252. return $out;
  5253. } else {
  5254. print $out;
  5255. }
  5256. }
  5257. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5258. /**
  5259. * Retourne la liste des devises, dans la langue de l'utilisateur
  5260. *
  5261. * @param string $selected preselected currency code
  5262. * @param string $htmlname name of HTML select list
  5263. * @deprecated
  5264. * @return void
  5265. */
  5266. public function select_currency($selected = '', $htmlname = 'currency_id')
  5267. {
  5268. // phpcs:enable
  5269. print $this->selectCurrency($selected, $htmlname);
  5270. }
  5271. /**
  5272. * Retourne la liste des devises, dans la langue de l'utilisateur
  5273. *
  5274. * @param string $selected preselected currency code
  5275. * @param string $htmlname name of HTML select list
  5276. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5277. * @return string
  5278. */
  5279. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0)
  5280. {
  5281. global $conf, $langs, $user;
  5282. $langs->loadCacheCurrencies('');
  5283. $out = '';
  5284. if ($selected == 'euro' || $selected == 'euros') {
  5285. $selected = 'EUR'; // Pour compatibilite
  5286. }
  5287. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  5288. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5289. $labeltoshow = $currency['label'];
  5290. if ($mode == 1) {
  5291. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  5292. } else {
  5293. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  5294. }
  5295. if ($selected && $selected == $code_iso) {
  5296. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5297. } else {
  5298. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5299. }
  5300. $out .= $labeltoshow;
  5301. $out .= '</option>';
  5302. }
  5303. $out .= '</select>';
  5304. if ($user->admin) {
  5305. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5306. }
  5307. // Make select dynamic
  5308. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5309. $out .= ajax_combobox($htmlname);
  5310. return $out;
  5311. }
  5312. /**
  5313. * Return array of currencies in user language
  5314. *
  5315. * @param string $selected preselected currency code
  5316. * @param string $htmlname name of HTML select list
  5317. * @param integer $useempty 1=Add empty line
  5318. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5319. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available. true = we are in currency_rate update , we don't want to see conf->currency in select
  5320. * @return string
  5321. */
  5322. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false)
  5323. {
  5324. global $conf, $langs;
  5325. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5326. $TCurrency = array();
  5327. $sql = "SELECT code FROM ".$this->db->prefix()."multicurrency";
  5328. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  5329. if ($filter) {
  5330. $sql .= " AND ".$filter;
  5331. }
  5332. $resql = $this->db->query($sql);
  5333. if ($resql) {
  5334. while ($obj = $this->db->fetch_object($resql)) {
  5335. $TCurrency[$obj->code] = $obj->code;
  5336. }
  5337. }
  5338. $out = '';
  5339. $out .= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  5340. if ($useempty) {
  5341. $out .= '<option value="">&nbsp;</option>';
  5342. }
  5343. // If company current currency not in table, we add it into list. Should always be available.
  5344. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5345. $TCurrency[$conf->currency] = $conf->currency;
  5346. }
  5347. if (count($TCurrency) > 0) {
  5348. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5349. if (isset($TCurrency[$code_iso])) {
  5350. if (!empty($selected) && $selected == $code_iso) {
  5351. $out .= '<option value="'.$code_iso.'" selected="selected">';
  5352. } else {
  5353. $out .= '<option value="'.$code_iso.'">';
  5354. }
  5355. $out .= $currency['label'];
  5356. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  5357. $out .= '</option>';
  5358. }
  5359. }
  5360. }
  5361. $out .= '</select>';
  5362. // Make select dynamic
  5363. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5364. $out .= ajax_combobox($htmlname);
  5365. return $out;
  5366. }
  5367. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5368. /**
  5369. * Load into the cache vat rates of a country
  5370. *
  5371. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5372. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5373. */
  5374. public function load_cache_vatrates($country_code)
  5375. {
  5376. // phpcs:enable
  5377. global $langs;
  5378. $num = count($this->cache_vatrates);
  5379. if ($num > 0) {
  5380. return $num; // Cache already loaded
  5381. }
  5382. dol_syslog(__METHOD__, LOG_DEBUG);
  5383. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5384. $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
  5385. $sql .= " WHERE t.fk_pays = c.rowid";
  5386. $sql .= " AND t.active > 0";
  5387. $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
  5388. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5389. $resql = $this->db->query($sql);
  5390. if ($resql) {
  5391. $num = $this->db->num_rows($resql);
  5392. if ($num) {
  5393. for ($i = 0; $i < $num; $i++) {
  5394. $obj = $this->db->fetch_object($resql);
  5395. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5396. $this->cache_vatrates[$i]['code'] = $obj->code;
  5397. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5398. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5399. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5400. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5401. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5402. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5403. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  5404. $this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1 ? $obj->localtax1 : '0').'/'.($obj->localtax2 ? $obj->localtax2 : '0').($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5405. $positiverates = '';
  5406. if ($obj->taux) {
  5407. $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  5408. }
  5409. if ($obj->localtax1) {
  5410. $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  5411. }
  5412. if ($obj->localtax2) {
  5413. $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  5414. }
  5415. if (empty($positiverates)) {
  5416. $positiverates = '0';
  5417. }
  5418. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5419. }
  5420. return $num;
  5421. } else {
  5422. $this->error = '<span class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</span>';
  5423. return -1;
  5424. }
  5425. } else {
  5426. $this->error = '<span class="error">'.$this->db->error().'</span>';
  5427. return -2;
  5428. }
  5429. }
  5430. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5431. /**
  5432. * Output an HTML select vat rate.
  5433. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5434. *
  5435. * @param string $htmlname Name of HTML select field
  5436. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5437. * @param Societe $societe_vendeuse Thirdparty seller
  5438. * @param Societe $societe_acheteuse Thirdparty buyer
  5439. * @param int $idprod Id product. O if unknown of NA.
  5440. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5441. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5442. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5443. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5444. * Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  5445. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5446. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5447. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5448. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5449. * @param int $mode 0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key
  5450. * @return string
  5451. */
  5452. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5453. {
  5454. // phpcs:enable
  5455. global $langs, $conf, $mysoc;
  5456. $langs->load('errors');
  5457. $return = '';
  5458. // Define defaultnpr, defaultttx and defaultcode
  5459. $defaultnpr = ($info_bits & 0x01);
  5460. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5461. $defaulttx = str_replace('*', '', $selectedrate);
  5462. $defaultcode = '';
  5463. $reg = array();
  5464. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5465. $defaultcode = $reg[1];
  5466. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5467. }
  5468. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5469. // Check parameters
  5470. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5471. if ($societe_vendeuse->id == $mysoc->id) {
  5472. $return .= '<span class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</span>';
  5473. } else {
  5474. $return .= '<span class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</span>';
  5475. }
  5476. return $return;
  5477. }
  5478. //var_dump($societe_acheteuse);
  5479. //print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->country_code." buyer=".$societe_acheteuse->country_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type";
  5480. //exit;
  5481. // Define list of countries to use to search VAT rates to show
  5482. // First we defined code_country to use to find list
  5483. if (is_object($societe_vendeuse)) {
  5484. $code_country = "'".$societe_vendeuse->country_code."'";
  5485. } else {
  5486. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  5487. }
  5488. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5489. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5490. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5491. // We also add the buyer
  5492. if (is_numeric($type)) {
  5493. if ($type == 1) { // We know product is a service
  5494. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5495. }
  5496. } elseif (!$idprod) { // We don't know type of product
  5497. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5498. } else {
  5499. $prodstatic = new Product($this->db);
  5500. $prodstatic->fetch($idprod);
  5501. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5502. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5503. }
  5504. }
  5505. }
  5506. }
  5507. // Now we get list
  5508. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5509. if ($num > 0) {
  5510. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5511. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5512. $tmpthirdparty = new Societe($this->db);
  5513. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5514. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5515. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5516. $defaultcode = $reg[1];
  5517. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5518. }
  5519. if (empty($defaulttx)) {
  5520. $defaultnpr = 0;
  5521. }
  5522. }
  5523. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  5524. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  5525. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5526. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5527. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5528. } else {
  5529. $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  5530. }
  5531. }
  5532. // Disabled if seller is not subject to VAT
  5533. $disabled = false;
  5534. $title = '';
  5535. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5536. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5537. // of using supplier invoices (this is a very bad idea !)
  5538. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5539. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  5540. $disabled = true;
  5541. }
  5542. }
  5543. if (!$options_only) {
  5544. $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  5545. }
  5546. $selectedfound = false;
  5547. foreach ($this->cache_vatrates as $rate) {
  5548. // Keep only 0 if seller is not subject to VAT
  5549. if ($disabled && $rate['txtva'] != 0) {
  5550. continue;
  5551. }
  5552. // Define key to use into select list
  5553. $key = $rate['txtva'];
  5554. $key .= $rate['nprtva'] ? '*' : '';
  5555. if ($mode > 0 && $rate['code']) {
  5556. $key .= ' ('.$rate['code'].')';
  5557. }
  5558. if ($mode < 0) {
  5559. $key = $rate['rowid'];
  5560. }
  5561. $return .= '<option value="'.$key.'"';
  5562. if (!$selectedfound) {
  5563. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5564. if ($defaultcode == $rate['code']) {
  5565. $return .= ' selected';
  5566. $selectedfound = true;
  5567. }
  5568. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5569. $return .= ' selected';
  5570. $selectedfound = true;
  5571. }
  5572. }
  5573. $return .= '>';
  5574. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  5575. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5576. $return .= $rate['labelpositiverates'];
  5577. } else {
  5578. $return .= vatrate($rate['label']);
  5579. }
  5580. //$return.=($rate['code']?' '.$rate['code']:'');
  5581. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5582. $return .= '</option>';
  5583. }
  5584. if (!$options_only) {
  5585. $return .= '</select>';
  5586. }
  5587. } else {
  5588. $return .= $this->error;
  5589. }
  5590. $this->num = $num;
  5591. return $return;
  5592. }
  5593. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5594. /**
  5595. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5596. * Fields are preselected with :
  5597. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5598. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5599. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5600. *
  5601. * @param integer $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5602. * @param string $prefix Prefix for fields name
  5603. * @param int $h 1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
  5604. * @param int $m 1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
  5605. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5606. * @param string $form_name Not used
  5607. * @param int $d 1=Show days, month, years
  5608. * @param int $addnowlink Add a link "Now"
  5609. * @param int $nooutput Do not output html string but return it
  5610. * @param int $disabled Disable input fields
  5611. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5612. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5613. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5614. * @return string|void Nothing or string if nooutput is 1
  5615. * @deprecated
  5616. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5617. */
  5618. public function select_date($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $nooutput = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '')
  5619. {
  5620. // phpcs:enable
  5621. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5622. if (!empty($nooutput)) {
  5623. return $retstring;
  5624. }
  5625. print $retstring;
  5626. return;
  5627. }
  5628. /**
  5629. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5630. * Fields are preselected with :
  5631. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5632. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5633. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5634. *
  5635. * @param integer $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5636. * @param integer $set_time_end Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5637. * @param string $prefix Prefix for fields name
  5638. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5639. * @param string $forcenewline Force new line between the 2 dates.
  5640. * @return string Html for selectDate
  5641. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5642. */
  5643. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5644. {
  5645. global $langs;
  5646. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5647. if ($forcenewline) {
  5648. $ret .= '<br>';
  5649. }
  5650. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5651. return $ret;
  5652. }
  5653. /**
  5654. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5655. * Fields are preselected with :
  5656. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5657. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5658. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5659. *
  5660. * @param integer $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5661. * @param string $prefix Prefix for fields name
  5662. * @param int $h 1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
  5663. * @param int $m 1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
  5664. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5665. * @param string $form_name Not used
  5666. * @param int $d 1=Show days, month, years
  5667. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5668. * @param int $disabled Disable input fields
  5669. * @param int $fullday When a checkbox with id #fullday is checked, hours are set with 00:00 (if value if 'fulldaystart') or 23:59 (if value is 'fulldayend')
  5670. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5671. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5672. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5673. * @param int $stepminutes Specify step for minutes between 1 and 30
  5674. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5675. * @param string $placeholder Placeholder
  5676. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5677. * @return string Html for selectDate
  5678. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5679. */
  5680. public function selectDate($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '', $openinghours = '', $stepminutes = 1, $labeladddateof = '', $placeholder = '', $gm = 'auto')
  5681. {
  5682. global $conf, $langs;
  5683. if ($gm === 'auto') {
  5684. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5685. }
  5686. $retstring = '';
  5687. if ($prefix == '') {
  5688. $prefix = 're';
  5689. }
  5690. if ($h == '') {
  5691. $h = 0;
  5692. }
  5693. if ($m == '') {
  5694. $m = 0;
  5695. }
  5696. $emptydate = 0;
  5697. $emptyhours = 0;
  5698. if ($stepminutes <= 0 || $stepminutes > 30) {
  5699. $stepminutes = 1;
  5700. }
  5701. if ($empty == 1) {
  5702. $emptydate = 1;
  5703. $emptyhours = 1;
  5704. }
  5705. if ($empty == 2) {
  5706. $emptydate = 0;
  5707. $emptyhours = 1;
  5708. }
  5709. $orig_set_time = $set_time;
  5710. if ($set_time === '' && $emptydate == 0) {
  5711. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5712. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5713. $set_time = dol_now($gm);
  5714. } else {
  5715. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5716. }
  5717. }
  5718. // Analysis of the pre-selection date
  5719. $reg = array();
  5720. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5721. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5722. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5723. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5724. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5725. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5726. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5727. } elseif (strval($set_time) != '' && $set_time != -1) {
  5728. // set_time est un timestamps (0 possible)
  5729. $syear = dol_print_date($set_time, "%Y", $gm);
  5730. $smonth = dol_print_date($set_time, "%m", $gm);
  5731. $sday = dol_print_date($set_time, "%d", $gm);
  5732. if ($orig_set_time != '') {
  5733. $shour = dol_print_date($set_time, "%H", $gm);
  5734. $smin = dol_print_date($set_time, "%M", $gm);
  5735. $ssec = dol_print_date($set_time, "%S", $gm);
  5736. } else {
  5737. $shour = '';
  5738. $smin = '';
  5739. $ssec = '';
  5740. }
  5741. } else {
  5742. // Date est '' ou vaut -1
  5743. $syear = '';
  5744. $smonth = '';
  5745. $sday = '';
  5746. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5747. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5748. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5749. }
  5750. if ($h == 3) {
  5751. $shour = '';
  5752. }
  5753. if ($m == 3) {
  5754. $smin = '';
  5755. }
  5756. $nowgmt = dol_now('gmt');
  5757. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5758. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5759. $usecalendar = 'combo';
  5760. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5761. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5762. }
  5763. if ($d) {
  5764. // Show date with popup
  5765. if ($usecalendar != 'combo') {
  5766. $formated_date = '';
  5767. //print "e".$set_time." t ".$conf->format_date_short;
  5768. if (strval($set_time) != '' && $set_time != -1) {
  5769. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5770. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5771. }
  5772. // Calendrier popup version eldy
  5773. if ($usecalendar == "eldy") {
  5774. // Input area to enter date manually
  5775. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5776. $retstring .= ($disabled ? ' disabled' : '');
  5777. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5778. $retstring .= '>';
  5779. // Icon calendar
  5780. $retstringbuttom = '';
  5781. if (!$disabled) {
  5782. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5783. $base = DOL_URL_ROOT.'/core/';
  5784. $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5785. $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5786. } else {
  5787. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5788. }
  5789. $retstring = $retstringbuttom.$retstring;
  5790. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5791. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5792. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5793. } elseif ($usecalendar == 'jquery') {
  5794. if (!$disabled) {
  5795. // Output javascript for datepicker
  5796. $retstring .= "<script type='text/javascript'>";
  5797. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5798. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5799. autoclose: true,
  5800. todayHighlight: true,";
  5801. if (!empty($conf->dol_use_jmobile)) {
  5802. $retstring .= "
  5803. beforeShow: function (input, datePicker) {
  5804. input.disabled = true;
  5805. },
  5806. onClose: function (dateText, datePicker) {
  5807. this.disabled = false;
  5808. },
  5809. ";
  5810. }
  5811. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  5812. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  5813. $retstring .= "
  5814. showOn: 'button', /* both has problem with autocompletion */
  5815. buttonImage: '".DOL_URL_ROOT."/theme/".dol_escape_js($conf->theme)."/img/object_calendarday.png',
  5816. buttonImageOnly: true";
  5817. }
  5818. $retstring .= "
  5819. }) });";
  5820. $retstring .= "</script>";
  5821. }
  5822. // Zone de saisie manuelle de la date
  5823. $retstring .= '<div class="nowrap inline-block divfordateinput">';
  5824. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5825. $retstring .= ($disabled ? ' disabled' : '');
  5826. $retstring .= ($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '');
  5827. $retstring .= ' onChange="dpChangeDay(\''.dol_escape_js($prefix).'\',\''.dol_escape_js($langs->trans("FormatDateShortJavaInput")).'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5828. $retstring .= '>';
  5829. // Icone calendrier
  5830. if (!$disabled) {
  5831. /* Not required. Managed by option buttonImage of jquery
  5832. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  5833. $retstring.="<script type='text/javascript'>";
  5834. $retstring.="jQuery(document).ready(function() {";
  5835. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  5836. $retstring.=" jQuery('#".$prefix."').focus();";
  5837. $retstring.=' });';
  5838. $retstring.='});';
  5839. $retstring.="</script>";*/
  5840. } else {
  5841. $retstringbutton = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5842. $retsring = $retstringbutton.$retstring;
  5843. }
  5844. $retstring .= '</div>';
  5845. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5846. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5847. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5848. } else {
  5849. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  5850. }
  5851. } else {
  5852. // Show date with combo selects
  5853. // Day
  5854. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  5855. if ($emptydate || $set_time == -1) {
  5856. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5857. }
  5858. for ($day = 1; $day <= 31; $day++) {
  5859. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  5860. }
  5861. $retstring .= "</select>";
  5862. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  5863. if ($emptydate || $set_time == -1) {
  5864. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5865. }
  5866. // Month
  5867. for ($month = 1; $month <= 12; $month++) {
  5868. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  5869. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  5870. $retstring .= "</option>";
  5871. }
  5872. $retstring .= "</select>";
  5873. // Year
  5874. if ($emptydate || $set_time == -1) {
  5875. $retstring .= '<input'.($disabled ? ' disabled' : '').' placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" class="flat maxwidth50imp valignmiddle" type="number" min="0" max="3000" maxlength="4" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">';
  5876. } else {
  5877. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  5878. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  5879. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  5880. }
  5881. $retstring .= "</select>\n";
  5882. }
  5883. }
  5884. }
  5885. if ($d && $h) {
  5886. $retstring .= ($h == 2 ? '<br>' : ' ');
  5887. $retstring .= '<span class="nowraponall">';
  5888. }
  5889. if ($h) {
  5890. $hourstart = 0;
  5891. $hourend = 24;
  5892. if ($openinghours != '') {
  5893. $openinghours = explode(',', $openinghours);
  5894. $hourstart = $openinghours[0];
  5895. $hourend = $openinghours[1];
  5896. if ($hourend < $hourstart) {
  5897. $hourend = $hourstart;
  5898. }
  5899. }
  5900. // Show hour
  5901. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  5902. if ($emptyhours) {
  5903. $retstring .= '<option value="-1">&nbsp;</option>';
  5904. }
  5905. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  5906. if (strlen($hour) < 2) {
  5907. $hour = "0".$hour;
  5908. }
  5909. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  5910. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  5911. $retstring .= '</option>';
  5912. }
  5913. $retstring .= '</select>';
  5914. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  5915. if ($m) {
  5916. $retstring .= ":";
  5917. }
  5918. }
  5919. if ($m) {
  5920. // Show minutes
  5921. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  5922. if ($emptyhours) {
  5923. $retstring .= '<option value="-1">&nbsp;</option>';
  5924. }
  5925. for ($min = 0; $min < 60; $min += $stepminutes) {
  5926. if (strlen($min) < 2) {
  5927. $min = "0".$min;
  5928. }
  5929. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  5930. }
  5931. $retstring .= '</select>';
  5932. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  5933. }
  5934. if ($d && $h) {
  5935. $retstring .= '</span>';
  5936. }
  5937. // Add a "Now" link
  5938. if ($conf->use_javascript_ajax && $addnowlink) {
  5939. // Script which will be inserted in the onClick of the "Now" link
  5940. $reset_scripts = "";
  5941. if ($addnowlink == 2) { // local computer time
  5942. // pad add leading 0 on numbers
  5943. $reset_scripts .= "Number.prototype.pad = function(size) {
  5944. var s = String(this);
  5945. while (s.length < (size || 2)) {s = '0' + s;}
  5946. return s;
  5947. };
  5948. var d = new Date();";
  5949. }
  5950. // Generate the date part, depending on the use or not of the javascript calendar
  5951. if ($addnowlink == 1) { // server time expressed in user time setup
  5952. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5953. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5954. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5955. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5956. } elseif ($addnowlink == 2) {
  5957. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  5958. * This break application for foreign languages.
  5959. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  5960. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  5961. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  5962. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  5963. */
  5964. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5965. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5966. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5967. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5968. }
  5969. /*if ($usecalendar == "eldy")
  5970. {
  5971. $base=DOL_URL_ROOT.'/core/';
  5972. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  5973. }
  5974. else
  5975. {
  5976. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  5977. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  5978. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  5979. }*/
  5980. // Update the hour part
  5981. if ($h) {
  5982. if ($fullday) {
  5983. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5984. }
  5985. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  5986. if ($addnowlink == 1) {
  5987. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  5988. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5989. } elseif ($addnowlink == 2) {
  5990. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  5991. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5992. }
  5993. if ($fullday) {
  5994. $reset_scripts .= ' } ';
  5995. }
  5996. }
  5997. // Update the minute part
  5998. if ($m) {
  5999. if ($fullday) {
  6000. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6001. }
  6002. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6003. if ($addnowlink == 1) {
  6004. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6005. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6006. } elseif ($addnowlink == 2) {
  6007. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  6008. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6009. }
  6010. if ($fullday) {
  6011. $reset_scripts .= ' } ';
  6012. }
  6013. }
  6014. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6015. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6016. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  6017. $retstring .= $langs->trans("Now");
  6018. $retstring .= '</button> ';
  6019. }
  6020. }
  6021. // Add a "Plus one hour" link
  6022. if ($conf->use_javascript_ajax && $addplusone) {
  6023. // Script which will be inserted in the onClick of the "Add plusone" link
  6024. $reset_scripts = "";
  6025. // Generate the date part, depending on the use or not of the javascript calendar
  6026. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');';
  6027. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6028. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6029. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6030. // Update the hour part
  6031. if ($h) {
  6032. if ($fullday) {
  6033. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6034. }
  6035. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  6036. if ($fullday) {
  6037. $reset_scripts .= ' } ';
  6038. }
  6039. }
  6040. // Update the minute part
  6041. if ($m) {
  6042. if ($fullday) {
  6043. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6044. }
  6045. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6046. if ($fullday) {
  6047. $reset_scripts .= ' } ';
  6048. }
  6049. }
  6050. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6051. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6052. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  6053. $retstring .= $langs->trans("DateStartPlusOne");
  6054. $retstring .= '</button> ';
  6055. }
  6056. }
  6057. // Add a link to set data
  6058. if ($conf->use_javascript_ajax && $adddateof) {
  6059. $tmparray = dol_getdate($adddateof);
  6060. if (empty($labeladddateof)) {
  6061. $labeladddateof = $langs->trans("DateInvoice");
  6062. }
  6063. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="console.log(\'Click on now link\'); jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'dayinputnoreduce').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$labeladddateof.'</a>';
  6064. }
  6065. return $retstring;
  6066. }
  6067. /**
  6068. * selectTypeDuration
  6069. *
  6070. * @param string $prefix Prefix
  6071. * @param string $selected Selected duration type
  6072. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6073. * @return string HTML select string
  6074. */
  6075. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6076. {
  6077. global $langs;
  6078. $TDurationTypes = array(
  6079. 'y'=>$langs->trans('Years'),
  6080. 'm'=>$langs->trans('Month'),
  6081. 'w'=>$langs->trans('Weeks'),
  6082. 'd'=>$langs->trans('Days'),
  6083. 'h'=>$langs->trans('Hours'),
  6084. 'i'=>$langs->trans('Minutes')
  6085. );
  6086. // Removed undesired duration types
  6087. foreach ($excludetypes as $value) {
  6088. unset($TDurationTypes[$value]);
  6089. }
  6090. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  6091. foreach ($TDurationTypes as $key => $typeduration) {
  6092. $retstring .= '<option value="'.$key.'"';
  6093. if ($key == $selected) {
  6094. $retstring .= " selected";
  6095. }
  6096. $retstring .= ">".$typeduration."</option>";
  6097. }
  6098. $retstring .= "</select>";
  6099. $retstring .= ajax_combobox('select_'.$prefix.'type_duration');
  6100. return $retstring;
  6101. }
  6102. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6103. /**
  6104. * Function to show a form to select a duration on a page
  6105. *
  6106. * @param string $prefix Prefix for input fields
  6107. * @param int $iSecond Default preselected duration (number of seconds or '')
  6108. * @param int $disabled Disable the combo box
  6109. * @param string $typehour If 'select' then input hour and input min is a combo,
  6110. * If 'text' input hour is in text and input min is a text,
  6111. * If 'textselect' input hour is in text and input min is a combo
  6112. * @param integer $minunderhours If 1, show minutes selection under the hours
  6113. * @param int $nooutput Do not output html string but return it
  6114. * @return string|void
  6115. */
  6116. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6117. {
  6118. // phpcs:enable
  6119. global $langs;
  6120. $retstring = '<span class="nowraponall">';
  6121. $hourSelected = 0;
  6122. $minSelected = 0;
  6123. // Hours
  6124. if ($iSecond != '') {
  6125. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6126. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6127. $minSelected = convertSecondToTime($iSecond, 'min');
  6128. }
  6129. if ($typehour == 'select') {
  6130. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  6131. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6132. $retstring .= '<option value="'.$hour.'"';
  6133. if ($hourSelected == $hour) {
  6134. $retstring .= " selected";
  6135. }
  6136. $retstring .= ">".$hour."</option>";
  6137. }
  6138. $retstring .= "</select>";
  6139. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6140. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  6141. } else {
  6142. return 'BadValueForParameterTypeHour';
  6143. }
  6144. if ($typehour != 'text') {
  6145. $retstring .= ' '.$langs->trans('HourShort');
  6146. } else {
  6147. $retstring .= '<span class="">:</span>';
  6148. }
  6149. // Minutes
  6150. if ($minunderhours) {
  6151. $retstring .= '<br>';
  6152. } else {
  6153. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6154. }
  6155. if ($typehour == 'select' || $typehour == 'textselect') {
  6156. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  6157. for ($min = 0; $min <= 55; $min = $min + 5) {
  6158. $retstring .= '<option value="'.$min.'"';
  6159. if ($minSelected == $min) {
  6160. $retstring .= ' selected';
  6161. }
  6162. $retstring .= '>'.$min.'</option>';
  6163. }
  6164. $retstring .= "</select>";
  6165. } elseif ($typehour == 'text') {
  6166. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  6167. }
  6168. if ($typehour != 'text') {
  6169. $retstring .= ' '.$langs->trans('MinuteShort');
  6170. }
  6171. $retstring.="</span>";
  6172. if (!empty($nooutput)) {
  6173. return $retstring;
  6174. }
  6175. print $retstring;
  6176. return;
  6177. }
  6178. /**
  6179. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6180. *
  6181. * @param int $selected Preselected tickets
  6182. * @param string $htmlname Name of HTML select field (must be unique in page).
  6183. * @param string $filtertype To add a filter
  6184. * @param int $limit Limit on number of returned lines
  6185. * @param int $status Ticket status
  6186. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6187. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6188. * @param array $ajaxoptions Options for ajax_autocompleter
  6189. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6190. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6191. * @param int $forcecombo Force to use combo box
  6192. * @param string $morecss Add more css on select
  6193. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6194. * @param string $nooutput No print, return the output into a string
  6195. * @return void|string
  6196. */
  6197. public function selectTickets($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6198. {
  6199. global $langs, $conf;
  6200. $out = '';
  6201. // check parameters
  6202. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6203. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6204. $placeholder = '';
  6205. if ($selected && empty($selected_input_value)) {
  6206. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6207. $tickettmpselect = new Ticket($this->db);
  6208. $tickettmpselect->fetch($selected);
  6209. $selected_input_value = $tickettmpselect->ref;
  6210. unset($tickettmpselect);
  6211. }
  6212. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6213. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6214. elseif ($hidelabel > 1) {
  6215. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6216. if ($hidelabel == 2) {
  6217. $out .= img_picto($langs->trans("Search"), 'search');
  6218. }
  6219. }
  6220. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6221. if ($hidelabel == 3) {
  6222. $out .= img_picto($langs->trans("Search"), 'search');
  6223. }
  6224. } else {
  6225. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6226. }
  6227. if (empty($nooutput)) print $out;
  6228. else return $out;
  6229. }
  6230. /**
  6231. * Return list of tickets.
  6232. * Called by selectTickets.
  6233. *
  6234. * @param int $selected Preselected ticket
  6235. * @param string $htmlname Name of select html
  6236. * @param string $filtertype Filter on ticket type
  6237. * @param int $limit Limit on number of returned lines
  6238. * @param string $filterkey Filter on ticket ref or subject
  6239. * @param int $status Ticket status
  6240. * @param int $outputmode 0=HTML select string, 1=Array
  6241. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6242. * @param int $forcecombo Force to use combo box
  6243. * @param string $morecss Add more css on select
  6244. * @return array Array of keys for json
  6245. */
  6246. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6247. {
  6248. global $langs, $conf;
  6249. $out = '';
  6250. $outarray = array();
  6251. $selectFields = " p.rowid, p.ref, p.message";
  6252. $sql = "SELECT ";
  6253. $sql .= $selectFields;
  6254. $sql .= " FROM ".$this->db->prefix()."ticket as p";
  6255. $sql .= ' WHERE p.entity IN ('.getEntity('ticket').')';
  6256. // Add criteria on ref/label
  6257. if ($filterkey != '') {
  6258. $sql .= ' AND (';
  6259. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6260. // For natural search
  6261. $scrit = explode(' ', $filterkey);
  6262. $i = 0;
  6263. if (count($scrit) > 1) $sql .= "(";
  6264. foreach ($scrit as $crit) {
  6265. if ($i > 0) $sql .= " AND ";
  6266. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.subject LIKE '".$this->db->escape($prefix.$crit)."%'";
  6267. $sql .= ")";
  6268. $i++;
  6269. }
  6270. if (count($scrit) > 1) $sql .= ")";
  6271. $sql .= ')';
  6272. }
  6273. $sql .= $this->db->plimit($limit, 0);
  6274. // Build output string
  6275. dol_syslog(get_class($this)."::selectTicketsList search tickets", LOG_DEBUG);
  6276. $result = $this->db->query($sql);
  6277. if ($result) {
  6278. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6279. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  6280. $num = $this->db->num_rows($result);
  6281. $events = null;
  6282. if (!$forcecombo) {
  6283. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6284. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6285. }
  6286. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6287. $textifempty = '';
  6288. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6289. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6290. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6291. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6292. else $textifempty .= $langs->trans("All");
  6293. } else {
  6294. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6295. }
  6296. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6297. $i = 0;
  6298. while ($num && $i < $num) {
  6299. $opt = '';
  6300. $optJson = array();
  6301. $objp = $this->db->fetch_object($result);
  6302. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6303. // Add new entry
  6304. // "key" value of json key array is used by jQuery automatically as selected value
  6305. // "label" value of json key array is used by jQuery automatically as text for combo box
  6306. $out .= $opt;
  6307. array_push($outarray, $optJson);
  6308. $i++;
  6309. }
  6310. $out .= '</select>';
  6311. $this->db->free($result);
  6312. if (empty($outputmode)) return $out;
  6313. return $outarray;
  6314. } else {
  6315. dol_print_error($this->db);
  6316. }
  6317. }
  6318. /**
  6319. * constructTicketListOption.
  6320. * This define value for &$opt and &$optJson.
  6321. *
  6322. * @param resource $objp Result set of fetch
  6323. * @param string $opt Option (var used for returned value in string option format)
  6324. * @param string $optJson Option (var used for returned value in json format)
  6325. * @param string $selected Preselected value
  6326. * @param string $filterkey Filter key to highlight
  6327. * @return void
  6328. */
  6329. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6330. {
  6331. $outkey = '';
  6332. $outval = '';
  6333. $outref = '';
  6334. $outlabel = '';
  6335. $outtype = '';
  6336. $label = $objp->label;
  6337. $outkey = $objp->rowid;
  6338. $outref = $objp->ref;
  6339. $outlabel = $objp->label;
  6340. $outtype = $objp->fk_product_type;
  6341. $opt = '<option value="'.$objp->rowid.'"';
  6342. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6343. $opt .= '>';
  6344. $opt .= $objp->ref;
  6345. $objRef = $objp->ref;
  6346. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6347. $outval .= $objRef;
  6348. $opt .= "</option>\n";
  6349. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtypem);
  6350. }
  6351. /**
  6352. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6353. *
  6354. * @param int $selected Preselected tickets
  6355. * @param string $htmlname Name of HTML select field (must be unique in page).
  6356. * @param string $filtertype To add a filter
  6357. * @param int $limit Limit on number of returned lines
  6358. * @param int $status Ticket status
  6359. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6360. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6361. * @param array $ajaxoptions Options for ajax_autocompleter
  6362. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6363. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6364. * @param int $forcecombo Force to use combo box
  6365. * @param string $morecss Add more css on select
  6366. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6367. * @param string $nooutput No print, return the output into a string
  6368. * @return void|string
  6369. */
  6370. public function selectProjects($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6371. {
  6372. global $langs, $conf;
  6373. $out = '';
  6374. // check parameters
  6375. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6376. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6377. $placeholder = '';
  6378. if ($selected && empty($selected_input_value)) {
  6379. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6380. $projecttmpselect = new Project($this->db);
  6381. $projecttmpselect->fetch($selected);
  6382. $selected_input_value = $projecttmpselect->ref;
  6383. unset($projecttmpselect);
  6384. }
  6385. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6386. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6387. elseif ($hidelabel > 1) {
  6388. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6389. if ($hidelabel == 2) {
  6390. $out .= img_picto($langs->trans("Search"), 'search');
  6391. }
  6392. }
  6393. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6394. if ($hidelabel == 3) {
  6395. $out .= img_picto($langs->trans("Search"), 'search');
  6396. }
  6397. } else {
  6398. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6399. }
  6400. if (empty($nooutput)) print $out;
  6401. else return $out;
  6402. }
  6403. /**
  6404. * Return list of projects.
  6405. * Called by selectProjects.
  6406. *
  6407. * @param int $selected Preselected project
  6408. * @param string $htmlname Name of select html
  6409. * @param string $filtertype Filter on project type
  6410. * @param int $limit Limit on number of returned lines
  6411. * @param string $filterkey Filter on project ref or subject
  6412. * @param int $status Ticket status
  6413. * @param int $outputmode 0=HTML select string, 1=Array
  6414. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6415. * @param int $forcecombo Force to use combo box
  6416. * @param string $morecss Add more css on select
  6417. * @return array Array of keys for json
  6418. */
  6419. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6420. {
  6421. global $langs, $conf;
  6422. $out = '';
  6423. $outarray = array();
  6424. $selectFields = " p.rowid, p.ref";
  6425. $sql = "SELECT ";
  6426. $sql .= $selectFields;
  6427. $sql .= " FROM ".$this->db->prefix()."projet as p";
  6428. $sql .= ' WHERE p.entity IN ('.getEntity('project').')';
  6429. // Add criteria on ref/label
  6430. if ($filterkey != '') {
  6431. $sql .= ' AND (';
  6432. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6433. // For natural search
  6434. $scrit = explode(' ', $filterkey);
  6435. $i = 0;
  6436. if (count($scrit) > 1) $sql .= "(";
  6437. foreach ($scrit as $crit) {
  6438. if ($i > 0) $sql .= " AND ";
  6439. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6440. $sql .= "";
  6441. $i++;
  6442. }
  6443. if (count($scrit) > 1) $sql .= ")";
  6444. $sql .= ')';
  6445. }
  6446. $sql .= $this->db->plimit($limit, 0);
  6447. // Build output string
  6448. dol_syslog(get_class($this)."::selectProjectsList search projects", LOG_DEBUG);
  6449. $result = $this->db->query($sql);
  6450. if ($result) {
  6451. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6452. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  6453. $num = $this->db->num_rows($result);
  6454. $events = null;
  6455. if (!$forcecombo) {
  6456. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6457. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6458. }
  6459. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6460. $textifempty = '';
  6461. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6462. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6463. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6464. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6465. else $textifempty .= $langs->trans("All");
  6466. } else {
  6467. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6468. }
  6469. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6470. $i = 0;
  6471. while ($num && $i < $num) {
  6472. $opt = '';
  6473. $optJson = array();
  6474. $objp = $this->db->fetch_object($result);
  6475. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6476. // Add new entry
  6477. // "key" value of json key array is used by jQuery automatically as selected value
  6478. // "label" value of json key array is used by jQuery automatically as text for combo box
  6479. $out .= $opt;
  6480. array_push($outarray, $optJson);
  6481. $i++;
  6482. }
  6483. $out .= '</select>';
  6484. $this->db->free($result);
  6485. if (empty($outputmode)) return $out;
  6486. return $outarray;
  6487. } else {
  6488. dol_print_error($this->db);
  6489. }
  6490. }
  6491. /**
  6492. * constructProjectListOption.
  6493. * This define value for &$opt and &$optJson.
  6494. *
  6495. * @param resource $objp Result set of fetch
  6496. * @param string $opt Option (var used for returned value in string option format)
  6497. * @param string $optJson Option (var used for returned value in json format)
  6498. * @param string $selected Preselected value
  6499. * @param string $filterkey Filter key to highlight
  6500. * @return void
  6501. */
  6502. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6503. {
  6504. $outkey = '';
  6505. $outval = '';
  6506. $outref = '';
  6507. $outlabel = '';
  6508. $outtype = '';
  6509. $label = $objp->label;
  6510. $outkey = $objp->rowid;
  6511. $outref = $objp->ref;
  6512. $outlabel = $objp->label;
  6513. $outtype = $objp->fk_product_type;
  6514. $opt = '<option value="'.$objp->rowid.'"';
  6515. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6516. $opt .= '>';
  6517. $opt .= $objp->ref;
  6518. $objRef = $objp->ref;
  6519. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6520. $outval .= $objRef;
  6521. $opt .= "</option>\n";
  6522. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6523. }
  6524. /**
  6525. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6526. *
  6527. * @param int $selected Preselected tickets
  6528. * @param string $htmlname Name of HTML select field (must be unique in page).
  6529. * @param string $filtertype To add a filter
  6530. * @param int $limit Limit on number of returned lines
  6531. * @param int $status Ticket status
  6532. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6533. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6534. * @param array $ajaxoptions Options for ajax_autocompleter
  6535. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6536. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6537. * @param int $forcecombo Force to use combo box
  6538. * @param string $morecss Add more css on select
  6539. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6540. * @param string $nooutput No print, return the output into a string
  6541. * @return void|string
  6542. */
  6543. public function selectMembers($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6544. {
  6545. global $langs, $conf;
  6546. $out = '';
  6547. // check parameters
  6548. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6549. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6550. $placeholder = '';
  6551. $urloption = '';
  6552. if ($selected && empty($selected_input_value)) {
  6553. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6554. $adherenttmpselect = new Adherent($this->db);
  6555. $adherenttmpselect->fetch($selected);
  6556. $selected_input_value = $adherenttmpselect->ref;
  6557. unset($adherenttmpselect);
  6558. }
  6559. $urloption = '';
  6560. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6561. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6562. elseif ($hidelabel > 1) {
  6563. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6564. if ($hidelabel == 2) {
  6565. $out .= img_picto($langs->trans("Search"), 'search');
  6566. }
  6567. }
  6568. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6569. if ($hidelabel == 3) {
  6570. $out .= img_picto($langs->trans("Search"), 'search');
  6571. }
  6572. } else {
  6573. $filterkey = '';
  6574. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  6575. }
  6576. if (empty($nooutput)) print $out;
  6577. else return $out;
  6578. }
  6579. /**
  6580. * Return list of adherents.
  6581. * Called by selectMembers.
  6582. *
  6583. * @param int $selected Preselected adherent
  6584. * @param string $htmlname Name of select html
  6585. * @param string $filtertype Filter on adherent type
  6586. * @param int $limit Limit on number of returned lines
  6587. * @param string $filterkey Filter on member status
  6588. * @param int $status Member status
  6589. * @param int $outputmode 0=HTML select string, 1=Array
  6590. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6591. * @param int $forcecombo Force to use combo box
  6592. * @param string $morecss Add more css on select
  6593. * @return array Array of keys for json
  6594. */
  6595. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6596. {
  6597. global $langs, $conf;
  6598. $out = '';
  6599. $outarray = array();
  6600. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname";
  6601. $sql = "SELECT ";
  6602. $sql .= $selectFields;
  6603. $sql .= " FROM ".$this->db->prefix()."adherent as p";
  6604. $sql .= ' WHERE p.entity IN ('.getEntity('adherent').')';
  6605. // Add criteria on ref/label
  6606. if ($filterkey != '') {
  6607. $sql .= ' AND (';
  6608. $prefix = empty($conf->global->MEMBER_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6609. // For natural search
  6610. $scrit = explode(' ', $filterkey);
  6611. $i = 0;
  6612. if (count($scrit) > 1) $sql .= "(";
  6613. foreach ($scrit as $crit) {
  6614. if ($i > 0) $sql .= " AND ";
  6615. $sql .= "(p.firstname LIKE '".$this->db->escape($prefix.$crit)."%'";
  6616. $sql .= " OR p.lastname LIKE '".$this->db->escape($prefix.$crit)."%')";
  6617. $i++;
  6618. }
  6619. if (count($scrit) > 1) $sql .= ")";
  6620. $sql .= ')';
  6621. }
  6622. if ($status != -1) {
  6623. $sql .= ' AND statut = '.((int) $status);
  6624. }
  6625. $sql .= $this->db->plimit($limit, 0);
  6626. // Build output string
  6627. dol_syslog(get_class($this)."::selectMembersList search adherents", LOG_DEBUG);
  6628. $result = $this->db->query($sql);
  6629. if ($result) {
  6630. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6631. require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
  6632. $num = $this->db->num_rows($result);
  6633. $events = null;
  6634. if (!$forcecombo) {
  6635. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6636. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6637. }
  6638. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6639. $textifempty = '';
  6640. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6641. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6642. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6643. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6644. else $textifempty .= $langs->trans("All");
  6645. } else {
  6646. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6647. }
  6648. if ($showempty) {
  6649. $out .= '<option value="-1" selected>'.$textifempty.'</option>';
  6650. }
  6651. $i = 0;
  6652. while ($num && $i < $num) {
  6653. $opt = '';
  6654. $optJson = array();
  6655. $objp = $this->db->fetch_object($result);
  6656. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6657. // Add new entry
  6658. // "key" value of json key array is used by jQuery automatically as selected value
  6659. // "label" value of json key array is used by jQuery automatically as text for combo box
  6660. $out .= $opt;
  6661. array_push($outarray, $optJson);
  6662. $i++;
  6663. }
  6664. $out .= '</select>';
  6665. $this->db->free($result);
  6666. if (empty($outputmode)) return $out;
  6667. return $outarray;
  6668. } else {
  6669. dol_print_error($this->db);
  6670. }
  6671. }
  6672. /**
  6673. * constructMemberListOption.
  6674. * This define value for &$opt and &$optJson.
  6675. *
  6676. * @param resource $objp Result set of fetch
  6677. * @param string $opt Option (var used for returned value in string option format)
  6678. * @param string $optJson Option (var used for returned value in json format)
  6679. * @param string $selected Preselected value
  6680. * @param string $filterkey Filter key to highlight
  6681. * @return void
  6682. */
  6683. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6684. {
  6685. $outkey = '';
  6686. $outlabel = '';
  6687. $outtype = '';
  6688. $outkey = $objp->rowid;
  6689. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  6690. $outtype = $objp->fk_adherent_type;
  6691. $opt = '<option value="'.$objp->rowid.'"';
  6692. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6693. $opt .= '>';
  6694. if (!empty($filterkey) && $filterkey != '') {
  6695. $outlabel = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $outlabel, 1);
  6696. }
  6697. $opt .= $outlabel;
  6698. $opt .= "</option>\n";
  6699. $optJson = array('key'=>$outkey, 'value'=>$outlabel, 'type'=>$outtype);
  6700. }
  6701. /**
  6702. * Generic method to select a component from a combo list.
  6703. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6704. * This is the generic method that will replace all specific existing methods.
  6705. *
  6706. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6707. * @param string $htmlname Name of HTML select component
  6708. * @param int $preselectedvalue Preselected value (ID of element)
  6709. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6710. * @param string $searchkey Search criteria
  6711. * @param string $placeholder Place holder
  6712. * @param string $morecss More CSS
  6713. * @param string $moreparams More params provided to ajax call
  6714. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6715. * @param int $disabled 1=Html component is disabled
  6716. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6717. * @return string Return HTML string
  6718. * @see selectForFormsList() select_thirdparty_list()
  6719. */
  6720. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6721. {
  6722. global $conf, $user;
  6723. $objecttmp = null;
  6724. // Example of value for $objectdec:
  6725. // Bom:bom/class/bom.class.php:0:t.status=1
  6726. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  6727. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  6728. $InfoFieldList = explode(":", $objectdesc, 4);
  6729. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  6730. $reg = array();
  6731. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  6732. $InfoFieldList[4] = $reg[1]; // take the sort field
  6733. }
  6734. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  6735. $classname = $InfoFieldList[0];
  6736. $classpath = $InfoFieldList[1];
  6737. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6738. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6739. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6740. if (!empty($classpath)) {
  6741. dol_include_once($classpath);
  6742. if ($classname && class_exists($classname)) {
  6743. $objecttmp = new $classname($this->db);
  6744. // Make some replacement
  6745. $sharedentities = getEntity(strtolower($classname));
  6746. $objecttmp->filter = str_replace(
  6747. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6748. array($conf->entity, $sharedentities, $user->id),
  6749. $filter
  6750. );
  6751. }
  6752. }
  6753. if (!is_object($objecttmp)) {
  6754. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  6755. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  6756. }
  6757. //var_dump($objecttmp->filter);
  6758. $prefixforautocompletemode = $objecttmp->element;
  6759. if ($prefixforautocompletemode == 'societe') {
  6760. $prefixforautocompletemode = 'company';
  6761. }
  6762. if ($prefixforautocompletemode == 'product') {
  6763. $prefixforautocompletemode = 'produit';
  6764. }
  6765. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6766. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  6767. $out = '';
  6768. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6769. // No immediate load of all database
  6770. $placeholder = '';
  6771. if ($preselectedvalue && empty($selected_input_value)) {
  6772. $objecttmp->fetch($preselectedvalue);
  6773. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6774. //unset($objecttmp);
  6775. }
  6776. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  6777. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  6778. // No immediate load of all database
  6779. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&objectdesc='.urlencode($objectdesc).'&filter='.urlencode($objecttmp->filter).($sortfield ? '&sortfield='.urlencode($sortfield) : '');
  6780. // Activate the auto complete using ajax call.
  6781. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6782. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6783. $out .= '<input type="text" class="'.$morecss.'"'.($disabled ? ' disabled="disabled"' : '').' name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '') .' />';
  6784. } else {
  6785. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  6786. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield);
  6787. }
  6788. return $out;
  6789. }
  6790. /**
  6791. * Function to forge a SQL criteria
  6792. *
  6793. * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
  6794. * @return string Forged criteria. Example: "t.field like 'abc%'"
  6795. */
  6796. protected static function forgeCriteriaCallback($matches)
  6797. {
  6798. global $db;
  6799. //dol_syslog("Convert matches ".$matches[1]);
  6800. if (empty($matches[1])) {
  6801. return '';
  6802. }
  6803. $tmp = explode(':', $matches[1]);
  6804. if (count($tmp) < 3) {
  6805. return '';
  6806. }
  6807. $tmpescaped = $tmp[2];
  6808. $regbis = array();
  6809. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  6810. $tmpescaped = "'".$db->escape($regbis[1])."'";
  6811. } else {
  6812. $tmpescaped = $db->escape($tmpescaped);
  6813. }
  6814. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  6815. }
  6816. /**
  6817. * Output html form to select an object.
  6818. * Note, this function is called by selectForForms or by ajax selectobject.php
  6819. *
  6820. * @param Object $objecttmp Object to knwo the table to scan for combo.
  6821. * @param string $htmlname Name of HTML select component
  6822. * @param int $preselectedvalue Preselected value (ID of element)
  6823. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6824. * @param string $searchkey Search value
  6825. * @param string $placeholder Place holder
  6826. * @param string $morecss More CSS
  6827. * @param string $moreparams More params provided to ajax call
  6828. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6829. * @param int $outputmode 0=HTML select string, 1=Array
  6830. * @param int $disabled 1=Html component is disabled
  6831. * @param string $sortfield Sort field
  6832. * @return string|array Return HTML string
  6833. * @see selectForForms()
  6834. */
  6835. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '')
  6836. {
  6837. global $conf, $langs, $user, $hookmanager;
  6838. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  6839. $prefixforautocompletemode = $objecttmp->element;
  6840. if ($prefixforautocompletemode == 'societe') {
  6841. $prefixforautocompletemode = 'company';
  6842. }
  6843. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6844. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  6845. $tmpfieldstoshow = '';
  6846. foreach ($objecttmp->fields as $key => $val) {
  6847. if (!dol_eval($val['enabled'], 1, 1, 1, '1')) {
  6848. continue;
  6849. }
  6850. if (!empty($val['showoncombobox'])) {
  6851. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  6852. }
  6853. }
  6854. if ($tmpfieldstoshow) {
  6855. $fieldstoshow = $tmpfieldstoshow;
  6856. }
  6857. } else {
  6858. // For backward compatibility
  6859. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  6860. }
  6861. if (empty($fieldstoshow)) {
  6862. if (isset($objecttmp->fields['ref'])) {
  6863. $fieldstoshow = 't.ref';
  6864. } else {
  6865. $langs->load("errors");
  6866. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  6867. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  6868. }
  6869. }
  6870. $out = '';
  6871. $outarray = array();
  6872. $num = 0;
  6873. // Search data
  6874. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".$this->db->prefix().$objecttmp->table_element." as t";
  6875. if (isset($objecttmp->ismultientitymanaged)) {
  6876. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6877. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  6878. $sql .= " INNER JOIN ".$this->db->prefix().$tmparray[1]." as parenttable ON parenttable.rowid = t.".$tmparray[0];
  6879. }
  6880. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6881. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6882. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  6883. }
  6884. }
  6885. }
  6886. // Add where from hooks
  6887. $parameters = array();
  6888. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  6889. if (!empty($hookmanager->resPrint)) {
  6890. $sql .= $hookmanager->resPrint;
  6891. } else {
  6892. $sql .= " WHERE 1=1";
  6893. if (isset($objecttmp->ismultientitymanaged)) {
  6894. if ($objecttmp->ismultientitymanaged == 1) {
  6895. $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  6896. }
  6897. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6898. $sql .= " AND parenttable.entity = t.".$tmparray[0];
  6899. }
  6900. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  6901. if ($objecttmp->element == 'societe') {
  6902. $sql .= " AND t.rowid = ".((int) $user->socid);
  6903. } else {
  6904. $sql .= " AND t.fk_soc = ".((int) $user->socid);
  6905. }
  6906. }
  6907. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6908. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6909. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  6910. }
  6911. }
  6912. }
  6913. if ($searchkey != '') {
  6914. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  6915. }
  6916. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  6917. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  6918. {
  6919. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  6920. }*/
  6921. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  6922. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  6923. }
  6924. }
  6925. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  6926. //$sql.=$this->db->plimit($limit, 0);
  6927. //print $sql;
  6928. // Build output string
  6929. $resql = $this->db->query($sql);
  6930. if ($resql) {
  6931. // Construct $out and $outarray
  6932. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  6933. // Warning: Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'. Seems it is no more true with selec2 v4
  6934. $textifempty = '&nbsp;';
  6935. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6936. if (!empty($conf->global->$confkeyforautocompletemode)) {
  6937. if ($showempty && !is_numeric($showempty)) {
  6938. $textifempty = $langs->trans($showempty);
  6939. } else {
  6940. $textifempty .= $langs->trans("All");
  6941. }
  6942. }
  6943. if ($showempty) {
  6944. $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  6945. }
  6946. $num = $this->db->num_rows($resql);
  6947. $i = 0;
  6948. if ($num) {
  6949. while ($i < $num) {
  6950. $obj = $this->db->fetch_object($resql);
  6951. $label = '';
  6952. $tmparray = explode(',', $fieldstoshow);
  6953. $oldvalueforshowoncombobox = 0;
  6954. foreach ($tmparray as $key => $val) {
  6955. $val = preg_replace('/t\./', '', $val);
  6956. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  6957. $label .= $obj->$val;
  6958. $oldvalueforshowoncombobox = !empty($objecttmp->fields[$val]['showoncombobox']) ? $objecttmp->fields[$val]['showoncombobox'] : 0;
  6959. }
  6960. if (empty($outputmode)) {
  6961. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  6962. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  6963. } else {
  6964. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  6965. }
  6966. } else {
  6967. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  6968. }
  6969. $i++;
  6970. if (($i % 10) == 0) {
  6971. $out .= "\n";
  6972. }
  6973. }
  6974. }
  6975. $out .= '</select>'."\n";
  6976. if (!$forcecombo) {
  6977. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6978. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  6979. }
  6980. } else {
  6981. dol_print_error($this->db);
  6982. }
  6983. $this->result = array('nbofelement'=>$num);
  6984. if ($outputmode) {
  6985. return $outarray;
  6986. }
  6987. return $out;
  6988. }
  6989. /**
  6990. * Return a HTML select string, built from an array of key+value.
  6991. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  6992. *
  6993. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  6994. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  6995. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  6996. * @param int|string $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (If 1: key is -1 and value is '' or '&nbsp;', If placeholder string: key is -1 and value is the string), <0 to add an empty value with key that is this value.
  6997. * @param int $key_in_label 1 to show key into label with format "[key] value"
  6998. * @param int $value_as_key 1 to use value as key
  6999. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7000. * @param int $translate 1=Translate and encode value
  7001. * @param int $maxlen Length maximum for labels
  7002. * @param int $disabled Html select box is disabled
  7003. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7004. * @param string $morecss Add more class to css styles
  7005. * @param int $addjscombo Add js combo
  7006. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7007. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7008. * @param int $nohtmlescape No html escaping.
  7009. * @return string HTML select string.
  7010. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7011. */
  7012. public static function selectarray($htmlname, $array, $id = '', $show_empty = 0, $key_in_label = 0, $value_as_key = 0, $moreparam = '', $translate = 0, $maxlen = 0, $disabled = 0, $sort = '', $morecss = '', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  7013. {
  7014. global $conf, $langs;
  7015. // Do we want a multiselect ?
  7016. //$jsbeautify = 0;
  7017. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7018. $jsbeautify = 1;
  7019. if ($value_as_key) {
  7020. $array = array_combine($array, $array);
  7021. }
  7022. $out = '';
  7023. if ($addjscombo < 0) {
  7024. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7025. $addjscombo = 1;
  7026. } else {
  7027. $addjscombo = 0;
  7028. }
  7029. }
  7030. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  7031. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  7032. $out .= '>';
  7033. if ($show_empty) {
  7034. $textforempty = ' ';
  7035. if (!empty($conf->use_javascript_ajax)) {
  7036. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7037. }
  7038. if (!is_numeric($show_empty)) {
  7039. $textforempty = $show_empty;
  7040. }
  7041. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  7042. }
  7043. if (is_array($array)) {
  7044. // Translate
  7045. if ($translate) {
  7046. foreach ($array as $key => $value) {
  7047. if (!is_array($value)) {
  7048. $array[$key] = $langs->trans($value);
  7049. } else {
  7050. $array[$key]['label'] = $langs->trans($value['label']);
  7051. }
  7052. }
  7053. }
  7054. // Sort
  7055. if ($sort == 'ASC') {
  7056. asort($array);
  7057. } elseif ($sort == 'DESC') {
  7058. arsort($array);
  7059. }
  7060. foreach ($array as $key => $tmpvalue) {
  7061. if (is_array($tmpvalue)) {
  7062. $value = $tmpvalue['label'];
  7063. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7064. $style = empty($tmpvalue['css']) ? '' : ' class="'.$tmpvalue['css'].'"';
  7065. } else {
  7066. $value = $tmpvalue;
  7067. $disabled = '';
  7068. $style = '';
  7069. }
  7070. if (!empty($disablebademail)) {
  7071. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7072. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7073. $disabled = ' disabled';
  7074. $style = ' class="warning"';
  7075. }
  7076. }
  7077. if ($key_in_label) {
  7078. if (empty($nohtmlescape)) {
  7079. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  7080. } else {
  7081. $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  7082. }
  7083. } else {
  7084. if (empty($nohtmlescape)) {
  7085. $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  7086. } else {
  7087. $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  7088. }
  7089. if ($value == '' || $value == '-') {
  7090. $selectOptionValue = '&nbsp;';
  7091. }
  7092. }
  7093. $out .= '<option value="'.$key.'"';
  7094. $out .= $style.$disabled;
  7095. if (is_array($id)) {
  7096. if (in_array($key, $id) && !$disabled) {
  7097. $out .= ' selected'; // To preselect a value
  7098. }
  7099. } else {
  7100. $id = (string) $id; // if $id = 0, then $id = '0'
  7101. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7102. $out .= ' selected'; // To preselect a value
  7103. }
  7104. }
  7105. if ($nohtmlescape) {
  7106. $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  7107. }
  7108. if (is_array($tmpvalue)) {
  7109. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7110. if (preg_match('/^data-/', $keyforvalue)) {
  7111. $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  7112. }
  7113. }
  7114. }
  7115. $out .= '>';
  7116. //var_dump($selectOptionValue);
  7117. $out .= $selectOptionValue;
  7118. $out .= "</option>\n";
  7119. }
  7120. }
  7121. $out .= "</select>";
  7122. // Add code for jquery to use multiselect
  7123. if ($addjscombo && $jsbeautify) {
  7124. // Enhance with select2
  7125. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7126. $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', $show_empty < 0 ? (string) $show_empty : '-1');
  7127. }
  7128. return $out;
  7129. }
  7130. /**
  7131. * Return a HTML select string, built from an array of key+value, but content returned into select come from an Ajax call of an URL.
  7132. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7133. *
  7134. * @param string $htmlname Name of html select area
  7135. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7136. * @param string $id Preselected key
  7137. * @param string $moreparam Add more parameters onto the select tag
  7138. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7139. * @param int $disabled Html select box is disabled
  7140. * @param int $minimumInputLength Minimum Input Length
  7141. * @param string $morecss Add more class to css styles
  7142. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7143. * @param string $placeholder String to use as placeholder
  7144. * @param integer $acceptdelayedhtml 1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
  7145. * @return string HTML select string
  7146. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7147. */
  7148. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7149. {
  7150. global $conf, $langs;
  7151. global $delayedhtmlcontent; // Will be used later outside of this function
  7152. // TODO Use an internal dolibarr component instead of select2
  7153. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7154. return '';
  7155. }
  7156. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  7157. $outdelayed = '';
  7158. if (!empty($conf->use_javascript_ajax)) {
  7159. $tmpplugin = 'select2';
  7160. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7161. <script>
  7162. $(document).ready(function () {
  7163. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  7164. $(".'.$htmlname.'").select2({
  7165. ajax: {
  7166. dir: "ltr",
  7167. url: "'.$url.'",
  7168. dataType: \'json\',
  7169. delay: 250,
  7170. data: function (params) {
  7171. return {
  7172. q: params.term, // search term
  7173. page: params.page
  7174. };
  7175. },
  7176. processResults: function (data) {
  7177. // parse the results into the format expected by Select2.
  7178. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7179. //console.log(data);
  7180. saveRemoteData = data;
  7181. /* format json result for select2 */
  7182. result = []
  7183. $.each( data, function( key, value ) {
  7184. result.push({id: key, text: value.text});
  7185. });
  7186. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7187. //console.log(result);
  7188. return {results: result, more: false}
  7189. },
  7190. cache: true
  7191. },
  7192. language: select2arrayoflanguage,
  7193. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7194. placeholder: "'.dol_escape_js($placeholder).'",
  7195. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7196. minimumInputLength: '.$minimumInputLength.',
  7197. formatResult: function(result, container, query, escapeMarkup) {
  7198. return escapeMarkup(result.text);
  7199. },
  7200. });
  7201. '.($callurlonselect ? '
  7202. /* Code to execute a GET when we select a value */
  7203. $(".'.$htmlname.'").change(function() {
  7204. var selected = $(".'.$htmlname.'").val();
  7205. console.log("We select in selectArrayAjax the entry "+selected)
  7206. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7207. $.each( saveRemoteData, function( key, value ) {
  7208. if (key == selected)
  7209. {
  7210. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7211. location.assign(value.url);
  7212. }
  7213. });
  7214. });' : '').'
  7215. });
  7216. </script>';
  7217. }
  7218. if ($acceptdelayedhtml) {
  7219. $delayedhtmlcontent .= $outdelayed;
  7220. } else {
  7221. $out .= $outdelayed;
  7222. }
  7223. return $out;
  7224. }
  7225. /**
  7226. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7227. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7228. *
  7229. * @param string $htmlname Name of html select area
  7230. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7231. * @param string $id Preselected key
  7232. * @param string $moreparam Add more parameters onto the select tag
  7233. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7234. * @param int $disabled Html select box is disabled
  7235. * @param int $minimumInputLength Minimum Input Length
  7236. * @param string $morecss Add more class to css styles
  7237. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7238. * @param string $placeholder String to use as placeholder
  7239. * @param integer $acceptdelayedhtml 1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
  7240. * @return string HTML select string
  7241. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7242. */
  7243. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7244. {
  7245. global $conf, $langs;
  7246. global $delayedhtmlcontent; // Will be used later outside of this function
  7247. // TODO Use an internal dolibarr component instead of select2
  7248. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7249. return '';
  7250. }
  7251. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  7252. $formattedarrayresult = array();
  7253. foreach ($array as $key => $value) {
  7254. $o = new stdClass();
  7255. $o->id = $key;
  7256. $o->text = $value['text'];
  7257. $o->url = $value['url'];
  7258. $formattedarrayresult[] = $o;
  7259. }
  7260. $outdelayed = '';
  7261. if (!empty($conf->use_javascript_ajax)) {
  7262. $tmpplugin = 'select2';
  7263. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7264. <script>
  7265. $(document).ready(function () {
  7266. var data = '.json_encode($formattedarrayresult).';
  7267. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  7268. $(".'.$htmlname.'").select2({
  7269. data: data,
  7270. language: select2arrayoflanguage,
  7271. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7272. placeholder: "'.dol_escape_js($placeholder).'",
  7273. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7274. minimumInputLength: '.$minimumInputLength.',
  7275. formatResult: function(result, container, query, escapeMarkup) {
  7276. return escapeMarkup(result.text);
  7277. },
  7278. matcher: function (params, data) {
  7279. if(! data.id) return null;';
  7280. if ($callurlonselect) {
  7281. $outdelayed .= '
  7282. var urlBase = data.url;
  7283. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7284. /* console.log("params.term="+params.term); */
  7285. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7286. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7287. }
  7288. if (!$disableFiltering) {
  7289. $outdelayed .= '
  7290. if(data.text.match(new RegExp(params.term))) {
  7291. return data;
  7292. }
  7293. return null;';
  7294. } else {
  7295. $outdelayed .= '
  7296. return data;';
  7297. }
  7298. $outdelayed .= '
  7299. }
  7300. });
  7301. '.($callurlonselect ? '
  7302. /* Code to execute a GET when we select a value */
  7303. $(".'.$htmlname.'").change(function() {
  7304. var selected = $(".'.$htmlname.'").val();
  7305. console.log("We select "+selected)
  7306. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7307. $.each( saveRemoteData, function( key, value ) {
  7308. if (key == selected)
  7309. {
  7310. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7311. location.assign(value.url);
  7312. }
  7313. });
  7314. });' : '').'
  7315. });
  7316. </script>';
  7317. }
  7318. if ($acceptdelayedhtml) {
  7319. $delayedhtmlcontent .= $outdelayed;
  7320. } else {
  7321. $out .= $outdelayed;
  7322. }
  7323. return $out;
  7324. }
  7325. /**
  7326. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7327. *
  7328. * @param string $htmlname Name of select
  7329. * @param array $array Array with key+value
  7330. * @param array $selected Array with key+value preselected
  7331. * @param int $key_in_label 1 to show key like in "[key] value"
  7332. * @param int $value_as_key 1 to use value as key
  7333. * @param string $morecss Add more css style
  7334. * @param int $translate Translate and encode value
  7335. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7336. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7337. * @param string $elemtype Type of element we show ('category', ...). Will execute a formating function on it. To use in readonly mode if js component support HTML formatting.
  7338. * @param string $placeholder String to use as placeholder
  7339. * @param int $addjscombo Add js combo
  7340. * @return string HTML multiselect string
  7341. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7342. */
  7343. public static function multiselectarray($htmlname, $array, $selected = array(), $key_in_label = 0, $value_as_key = 0, $morecss = '', $translate = 0, $width = 0, $moreattrib = '', $elemtype = '', $placeholder = '', $addjscombo = -1)
  7344. {
  7345. global $conf, $langs;
  7346. $out = '';
  7347. if ($addjscombo < 0) {
  7348. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7349. $addjscombo = 1;
  7350. } else {
  7351. $addjscombo = 0;
  7352. }
  7353. }
  7354. // Try also magic suggest
  7355. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  7356. if (is_array($array) && !empty($array)) {
  7357. if ($value_as_key) {
  7358. $array = array_combine($array, $array);
  7359. }
  7360. if (!empty($array)) {
  7361. foreach ($array as $key => $value) {
  7362. $newval = ($translate ? $langs->trans($value) : $value);
  7363. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  7364. $out .= '<option value="'.$key.'"';
  7365. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != '')) {
  7366. $out .= ' selected';
  7367. }
  7368. $out .= ' data-html="'.dol_escape_htmltag($newval).'"';
  7369. $out .= '>';
  7370. $out .= dol_htmlentitiesbr($newval);
  7371. $out .= '</option>'."\n";
  7372. }
  7373. }
  7374. }
  7375. $out .= '</select>'."\n";
  7376. // Add code for jquery to use multiselect
  7377. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7378. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.', addjscombo='.$addjscombo.' -->';
  7379. $out .= "\n".'<script>'."\n";
  7380. if ($addjscombo == 1) {
  7381. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7382. $out .= 'function formatResult(record, container) {'."\n";
  7383. $out .= ' if ($(record.element).attr("data-html") != undefined) return htmlEntityDecodeJs($(record.element).attr("data-html")); // If property html set, we decode html entities and use this'."\n";
  7384. $out .= ' return record.text;';
  7385. $out .= '};'."\n";
  7386. $out .= 'function formatSelection(record) {'."\n";
  7387. if ($elemtype == 'category') {
  7388. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7389. } else {
  7390. $out .= 'return record.text;';
  7391. }
  7392. $out .= '};'."\n";
  7393. $out .= '$(document).ready(function () {
  7394. $(\'#'.$htmlname.'\').'.$tmpplugin.'({';
  7395. if ($placeholder) {
  7396. $out .= '
  7397. placeholder: {
  7398. id: \'-1\',
  7399. text: \''.dol_escape_js($placeholder).'\'
  7400. },';
  7401. }
  7402. $out .= ' dir: \'ltr\',
  7403. // Specify format function for dropdown item
  7404. formatResult: formatResult,
  7405. templateResult: formatResult, /* For 4.0 */
  7406. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7407. // Specify format function for selected item
  7408. formatSelection: formatSelection,
  7409. templateSelection: formatSelection /* For 4.0 */
  7410. });
  7411. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7412. the size only if component is not hidden by default on load */
  7413. $(\'#'.$htmlname.' + .select2\').addClass(\''.$morecss.'\');
  7414. });'."\n";
  7415. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7416. // Add other js lib
  7417. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7418. // ...
  7419. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  7420. $out .= '$(document).ready(function () {
  7421. $(\'#'.$htmlname.'\').multiSelect({
  7422. containerHTML: \'<div class="multi-select-container">\',
  7423. menuHTML: \'<div class="multi-select-menu">\',
  7424. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  7425. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7426. activeClass: \'multi-select-container--open\',
  7427. noneText: \''.$placeholder.'\'
  7428. });
  7429. })';
  7430. }
  7431. $out .= '</script>';
  7432. }
  7433. return $out;
  7434. }
  7435. /**
  7436. * Show a multiselect dropbox from an array. If a saved selection of fields exists for user (into $user->conf->MAIN_SELECTEDFIELDS_contextofpage), we use this one instead of default.
  7437. *
  7438. * @param string $htmlname Name of HTML field
  7439. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7440. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7441. * @param string $pos position colon on liste value left or right
  7442. * @return string HTML multiselect string
  7443. * @see selectarray()
  7444. */
  7445. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7446. {
  7447. global $conf, $langs, $user, $extrafields;
  7448. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7449. return '';
  7450. }
  7451. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved selected fields to show
  7452. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7453. $tmparray = explode(',', $user->conf->$tmpvar);
  7454. foreach ($array as $key => $val) {
  7455. //var_dump($key);
  7456. //var_dump($tmparray);
  7457. if (in_array($key, $tmparray)) {
  7458. $array[$key]['checked'] = 1;
  7459. } else {
  7460. $array[$key]['checked'] = 0;
  7461. }
  7462. }
  7463. } else { // There is no list of fields already customized for user
  7464. foreach ($array as $key => $val) {
  7465. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7466. $array[$key]['checked'] = 0;
  7467. }
  7468. }
  7469. }
  7470. $listoffieldsforselection = '';
  7471. $listcheckedstring = '';
  7472. foreach ($array as $key => $val) {
  7473. /* var_dump($val);
  7474. var_dump(array_key_exists('enabled', $val));
  7475. var_dump(!$val['enabled']);*/
  7476. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7477. unset($array[$key]); // We don't want this field
  7478. continue;
  7479. }
  7480. if (!empty($val['type']) && $val['type'] == 'separate') {
  7481. // Field remains in array but we don't add it into $listoffieldsforselection
  7482. //$listoffieldsforselection .= '<li>-----</li>';
  7483. continue;
  7484. }
  7485. if ($val['label']) {
  7486. if (!empty($val['langfile']) && is_object($langs)) {
  7487. $langs->load($val['langfile']);
  7488. }
  7489. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7490. $listoffieldsforselection .= '<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.((empty($val['checked']) || $val['checked'] == '-1') ? '' : ' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
  7491. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  7492. }
  7493. }
  7494. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  7495. <dl class="dropdown">
  7496. <dt>
  7497. <a href="#'.$htmlname.'">
  7498. '.img_picto('', 'list').'
  7499. </a>
  7500. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  7501. </dt>
  7502. <dd class="dropdowndd">
  7503. <div class="multiselectcheckbox'.$htmlname.'">
  7504. <ul class="ul'.$htmlname.' '.$htmlname.$pos.'">
  7505. '.$listoffieldsforselection.'
  7506. </ul>
  7507. </div>
  7508. </dd>
  7509. </dl>
  7510. <script type="text/javascript">
  7511. jQuery(document).ready(function () {
  7512. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  7513. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7514. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7515. var title = $(this).val() + ",";
  7516. if ($(this).is(\':checked\')) {
  7517. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  7518. }
  7519. else {
  7520. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  7521. }
  7522. // Now, we submit page
  7523. //$(this).parents(\'form:first\').submit();
  7524. });
  7525. });
  7526. </script>
  7527. ';
  7528. return $out;
  7529. }
  7530. /**
  7531. * Render list of categories linked to object with id $id and type $type
  7532. *
  7533. * @param int $id Id of object
  7534. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7535. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7536. * @param int $nolink 1=Do not add html links
  7537. * @return string String with categories
  7538. */
  7539. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7540. {
  7541. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7542. $cat = new Categorie($this->db);
  7543. $categories = $cat->containing($id, $type);
  7544. if ($rendermode == 1) {
  7545. $toprint = array();
  7546. foreach ($categories as $c) {
  7547. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7548. foreach ($ways as $way) {
  7549. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  7550. }
  7551. }
  7552. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  7553. }
  7554. if ($rendermode == 0) {
  7555. $arrayselected = array();
  7556. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7557. foreach ($categories as $c) {
  7558. $arrayselected[] = $c->id;
  7559. }
  7560. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7561. }
  7562. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7563. }
  7564. /**
  7565. * Show linked object block.
  7566. *
  7567. * @param CommonObject $object Object we want to show links to
  7568. * @param string $morehtmlright More html to show on right of title
  7569. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7570. * @return int <0 if KO, >=0 if OK
  7571. */
  7572. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
  7573. {
  7574. global $conf, $langs, $hookmanager;
  7575. global $bc, $action;
  7576. $object->fetchObjectLinked();
  7577. // Bypass the default method
  7578. $hookmanager->initHooks(array('commonobject'));
  7579. $parameters = array(
  7580. 'morehtmlright' => $morehtmlright,
  7581. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7582. );
  7583. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7584. if (empty($reshook)) {
  7585. $nbofdifferenttypes = count($object->linkedObjects);
  7586. print '<!-- showLinkedObjectBlock -->';
  7587. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7588. print '<div class="div-table-responsive-no-min">';
  7589. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  7590. print '<tr class="liste_titre">';
  7591. print '<td>'.$langs->trans("Type").'</td>';
  7592. print '<td>'.$langs->trans("Ref").'</td>';
  7593. print '<td class="center"></td>';
  7594. print '<td class="center">'.$langs->trans("Date").'</td>';
  7595. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7596. print '<td class="right">'.$langs->trans("Status").'</td>';
  7597. print '<td></td>';
  7598. print '</tr>';
  7599. $nboftypesoutput = 0;
  7600. foreach ($object->linkedObjects as $objecttype => $objects) {
  7601. $tplpath = $element = $subelement = $objecttype;
  7602. // to display inport button on tpl
  7603. $showImportButton = false;
  7604. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7605. $showImportButton = true;
  7606. }
  7607. $regs = array();
  7608. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7609. $element = $regs[1];
  7610. $subelement = $regs[2];
  7611. $tplpath = $element.'/'.$subelement;
  7612. }
  7613. $tplname = 'linkedobjectblock';
  7614. // To work with non standard path
  7615. if ($objecttype == 'facture') {
  7616. $tplpath = 'compta/'.$element;
  7617. if (empty($conf->facture->enabled)) {
  7618. continue; // Do not show if module disabled
  7619. }
  7620. } elseif ($objecttype == 'facturerec') {
  7621. $tplpath = 'compta/facture';
  7622. $tplname = 'linkedobjectblockForRec';
  7623. if (empty($conf->facture->enabled)) {
  7624. continue; // Do not show if module disabled
  7625. }
  7626. } elseif ($objecttype == 'propal') {
  7627. $tplpath = 'comm/'.$element;
  7628. if (empty($conf->propal->enabled)) {
  7629. continue; // Do not show if module disabled
  7630. }
  7631. } elseif ($objecttype == 'supplier_proposal') {
  7632. if (empty($conf->supplier_proposal->enabled)) {
  7633. continue; // Do not show if module disabled
  7634. }
  7635. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  7636. $tplpath = 'expedition';
  7637. if (empty($conf->expedition->enabled)) {
  7638. continue; // Do not show if module disabled
  7639. }
  7640. } elseif ($objecttype == 'reception') {
  7641. $tplpath = 'reception';
  7642. if (empty($conf->reception->enabled)) {
  7643. continue; // Do not show if module disabled
  7644. }
  7645. } elseif ($objecttype == 'delivery') {
  7646. $tplpath = 'delivery';
  7647. if (empty($conf->expedition->enabled)) {
  7648. continue; // Do not show if module disabled
  7649. }
  7650. } elseif ($objecttype == 'mo') {
  7651. $tplpath = 'mrp/mo';
  7652. if (empty($conf->mrp->enabled)) {
  7653. continue; // Do not show if module disabled
  7654. }
  7655. } elseif ($objecttype == 'ficheinter') {
  7656. $tplpath = 'fichinter';
  7657. if (empty($conf->ficheinter->enabled)) {
  7658. continue; // Do not show if module disabled
  7659. }
  7660. } elseif ($objecttype == 'invoice_supplier') {
  7661. $tplpath = 'fourn/facture';
  7662. } elseif ($objecttype == 'order_supplier') {
  7663. $tplpath = 'fourn/commande';
  7664. } elseif ($objecttype == 'expensereport') {
  7665. $tplpath = 'expensereport';
  7666. } elseif ($objecttype == 'subscription') {
  7667. $tplpath = 'adherents';
  7668. } elseif ($objecttype == 'conferenceorbooth') {
  7669. $tplpath = 'eventorganization';
  7670. } elseif ($objecttype == 'conferenceorboothattendee') {
  7671. $tplpath = 'eventorganization';
  7672. } elseif ($objecttype == 'mo') {
  7673. $tplpath = 'mrp';
  7674. if (empty($conf->mrp->enabled)) {
  7675. continue; // Do not show if module disabled
  7676. }
  7677. }
  7678. global $linkedObjectBlock;
  7679. $linkedObjectBlock = $objects;
  7680. // Output template part (modules that overwrite templates must declare this into descriptor)
  7681. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  7682. foreach ($dirtpls as $reldir) {
  7683. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7684. global $noMoreLinkedObjectBlockAfter;
  7685. $noMoreLinkedObjectBlockAfter = 1;
  7686. }
  7687. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  7688. if ($res) {
  7689. $nboftypesoutput++;
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. if (!$nboftypesoutput) {
  7695. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  7696. }
  7697. print '</table>';
  7698. if (!empty($compatibleImportElementsList)) {
  7699. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  7700. }
  7701. print '</div>';
  7702. return $nbofdifferenttypes;
  7703. }
  7704. }
  7705. /**
  7706. * Show block with links to link to other objects.
  7707. *
  7708. * @param CommonObject $object Object we want to show links to
  7709. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7710. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7711. * @return string <0 if KO, >0 if OK
  7712. */
  7713. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7714. {
  7715. global $conf, $langs, $hookmanager;
  7716. global $action;
  7717. $linktoelem = '';
  7718. $linktoelemlist = '';
  7719. $listofidcompanytoscan = '';
  7720. if (!is_object($object->thirdparty)) {
  7721. $object->fetch_thirdparty();
  7722. }
  7723. $possiblelinks = array();
  7724. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7725. $listofidcompanytoscan = $object->thirdparty->id;
  7726. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7727. $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  7728. }
  7729. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7730. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7731. $tmpproject = new Project($this->db);
  7732. $tmpproject->fetch($object->fk_project);
  7733. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7734. $listofidcompanytoscan .= ','.$tmpproject->socid;
  7735. }
  7736. unset($tmpproject);
  7737. }
  7738. $possiblelinks = array(
  7739. 'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('propal').')'),
  7740. 'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('commande').')'),
  7741. 'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('invoice').')'),
  7742. 'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('invoice').')'),
  7743. 'contrat'=>array(
  7744. 'enabled'=>$conf->contrat->enabled,
  7745. 'perms'=>1,
  7746. 'label'=>'LinkToContract',
  7747. 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_customer as ref_client, t.ref_supplier, SUM(td.total_ht) as total_ht
  7748. FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."contrat as t, ".$this->db->prefix()."contratdet as td WHERE t.fk_soc = s.rowid AND td.fk_contrat = t.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('contract').') GROUP BY s.rowid, s.nom, s.client, t.rowid, t.ref, t.ref_customer, t.ref_supplier'
  7749. ),
  7750. 'fichinter'=>array('enabled'=>!empty($conf->ficheinter->enabled) ? $conf->ficheinter->enabled : 0, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('intervention').')'),
  7751. 'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled, 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('supplier_proposal').')'),
  7752. 'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled, 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
  7753. 'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled, 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('facture_fourn').')'),
  7754. 'ticket'=>array('enabled'=>$conf->ticket->enabled, 'perms'=>1, 'label'=>'LinkToTicket', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('ticket').')'),
  7755. 'mo'=>array('enabled'=>$conf->mrp->enabled, 'perms'=>1, 'label'=>'LinkToMo', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM ".$this->db->prefix()."societe as s INNER JOIN ".$this->db->prefix()."mrp_mo as t ON t.fk_soc = s.rowid WHERE t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('mo').')')
  7756. );
  7757. }
  7758. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  7759. // Can complete the possiblelink array
  7760. $hookmanager->initHooks(array('commonobject'));
  7761. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  7762. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7763. }
  7764. if (empty($reshook)) {
  7765. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7766. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  7767. }
  7768. } elseif ($reshook > 0) {
  7769. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7770. $possiblelinks = $hookmanager->resArray;
  7771. }
  7772. }
  7773. foreach ($possiblelinks as $key => $possiblelink) {
  7774. $num = 0;
  7775. if (empty($possiblelink['enabled'])) {
  7776. continue;
  7777. }
  7778. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  7779. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  7780. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7781. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  7782. print '<input type="hidden" name="id" value="' . $object->id . '">';
  7783. print '<input type="hidden" name="action" value="addlinkbyref">';
  7784. print '<input type="hidden" name="token" value="'.newToken().'">';
  7785. print '<input type="hidden" name="addlink" value="' . $key . '">';
  7786. print '<table class="noborder">';
  7787. print '<tr>';
  7788. print '<td>' . $langs->trans("Ref") . '</td>';
  7789. print '<td><input type="text" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;<input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  7790. print '</tr>';
  7791. print '</table>';
  7792. print '</form>';
  7793. }
  7794. $sql = $possiblelink['sql'];
  7795. $resqllist = $this->db->query($sql);
  7796. if ($resqllist) {
  7797. $num = $this->db->num_rows($resqllist);
  7798. $i = 0;
  7799. print '<br>';
  7800. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  7801. print '<input type="hidden" name="action" value="addlink">';
  7802. print '<input type="hidden" name="token" value="'.newToken().'">';
  7803. print '<input type="hidden" name="id" value="'.$object->id.'">';
  7804. print '<input type="hidden" name="addlink" value="'.$key.'">';
  7805. print '<table class="noborder">';
  7806. print '<tr class="liste_titre">';
  7807. print '<td class="nowrap"></td>';
  7808. print '<td class="center">'.$langs->trans("Ref").'</td>';
  7809. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  7810. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7811. print '<td class="left">'.$langs->trans("Company").'</td>';
  7812. print '</tr>';
  7813. while ($i < $num) {
  7814. $objp = $this->db->fetch_object($resqllist);
  7815. print '<tr class="oddeven">';
  7816. print '<td class="left">';
  7817. print '<input type="radio" name="idtolinkto" id="'.$key.'_'.$objp->rowid.'" value="'.$objp->rowid.'">';
  7818. print '</td>';
  7819. print '<td class="center"><label for="'.$key.'_'.$objp->rowid.'">'.$objp->ref.'</label></td>';
  7820. print '<td>'.(!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')).'</td>';
  7821. print '<td class="right">';
  7822. if ($possiblelink['label'] == 'LinkToContract') {
  7823. $form = new Form($this->db);
  7824. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' ';
  7825. }
  7826. print '<span class="amount">'.price($objp->total_ht).'</span>';
  7827. print '</td>';
  7828. print '<td>'.$objp->name.'</td>';
  7829. print '</tr>';
  7830. $i++;
  7831. }
  7832. print '</table>';
  7833. print '<div class="center">';
  7834. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="'.$langs->trans('ToLink').'">';
  7835. if (empty($conf->use_javascript_ajax)) {
  7836. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7837. } else {
  7838. print '<input type="submit"; onclick="javascript:jQuery(\'#'.$key.'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7839. }
  7840. print '</form>';
  7841. $this->db->free($resqllist);
  7842. } else {
  7843. dol_print_error($this->db);
  7844. }
  7845. print '</div>';
  7846. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  7847. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7848. $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  7849. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  7850. } else {
  7851. $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  7852. }
  7853. }
  7854. }
  7855. if ($linktoelemlist) {
  7856. $linktoelem = '
  7857. <dl class="dropdown" id="linktoobjectname">
  7858. ';
  7859. if (!empty($conf->use_javascript_ajax)) {
  7860. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>'.$langs->trans("LinkTo").'...</a></dt>';
  7861. }
  7862. $linktoelem .= '<dd>
  7863. <div class="multiselectlinkto">
  7864. <ul class="ulselectedfields">'.$linktoelemlist.'
  7865. </ul>
  7866. </div>
  7867. </dd>
  7868. </dl>';
  7869. } else {
  7870. $linktoelem = '';
  7871. }
  7872. if (!empty($conf->use_javascript_ajax)) {
  7873. print '<!-- Add js to show linkto box -->
  7874. <script>
  7875. jQuery(document).ready(function() {
  7876. jQuery(".linkto").click(function() {
  7877. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  7878. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  7879. });
  7880. });
  7881. </script>
  7882. ';
  7883. }
  7884. return $linktoelem;
  7885. }
  7886. /**
  7887. * Return an html string with a select combo box to choose yes or no
  7888. *
  7889. * @param string $htmlname Name of html select field
  7890. * @param string $value Pre-selected value
  7891. * @param int $option 0 return yes/no, 1 return 1/0
  7892. * @param bool $disabled true or false
  7893. * @param int $useempty 1=Add empty line
  7894. * @param int $addjscombo 1=Add js beautifier on combo box
  7895. * @param string $morecss More CSS
  7896. * @return string See option
  7897. */
  7898. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '')
  7899. {
  7900. global $langs;
  7901. $yes = "yes";
  7902. $no = "no";
  7903. if ($option) {
  7904. $yes = "1";
  7905. $no = "0";
  7906. }
  7907. $disabled = ($disabled ? ' disabled' : '');
  7908. $resultyesno = '<select class="flat width75'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  7909. if ($useempty) {
  7910. $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  7911. }
  7912. if (("$value" == 'yes') || ($value == 1)) {
  7913. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  7914. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  7915. } else {
  7916. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  7917. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  7918. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  7919. }
  7920. $resultyesno .= '</select>'."\n";
  7921. if ($addjscombo) {
  7922. $resultyesno .= ajax_combobox($htmlname);
  7923. }
  7924. return $resultyesno;
  7925. }
  7926. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7927. /**
  7928. * Return list of export templates
  7929. *
  7930. * @param string $selected Id modele pre-selectionne
  7931. * @param string $htmlname Name of HTML select
  7932. * @param string $type Type of searched templates
  7933. * @param int $useempty Affiche valeur vide dans liste
  7934. * @return void
  7935. */
  7936. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  7937. {
  7938. // phpcs:enable
  7939. $sql = "SELECT rowid, label";
  7940. $sql .= " FROM ".$this->db->prefix()."export_model";
  7941. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  7942. $sql .= " ORDER BY rowid";
  7943. $result = $this->db->query($sql);
  7944. if ($result) {
  7945. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  7946. if ($useempty) {
  7947. print '<option value="-1">&nbsp;</option>';
  7948. }
  7949. $num = $this->db->num_rows($result);
  7950. $i = 0;
  7951. while ($i < $num) {
  7952. $obj = $this->db->fetch_object($result);
  7953. if ($selected == $obj->rowid) {
  7954. print '<option value="'.$obj->rowid.'" selected>';
  7955. } else {
  7956. print '<option value="'.$obj->rowid.'">';
  7957. }
  7958. print $obj->label;
  7959. print '</option>';
  7960. $i++;
  7961. }
  7962. print "</select>";
  7963. } else {
  7964. dol_print_error($this->db);
  7965. }
  7966. }
  7967. /**
  7968. * Return a HTML area with the reference of object and a navigation bar for a business object
  7969. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  7970. *
  7971. * @param object $object Object to show.
  7972. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  7973. * @param string $morehtml More html content to output just before the nav bar.
  7974. * @param int $shownav Show Condition (navigation is shown if value is 1).
  7975. * @param string $fieldid Name of field id into database to use for select next and previous (we make the select max and min on this field compared to $object->ref). Use 'none' to disable next/prev.
  7976. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  7977. * @param string $morehtmlref More html to show after ref.
  7978. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  7979. * @param int $nodbprefix Do not include DB prefix to forge table name.
  7980. * @param string $morehtmlleft More html code to show before ref.
  7981. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  7982. * @param string $morehtmlright More html code to show after ref.
  7983. * @return string Portion HTML with ref + navigation buttons
  7984. */
  7985. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  7986. {
  7987. global $conf, $langs, $hookmanager, $extralanguages;
  7988. $ret = '';
  7989. if (empty($fieldid)) {
  7990. $fieldid = 'rowid';
  7991. }
  7992. if (empty($fieldref)) {
  7993. $fieldref = 'ref';
  7994. }
  7995. // Preparing gender's display if there is one
  7996. $addgendertxt = '';
  7997. if (property_exists($object, 'gender') && !empty($object->gender)) {
  7998. $addgendertxt = ' ';
  7999. switch ($object->gender) {
  8000. case 'man':
  8001. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8002. break;
  8003. case 'woman':
  8004. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8005. break;
  8006. case 'other':
  8007. $addgendertxt .= '<i class="fas fa-genderless"></i>';
  8008. break;
  8009. }
  8010. }
  8011. /*
  8012. $addadmin = '';
  8013. if (property_exists($object, 'admin')) {
  8014. if (!empty($conf->multicompany->enabled) && !empty($object->admin) && empty($object->entity)) {
  8015. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  8016. } elseif (!empty($object->admin)) {
  8017. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  8018. }
  8019. }*/
  8020. // Add where from hooks
  8021. if (is_object($hookmanager)) {
  8022. $parameters = array('showrefnav' => true);
  8023. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8024. $object->next_prev_filter .= $hookmanager->resPrint;
  8025. }
  8026. $previous_ref = $next_ref = '';
  8027. if ($shownav) {
  8028. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8029. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8030. $navurl = $_SERVER["PHP_SELF"];
  8031. // Special case for project/task page
  8032. if ($paramid == 'project_ref') {
  8033. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8034. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8035. $paramid = 'ref';
  8036. }
  8037. }
  8038. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8039. // accesskey is for Mac: CTRL + key for all browsers
  8040. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8041. if ($conf->browser->name == 'chrome') {
  8042. $stringforfirstkey .= ' ALT +';
  8043. } elseif ($conf->browser->name == 'firefox') {
  8044. $stringforfirstkey .= ' ALT + SHIFT +';
  8045. } else {
  8046. $stringforfirstkey .= ' CTL +';
  8047. }
  8048. $previous_ref = $object->ref_previous ? '<a accesskey="p" title="'.$stringforfirstkey.' p" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'"><i class="fa fa-chevron-left"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
  8049. $next_ref = $object->ref_next ? '<a accesskey="n" title="'.$stringforfirstkey.' n" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'"><i class="fa fa-chevron-right"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
  8050. }
  8051. //print "xx".$previous_ref."x".$next_ref;
  8052. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8053. // Right part of banner
  8054. if ($morehtmlright) {
  8055. $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  8056. }
  8057. if ($previous_ref || $next_ref || $morehtml) {
  8058. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8059. }
  8060. if ($morehtml) {
  8061. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  8062. }
  8063. if ($shownav && ($previous_ref || $next_ref)) {
  8064. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  8065. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  8066. }
  8067. if ($previous_ref || $next_ref || $morehtml) {
  8068. $ret .= '</ul></div>';
  8069. }
  8070. $parameters = array();
  8071. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8072. if (empty($reshook)) {
  8073. $morehtmlstatus .= $hookmanager->resPrint;
  8074. } else {
  8075. $morehtmlstatus = $hookmanager->resPrint;
  8076. }
  8077. if ($morehtmlstatus) {
  8078. $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  8079. }
  8080. $parameters = array();
  8081. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8082. if (empty($reshook)) {
  8083. $morehtmlref .= $hookmanager->resPrint;
  8084. } elseif ($reshook > 0) {
  8085. $morehtmlref = $hookmanager->resPrint;
  8086. }
  8087. // Left part of banner
  8088. if ($morehtmlleft) {
  8089. if ($conf->browser->layout == 'phone') {
  8090. $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  8091. } else {
  8092. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  8093. }
  8094. }
  8095. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8096. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  8097. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8098. if ($object->element == 'societe') {
  8099. $ret .= dol_htmlentities($object->name);
  8100. // List of extra languages
  8101. $arrayoflangcode = array();
  8102. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8103. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8104. }
  8105. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8106. if (!is_object($extralanguages)) {
  8107. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  8108. $extralanguages = new ExtraLanguages($this->db);
  8109. }
  8110. $extralanguages->fetch_name_extralanguages('societe');
  8111. if (!empty($extralanguages->attributes['societe']['name'])) {
  8112. $object->fetchValuesForExtraLanguages();
  8113. $htmltext = '';
  8114. // If there is extra languages
  8115. foreach ($arrayoflangcode as $extralangcode) {
  8116. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8117. if ($object->array_languages['name'][$extralangcode]) {
  8118. $htmltext .= $object->array_languages['name'][$extralangcode];
  8119. } else {
  8120. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  8121. }
  8122. }
  8123. $ret .= '<!-- Show translations of name -->'."\n";
  8124. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8125. }
  8126. }
  8127. } elseif ($object->element == 'member') {
  8128. $ret .= $object->ref.'<br>';
  8129. $fullname = $object->getFullName($langs);
  8130. if ($object->morphy == 'mor' && $object->societe) {
  8131. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).$addgendertxt.')' : '');
  8132. } else {
  8133. $ret .= dol_htmlentities($fullname).$addgendertxt.((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  8134. }
  8135. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8136. $ret .= dol_htmlentities($object->getFullName($langs));
  8137. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8138. $ret .= $object->ref.'<br>'.$object->label;
  8139. } elseif (in_array($object->element, array('adherent_type'))) {
  8140. $ret .= $object->label;
  8141. } elseif ($object->element == 'ecm_directories') {
  8142. $ret .= '';
  8143. } elseif ($fieldref != 'none') {
  8144. $ret .= dol_htmlentities($object->$fieldref);
  8145. }
  8146. if ($morehtmlref) {
  8147. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8148. if (substr($morehtmlref, 0, 4) != '<div') {
  8149. $ret .= ' ';
  8150. }
  8151. $ret .= $morehtmlref;
  8152. }
  8153. $ret .= '</div>';
  8154. $ret .= '</div><!-- End banner content -->';
  8155. return $ret;
  8156. }
  8157. /**
  8158. * Return HTML code to output a barcode
  8159. *
  8160. * @param Object $object Object containing data to retrieve file name
  8161. * @param int $width Width of photo
  8162. * @param string $morecss More CSS on img of barcode
  8163. * @return string HTML code to output barcode
  8164. */
  8165. public function showbarcode(&$object, $width = 100, $morecss = '')
  8166. {
  8167. global $conf;
  8168. //Check if barcode is filled in the card
  8169. if (empty($object->barcode)) {
  8170. return '';
  8171. }
  8172. // Complete object if not complete
  8173. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8174. $result = $object->fetch_barcode();
  8175. //Check if fetch_barcode() failed
  8176. if ($result < 1) {
  8177. return '<!-- ErrorFetchBarcode -->';
  8178. }
  8179. }
  8180. // Barcode image
  8181. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  8182. $out = '<!-- url barcode = '.$url.' -->';
  8183. $out .= '<img src="'.$url.'"'.($morecss ? ' class="'.$morecss.'"' : '').'>';
  8184. return $out;
  8185. }
  8186. /**
  8187. * Return HTML code to output a photo
  8188. *
  8189. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8190. * @param object $object Object containing data to retrieve file name
  8191. * @param int $width Width of photo
  8192. * @param int $height Height of photo (auto if 0)
  8193. * @param int $caneditfield Add edit fields
  8194. * @param string $cssclass CSS name to use on img for photo
  8195. * @param string $imagesize 'mini', 'small' or '' (original)
  8196. * @param int $addlinktofullsize Add link to fullsize image
  8197. * @param int $cache 1=Accept to use image in cache
  8198. * @param string $forcecapture '', 'user' or 'environment'. Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if ''.
  8199. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8200. * @return string HTML code to output photo
  8201. */
  8202. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8203. {
  8204. global $conf, $langs;
  8205. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8206. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8207. $ret = '';
  8208. $dir = '';
  8209. $file = '';
  8210. $originalfile = '';
  8211. $altfile = '';
  8212. $email = '';
  8213. $capture = '';
  8214. if ($modulepart == 'societe') {
  8215. $dir = $conf->societe->multidir_output[$entity];
  8216. if (!empty($object->logo)) {
  8217. if (dolIsAllowedForPreview($object->logo)) {
  8218. if ((string) $imagesize == 'mini') {
  8219. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8220. } elseif ((string) $imagesize == 'small') {
  8221. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_small');
  8222. } else {
  8223. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8224. }
  8225. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8226. }
  8227. }
  8228. $email = $object->email;
  8229. } elseif ($modulepart == 'contact') {
  8230. $dir = $conf->societe->multidir_output[$entity].'/contact';
  8231. if (!empty($object->photo)) {
  8232. if (dolIsAllowedForPreview($object->photo)) {
  8233. if ((string) $imagesize == 'mini') {
  8234. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8235. } elseif ((string) $imagesize == 'small') {
  8236. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8237. } else {
  8238. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8239. }
  8240. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8241. }
  8242. }
  8243. $email = $object->email;
  8244. $capture = 'user';
  8245. } elseif ($modulepart == 'userphoto') {
  8246. $dir = $conf->user->dir_output;
  8247. if (!empty($object->photo)) {
  8248. if (dolIsAllowedForPreview($object->photo)) {
  8249. if ((string) $imagesize == 'mini') {
  8250. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8251. } elseif ((string) $imagesize == 'small') {
  8252. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8253. } else {
  8254. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8255. }
  8256. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8257. }
  8258. }
  8259. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8260. $altfile = $object->id.".jpg"; // For backward compatibility
  8261. }
  8262. $email = $object->email;
  8263. $capture = 'user';
  8264. } elseif ($modulepart == 'memberphoto') {
  8265. $dir = $conf->adherent->dir_output;
  8266. if (!empty($object->photo)) {
  8267. if (dolIsAllowedForPreview($object->photo)) {
  8268. if ((string) $imagesize == 'mini') {
  8269. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8270. } elseif ((string) $imagesize == 'small') {
  8271. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8272. } else {
  8273. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8274. }
  8275. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8276. }
  8277. }
  8278. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8279. $altfile = $object->id.".jpg"; // For backward compatibility
  8280. }
  8281. $email = $object->email;
  8282. $capture = 'user';
  8283. } else {
  8284. // Generic case to show photos
  8285. $dir = $conf->$modulepart->dir_output;
  8286. if (!empty($object->photo)) {
  8287. if (dolIsAllowedForPreview($object->photo)) {
  8288. if ((string) $imagesize == 'mini') {
  8289. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8290. } elseif ((string) $imagesize == 'small') {
  8291. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  8292. } else {
  8293. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8294. }
  8295. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8296. }
  8297. }
  8298. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8299. $altfile = $object->id.".jpg"; // For backward compatibility
  8300. }
  8301. $email = $object->email;
  8302. }
  8303. if ($forcecapture) {
  8304. $capture = $forcecapture;
  8305. }
  8306. if ($dir) {
  8307. if ($file && file_exists($dir."/".$file)) {
  8308. if ($addlinktofullsize) {
  8309. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8310. if ($urladvanced) {
  8311. $ret .= '<a href="'.$urladvanced.'">';
  8312. } else {
  8313. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8314. }
  8315. }
  8316. $ret .= '<img alt="Photo" class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').' photologo'.(preg_replace('/[^a-z]/i', '_', $file)).'" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'">';
  8317. if ($addlinktofullsize) {
  8318. $ret .= '</a>';
  8319. }
  8320. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  8321. if ($addlinktofullsize) {
  8322. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8323. if ($urladvanced) {
  8324. $ret .= '<a href="'.$urladvanced.'">';
  8325. } else {
  8326. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8327. }
  8328. }
  8329. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="Photo alt" id="photologo'.(preg_replace('/[^a-z]/i', '_', $file)).'" class="'.$cssclass.'" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'">';
  8330. if ($addlinktofullsize) {
  8331. $ret .= '</a>';
  8332. }
  8333. } else {
  8334. $nophoto = '/public/theme/common/nophoto.png';
  8335. $defaultimg = 'identicon'; // For gravatar
  8336. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8337. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8338. $nophoto = 'company';
  8339. } else {
  8340. $nophoto = '/public/theme/common/user_anonymous.png';
  8341. if (!empty($object->gender) && $object->gender == 'man') {
  8342. $nophoto = '/public/theme/common/user_man.png';
  8343. }
  8344. if (!empty($object->gender) && $object->gender == 'woman') {
  8345. $nophoto = '/public/theme/common/user_woman.png';
  8346. }
  8347. }
  8348. }
  8349. if (!empty($conf->gravatar->enabled) && $email && empty($noexternsourceoverwrite)) {
  8350. // see https://gravatar.com/site/implement/images/php/
  8351. $ret .= '<!-- Put link to gravatar -->';
  8352. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" title="'.$email.' Gravatar avatar" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="https://www.gravatar.com/avatar/'.md5(strtolower(trim($email))).'?s='.$width.'&d='.$defaultimg.'">'; // gravatar need md5 hash
  8353. } else {
  8354. if ($nophoto == 'company') {
  8355. $ret .= '<div class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'">'.img_picto('', 'company').'</div>';
  8356. } else {
  8357. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  8358. }
  8359. }
  8360. }
  8361. if ($caneditfield) {
  8362. if ($object->photo) {
  8363. $ret .= "<br>\n";
  8364. }
  8365. $ret .= '<table class="nobordernopadding centpercent">';
  8366. if ($object->photo) {
  8367. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">'.$langs->trans("Delete").'</label><br><br></td></tr>';
  8368. }
  8369. $ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
  8370. $ret .= '</table>';
  8371. }
  8372. } else {
  8373. dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  8374. }
  8375. return $ret;
  8376. }
  8377. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8378. /**
  8379. * Return select list of groups
  8380. *
  8381. * @param string $selected Id group preselected
  8382. * @param string $htmlname Field name in form
  8383. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8384. * @param string $exclude Array list of groups id to exclude
  8385. * @param int $disabled If select list must be disabled
  8386. * @param string $include Array list of groups id to include
  8387. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8388. * @param string $force_entity '0' or Ids of environment to force
  8389. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8390. * @param string $morecss More css to add to html component
  8391. * @return string
  8392. * @see select_dolusers()
  8393. */
  8394. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8395. {
  8396. // phpcs:enable
  8397. global $conf, $user, $langs;
  8398. // Permettre l'exclusion de groupes
  8399. if (is_array($exclude)) {
  8400. $excludeGroups = implode(",", $exclude);
  8401. }
  8402. // Permettre l'inclusion de groupes
  8403. if (is_array($include)) {
  8404. $includeGroups = implode(",", $include);
  8405. }
  8406. if (!is_array($selected)) {
  8407. $selected = array($selected);
  8408. }
  8409. $out = '';
  8410. // On recherche les groupes
  8411. $sql = "SELECT ug.rowid, ug.nom as name";
  8412. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8413. $sql .= ", e.label";
  8414. }
  8415. $sql .= " FROM ".$this->db->prefix()."usergroup as ug ";
  8416. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8417. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid=ug.entity";
  8418. if ($force_entity) {
  8419. $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  8420. } else {
  8421. $sql .= " WHERE ug.entity IS NOT NULL";
  8422. }
  8423. } else {
  8424. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  8425. }
  8426. if (is_array($exclude) && $excludeGroups) {
  8427. $sql .= " AND ug.rowid NOT IN (".$this->db->sanitize($excludeGroups).")";
  8428. }
  8429. if (is_array($include) && $includeGroups) {
  8430. $sql .= " AND ug.rowid IN (".$this->db->sanitize($includeGroups).")";
  8431. }
  8432. $sql .= " ORDER BY ug.nom ASC";
  8433. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  8434. $resql = $this->db->query($sql);
  8435. if ($resql) {
  8436. // Enhance with select2
  8437. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8438. $out .= ajax_combobox($htmlname);
  8439. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  8440. $num = $this->db->num_rows($resql);
  8441. $i = 0;
  8442. if ($num) {
  8443. if ($show_empty && !$multiple) {
  8444. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8445. }
  8446. while ($i < $num) {
  8447. $obj = $this->db->fetch_object($resql);
  8448. $disableline = 0;
  8449. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8450. $disableline = 1;
  8451. }
  8452. $out .= '<option value="'.$obj->rowid.'"';
  8453. if ($disableline) {
  8454. $out .= ' disabled';
  8455. }
  8456. if ((isset($selected[0]) && is_object($selected[0]) && $selected[0]->id == $obj->rowid) || ((!isset($selected[0]) || !is_object($selected[0])) && !empty($selected) && in_array($obj->rowid, $selected))) {
  8457. $out .= ' selected';
  8458. }
  8459. $out .= '>';
  8460. $out .= $obj->name;
  8461. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8462. $out .= " (".$obj->label.")";
  8463. }
  8464. $out .= '</option>';
  8465. $i++;
  8466. }
  8467. } else {
  8468. if ($show_empty) {
  8469. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  8470. }
  8471. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  8472. }
  8473. $out .= '</select>';
  8474. } else {
  8475. dol_print_error($this->db);
  8476. }
  8477. return $out;
  8478. }
  8479. /**
  8480. * Return HTML to show the search and clear seach button
  8481. *
  8482. * @param string $pos position colon on liste value left or right
  8483. * @return string
  8484. */
  8485. public function showFilterButtons($pos = '')
  8486. {
  8487. $out = '<div class="nowraponall">';
  8488. if ($pos == 'left') {
  8489. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8490. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8491. } else {
  8492. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8493. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8494. }
  8495. $out .= '</div>';
  8496. return $out;
  8497. }
  8498. /**
  8499. * Return HTML to show the search and clear search button
  8500. *
  8501. * @param string $cssclass CSS class
  8502. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8503. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8504. * @return string
  8505. */
  8506. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8507. {
  8508. global $conf, $langs;
  8509. $out = '';
  8510. if (!empty($conf->use_javascript_ajax)) {
  8511. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  8512. }
  8513. $out .= '<script>
  8514. $(document).ready(function() {
  8515. $("#' . $cssclass.'s").click(function() {
  8516. if($(this).is(\':checked\')){
  8517. console.log("We check all '.$cssclass.' and trigger the change method");
  8518. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  8519. }
  8520. else
  8521. {
  8522. console.log("We uncheck all");
  8523. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  8524. }'."\n";
  8525. if ($calljsfunction) {
  8526. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8527. }
  8528. $out .= ' });
  8529. $(".' . $cssclass.'").change(function() {
  8530. $(this).closest("tr").toggleClass("highlight", this.checked);
  8531. });
  8532. });
  8533. </script>';
  8534. return $out;
  8535. }
  8536. /**
  8537. * Return HTML to show the search and clear seach button
  8538. *
  8539. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8540. * @param string $cssclass CSS class
  8541. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8542. * @param string $massactionname Mass action name
  8543. * @return string
  8544. */
  8545. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8546. {
  8547. $out = $this->showFilterButtons();
  8548. if ($addcheckuncheckall) {
  8549. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8550. }
  8551. return $out;
  8552. }
  8553. /**
  8554. * Return HTML to show the select of expense categories
  8555. *
  8556. * @param string $selected preselected category
  8557. * @param string $htmlname name of HTML select list
  8558. * @param integer $useempty 1=Add empty line
  8559. * @param array $excludeid id to exclude
  8560. * @param string $target htmlname of target select to bind event
  8561. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8562. * @param array $params param to give
  8563. * @param int $info_admin Show the tooltip help picto to setup list
  8564. * @return string
  8565. */
  8566. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8567. {
  8568. global $langs, $user;
  8569. $out = '';
  8570. $sql = "SELECT rowid, label FROM ".$this->db->prefix()."c_exp_tax_cat WHERE active = 1";
  8571. $sql .= " AND entity IN (0,".getEntity('exp_tax_cat').")";
  8572. if (!empty($excludeid)) {
  8573. $sql .= " AND rowid NOT IN (".$this->db->sanitize(implode(',', $excludeid)).")";
  8574. }
  8575. $sql .= " ORDER BY label";
  8576. $resql = $this->db->query($sql);
  8577. if ($resql) {
  8578. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  8579. if ($useempty) {
  8580. $out .= '<option value="0">&nbsp;</option>';
  8581. }
  8582. while ($obj = $this->db->fetch_object($resql)) {
  8583. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  8584. }
  8585. $out .= '</select>';
  8586. $out .= ajax_combobox('select_'.$htmlname);
  8587. if (!empty($htmlname) && $user->admin && $info_admin) {
  8588. $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8589. }
  8590. if (!empty($target)) {
  8591. $sql = "SELECT c.id FROM ".$this->db->prefix()."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8592. $resql = $this->db->query($sql);
  8593. if ($resql) {
  8594. if ($this->db->num_rows($resql) > 0) {
  8595. $obj = $this->db->fetch_object($resql);
  8596. $out .= '<script>
  8597. $(function() {
  8598. $("select[name='.$target.']").on("change", function() {
  8599. var current_val = $(this).val();
  8600. if (current_val == '.$obj->id.') {';
  8601. if (!empty($default_selected) || !empty($selected)) {
  8602. $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  8603. }
  8604. $out .= '
  8605. $("select[name='.$htmlname.']").change();
  8606. }
  8607. });
  8608. $("select[name='.$htmlname.']").change(function() {
  8609. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  8610. // get price of kilometer to fill the unit price
  8611. $.ajax({
  8612. method: "POST",
  8613. dataType: "json",
  8614. data: { fk_c_exp_tax_cat: $(this).val(), token: \''.currentToken().'\' },
  8615. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php?'.$params).'",
  8616. }).done(function( data, textStatus, jqXHR ) {
  8617. console.log(data);
  8618. if (typeof data.up != "undefined") {
  8619. $("input[name=value_unit]").val(data.up);
  8620. $("select[name='.$htmlname.']").attr("title", data.title);
  8621. } else {
  8622. $("input[name=value_unit]").val("");
  8623. $("select[name='.$htmlname.']").attr("title", "");
  8624. }
  8625. });
  8626. }
  8627. });
  8628. });
  8629. </script>';
  8630. }
  8631. }
  8632. }
  8633. } else {
  8634. dol_print_error($this->db);
  8635. }
  8636. return $out;
  8637. }
  8638. /**
  8639. * Return HTML to show the select ranges of expense range
  8640. *
  8641. * @param string $selected preselected category
  8642. * @param string $htmlname name of HTML select list
  8643. * @param integer $useempty 1=Add empty line
  8644. * @return string
  8645. */
  8646. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8647. {
  8648. global $conf, $langs;
  8649. $out = '';
  8650. $sql = "SELECT rowid, range_ik FROM ".$this->db->prefix()."c_exp_tax_range";
  8651. $sql .= " WHERE entity = ".$conf->entity." AND active = 1";
  8652. $resql = $this->db->query($sql);
  8653. if ($resql) {
  8654. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8655. if ($useempty) {
  8656. $out .= '<option value="0"></option>';
  8657. }
  8658. while ($obj = $this->db->fetch_object($resql)) {
  8659. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  8660. }
  8661. $out .= '</select>';
  8662. } else {
  8663. dol_print_error($this->db);
  8664. }
  8665. return $out;
  8666. }
  8667. /**
  8668. * Return HTML to show a select of expense
  8669. *
  8670. * @param string $selected preselected category
  8671. * @param string $htmlname name of HTML select list
  8672. * @param integer $useempty 1=Add empty choice
  8673. * @param integer $allchoice 1=Add all choice
  8674. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8675. * @return string
  8676. */
  8677. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8678. {
  8679. global $langs;
  8680. $out = '';
  8681. $sql = "SELECT id, code, label FROM ".$this->db->prefix()."c_type_fees";
  8682. $sql .= " WHERE active = 1";
  8683. $resql = $this->db->query($sql);
  8684. if ($resql) {
  8685. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8686. if ($useempty) {
  8687. $out .= '<option value="0"></option>';
  8688. }
  8689. if ($allchoice) {
  8690. $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  8691. }
  8692. $field = 'code';
  8693. if ($useid) {
  8694. $field = 'id';
  8695. }
  8696. while ($obj = $this->db->fetch_object($resql)) {
  8697. $key = $langs->trans($obj->code);
  8698. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  8699. }
  8700. $out .= '</select>';
  8701. } else {
  8702. dol_print_error($this->db);
  8703. }
  8704. return $out;
  8705. }
  8706. /**
  8707. * Output a combo list with invoices qualified for a third party
  8708. *
  8709. * @param int $socid Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
  8710. * @param int $selected Id invoice preselected
  8711. * @param string $htmlname Name of HTML select
  8712. * @param int $maxlength Maximum length of label
  8713. * @param int $option_only Return only html options lines without the select tag
  8714. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8715. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8716. * @param int $forcefocus Force focus on field (works with javascript only)
  8717. * @param int $disabled Disabled
  8718. * @param string $morecss More css added to the select component
  8719. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  8720. * @param string $showproject 'all' = Show project info, ''=Hide project info
  8721. * @param User $usertofilter User object to use for filtering
  8722. * @return int Nbr of project if OK, <0 if KO
  8723. */
  8724. public function selectInvoice($socid = -1, $selected = '', $htmlname = 'invoiceid', $maxlength = 24, $option_only = 0, $show_empty = '1', $discard_closed = 0, $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500', $projectsListId = '', $showproject = 'all', $usertofilter = null)
  8725. {
  8726. global $user, $conf, $langs;
  8727. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  8728. if (is_null($usertofilter)) {
  8729. $usertofilter = $user;
  8730. }
  8731. $out = '';
  8732. $hideunselectables = false;
  8733. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  8734. $hideunselectables = true;
  8735. }
  8736. if (empty($projectsListId)) {
  8737. if (empty($usertofilter->rights->projet->all->lire)) {
  8738. $projectstatic = new Project($this->db);
  8739. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  8740. }
  8741. }
  8742. // Search all projects
  8743. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  8744. p.title, p.fk_soc, p.fk_statut, p.public,";
  8745. $sql .= ' s.nom as name';
  8746. $sql .= ' FROM '.$this->db->prefix().'projet as p';
  8747. $sql .= ' LEFT JOIN '.$this->db->prefix().'societe as s ON s.rowid = p.fk_soc,';
  8748. $sql .= ' '.$this->db->prefix().'facture as f';
  8749. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  8750. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  8751. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  8752. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  8753. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  8754. $sql .= " ORDER BY p.ref, f.ref ASC";
  8755. $resql = $this->db->query($sql);
  8756. if ($resql) {
  8757. // Use select2 selector
  8758. if (!empty($conf->use_javascript_ajax)) {
  8759. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8760. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8761. $out .= $comboenhancement;
  8762. $morecss = 'minwidth200imp maxwidth500';
  8763. }
  8764. if (empty($option_only)) {
  8765. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  8766. }
  8767. if (!empty($show_empty)) {
  8768. $out .= '<option value="0" class="optiongrey">';
  8769. if (!is_numeric($show_empty)) {
  8770. $out .= $show_empty;
  8771. } else {
  8772. $out .= '&nbsp;';
  8773. }
  8774. $out .= '</option>';
  8775. }
  8776. $num = $this->db->num_rows($resql);
  8777. $i = 0;
  8778. if ($num) {
  8779. while ($i < $num) {
  8780. $obj = $this->db->fetch_object($resql);
  8781. // If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
  8782. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  8783. // Do nothing
  8784. } else {
  8785. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  8786. $i++;
  8787. continue;
  8788. }
  8789. $labeltoshow = '';
  8790. if ($showproject == 'all') {
  8791. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  8792. if ($obj->name) {
  8793. $labeltoshow .= ' - '.$obj->name; // Soc name
  8794. }
  8795. $disabled = 0;
  8796. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  8797. $disabled = 1;
  8798. $labeltoshow .= ' - '.$langs->trans("Draft");
  8799. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  8800. if ($discard_closed == 2) {
  8801. $disabled = 1;
  8802. }
  8803. $labeltoshow .= ' - '.$langs->trans("Closed");
  8804. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  8805. $disabled = 1;
  8806. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  8807. }
  8808. }
  8809. if (!empty($selected) && $selected == $obj->rowid) {
  8810. $out .= '<option value="'.$obj->rowid.'" selected';
  8811. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8812. $out .= '>'.$labeltoshow.'</option>';
  8813. } else {
  8814. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  8815. $resultat = '';
  8816. } else {
  8817. $resultat = '<option value="'.$obj->rowid.'"';
  8818. if ($disabled) {
  8819. $resultat .= ' disabled';
  8820. }
  8821. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  8822. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  8823. $resultat .= '>';
  8824. $resultat .= $labeltoshow;
  8825. $resultat .= '</option>';
  8826. }
  8827. $out .= $resultat;
  8828. }
  8829. }
  8830. $i++;
  8831. }
  8832. }
  8833. if (empty($option_only)) {
  8834. $out .= '</select>';
  8835. }
  8836. print $out;
  8837. $this->db->free($resql);
  8838. return $num;
  8839. } else {
  8840. dol_print_error($this->db);
  8841. return -1;
  8842. }
  8843. }
  8844. /**
  8845. * Output a combo list with invoices qualified for a third party
  8846. *
  8847. * @param int $selected Id invoice preselected
  8848. * @param string $htmlname Name of HTML select
  8849. * @param int $maxlength Maximum length of label
  8850. * @param int $option_only Return only html options lines without the select tag
  8851. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8852. * @param int $forcefocus Force focus on field (works with javascript only)
  8853. * @param int $disabled Disabled
  8854. * @param string $morecss More css added to the select component
  8855. * @return int Nbr of project if OK, <0 if KO
  8856. */
  8857. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  8858. {
  8859. global $user, $conf, $langs;
  8860. $out = '';
  8861. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  8862. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  8863. //$sql.= ', el.fk_source';
  8864. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  8865. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  8866. $sql .= " ORDER BY f.titre ASC";
  8867. $resql = $this->db->query($sql);
  8868. if ($resql) {
  8869. // Use select2 selector
  8870. if (!empty($conf->use_javascript_ajax)) {
  8871. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  8872. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8873. $out .= $comboenhancement;
  8874. $morecss = 'minwidth200imp maxwidth500';
  8875. }
  8876. if (empty($option_only)) {
  8877. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  8878. }
  8879. if (!empty($show_empty)) {
  8880. $out .= '<option value="0" class="optiongrey">';
  8881. if (!is_numeric($show_empty)) {
  8882. $out .= $show_empty;
  8883. } else {
  8884. $out .= '&nbsp;';
  8885. }
  8886. $out .= '</option>';
  8887. }
  8888. $num = $this->db->num_rows($resql);
  8889. if ($num) {
  8890. while ($obj = $this->db->fetch_object($resql)) {
  8891. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  8892. $disabled = 0;
  8893. if (!empty($obj->suspended)) {
  8894. $disabled = 1;
  8895. $labeltoshow .= ' - ' . $langs->trans("Closed");
  8896. }
  8897. if (!empty($selected) && $selected == $obj->rowid) {
  8898. $out .= '<option value="' . $obj->rowid . '" selected';
  8899. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8900. $out .= '>' . $labeltoshow . '</option>';
  8901. } else {
  8902. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  8903. $resultat = '';
  8904. } else {
  8905. $resultat = '<option value="' . $obj->rowid . '"';
  8906. if ($disabled) {
  8907. $resultat .= ' disabled';
  8908. }
  8909. $resultat .= '>';
  8910. $resultat .= $labeltoshow;
  8911. $resultat .= '</option>';
  8912. }
  8913. $out .= $resultat;
  8914. }
  8915. }
  8916. }
  8917. if (empty($option_only)) {
  8918. $out .= '</select>';
  8919. }
  8920. print $out;
  8921. $this->db->free($resql);
  8922. return $num;
  8923. } else {
  8924. $this->errors[]=$this->db->lasterror;
  8925. return -1;
  8926. }
  8927. }
  8928. /**
  8929. * Output the component to make advanced search criteries
  8930. *
  8931. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  8932. * @param array $search_component_params Array of selected search criterias
  8933. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  8934. * @param string $search_component_params_hidden String with $search_component_params criterias
  8935. * @return string HTML component for advanced search
  8936. */
  8937. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  8938. {
  8939. global $langs;
  8940. $ret = '';
  8941. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  8942. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8943. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  8944. $ret .= '<span class="fas fa-filter linkobject boxfilter pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("Filters")).'" id="idsubimgproductdistribution"></span>';
  8945. //$ret .= $langs->trans("Filters");
  8946. $ret .= '</a>';
  8947. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  8948. // Show select fields as tags.
  8949. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  8950. if ($search_component_params_hidden) {
  8951. if (!preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  8952. $search_component_params_hidden .= '('.$search_component_params_hidden.')';
  8953. }
  8954. $errormessage = '';
  8955. if (!dolCheckFilters($search_component_params_hidden, $errormessage)) {
  8956. print 'ERROR in parsing search string';
  8957. }
  8958. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  8959. //var_dump($search_component_params_hidden);
  8960. $htmltags = preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $search_component_params_hidden);
  8961. //var_dump($htmltags);
  8962. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch"><span class="tagsearchdelete select2-selection__choice__remove">x</span> '.$htmltags.'</span>';
  8963. }
  8964. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8965. //$ret .= search_component_params
  8966. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  8967. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  8968. $show_search_component_params_hidden = 1;
  8969. if ($show_search_component_params_hidden) {
  8970. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  8971. }
  8972. $ret .= "<!-- We store the full search string into this field. For example: (t.ref:like:'SO-%') and ((t.ref:like:'CO-%') or (t.ref:like:'AA%')) -->";
  8973. $ret .= '<input type="hidden" name="search_component_params_hidden" value="'.dol_escape_htmltag($search_component_params_hidden).'">';
  8974. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  8975. foreach ($arrayofcriterias as $criterias) {
  8976. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  8977. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  8978. continue;
  8979. }
  8980. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  8981. continue;
  8982. }
  8983. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  8984. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  8985. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  8986. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  8987. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  8988. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  8989. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  8990. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  8991. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  8992. } else {
  8993. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  8994. }
  8995. }
  8996. }
  8997. $ret .= '</div>';
  8998. $ret .= "<!-- Syntax of Generic filter string: t.ref:like:'SO-%', t.date_creation:<:'20160101', t.date_creation:<:'2016-01-01 12:30:00', t.nature:is:NULL, t.field2:isnot:NULL -->\n";
  8999. $ret .= '<input type="text" placeholder="'.$langs->trans("Search").'" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9000. $ret .= '</div>';
  9001. $ret .= '</div>';
  9002. return $ret;
  9003. }
  9004. /**
  9005. * selectModelMail
  9006. *
  9007. * @param string $prefix Prefix
  9008. * @param string $modelType Model type
  9009. * @param int $default 1=Show also Default mail template
  9010. * @param int $addjscombo Add js combobox
  9011. * @return string HTML select string
  9012. */
  9013. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9014. {
  9015. global $langs, $user;
  9016. $retstring = '';
  9017. $TModels = array();
  9018. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  9019. $formmail = new FormMail($this->db);
  9020. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9021. if ($default) {
  9022. $TModels[0] = $langs->trans('DefaultMailModel');
  9023. }
  9024. if ($result > 0) {
  9025. foreach ($formmail->lines_model as $model) {
  9026. $TModels[$model->id] = $model->label;
  9027. }
  9028. }
  9029. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  9030. foreach ($TModels as $id_model => $label_model) {
  9031. $retstring .= '<option value="'.$id_model.'"';
  9032. $retstring .= ">".$label_model."</option>";
  9033. }
  9034. $retstring .= "</select>";
  9035. if ($addjscombo) {
  9036. $retstring .= ajax_combobox('select_'.$prefix.'model_mail');
  9037. }
  9038. return $retstring;
  9039. }
  9040. /**
  9041. * Output the buttons to submit a creation/edit form
  9042. *
  9043. * @param string $save_label Alternative label for save button
  9044. * @param string $cancel_label Alternative label for cancel button
  9045. * @param array $morebuttons Add additional buttons between save and cancel
  9046. * @param bool $withoutdiv Option to remove enclosing centered div
  9047. * @param string $morecss More CSS
  9048. * @param string $dol_openinpopup If the button are shown in a context of a page shown inside a popup, we put here the string name of popup.
  9049. * @return string Html code with the buttons
  9050. */
  9051. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9052. {
  9053. global $langs;
  9054. $buttons = array();
  9055. $save = array(
  9056. 'name' => 'save',
  9057. 'label_key' => $save_label,
  9058. );
  9059. if ($save_label == 'Create' || $save_label == 'Add' ) {
  9060. $save['name'] = 'add';
  9061. } elseif ($save_label == 'Modify') {
  9062. $save['name'] = 'edit';
  9063. }
  9064. $cancel = array(
  9065. 'name' => 'cancel',
  9066. 'label_key' => 'Cancel',
  9067. );
  9068. !empty($save_label) ? $buttons[] = $save : '';
  9069. if (!empty($morebuttons)) {
  9070. $buttons[] = $morebuttons;
  9071. }
  9072. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9073. $retstring = $withoutdiv ? '': '<div class="center">';
  9074. foreach ($buttons as $button) {
  9075. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9076. $retstring .= '<input type="submit" class="button button-'.$button['name'].($morecss ? ' '.$morecss : '').' '.$addclass.'" name="'.$button['name'].'" value="'.dol_escape_htmltag($langs->trans($button['label_key'])).'">';
  9077. }
  9078. $retstring .= $withoutdiv ? '': '</div>';
  9079. if ($dol_openinpopup) {
  9080. $retstring .= '<!-- buttons are shown into a $dol_openinpopup='.$dol_openinpopup.' context, so we enable the close of dialog on cancel -->'."\n";
  9081. $retstring .= '<script>';
  9082. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9083. e.preventDefault(); console.log(\'We click on cancel in iframe popup '.$dol_openinpopup.'\');
  9084. window.parent.jQuery(\'#idfordialog'.$dol_openinpopup.'\').dialog(\'close\');
  9085. });';
  9086. $retstring .= '</script>';
  9087. // TODO @LDR for the save button, in action "add", set parent var to return data and close the window
  9088. //$retstring .= '<a onclick="javascript:$(\'#varforreturndialogid'.$dol_openinpopup.'\', window.parent.document).text(\'setid\');">setid</a> ';
  9089. //$retstring .= '<a onclick="javascript:$(\'#varforreturndialoglabel'.$dol_openinpopup.'\', window.parent.document).text(\'setlabel\');">setlabel</a>';
  9090. }
  9091. return $retstring;
  9092. }
  9093. }