html.form.class.php 406 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804
  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-2021 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) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $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) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  150. $ret .= '</td>';
  151. }
  152. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $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) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  165. $ret .= '</td>';
  166. }
  167. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $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. * @return string HTML edit field
  190. */
  191. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id')
  192. {
  193. global $conf, $langs, $db;
  194. $ret = '';
  195. // Check parameters
  196. if (empty($typeofdata)) {
  197. return 'ErrorBadParameter';
  198. }
  199. // When option to edit inline is activated
  200. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  201. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  202. } else {
  203. $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
  204. if ($editmode) {
  205. $ret .= "\n";
  206. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  207. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  208. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  209. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  210. if (empty($notabletag)) {
  211. $ret .= '<table class="nobordernopadding centpercent">';
  212. }
  213. if (empty($notabletag)) {
  214. $ret .= '<tr><td>';
  215. }
  216. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) {
  217. $tmp = explode(':', $typeofdata);
  218. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  219. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  220. $tmp = explode(':', $typeofdata);
  221. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  222. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ? price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  223. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  224. $tmp = explode(':', $typeofdata);
  225. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  226. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  227. $tmp = explode(':', $typeofdata);
  228. $cols = $tmp[2];
  229. $morealt = '';
  230. if (preg_match('/%/', $cols)) {
  231. $morealt = ' style="width: '.$cols.'"';
  232. $cols = '';
  233. }
  234. $valuetoshow = ($editvalue ? $editvalue : $value);
  235. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  236. // textarea convert automatically entities chars into simple chars.
  237. // 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.
  238. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  239. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  240. $ret .= '</textarea>';
  241. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  242. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0);
  243. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  244. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0);
  245. } elseif (preg_match('/^select;/', $typeofdata)) {
  246. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  247. $arraylist = array();
  248. foreach ($arraydata as $val) {
  249. $tmp = explode(':', $val);
  250. $tmpkey = str_replace('|', ':', $tmp[0]);
  251. $arraylist[$tmpkey] = $tmp[1];
  252. }
  253. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  254. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  255. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  256. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  257. $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'));
  258. $ret .= $doleditor->Create(1);
  259. }
  260. if (empty($notabletag)) {
  261. $ret .= '</td>';
  262. }
  263. if (empty($notabletag)) {
  264. $ret .= '<td class="left">';
  265. }
  266. //else $ret.='<div class="clearboth"></div>';
  267. $ret .= '<input type="submit" class="smallpaddingimp button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  268. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  269. $ret .= '<br>'."\n";
  270. }
  271. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  272. if (empty($notabletag)) {
  273. $ret .= '</td>';
  274. }
  275. if (empty($notabletag)) {
  276. $ret .= '</tr></table>'."\n";
  277. }
  278. $ret .= '</form>'."\n";
  279. } else {
  280. if (preg_match('/^(email)/', $typeofdata)) {
  281. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  282. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  283. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  284. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  285. $tmp = explode(':', $typeofdata);
  286. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  287. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  288. $ret .= dol_htmlentitiesbr($value);
  289. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  290. $ret .= dol_string_onlythesehtmltags($value);
  291. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  292. $ret .= dol_string_onlythesehtmltags($value);
  293. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  294. $ret .= '<span class="valuedate">'.dol_print_date($value, 'day').'</span>';
  295. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  296. $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour').'</span>';
  297. } elseif (preg_match('/^select;/', $typeofdata)) {
  298. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  299. $arraylist = array();
  300. foreach ($arraydata as $val) {
  301. $tmp = explode(':', $val);
  302. $arraylist[$tmp[0]] = $tmp[1];
  303. }
  304. $ret .= $arraylist[$value];
  305. if ($htmlname == 'fk_product_type') {
  306. if ($value == 0) {
  307. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  308. } else {
  309. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  310. }
  311. }
  312. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  313. $tmpcontent = dol_htmlentitiesbr($value);
  314. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  315. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  316. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  317. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  318. }
  319. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  320. // clean data from some dangerous html
  321. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  322. } else {
  323. $ret .= dol_escape_htmltag($value);
  324. }
  325. if ($formatfunc && method_exists($object, $formatfunc)) {
  326. $ret = $object->$formatfunc($ret);
  327. }
  328. }
  329. }
  330. return $ret;
  331. }
  332. /**
  333. * Output edit in place form
  334. *
  335. * @param string $fieldname Name of the field
  336. * @param object $object Object
  337. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  338. * @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]'...)
  339. * @param string $check Same coe than $check parameter of GETPOST()
  340. * @param string $morecss More CSS
  341. * @return string HTML code for the edit of alternative language
  342. */
  343. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  344. {
  345. global $conf, $langs, $extralanguages;
  346. $result = '';
  347. // List of extra languages
  348. $arrayoflangcode = array();
  349. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  350. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  351. }
  352. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  353. if (!is_object($extralanguages)) {
  354. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  355. $extralanguages = new ExtraLanguages($this->db);
  356. }
  357. $extralanguages->fetch_name_extralanguages('societe');
  358. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  359. return ''; // No extralang field to show
  360. }
  361. $result .= '<!-- Widget for translation -->'."\n";
  362. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  363. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  364. $result .= $s;
  365. $result .= '</div>';
  366. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  367. $resultforextrlang = '';
  368. foreach ($arrayoflangcode as $langcode) {
  369. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  370. if (empty($valuetoshow)) {
  371. $object->fetchValuesForExtraLanguages();
  372. //var_dump($object->array_languages);
  373. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  374. }
  375. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  376. $resultforextrlang .= $s;
  377. // TODO Use the showInputField() method of ExtraLanguages object
  378. if ($typeofdata == 'textarea') {
  379. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  380. $resultforextrlang .= $valuetoshow;
  381. $resultforextrlang .= '</textarea>';
  382. } else {
  383. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  384. }
  385. }
  386. $result .= $resultforextrlang;
  387. $result .= '</div>';
  388. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  389. }
  390. return $result;
  391. }
  392. /**
  393. * Output edit in place form
  394. *
  395. * @param object $object Object
  396. * @param string $value Value to show/edit
  397. * @param string $htmlname DIV ID (field name)
  398. * @param int $condition Condition to edit
  399. * @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')
  400. * @param string $editvalue When in edit mode, use this value as $value instead of value
  401. * @param object $extObject External object
  402. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  403. * @return string HTML edit in place
  404. */
  405. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  406. {
  407. global $conf;
  408. $out = '';
  409. // Check parameters
  410. if (preg_match('/^text/', $inputType)) {
  411. $value = dol_nl2br($value);
  412. } elseif (preg_match('/^numeric/', $inputType)) {
  413. $value = price($value);
  414. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  415. $value = dol_print_date($value, 'day');
  416. }
  417. if ($condition) {
  418. $element = false;
  419. $table_element = false;
  420. $fk_element = false;
  421. $loadmethod = false;
  422. $savemethod = false;
  423. $ext_element = false;
  424. $button_only = false;
  425. $inputOption = '';
  426. if (is_object($object)) {
  427. $element = $object->element;
  428. $table_element = $object->table_element;
  429. $fk_element = $object->id;
  430. }
  431. if (is_object($extObject)) {
  432. $ext_element = $extObject->element;
  433. }
  434. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  435. $tmp = explode(':', $inputType);
  436. $inputType = $tmp[0];
  437. if (!empty($tmp[1])) {
  438. $inputOption = $tmp[1];
  439. }
  440. if (!empty($tmp[2])) {
  441. $savemethod = $tmp[2];
  442. }
  443. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  444. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  445. $tmp = explode(':', $inputType);
  446. $inputType = $tmp[0];
  447. if (!empty($tmp[1])) {
  448. $inputOption = $tmp[1];
  449. }
  450. if (!empty($tmp[2])) {
  451. $savemethod = $tmp[2];
  452. }
  453. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  454. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  455. $tmp = explode(':', $inputType);
  456. $inputType = $tmp[0];
  457. $loadmethod = $tmp[1];
  458. if (!empty($tmp[2])) {
  459. $savemethod = $tmp[2];
  460. }
  461. if (!empty($tmp[3])) {
  462. $button_only = true;
  463. }
  464. } elseif (preg_match('/^textarea/', $inputType)) {
  465. $tmp = explode(':', $inputType);
  466. $inputType = $tmp[0];
  467. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  468. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  469. } elseif (preg_match('/^ckeditor/', $inputType)) {
  470. $tmp = explode(':', $inputType);
  471. $inputType = $tmp[0];
  472. $toolbar = $tmp[1];
  473. if (!empty($tmp[2])) {
  474. $width = $tmp[2];
  475. }
  476. if (!empty($tmp[3])) {
  477. $heigth = $tmp[3];
  478. }
  479. if (!empty($tmp[4])) {
  480. $savemethod = $tmp[4];
  481. }
  482. if (!empty($conf->fckeditor->enabled)) {
  483. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  484. } else {
  485. $inputType = 'textarea';
  486. }
  487. }
  488. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  489. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  490. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  491. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  492. if (!empty($savemethod)) {
  493. $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  494. }
  495. if (!empty($ext_element)) {
  496. $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  497. }
  498. if (!empty($custommsg)) {
  499. if (is_array($custommsg)) {
  500. if (!empty($custommsg['success'])) {
  501. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  502. }
  503. if (!empty($custommsg['error'])) {
  504. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  505. }
  506. } else {
  507. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  508. }
  509. }
  510. if ($inputType == 'textarea') {
  511. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  512. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  513. }
  514. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  515. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  516. } else {
  517. $out = $value;
  518. }
  519. return $out;
  520. }
  521. /**
  522. * Show a text and picto with tooltip on text or picto.
  523. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  524. *
  525. * @param string $text Text to show
  526. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  527. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  528. * @param int $direction -1=image is before, 0=no image, 1=image is after
  529. * @param string $img Html code for image (use img_xxx() function to get it)
  530. * @param string $extracss Add a CSS style to td tags
  531. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  532. * @param string $incbefore Include code before the text
  533. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  534. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  535. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  536. * @return string Code html du tooltip (texte+picto)
  537. * @see textwithpicto() Use thisfunction if you can.
  538. */
  539. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  540. {
  541. if ($incbefore) {
  542. $text = $incbefore.$text;
  543. }
  544. if (!$htmltext) {
  545. return $text;
  546. }
  547. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  548. $tag = 'td';
  549. if ($notabs == 2) {
  550. $tag = 'div';
  551. }
  552. if ($notabs == 3) {
  553. $tag = 'span';
  554. }
  555. // Sanitize tooltip
  556. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  557. $extrastyle = '';
  558. if ($direction < 0) {
  559. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  560. $extrastyle = 'padding: 0px; padding-left: 3px !important;';
  561. }
  562. if ($direction > 0) {
  563. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  564. $extrastyle = 'padding: 0px; padding-right: 3px !important;';
  565. }
  566. $classfortooltip = 'classfortooltip';
  567. $s = '';
  568. $textfordialog = '';
  569. if ($tooltiptrigger == '') {
  570. $htmltext = str_replace('"', '&quot;', $htmltext);
  571. } else {
  572. $classfortooltip = 'classfortooltiponclick';
  573. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  574. }
  575. if ($tooltipon == 2 || $tooltipon == 3) {
  576. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  577. if ($tooltiptrigger == '') {
  578. $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  579. } else {
  580. $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  581. }
  582. } else {
  583. $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  584. }
  585. if ($tooltipon == 1 || $tooltipon == 3) {
  586. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  587. if ($tooltiptrigger == '') {
  588. $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  589. } else {
  590. $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  591. }
  592. } else {
  593. $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  594. }
  595. if (empty($notabs)) {
  596. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  597. } elseif ($notabs == 2) {
  598. $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  599. }
  600. // Define value if value is before
  601. if ($direction < 0) {
  602. $s .= '<'.$tag.$paramfortooltipimg;
  603. if ($tag == 'td') {
  604. $s .= ' class=valigntop" width="14"';
  605. }
  606. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  607. }
  608. // Use another method to help avoid having a space in value in order to use this value with jquery
  609. // Define label
  610. if ((string) $text != '') {
  611. $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  612. }
  613. // Define value if value is after
  614. if ($direction > 0) {
  615. $s .= '<'.$tag.$paramfortooltipimg;
  616. if ($tag == 'td') {
  617. $s .= ' class="valignmiddle" width="14"';
  618. }
  619. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  620. }
  621. if (empty($notabs)) {
  622. $s .= '</tr></table>';
  623. } elseif ($notabs == 2) {
  624. $s .= '</div>';
  625. }
  626. return $s;
  627. }
  628. /**
  629. * Show a text with a picto and a tooltip on picto
  630. *
  631. * @param string $text Text to show
  632. * @param string $htmltext Content of tooltip
  633. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  634. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  635. * @param string $extracss Add a CSS style to td, div or span tag
  636. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  637. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  638. * @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')
  639. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  640. * @return string HTML code of text, picto, tooltip
  641. */
  642. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  643. {
  644. global $conf, $langs;
  645. $alt = '';
  646. if ($tooltiptrigger) {
  647. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  648. }
  649. //For backwards compatibility
  650. if ($type == '0') {
  651. $type = 'info';
  652. } elseif ($type == '1') {
  653. $type = 'help';
  654. }
  655. // If info or help with no javascript, show only text
  656. if (empty($conf->use_javascript_ajax)) {
  657. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  658. return $text;
  659. } else {
  660. $alt = $htmltext;
  661. $htmltext = '';
  662. }
  663. }
  664. // If info or help with smartphone, show only text (tooltip hover can't works)
  665. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  666. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  667. return $text;
  668. }
  669. }
  670. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  671. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  672. //{
  673. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  674. //}
  675. $img = '';
  676. if ($type == 'info') {
  677. $img = img_help(0, $alt);
  678. } elseif ($type == 'help') {
  679. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  680. } elseif ($type == 'helpclickable') {
  681. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  682. } elseif ($type == 'superadmin') {
  683. $img = img_picto($alt, 'redstar');
  684. } elseif ($type == 'admin') {
  685. $img = img_picto($alt, 'star');
  686. } elseif ($type == 'warning') {
  687. $img = img_warning($alt);
  688. } elseif ($type != 'none') {
  689. $img = img_picto($alt, $type); // $type can be an image path
  690. }
  691. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  692. }
  693. /**
  694. * Generate select HTML to choose massaction
  695. *
  696. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  697. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  698. * @param int $alwaysvisible 1=select button always visible
  699. * @param string $name Name for massaction
  700. * @param string $cssclass CSS class used to check for select
  701. * @return string|void Select list
  702. */
  703. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  704. {
  705. global $conf, $langs, $hookmanager;
  706. $disabled = 0;
  707. $ret = '<div class="centpercent center">';
  708. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  709. // 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.
  710. $parameters = array();
  711. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  712. // check if there is a mass action
  713. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  714. return;
  715. }
  716. if (empty($reshook)) {
  717. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  718. foreach ($arrayofaction as $code => $label) {
  719. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  720. }
  721. }
  722. $ret .= $hookmanager->resPrint;
  723. $ret .= '</select>';
  724. if (empty($conf->dol_optimize_smallscreen)) {
  725. $ret .= ajax_combobox('.'.$name.'select');
  726. }
  727. // 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
  728. $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.
  729. $ret .= '<input type="submit" disabled name="confirmmassaction"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display: none"').' class="button small'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'confirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  730. $ret .= '</div>';
  731. if (!empty($conf->use_javascript_ajax)) {
  732. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  733. <script>
  734. 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 */
  735. {
  736. atleastoneselected=0;
  737. jQuery("."+cssclass).each(function( index ) {
  738. /* console.log( index + ": " + $( this ).text() ); */
  739. if ($(this).is(\':checked\')) atleastoneselected++;
  740. });
  741. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  742. if (atleastoneselected || '.$alwaysvisible.')
  743. {
  744. jQuery("."+name).show();
  745. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  746. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  747. }
  748. else
  749. {
  750. jQuery("."+name).hide();
  751. jQuery("."+name+"other").hide();
  752. }
  753. }
  754. jQuery(document).ready(function () {
  755. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  756. jQuery(".' . $cssclass.'").click(function() {
  757. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  758. });
  759. jQuery(".' . $name.'select").change(function() {
  760. var massaction = $( this ).val();
  761. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  762. if (massaction == "builddoc")
  763. {
  764. urlform = urlform + "#show_files";
  765. }
  766. $( this ).closest("form").attr("action", urlform);
  767. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  768. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  769. if ($(this).val() != \'0\')
  770. {
  771. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  772. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  773. jQuery(".' . $name.'"+massaction).show();
  774. }
  775. else
  776. {
  777. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  778. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  779. }
  780. });
  781. });
  782. </script>
  783. ';
  784. }
  785. return $ret;
  786. }
  787. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  788. /**
  789. * Return combo list of activated countries, into language of user
  790. *
  791. * @param string $selected Id or Code or Label of preselected country
  792. * @param string $htmlname Name of html select object
  793. * @param string $htmloption More html options on select object
  794. * @param integer $maxlength Max length for labels (0=no limit)
  795. * @param string $morecss More css class
  796. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  797. * @param int $showempty Show empty choice
  798. * @param int $disablefavorites 1=Disable favorites,
  799. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  800. * @param array $exclude_country_code Array of country code (iso2) to exclude
  801. * @param int $hideflags Hide flags
  802. * @return string HTML string with select
  803. */
  804. 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)
  805. {
  806. // phpcs:enable
  807. global $conf, $langs, $mysoc;
  808. $langs->load("dict");
  809. $out = '';
  810. $countryArray = array();
  811. $favorite = array();
  812. $label = array();
  813. $atleastonefavorite = 0;
  814. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  815. $sql .= " FROM ".MAIN_DB_PREFIX."c_country";
  816. $sql .= " WHERE active > 0";
  817. //$sql.= " ORDER BY code ASC";
  818. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  819. $resql = $this->db->query($sql);
  820. if ($resql) {
  821. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  822. $num = $this->db->num_rows($resql);
  823. $i = 0;
  824. if ($num) {
  825. while ($i < $num) {
  826. $obj = $this->db->fetch_object($resql);
  827. $countryArray[$i]['rowid'] = $obj->rowid;
  828. $countryArray[$i]['code_iso'] = $obj->code_iso;
  829. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  830. $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 : ''));
  831. $countryArray[$i]['favorite'] = $obj->favorite;
  832. $countryArray[$i]['eec'] = $obj->eec;
  833. $favorite[$i] = $obj->favorite;
  834. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  835. $i++;
  836. }
  837. if (empty($disablefavorites)) {
  838. array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  839. } else {
  840. $countryArray = dol_sort_array($countryArray, 'label');
  841. }
  842. if ($showempty) {
  843. $out .= '<option value="">&nbsp;</option>'."\n";
  844. }
  845. if ($addspecialentries) { // Add dedicated entries for groups of countries
  846. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  847. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  848. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  849. if ($mysoc->isInEEC()) {
  850. $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  851. }
  852. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  853. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  854. }
  855. foreach ($countryArray as $row) {
  856. //if (empty($showempty) && empty($row['rowid'])) continue;
  857. if (empty($row['rowid'])) {
  858. continue;
  859. }
  860. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  861. continue; // exclude some countries
  862. }
  863. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  864. $atleastonefavorite++;
  865. }
  866. if (empty($row['favorite']) && $atleastonefavorite) {
  867. $atleastonefavorite = 0;
  868. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  869. }
  870. $labeltoshow = '';
  871. if ($row['label']) {
  872. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  873. } else {
  874. $labeltoshow .= '&nbsp;';
  875. }
  876. if ($row['code_iso']) {
  877. $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
  878. if (empty($hideflags)) {
  879. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  880. $labeltoshow = $tmpflag.' '.$labeltoshow;
  881. }
  882. }
  883. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  884. $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']).'">';
  885. } else {
  886. $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']).'">';
  887. }
  888. $out .= $labeltoshow;
  889. $out .= '</option>'."\n";
  890. }
  891. }
  892. $out .= '</select>';
  893. } else {
  894. dol_print_error($this->db);
  895. }
  896. // Make select dynamic
  897. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  898. $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
  899. return $out;
  900. }
  901. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  902. /**
  903. * Return select list of incoterms
  904. *
  905. * @param string $selected Id or Code of preselected incoterm
  906. * @param string $location_incoterms Value of input location
  907. * @param string $page Defined the form action
  908. * @param string $htmlname Name of html select object
  909. * @param string $htmloption Options html on select object
  910. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  911. * @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')))
  912. * @return string HTML string with select and input
  913. */
  914. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
  915. {
  916. // phpcs:enable
  917. global $conf, $langs;
  918. $langs->load("dict");
  919. $out = '';
  920. $moreattrib = '';
  921. $incotermArray = array();
  922. $sql = "SELECT rowid, code";
  923. $sql .= " FROM ".MAIN_DB_PREFIX."c_incoterms";
  924. $sql .= " WHERE active > 0";
  925. $sql .= " ORDER BY code ASC";
  926. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  927. $resql = $this->db->query($sql);
  928. if ($resql) {
  929. if ($conf->use_javascript_ajax && !$forcecombo) {
  930. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  931. $out .= ajax_combobox($htmlname, $events);
  932. }
  933. if (!empty($page)) {
  934. $out .= '<form method="post" action="'.$page.'">';
  935. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  936. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  937. }
  938. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm width75" name="'.$htmlname.'" '.$htmloption.'>';
  939. $out .= '<option value="0">&nbsp;</option>';
  940. $num = $this->db->num_rows($resql);
  941. $i = 0;
  942. if ($num) {
  943. $foundselected = false;
  944. while ($i < $num) {
  945. $obj = $this->db->fetch_object($resql);
  946. $incotermArray[$i]['rowid'] = $obj->rowid;
  947. $incotermArray[$i]['code'] = $obj->code;
  948. $i++;
  949. }
  950. foreach ($incotermArray as $row) {
  951. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  952. $out .= '<option value="'.$row['rowid'].'" selected>';
  953. } else {
  954. $out .= '<option value="'.$row['rowid'].'">';
  955. }
  956. if ($row['code']) {
  957. $out .= $row['code'];
  958. }
  959. $out .= '</option>';
  960. }
  961. }
  962. $out .= '</select>';
  963. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  964. $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT.'/core/ajax/locationincoterms.php')."\n";
  965. $moreattrib .= ' autocomplete="off"';
  966. }
  967. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="'.$location_incoterms.'">'."\n";
  968. if (!empty($page)) {
  969. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="'.$langs->trans("Modify").'"></form>';
  970. }
  971. } else {
  972. dol_print_error($this->db);
  973. }
  974. return $out;
  975. }
  976. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  977. /**
  978. * Return list of types of lines (product or service)
  979. * Example: 0=product, 1=service, 9=other (for external module)
  980. *
  981. * @param string $selected Preselected type
  982. * @param string $htmlname Name of field in html form
  983. * @param int $showempty Add an empty field
  984. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  985. * @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')
  986. * @return void
  987. */
  988. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  989. {
  990. // phpcs:enable
  991. global $db, $langs, $user, $conf;
  992. // If product & services are enabled or both disabled.
  993. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  994. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled))) {
  995. if (empty($hidetext)) {
  996. print $langs->trans("Type").': ';
  997. }
  998. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  999. if ($showempty) {
  1000. print '<option value="-1"';
  1001. if ($selected == -1) {
  1002. print ' selected';
  1003. }
  1004. print '>&nbsp;</option>';
  1005. }
  1006. print '<option value="0"';
  1007. if (0 == $selected) {
  1008. print ' selected';
  1009. }
  1010. print '>'.$langs->trans("Product");
  1011. print '<option value="1"';
  1012. if (1 == $selected) {
  1013. print ' selected';
  1014. }
  1015. print '>'.$langs->trans("Service");
  1016. print '</select>';
  1017. print ajax_combobox('select_'.$htmlname);
  1018. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1019. }
  1020. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3) {
  1021. print $langs->trans("Service");
  1022. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  1023. }
  1024. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2) {
  1025. print $langs->trans("Product");
  1026. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  1027. }
  1028. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1029. 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
  1030. }
  1031. }
  1032. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1033. /**
  1034. * Load into cache cache_types_fees, array of types of fees
  1035. *
  1036. * @return int Nb of lines loaded, <0 if KO
  1037. */
  1038. public function load_cache_types_fees()
  1039. {
  1040. // phpcs:enable
  1041. global $langs;
  1042. $num = count($this->cache_types_fees);
  1043. if ($num > 0) {
  1044. return 0; // Cache already loaded
  1045. }
  1046. dol_syslog(__METHOD__, LOG_DEBUG);
  1047. $langs->load("trips");
  1048. $sql = "SELECT c.code, c.label";
  1049. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  1050. $sql .= " WHERE active > 0";
  1051. $resql = $this->db->query($sql);
  1052. if ($resql) {
  1053. $num = $this->db->num_rows($resql);
  1054. $i = 0;
  1055. while ($i < $num) {
  1056. $obj = $this->db->fetch_object($resql);
  1057. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1058. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1059. $this->cache_types_fees[$obj->code] = $label;
  1060. $i++;
  1061. }
  1062. asort($this->cache_types_fees);
  1063. return $num;
  1064. } else {
  1065. dol_print_error($this->db);
  1066. return -1;
  1067. }
  1068. }
  1069. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1070. /**
  1071. * Return list of types of notes
  1072. *
  1073. * @param string $selected Preselected type
  1074. * @param string $htmlname Name of field in form
  1075. * @param int $showempty Add an empty field
  1076. * @return void
  1077. */
  1078. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1079. {
  1080. // phpcs:enable
  1081. global $user, $langs;
  1082. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  1083. $this->load_cache_types_fees();
  1084. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  1085. if ($showempty) {
  1086. print '<option value="-1"';
  1087. if ($selected == -1) {
  1088. print ' selected';
  1089. }
  1090. print '>&nbsp;</option>';
  1091. }
  1092. foreach ($this->cache_types_fees as $key => $value) {
  1093. print '<option value="'.$key.'"';
  1094. if ($key == $selected) {
  1095. print ' selected';
  1096. }
  1097. print '>';
  1098. print $value;
  1099. print '</option>';
  1100. }
  1101. print '</select>';
  1102. if ($user->admin) {
  1103. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1104. }
  1105. }
  1106. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1107. /**
  1108. * Output html form to select a third party
  1109. *
  1110. * @param string $selected Preselected type
  1111. * @param string $htmlname Name of field in form
  1112. * @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)')
  1113. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1114. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1115. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1116. * @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')))
  1117. * @param int $limit Maximum number of elements
  1118. * @param string $morecss Add more css styles to the SELECT component
  1119. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1120. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1121. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1122. * @param array $ajaxoptions Options for ajax_autocompleter
  1123. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1124. * @param array $excludeids Exclude IDs from the select combo
  1125. * @return string HTML string with select box for thirdparty.
  1126. */
  1127. 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())
  1128. {
  1129. // phpcs:enable
  1130. global $conf, $user, $langs;
  1131. $out = '';
  1132. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1133. if (is_null($ajaxoptions)) {
  1134. $ajaxoptions = array();
  1135. }
  1136. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1137. // No immediate load of all database
  1138. $placeholder = '';
  1139. if ($selected && empty($selected_input_value)) {
  1140. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1141. $societetmp = new Societe($this->db);
  1142. $societetmp->fetch($selected);
  1143. $selected_input_value = $societetmp->name;
  1144. unset($societetmp);
  1145. }
  1146. // mode 1
  1147. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '');
  1148. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1149. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1150. if (empty($hidelabel)) {
  1151. print $langs->trans("RefOrLabel").' : ';
  1152. } elseif ($hidelabel > 1) {
  1153. $placeholder = $langs->trans("RefOrLabel");
  1154. if ($hidelabel == 2) {
  1155. $out .= img_picto($langs->trans("Search"), 'search');
  1156. }
  1157. }
  1158. $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' : '').' />';
  1159. if ($hidelabel == 3) {
  1160. $out .= img_picto($langs->trans("Search"), 'search');
  1161. }
  1162. } else {
  1163. // Immediate load of all database
  1164. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids);
  1165. }
  1166. return $out;
  1167. }
  1168. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1169. /**
  1170. * Output html form to select a third party.
  1171. * 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.
  1172. *
  1173. * @param string $selected Preselected type
  1174. * @param string $htmlname Name of field in form
  1175. * @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.
  1176. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1177. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1178. * @param int $forcecombo Force to use standard HTML select component without beautification
  1179. * @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')))
  1180. * @param string $filterkey Filter on key value
  1181. * @param int $outputmode 0=HTML select string, 1=Array
  1182. * @param int $limit Limit number of answers
  1183. * @param string $morecss Add more css styles to the SELECT component
  1184. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1185. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1186. * @param array $excludeids Exclude IDs from the select combo
  1187. * @return string HTML string with
  1188. */
  1189. 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())
  1190. {
  1191. // phpcs:enable
  1192. global $conf, $user, $langs;
  1193. $out = '';
  1194. $num = 0;
  1195. $outarray = array();
  1196. if ($selected === '') {
  1197. $selected = array();
  1198. } elseif (!is_array($selected)) {
  1199. $selected = array($selected);
  1200. }
  1201. // Clean $filter that may contains sql conditions so sql code
  1202. if (function_exists('testSqlAndScriptInject')) {
  1203. if (testSqlAndScriptInject($filter, 3) > 0) {
  1204. $filter = '';
  1205. }
  1206. }
  1207. // We search companies
  1208. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1209. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1210. $sql .= ", s.address, s.zip, s.town";
  1211. $sql .= ", dictp.code as country_code";
  1212. }
  1213. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  1214. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1215. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid = s.fk_pays";
  1216. }
  1217. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1218. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1219. }
  1220. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1221. if (!empty($user->socid)) {
  1222. $sql .= " AND s.rowid = ".((int) $user->socid);
  1223. }
  1224. if ($filter) {
  1225. $sql .= " AND (".$filter.")";
  1226. }
  1227. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1228. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1229. }
  1230. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1231. $sql .= " AND s.status <> 0";
  1232. }
  1233. if (!empty($excludeids)) {
  1234. $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
  1235. }
  1236. // Add criteria
  1237. if ($filterkey && $filterkey != '') {
  1238. $sql .= " AND (";
  1239. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1240. // For natural search
  1241. $scrit = explode(' ', $filterkey);
  1242. $i = 0;
  1243. if (count($scrit) > 1) {
  1244. $sql .= "(";
  1245. }
  1246. foreach ($scrit as $crit) {
  1247. if ($i > 0) {
  1248. $sql .= " AND ";
  1249. }
  1250. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1251. $i++;
  1252. }
  1253. if (count($scrit) > 1) {
  1254. $sql .= ")";
  1255. }
  1256. if (!empty($conf->barcode->enabled)) {
  1257. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1258. }
  1259. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1260. $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1261. $sql .= ")";
  1262. }
  1263. $sql .= $this->db->order("nom", "ASC");
  1264. $sql .= $this->db->plimit($limit, 0);
  1265. // Build output string
  1266. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1267. $resql = $this->db->query($sql);
  1268. if ($resql) {
  1269. if (!$forcecombo) {
  1270. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1271. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1272. }
  1273. // Construct $out and $outarray
  1274. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1275. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1276. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1277. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1278. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1279. if ($showempty && !is_numeric($showempty)) {
  1280. $textifempty = $langs->trans($showempty);
  1281. } else {
  1282. $textifempty .= $langs->trans("All");
  1283. }
  1284. }
  1285. if ($showempty) {
  1286. $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
  1287. }
  1288. $num = $this->db->num_rows($resql);
  1289. $i = 0;
  1290. if ($num) {
  1291. while ($i < $num) {
  1292. $obj = $this->db->fetch_object($resql);
  1293. $label = '';
  1294. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1295. if (($obj->client) && (!empty($obj->code_client))) {
  1296. $label = $obj->code_client.' - ';
  1297. }
  1298. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1299. $label .= $obj->code_fournisseur.' - ';
  1300. }
  1301. $label .= ' '.$obj->name;
  1302. } else {
  1303. $label = $obj->name;
  1304. }
  1305. if (!empty($obj->name_alias)) {
  1306. $label .= ' ('.$obj->name_alias.')';
  1307. }
  1308. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1309. $label .= ' - '.$obj->tva_intra.'';
  1310. }
  1311. if ($showtype) {
  1312. if ($obj->client || $obj->fournisseur) {
  1313. $label .= ' (';
  1314. }
  1315. if ($obj->client == 1 || $obj->client == 3) {
  1316. $label .= $langs->trans("Customer");
  1317. }
  1318. if ($obj->client == 2 || $obj->client == 3) {
  1319. $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1320. }
  1321. if ($obj->fournisseur) {
  1322. $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1323. }
  1324. if ($obj->client || $obj->fournisseur) {
  1325. $label .= ')';
  1326. }
  1327. }
  1328. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1329. $label .= ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1330. if (!empty($obj->country_code)) {
  1331. $label .= ', '.$langs->trans('Country'.$obj->country_code);
  1332. }
  1333. }
  1334. if (empty($outputmode)) {
  1335. if (in_array($obj->rowid, $selected)) {
  1336. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1337. } else {
  1338. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1339. }
  1340. } else {
  1341. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1342. }
  1343. $i++;
  1344. if (($i % 10) == 0) {
  1345. $out .= "\n";
  1346. }
  1347. }
  1348. }
  1349. $out .= '</select>'."\n";
  1350. } else {
  1351. dol_print_error($this->db);
  1352. }
  1353. $this->result = array('nbofthirdparties'=>$num);
  1354. if ($outputmode) {
  1355. return $outarray;
  1356. }
  1357. return $out;
  1358. }
  1359. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1360. /**
  1361. * Return HTML combo list of absolute discounts
  1362. *
  1363. * @param string $selected Id remise fixe pre-selectionnee
  1364. * @param string $htmlname Nom champ formulaire
  1365. * @param string $filter Criteres optionnels de filtre
  1366. * @param int $socid Id of thirdparty
  1367. * @param int $maxvalue Max value for lines that can be selected
  1368. * @return int Return number of qualifed lines in list
  1369. */
  1370. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1371. {
  1372. // phpcs:enable
  1373. global $langs, $conf;
  1374. // On recherche les remises
  1375. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1376. $sql .= " re.description, re.fk_facture_source";
  1377. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  1378. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1379. $sql .= " AND re.entity = ".$conf->entity;
  1380. if ($filter) {
  1381. $sql .= " AND ".$filter;
  1382. }
  1383. $sql .= " ORDER BY re.description ASC";
  1384. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1385. $resql = $this->db->query($sql);
  1386. if ($resql) {
  1387. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1388. $num = $this->db->num_rows($resql);
  1389. $qualifiedlines = $num;
  1390. $i = 0;
  1391. if ($num) {
  1392. print '<option value="0">&nbsp;</option>';
  1393. while ($i < $num) {
  1394. $obj = $this->db->fetch_object($resql);
  1395. $desc = dol_trunc($obj->description, 40);
  1396. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1397. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1398. }
  1399. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1400. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1401. }
  1402. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1403. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1404. }
  1405. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1406. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1407. }
  1408. $selectstring = '';
  1409. if ($selected > 0 && $selected == $obj->rowid) {
  1410. $selectstring = ' selected';
  1411. }
  1412. $disabled = '';
  1413. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1414. $qualifiedlines--;
  1415. $disabled = ' disabled';
  1416. }
  1417. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1418. $tmpfac = new Facture($this->db);
  1419. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1420. $desc = $desc.' - '.$tmpfac->ref;
  1421. }
  1422. }
  1423. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1424. $i++;
  1425. }
  1426. }
  1427. print '</select>';
  1428. return $qualifiedlines;
  1429. } else {
  1430. dol_print_error($this->db);
  1431. return -1;
  1432. }
  1433. }
  1434. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1435. /**
  1436. * Return list of all contacts (for a third party or all)
  1437. *
  1438. * @param int $socid Id ot third party or 0 for all
  1439. * @param string $selected Id contact pre-selectionne
  1440. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1441. * @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
  1442. * @param string $exclude List of contacts id to exclude
  1443. * @param string $limitto Disable answers that are not id in this array list
  1444. * @param integer $showfunction Add function into label
  1445. * @param string $moreclass Add more class to class style
  1446. * @param integer $showsoc Add company into label
  1447. * @param int $forcecombo Force to use combo box
  1448. * @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')))
  1449. * @param bool $options_only Return options only (for ajax treatment)
  1450. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1451. * @param string $htmlid Html id to use instead of htmlname
  1452. * @return int <0 if KO, Nb of contact in list if OK
  1453. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1454. */
  1455. public function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
  1456. {
  1457. // phpcs:enable
  1458. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1459. return $this->num;
  1460. }
  1461. /**
  1462. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1463. * This also set the number of contacts found into $this->num
  1464. *
  1465. * @since 9.0 Add afterSelectContactOptions hook
  1466. *
  1467. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1468. * @param array|int $selected Array of ID of pre-selected contact id
  1469. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1470. * @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
  1471. * @param string $exclude List of contacts id to exclude
  1472. * @param string $limitto Disable answers that are not id in this array list
  1473. * @param integer $showfunction Add function into label
  1474. * @param string $moreclass Add more class to class style
  1475. * @param bool $options_only Return options only (for ajax treatment)
  1476. * @param integer $showsoc Add company into label
  1477. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1478. * @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')))
  1479. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1480. * @param string $htmlid Html id to use instead of htmlname
  1481. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1482. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1483. * @return int|string <0 if KO, HTML with select string if OK.
  1484. */
  1485. public function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0)
  1486. {
  1487. global $conf, $langs, $hookmanager, $action;
  1488. $langs->load('companies');
  1489. if (empty($htmlid)) {
  1490. $htmlid = $htmlname;
  1491. }
  1492. $num = 0;
  1493. if ($selected === '') {
  1494. $selected = array();
  1495. } elseif (!is_array($selected)) {
  1496. $selected = array($selected);
  1497. }
  1498. $out = '';
  1499. if (!is_object($hookmanager)) {
  1500. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1501. $hookmanager = new HookManager($this->db);
  1502. }
  1503. // We search third parties
  1504. $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";
  1505. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1506. $sql .= ", s.nom as company, s.town AS company_town";
  1507. }
  1508. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
  1509. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1510. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=sp.fk_soc";
  1511. }
  1512. $sql .= " WHERE sp.entity IN (".getEntity('socpeople').")";
  1513. if ($socid > 0 || $socid == -1) {
  1514. $sql .= " AND sp.fk_soc = ".((int) $socid);
  1515. }
  1516. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1517. $sql .= " AND sp.statut <> 0";
  1518. }
  1519. $sql .= " ORDER BY sp.lastname ASC";
  1520. dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
  1521. $resql = $this->db->query($sql);
  1522. if ($resql) {
  1523. $num = $this->db->num_rows($resql);
  1524. if ($htmlname != 'none' && !$options_only) {
  1525. $out .= '<select class="flat'.($moreclass ? ' '.$moreclass : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1526. }
  1527. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
  1528. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1529. }
  1530. if ($showempty == 2) {
  1531. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1532. }
  1533. $i = 0;
  1534. if ($num) {
  1535. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1536. $contactstatic = new Contact($this->db);
  1537. while ($i < $num) {
  1538. $obj = $this->db->fetch_object($resql);
  1539. // Set email (or phones) and town extended infos
  1540. $extendedInfos = '';
  1541. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1542. $extendedInfos = array();
  1543. $email = trim($obj->email);
  1544. if (!empty($email)) {
  1545. $extendedInfos[] = $email;
  1546. } else {
  1547. $phone = trim($obj->phone);
  1548. $phone_perso = trim($obj->phone_perso);
  1549. $phone_mobile = trim($obj->phone_mobile);
  1550. if (!empty($phone)) {
  1551. $extendedInfos[] = $phone;
  1552. }
  1553. if (!empty($phone_perso)) {
  1554. $extendedInfos[] = $phone_perso;
  1555. }
  1556. if (!empty($phone_mobile)) {
  1557. $extendedInfos[] = $phone_mobile;
  1558. }
  1559. }
  1560. $contact_town = trim($obj->contact_town);
  1561. $company_town = trim($obj->company_town);
  1562. if (!empty($contact_town)) {
  1563. $extendedInfos[] = $contact_town;
  1564. } elseif (!empty($company_town)) {
  1565. $extendedInfos[] = $company_town;
  1566. }
  1567. $extendedInfos = implode(' - ', $extendedInfos);
  1568. if (!empty($extendedInfos)) {
  1569. $extendedInfos = ' - '.$extendedInfos;
  1570. }
  1571. }
  1572. $contactstatic->id = $obj->rowid;
  1573. $contactstatic->lastname = $obj->lastname;
  1574. $contactstatic->firstname = $obj->firstname;
  1575. if ($obj->statut == 1) {
  1576. if ($htmlname != 'none') {
  1577. $disabled = 0;
  1578. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1579. $disabled = 1;
  1580. }
  1581. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1582. $disabled = 1;
  1583. }
  1584. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1585. $out .= '<option value="'.$obj->rowid.'"';
  1586. if ($disabled) {
  1587. $out .= ' disabled';
  1588. }
  1589. $out .= ' selected>';
  1590. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1591. if ($showfunction && $obj->poste) {
  1592. $out .= ' ('.$obj->poste.')';
  1593. }
  1594. if (($showsoc > 0) && $obj->company) {
  1595. $out .= ' - ('.$obj->company.')';
  1596. }
  1597. $out .= '</option>';
  1598. } else {
  1599. $out .= '<option value="'.$obj->rowid.'"';
  1600. if ($disabled) {
  1601. $out .= ' disabled';
  1602. }
  1603. $out .= '>';
  1604. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1605. if ($showfunction && $obj->poste) {
  1606. $out .= ' ('.$obj->poste.')';
  1607. }
  1608. if (($showsoc > 0) && $obj->company) {
  1609. $out .= ' - ('.$obj->company.')';
  1610. }
  1611. $out .= '</option>';
  1612. }
  1613. } else {
  1614. if (in_array($obj->rowid, $selected)) {
  1615. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1616. if ($showfunction && $obj->poste) {
  1617. $out .= ' ('.$obj->poste.')';
  1618. }
  1619. if (($showsoc > 0) && $obj->company) {
  1620. $out .= ' - ('.$obj->company.')';
  1621. }
  1622. }
  1623. }
  1624. }
  1625. $i++;
  1626. }
  1627. } else {
  1628. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1629. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1630. $out .= $labeltoshow;
  1631. $out .= '</option>';
  1632. }
  1633. $parameters = array(
  1634. 'socid'=>$socid,
  1635. 'htmlname'=>$htmlname,
  1636. 'resql'=>$resql,
  1637. 'out'=>&$out,
  1638. 'showfunction'=>$showfunction,
  1639. 'showsoc'=>$showsoc,
  1640. );
  1641. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1642. if ($htmlname != 'none' && !$options_only) {
  1643. $out .= '</select>';
  1644. }
  1645. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1646. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1647. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1648. }
  1649. $this->num = $num;
  1650. return $out;
  1651. } else {
  1652. dol_print_error($this->db);
  1653. return -1;
  1654. }
  1655. }
  1656. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1657. /**
  1658. * Return the HTML select list of users
  1659. *
  1660. * @param string $selected Id user preselected
  1661. * @param string $htmlname Field name in form
  1662. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1663. * @param array $exclude Array list of users id to exclude
  1664. * @param int $disabled If select list must be disabled
  1665. * @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
  1666. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1667. * @param string $force_entity '0' or Ids of environment to force
  1668. * @return void
  1669. * @deprecated Use select_dolusers instead
  1670. * @see select_dolusers()
  1671. */
  1672. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1673. {
  1674. // phpcs:enable
  1675. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1676. }
  1677. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1678. /**
  1679. * Return select list of users
  1680. *
  1681. * @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)
  1682. * @param string $htmlname Field name in form
  1683. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1684. * @param array $exclude Array list of users id to exclude
  1685. * @param int $disabled If select list must be disabled
  1686. * @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
  1687. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1688. * @param string $force_entity '0' or Ids of environment to force
  1689. * @param int $maxlength Maximum length of string into list (0=no limit)
  1690. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1691. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1692. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1693. * @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.
  1694. * @param string $morecss More css
  1695. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1696. * @param int $outputmode 0=HTML select string, 1=Array
  1697. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1698. * @return string HTML select string
  1699. * @see select_dolgroups()
  1700. */
  1701. 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)
  1702. {
  1703. // phpcs:enable
  1704. global $conf, $user, $langs, $hookmanager;
  1705. // If no preselected user defined, we take current user
  1706. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1707. $selected = $user->id;
  1708. }
  1709. if ($selected === '') {
  1710. $selected = array();
  1711. } elseif (!is_array($selected)) {
  1712. $selected = array($selected);
  1713. }
  1714. $excludeUsers = null;
  1715. $includeUsers = null;
  1716. // Permettre l'exclusion d'utilisateurs
  1717. if (is_array($exclude)) {
  1718. $excludeUsers = implode(",", $exclude);
  1719. }
  1720. // Permettre l'inclusion d'utilisateurs
  1721. if (is_array($include)) {
  1722. $includeUsers = implode(",", $include);
  1723. } elseif ($include == 'hierarchy') {
  1724. // Build list includeUsers to have only hierarchy
  1725. $includeUsers = implode(",", $user->getAllChildIds(0));
  1726. } elseif ($include == 'hierarchyme') {
  1727. // Build list includeUsers to have only hierarchy and current user
  1728. $includeUsers = implode(",", $user->getAllChildIds(1));
  1729. }
  1730. $out = '';
  1731. $outarray = array();
  1732. // Forge request to select users
  1733. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1734. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1735. $sql .= ", e.label";
  1736. }
  1737. $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
  1738. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1739. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid = u.entity";
  1740. if ($force_entity) {
  1741. $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
  1742. } else {
  1743. $sql .= " WHERE u.entity IS NOT NULL";
  1744. }
  1745. } else {
  1746. if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1747. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
  1748. $sql .= " ON ug.fk_user = u.rowid";
  1749. $sql .= " WHERE ug.entity = ".$conf->entity;
  1750. } else {
  1751. $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
  1752. }
  1753. }
  1754. if (!empty($user->socid)) {
  1755. $sql .= " AND u.fk_soc = ".((int) $user->socid);
  1756. }
  1757. if (is_array($exclude) && $excludeUsers) {
  1758. $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
  1759. }
  1760. if ($includeUsers) {
  1761. $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
  1762. }
  1763. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) {
  1764. $sql .= " AND u.statut <> 0";
  1765. }
  1766. if (!empty($morefilter)) {
  1767. $sql .= " ".$morefilter;
  1768. }
  1769. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1770. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1771. if (!empty($reshook)) {
  1772. $sql .= $hookmanager->resPrint;
  1773. }
  1774. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1775. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1776. } else {
  1777. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1778. }
  1779. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1780. $resql = $this->db->query($sql);
  1781. if ($resql) {
  1782. $num = $this->db->num_rows($resql);
  1783. $i = 0;
  1784. if ($num) {
  1785. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1786. $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1787. if ($show_empty && !$multiple) {
  1788. $textforempty = ' ';
  1789. if (!empty($conf->use_javascript_ajax)) {
  1790. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1791. }
  1792. if (!is_numeric($show_empty)) {
  1793. $textforempty = $show_empty;
  1794. }
  1795. $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  1796. }
  1797. if ($show_every) {
  1798. $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1799. }
  1800. $userstatic = new User($this->db);
  1801. while ($i < $num) {
  1802. $obj = $this->db->fetch_object($resql);
  1803. $userstatic->id = $obj->rowid;
  1804. $userstatic->lastname = $obj->lastname;
  1805. $userstatic->firstname = $obj->firstname;
  1806. $userstatic->photo = $obj->photo;
  1807. $userstatic->statut = $obj->status;
  1808. $userstatic->entity = $obj->entity;
  1809. $userstatic->admin = $obj->admin;
  1810. $disableline = '';
  1811. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1812. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1813. }
  1814. $labeltoshow = '';
  1815. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1816. $fullNameMode = 0;
  1817. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1818. $fullNameMode = 1; //Firstname+lastname
  1819. }
  1820. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1821. if (empty($obj->firstname) && empty($obj->lastname)) {
  1822. $labeltoshow .= $obj->login;
  1823. }
  1824. // Complete name with more info
  1825. $moreinfo = '';
  1826. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1827. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1828. }
  1829. if ($showstatus >= 0) {
  1830. if ($obj->status == 1 && $showstatus == 1) {
  1831. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1832. }
  1833. if ($obj->status == 0 && $showstatus == 1) {
  1834. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1835. }
  1836. }
  1837. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1838. if (!$obj->entity) {
  1839. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1840. } else {
  1841. if ($obj->entity != $conf->entity) {
  1842. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1843. }
  1844. }
  1845. }
  1846. $moreinfo .= ($moreinfo ? ')' : '');
  1847. if ($disableline && $disableline != '1') {
  1848. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1849. }
  1850. $labeltoshow .= $moreinfo;
  1851. $out .= '<option value="'.$obj->rowid.'"';
  1852. if ($disableline) {
  1853. $out .= ' disabled';
  1854. }
  1855. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1856. $out .= ' selected';
  1857. }
  1858. $out .= ' data-html="';
  1859. $outhtml = '';
  1860. // if (!empty($obj->photo)) {
  1861. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1862. // }
  1863. if ($showstatus >= 0 && $obj->status == 0) {
  1864. $outhtml .= '<strike class="opacitymediumxxx">';
  1865. }
  1866. $outhtml .= $labeltoshow;
  1867. if ($showstatus >= 0 && $obj->status == 0) {
  1868. $outhtml .= '</strike>';
  1869. }
  1870. $out .= dol_escape_htmltag($outhtml);
  1871. $out .= '">';
  1872. $out .= $labeltoshow;
  1873. $out .= '</option>';
  1874. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1875. $i++;
  1876. }
  1877. } else {
  1878. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1879. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1880. }
  1881. $out .= '</select>';
  1882. if ($num) {
  1883. // Enhance with select2
  1884. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1885. $out = ajax_combobox($htmlname).$out;
  1886. }
  1887. } else {
  1888. dol_print_error($this->db);
  1889. }
  1890. if ($outputmode) {
  1891. return $outarray;
  1892. }
  1893. return $out;
  1894. }
  1895. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1896. /**
  1897. * Return select list of users. Selected users are stored into session.
  1898. * List of users are provided into $_SESSION['assignedtouser'].
  1899. *
  1900. * @param string $action Value for $action
  1901. * @param string $htmlname Field name in form
  1902. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1903. * @param array $exclude Array list of users id to exclude
  1904. * @param int $disabled If select list must be disabled
  1905. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1906. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1907. * @param int $force_entity '0' or Ids of environment to force
  1908. * @param int $maxlength Maximum length of string into list (0=no limit)
  1909. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1910. * @param string $morefilter Add more filters into sql request
  1911. * @param int $showproperties Show properties of each attendees
  1912. * @param array $listofuserid Array with properties of each user
  1913. * @param array $listofcontactid Array with properties of each contact
  1914. * @param array $listofotherid Array with properties of each other contact
  1915. * @return string HTML select string
  1916. * @see select_dolgroups()
  1917. */
  1918. 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())
  1919. {
  1920. // phpcs:enable
  1921. global $conf, $user, $langs;
  1922. $userstatic = new User($this->db);
  1923. $out = '';
  1924. $assignedtouser = array();
  1925. if (!empty($_SESSION['assignedtouser'])) {
  1926. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1927. }
  1928. $nbassignetouser = count($assignedtouser);
  1929. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1930. if ($nbassignetouser) {
  1931. $out .= '<ul class="attendees">';
  1932. }
  1933. $i = 0;
  1934. $ownerid = 0;
  1935. foreach ($assignedtouser as $key => $value) {
  1936. if ($value['id'] == $ownerid) {
  1937. continue;
  1938. }
  1939. $out .= '<li>';
  1940. $userstatic->fetch($value['id']);
  1941. $out .= $userstatic->getNomUrl(-1);
  1942. if ($i == 0) {
  1943. $ownerid = $value['id'];
  1944. $out .= ' ('.$langs->trans("Owner").')';
  1945. }
  1946. if ($nbassignetouser > 1 && $action != 'view') {
  1947. $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.'">';
  1948. }
  1949. // Show my availability
  1950. if ($showproperties) {
  1951. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  1952. $out .= '<div class="myavailability inline-block">';
  1953. $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>';
  1954. $out .= '</div>';
  1955. }
  1956. }
  1957. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1958. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1959. $out .= '</li>';
  1960. $i++;
  1961. }
  1962. if ($nbassignetouser) {
  1963. $out .= '</ul>';
  1964. }
  1965. // Method with no ajax
  1966. if ($action != 'view') {
  1967. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1968. $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
  1969. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  1970. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  1971. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  1972. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  1973. $out .= '});';
  1974. $out .= '})</script>';
  1975. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1976. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1977. $out .= '<br>';
  1978. }
  1979. return $out;
  1980. }
  1981. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1982. /**
  1983. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1984. *
  1985. * @param int $selected Preselected products
  1986. * @param string $htmlname Name of HTML select field (must be unique in page).
  1987. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1988. * @param int $limit Limit on number of returned lines
  1989. * @param int $price_level Level of price to show
  1990. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1991. * @param int $finished 2=all, 1=finished, 0=raw material
  1992. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1993. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1994. * @param array $ajaxoptions Options for ajax_autocompleter
  1995. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1996. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1997. * @param int $forcecombo Force to use combo box
  1998. * @param string $morecss Add more css on select
  1999. * @param int $hidepriceinlabel 1=Hide prices in label
  2000. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2001. * 'warehouseopen' = count products from open warehouses,
  2002. * 'warehouseclosed' = count products from closed warehouses,
  2003. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2004. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2005. * @param string $nooutput No print, return the output into a string
  2006. * @return void|string
  2007. */
  2008. 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)
  2009. {
  2010. // phpcs:enable
  2011. global $langs, $conf;
  2012. $out = '';
  2013. // check parameters
  2014. $price_level = (!empty($price_level) ? $price_level : 0);
  2015. if (is_null($ajaxoptions)) {
  2016. $ajaxoptions = array();
  2017. }
  2018. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  2019. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  2020. $filtertype = '0';
  2021. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  2022. $filtertype = '1';
  2023. }
  2024. }
  2025. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2026. $placeholder = '';
  2027. if ($selected && empty($selected_input_value)) {
  2028. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2029. $producttmpselect = new Product($this->db);
  2030. $producttmpselect->fetch($selected);
  2031. $selected_input_value = $producttmpselect->ref;
  2032. unset($producttmpselect);
  2033. }
  2034. // handle case where product or service module is disabled + no filter specified
  2035. if ($filtertype == '') {
  2036. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2037. $filtertype = 1;
  2038. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2039. $filtertype = 0;
  2040. }
  2041. }
  2042. // mode=1 means customers products
  2043. $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  2044. //Price by customer
  2045. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2046. $urloption .= '&socid='.$socid;
  2047. }
  2048. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2049. if (!empty($conf->variants->enabled) && is_array($selected_combinations)) {
  2050. // Code to automatically insert with javascript the select of attributes under the select of product
  2051. // when a parent of variant has been selected.
  2052. $out .= '
  2053. <!-- script to auto show attributes select tags if a variant was selected -->
  2054. <script>
  2055. // auto show attributes fields
  2056. selected = '.json_encode($selected_combinations).';
  2057. combvalues = {};
  2058. jQuery(document).ready(function () {
  2059. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2060. if (jQuery(this).val() == \'free\') {
  2061. jQuery(\'div#attributes_box\').empty();
  2062. }
  2063. });
  2064. jQuery("input#'.$htmlname.'").change(function () {
  2065. if (!jQuery(this).val()) {
  2066. jQuery(\'div#attributes_box\').empty();
  2067. return;
  2068. }
  2069. console.log("A change has started. We get variants fields to inject html select");
  2070. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  2071. id: jQuery(this).val()
  2072. }, function (data) {
  2073. jQuery(\'div#attributes_box\').empty();
  2074. jQuery.each(data, function (key, val) {
  2075. combvalues[val.id] = val.values;
  2076. var span = jQuery(document.createElement(\'div\')).css({
  2077. \'display\': \'table-row\'
  2078. });
  2079. span.append(
  2080. jQuery(document.createElement(\'div\')).text(val.label).css({
  2081. \'font-weight\': \'bold\',
  2082. \'display\': \'table-cell\'
  2083. })
  2084. );
  2085. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2086. \'margin-left\': \'15px\',
  2087. \'white-space\': \'pre\'
  2088. }).append(
  2089. jQuery(document.createElement(\'option\')).val(\'\')
  2090. );
  2091. jQuery.each(combvalues[val.id], function (key, val) {
  2092. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2093. if (selected[val.fk_product_attribute] == val.id) {
  2094. tag.attr(\'selected\', \'selected\');
  2095. }
  2096. html.append(tag);
  2097. });
  2098. span.append(html);
  2099. jQuery(\'div#attributes_box\').append(span);
  2100. });
  2101. })
  2102. });
  2103. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  2104. });
  2105. </script>
  2106. ';
  2107. }
  2108. if (empty($hidelabel)) {
  2109. $out .= $langs->trans("RefOrLabel").' : ';
  2110. } elseif ($hidelabel > 1) {
  2111. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  2112. if ($hidelabel == 2) {
  2113. $out .= img_picto($langs->trans("Search"), 'search');
  2114. }
  2115. }
  2116. $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' : '').' />';
  2117. if ($hidelabel == 3) {
  2118. $out .= img_picto($langs->trans("Search"), 'search');
  2119. }
  2120. } else {
  2121. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus);
  2122. }
  2123. if (empty($nooutput)) {
  2124. print $out;
  2125. } else {
  2126. return $out;
  2127. }
  2128. }
  2129. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2130. /**
  2131. * Return list of products for a customer.
  2132. * Called by select_produits.
  2133. *
  2134. * @param int $selected Preselected product
  2135. * @param string $htmlname Name of select html
  2136. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2137. * @param int $limit Limit on number of returned lines
  2138. * @param int $price_level Level of price to show
  2139. * @param string $filterkey Filter on product
  2140. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2141. * @param int $finished Filter on finished field: 2=No filter
  2142. * @param int $outputmode 0=HTML select string, 1=Array
  2143. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2144. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2145. * @param int $forcecombo Force to use combo box
  2146. * @param string $morecss Add more css on select
  2147. * @param int $hidepriceinlabel 1=Hide prices in label
  2148. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2149. * 'warehouseopen' = count products from open warehouses,
  2150. * 'warehouseclosed' = count products from closed warehouses,
  2151. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2152. * @return array Array of keys for json
  2153. */
  2154. 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 = '')
  2155. {
  2156. // phpcs:enable
  2157. global $langs, $conf, $user, $db;
  2158. $out = '';
  2159. $outarray = array();
  2160. // Units
  2161. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2162. $langs->load('other');
  2163. }
  2164. $warehouseStatusArray = array();
  2165. if (!empty($warehouseStatus)) {
  2166. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2167. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2168. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2169. }
  2170. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2171. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2172. }
  2173. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2174. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2175. }
  2176. }
  2177. $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";
  2178. if (count($warehouseStatusArray)) {
  2179. $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
  2180. } else {
  2181. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  2182. }
  2183. $sql = "SELECT ";
  2184. $sql .= $selectFields.$selectFieldsGrouped;
  2185. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2186. //Product category
  2187. $sql .= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
  2188. FROM ".MAIN_DB_PREFIX."categorie_product
  2189. WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
  2190. LIMIT 1
  2191. ) AS categorie_product_id ";
  2192. }
  2193. //Price by customer
  2194. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2195. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2196. $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';
  2197. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2198. }
  2199. // Units
  2200. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2201. $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";
  2202. $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';
  2203. }
  2204. // Multilang : we add translation
  2205. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2206. $sql .= ", pl.label as label_translated";
  2207. $sql .= ", pl.description as description_translated";
  2208. $selectFields .= ", label_translated";
  2209. $selectFields .= ", description_translated";
  2210. }
  2211. // Price by quantity
  2212. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2213. $sql .= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  2214. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2215. $sql .= " AND price_level = ".((int) $price_level);
  2216. }
  2217. $sql .= " ORDER BY date_price";
  2218. $sql .= " DESC LIMIT 1) as price_rowid";
  2219. $sql .= ", (SELECT pp.price_by_qty FROM ".MAIN_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
  2220. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2221. $sql .= " AND price_level = ".((int) $price_level);
  2222. }
  2223. $sql .= " ORDER BY date_price";
  2224. $sql .= " DESC LIMIT 1) as price_by_qty";
  2225. $selectFields .= ", price_rowid, price_by_qty";
  2226. }
  2227. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2228. if (count($warehouseStatusArray)) {
  2229. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
  2230. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  2231. $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.
  2232. }
  2233. // include search in supplier ref
  2234. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2235. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2236. }
  2237. //Price by customer
  2238. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2239. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
  2240. }
  2241. // Units
  2242. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2243. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  2244. }
  2245. // Multilang : we add translation
  2246. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2247. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid ";
  2248. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2249. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  2250. $soc = new Societe($db);
  2251. $result = $soc->fetch($socid);
  2252. if ($result > 0 && !empty($soc->default_lang)) {
  2253. $sql .= " AND pl.lang = '".$this->db->escape($soc->default_lang)."'";
  2254. } else {
  2255. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2256. }
  2257. } else {
  2258. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2259. }
  2260. }
  2261. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2262. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2263. }
  2264. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  2265. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2266. $sql .= " AND pac.rowid IS NULL";
  2267. }
  2268. if ($finished == 0) {
  2269. $sql .= " AND p.finished = ".((int) $finished);
  2270. } elseif ($finished == 1) {
  2271. $sql .= " AND p.finished = ".((int) $finished);
  2272. if ($status >= 0) {
  2273. $sql .= " AND p.tosell = ".((int) $status);
  2274. }
  2275. } elseif ($status >= 0) {
  2276. $sql .= " AND p.tosell = ".((int) $status);
  2277. }
  2278. // Filter by product type
  2279. if (strval($filtertype) != '') {
  2280. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2281. } elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2282. $sql .= " AND p.fk_product_type = 1";
  2283. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2284. $sql .= " AND p.fk_product_type = 0";
  2285. }
  2286. // Add criteria on ref/label
  2287. if ($filterkey != '') {
  2288. $sql .= ' AND (';
  2289. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2290. // For natural search
  2291. $scrit = explode(' ', $filterkey);
  2292. $i = 0;
  2293. if (count($scrit) > 1) {
  2294. $sql .= "(";
  2295. }
  2296. foreach ($scrit as $crit) {
  2297. if ($i > 0) {
  2298. $sql .= " AND ";
  2299. }
  2300. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2301. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2302. $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2303. }
  2304. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && ! empty($socid)) {
  2305. $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
  2306. }
  2307. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2308. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2309. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2310. $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2311. }
  2312. }
  2313. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2314. $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2315. }
  2316. $sql .= ")";
  2317. $i++;
  2318. }
  2319. if (count($scrit) > 1) {
  2320. $sql .= ")";
  2321. }
  2322. if (!empty($conf->barcode->enabled)) {
  2323. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2324. }
  2325. $sql .= ')';
  2326. }
  2327. if (count($warehouseStatusArray)) {
  2328. $sql .= " GROUP BY ".$selectFields;
  2329. }
  2330. //Sort by category
  2331. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2332. $sql .= " ORDER BY categorie_product_id ";
  2333. //ASC OR DESC order
  2334. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2335. } else {
  2336. $sql .= $this->db->order("p.ref");
  2337. }
  2338. $sql .= $this->db->plimit($limit, 0);
  2339. // Build output string
  2340. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2341. $result = $this->db->query($sql);
  2342. if ($result) {
  2343. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2344. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2345. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2346. $num = $this->db->num_rows($result);
  2347. $events = null;
  2348. if (!$forcecombo) {
  2349. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2350. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2351. }
  2352. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2353. $textifempty = '';
  2354. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2355. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2356. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2357. if ($showempty && !is_numeric($showempty)) {
  2358. $textifempty = $langs->trans($showempty);
  2359. } else {
  2360. $textifempty .= $langs->trans("All");
  2361. }
  2362. } else {
  2363. if ($showempty && !is_numeric($showempty)) {
  2364. $textifempty = $langs->trans($showempty);
  2365. }
  2366. }
  2367. if ($showempty) {
  2368. $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
  2369. }
  2370. $i = 0;
  2371. while ($num && $i < $num) {
  2372. $opt = '';
  2373. $optJson = array();
  2374. $objp = $this->db->fetch_object($result);
  2375. 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
  2376. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2377. $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
  2378. $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
  2379. $sql .= " ORDER BY quantity ASC";
  2380. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2381. $result2 = $this->db->query($sql);
  2382. if ($result2) {
  2383. $nb_prices = $this->db->num_rows($result2);
  2384. $j = 0;
  2385. while ($nb_prices && $j < $nb_prices) {
  2386. $objp2 = $this->db->fetch_object($result2);
  2387. $objp->price_by_qty_rowid = $objp2->rowid;
  2388. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2389. $objp->price_by_qty_quantity = $objp2->quantity;
  2390. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2391. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2392. // For backward compatibility
  2393. $objp->quantity = $objp2->quantity;
  2394. $objp->price = $objp2->price;
  2395. $objp->unitprice = $objp2->unitprice;
  2396. $objp->remise_percent = $objp2->remise_percent;
  2397. $objp->remise = $objp2->remise;
  2398. //$objp->tva_tx is not overwritten by $objp2 value
  2399. //$objp->default_vat_code is not overwritten by $objp2 value
  2400. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2401. $j++;
  2402. // Add new entry
  2403. // "key" value of json key array is used by jQuery automatically as selected value
  2404. // "label" value of json key array is used by jQuery automatically as text for combo box
  2405. $out .= $opt;
  2406. array_push($outarray, $optJson);
  2407. }
  2408. }
  2409. } else {
  2410. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2411. $price_product = new Product($this->db);
  2412. $price_product->fetch($objp->rowid, '', '', 1);
  2413. $priceparser = new PriceParser($this->db);
  2414. $price_result = $priceparser->parseProduct($price_product);
  2415. if ($price_result >= 0) {
  2416. $objp->price = $price_result;
  2417. $objp->unitprice = $price_result;
  2418. //Calculate the VAT
  2419. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2420. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2421. }
  2422. }
  2423. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2424. // Add new entry
  2425. // "key" value of json key array is used by jQuery automatically as selected value
  2426. // "label" value of json key array is used by jQuery automatically as text for combo box
  2427. $out .= $opt;
  2428. array_push($outarray, $optJson);
  2429. }
  2430. $i++;
  2431. }
  2432. $out .= '</select>';
  2433. $this->db->free($result);
  2434. if (empty($outputmode)) {
  2435. return $out;
  2436. }
  2437. return $outarray;
  2438. } else {
  2439. dol_print_error($db);
  2440. }
  2441. }
  2442. /**
  2443. * Function to forge the string with OPTIONs of SELECT.
  2444. * This define value for &$opt and &$optJson.
  2445. * This function is called by select_produits_list().
  2446. *
  2447. * @param resource $objp Resultset of fetch
  2448. * @param string $opt Option (var used for returned value in string option format)
  2449. * @param string $optJson Option (var used for returned value in json format)
  2450. * @param int $price_level Price level
  2451. * @param string $selected Preselected value
  2452. * @param int $hidepriceinlabel Hide price in label
  2453. * @param string $filterkey Filter key to highlight
  2454. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2455. * @return void
  2456. */
  2457. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2458. {
  2459. global $langs, $conf, $user, $db;
  2460. $outkey = '';
  2461. $outval = '';
  2462. $outref = '';
  2463. $outlabel = '';
  2464. $outlabel_translated = '';
  2465. $outdesc = '';
  2466. $outdesc_translated = '';
  2467. $outbarcode = '';
  2468. $outorigin = '';
  2469. $outtype = '';
  2470. $outprice_ht = '';
  2471. $outprice_ttc = '';
  2472. $outpricebasetype = '';
  2473. $outtva_tx = '';
  2474. $outdefault_vat_code = '';
  2475. $outqty = 1;
  2476. $outdiscount = 0;
  2477. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2478. $label = $objp->label;
  2479. if (!empty($objp->label_translated)) {
  2480. $label = $objp->label_translated;
  2481. }
  2482. if (!empty($filterkey) && $filterkey != '') {
  2483. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2484. }
  2485. $outkey = $objp->rowid;
  2486. $outref = $objp->ref;
  2487. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2488. $outlabel = $objp->label;
  2489. $outdesc = $objp->description;
  2490. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2491. $outlabel_translated = $objp->label_translated;
  2492. $outdesc_translated = $objp->description_translated;
  2493. }
  2494. $outbarcode = $objp->barcode;
  2495. $outorigin = $objp->fk_country;
  2496. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2497. $outtype = $objp->fk_product_type;
  2498. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2499. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2500. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2501. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2502. }
  2503. // Units
  2504. $outvalUnits = '';
  2505. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2506. if (!empty($objp->unit_short)) {
  2507. $outvalUnits .= ' - '.$objp->unit_short;
  2508. }
  2509. }
  2510. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2511. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2512. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2513. $outvalUnits .= ' - '.$unitToShow;
  2514. }
  2515. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2516. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2517. $outvalUnits .= ' - '.$unitToShow;
  2518. }
  2519. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2520. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2521. $outvalUnits .= ' - '.$unitToShow;
  2522. }
  2523. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2524. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2525. $outvalUnits .= ' - '.$unitToShow;
  2526. }
  2527. }
  2528. if ($outdurationvalue && $outdurationunit) {
  2529. $da = array(
  2530. 'h' => $langs->trans('Hour'),
  2531. 'd' => $langs->trans('Day'),
  2532. 'w' => $langs->trans('Week'),
  2533. 'm' => $langs->trans('Month'),
  2534. 'y' => $langs->trans('Year')
  2535. );
  2536. if (isset($da[$outdurationunit])) {
  2537. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2538. }
  2539. }
  2540. $opt = '<option value="'.$objp->rowid.'"';
  2541. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2542. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2543. $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.'"';
  2544. }
  2545. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2546. if (!empty($user->rights->stock->lire)) {
  2547. if ($objp->stock > 0) {
  2548. $opt .= ' class="product_line_stock_ok"';
  2549. } elseif ($objp->stock <= 0) {
  2550. $opt .= ' class="product_line_stock_too_low"';
  2551. }
  2552. }
  2553. }
  2554. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2555. $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
  2556. $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
  2557. }
  2558. $opt .= '>';
  2559. $opt .= $objp->ref;
  2560. if (! empty($objp->custref)) {
  2561. $opt.= ' (' . $objp->custref . ')';
  2562. }
  2563. if ($outbarcode) {
  2564. $opt .= ' ('.$outbarcode.')';
  2565. }
  2566. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2567. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2568. $opt .= ' ('.getCountry($outorigin, 1).')';
  2569. }
  2570. $objRef = $objp->ref;
  2571. if (! empty($objp->custref)) {
  2572. $objRef .= ' (' . $objp->custref . ')';
  2573. }
  2574. if (!empty($filterkey) && $filterkey != '') {
  2575. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2576. }
  2577. $outval .= $objRef;
  2578. if ($outbarcode) {
  2579. $outval .= ' ('.$outbarcode.')';
  2580. }
  2581. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2582. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2583. $outval .= ' ('.getCountry($outorigin, 1).')';
  2584. }
  2585. // Units
  2586. $opt .= $outvalUnits;
  2587. $outval .= $outvalUnits;
  2588. $found = 0;
  2589. // Multiprice
  2590. // If we need a particular price level (from 1 to n)
  2591. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2592. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2593. $sql .= " FROM ".MAIN_DB_PREFIX."product_price";
  2594. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2595. $sql .= " AND entity IN (".getEntity('productprice').")";
  2596. $sql .= " AND price_level = ".((int) $price_level);
  2597. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2598. $sql .= " LIMIT 1";
  2599. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2600. $result2 = $this->db->query($sql);
  2601. if ($result2) {
  2602. $objp2 = $this->db->fetch_object($result2);
  2603. if ($objp2) {
  2604. $found = 1;
  2605. if ($objp2->price_base_type == 'HT') {
  2606. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2607. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2608. } else {
  2609. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2610. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2611. }
  2612. $outprice_ht = price($objp2->price);
  2613. $outprice_ttc = price($objp2->price_ttc);
  2614. $outpricebasetype = $objp2->price_base_type;
  2615. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2616. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2617. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2618. } else {
  2619. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2620. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2621. }
  2622. }
  2623. } else {
  2624. dol_print_error($this->db);
  2625. }
  2626. }
  2627. // Price by quantity
  2628. 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))) {
  2629. $found = 1;
  2630. $outqty = $objp->quantity;
  2631. $outdiscount = $objp->remise_percent;
  2632. if ($objp->quantity == 1) {
  2633. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2634. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2635. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2636. $outval .= $langs->transnoentities("Unit");
  2637. } else {
  2638. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2639. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2640. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2641. $outval .= $langs->transnoentities("Units");
  2642. }
  2643. $outprice_ht = price($objp->unitprice);
  2644. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2645. $outpricebasetype = $objp->price_base_type;
  2646. $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
  2647. $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
  2648. }
  2649. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2650. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2651. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2652. }
  2653. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2654. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2655. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2656. }
  2657. // Price by customer
  2658. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2659. if (!empty($objp->idprodcustprice)) {
  2660. $found = 1;
  2661. if ($objp->custprice_base_type == 'HT') {
  2662. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2663. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2664. } else {
  2665. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2666. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2667. }
  2668. $outprice_ht = price($objp->custprice);
  2669. $outprice_ttc = price($objp->custprice_ttc);
  2670. $outpricebasetype = $objp->custprice_base_type;
  2671. $outtva_tx = $objp->custtva_tx;
  2672. $outdefault_vat_code = $objp->custdefault_vat_code;
  2673. }
  2674. }
  2675. // If level no defined or multiprice not found, we used the default price
  2676. if (empty($hidepriceinlabel) && !$found) {
  2677. if ($objp->price_base_type == 'HT') {
  2678. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2679. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2680. } else {
  2681. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2682. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2683. }
  2684. $outprice_ht = price($objp->price);
  2685. $outprice_ttc = price($objp->price_ttc);
  2686. $outpricebasetype = $objp->price_base_type;
  2687. $outtva_tx = $objp->tva_tx;
  2688. $outdefault_vat_code = $objp->default_vat_code;
  2689. }
  2690. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2691. if (!empty($user->rights->stock->lire)) {
  2692. $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  2693. if ($objp->stock > 0) {
  2694. $outval .= ' - <span class="product_line_stock_ok">';
  2695. } elseif ($objp->stock <= 0) {
  2696. $outval .= ' - <span class="product_line_stock_too_low">';
  2697. }
  2698. $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
  2699. $outval .= '</span>';
  2700. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2701. $langs->load("stocks");
  2702. $tmpproduct = new Product($this->db);
  2703. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2704. $tmpproduct->load_virtual_stock();
  2705. $virtualstock = $tmpproduct->stock_theorique;
  2706. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2707. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2708. if ($virtualstock > 0) {
  2709. $outval .= '<span class="product_line_stock_ok">';
  2710. } elseif ($virtualstock <= 0) {
  2711. $outval .= '<span class="product_line_stock_too_low">';
  2712. }
  2713. $outval .= $virtualstock;
  2714. $outval .= '</span>';
  2715. unset($tmpproduct);
  2716. }
  2717. }
  2718. }
  2719. $opt .= "</option>\n";
  2720. $optJson = array(
  2721. 'key'=>$outkey,
  2722. 'value'=>$outref,
  2723. 'label'=>$outval,
  2724. 'label2'=>$outlabel,
  2725. 'desc'=>$outdesc,
  2726. 'type'=>$outtype,
  2727. 'price_ht'=>price2num($outprice_ht),
  2728. 'price_ttc'=>price2num($outprice_ttc),
  2729. 'pricebasetype'=>$outpricebasetype,
  2730. 'tva_tx'=>$outtva_tx,
  2731. 'default_vat_code'=>$outdefault_vat_code,
  2732. 'qty'=>$outqty,
  2733. 'discount'=>$outdiscount,
  2734. 'duration_value'=>$outdurationvalue,
  2735. 'duration_unit'=>$outdurationunit,
  2736. 'pbq'=>$outpbq,
  2737. 'labeltrans'=>$outlabel_translated,
  2738. 'desctrans'=>$outdesc_translated,
  2739. 'ref_customer'=>$outrefcust
  2740. );
  2741. }
  2742. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2743. /**
  2744. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2745. *
  2746. * @param int $socid Id third party
  2747. * @param string $selected Preselected product
  2748. * @param string $htmlname Name of HTML Select
  2749. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2750. * @param string $filtre For a SQL filter
  2751. * @param array $ajaxoptions Options for ajax_autocompleter
  2752. * @param int $hidelabel Hide label (0=no, 1=yes)
  2753. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2754. * @param string $morecss More CSS
  2755. * @param string $placeholder Placeholder
  2756. * @return void
  2757. */
  2758. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2759. {
  2760. // phpcs:enable
  2761. global $langs, $conf;
  2762. global $price_level, $status, $finished;
  2763. if (!isset($status)) {
  2764. $status = 1;
  2765. }
  2766. $selected_input_value = '';
  2767. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2768. if ($selected > 0) {
  2769. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2770. $producttmpselect = new Product($this->db);
  2771. $producttmpselect->fetch($selected);
  2772. $selected_input_value = $producttmpselect->ref;
  2773. unset($producttmpselect);
  2774. }
  2775. // mode=2 means suppliers products
  2776. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2777. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2778. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
  2779. } else {
  2780. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2781. }
  2782. }
  2783. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2784. /**
  2785. * Return list of suppliers products
  2786. *
  2787. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2788. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2789. * @param string $htmlname Name of HTML select
  2790. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2791. * @param string $filtre Generic filter. Data must not come from user input.
  2792. * @param string $filterkey Filter of produdts
  2793. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2794. * @param int $outputmode 0=HTML select string, 1=Array
  2795. * @param int $limit Limit of line number
  2796. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2797. * @param string $morecss Add more CSS
  2798. * @param int $showstockinlist Show stock information (slower).
  2799. * @param string $placeholder Placeholder
  2800. * @return array Array of keys for json
  2801. */
  2802. 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 = '')
  2803. {
  2804. // phpcs:enable
  2805. global $langs, $conf, $db, $user;
  2806. $out = '';
  2807. $outarray = array();
  2808. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2809. $langs->load('stocks');
  2810. // Units
  2811. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2812. $langs->load('other');
  2813. }
  2814. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock,";
  2815. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2816. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  2817. $sql .= " pfp.supplier_reputation";
  2818. // if we use supplier description of the products
  2819. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2820. $sql .= " ,pfp.desc_fourn as description";
  2821. } else {
  2822. $sql .= " ,p.description";
  2823. }
  2824. // Units
  2825. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2826. $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";
  2827. }
  2828. if (!empty($conf->barcode->enabled)) {
  2829. $sql .= ", pfp.barcode";
  2830. }
  2831. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2832. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2833. if ($socid > 0) {
  2834. $sql .= " AND pfp.fk_soc = ".((int) $socid);
  2835. }
  2836. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2837. // Units
  2838. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2839. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  2840. }
  2841. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2842. if ($statut != -1) {
  2843. $sql .= " AND p.tobuy = ".((int) $statut);
  2844. }
  2845. if (strval($filtertype) != '') {
  2846. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2847. }
  2848. if (!empty($filtre)) {
  2849. $sql .= " ".$filtre;
  2850. }
  2851. // Add criteria on ref/label
  2852. if ($filterkey != '') {
  2853. $sql .= ' AND (';
  2854. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2855. // For natural search
  2856. $scrit = explode(' ', $filterkey);
  2857. $i = 0;
  2858. if (count($scrit) > 1) {
  2859. $sql .= "(";
  2860. }
  2861. foreach ($scrit as $crit) {
  2862. if ($i > 0) {
  2863. $sql .= " AND ";
  2864. }
  2865. $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)."%'";
  2866. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2867. $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2868. }
  2869. $sql .= ")";
  2870. $i++;
  2871. }
  2872. if (count($scrit) > 1) {
  2873. $sql .= ")";
  2874. }
  2875. if (!empty($conf->barcode->enabled)) {
  2876. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2877. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2878. }
  2879. $sql .= ')';
  2880. }
  2881. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2882. $sql .= $this->db->plimit($limit, 0);
  2883. // Build output string
  2884. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2885. $result = $this->db->query($sql);
  2886. if ($result) {
  2887. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2888. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2889. $num = $this->db->num_rows($result);
  2890. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2891. $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2892. if (!$selected) {
  2893. $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2894. } else {
  2895. $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2896. }
  2897. $i = 0;
  2898. while ($i < $num) {
  2899. $objp = $this->db->fetch_object($result);
  2900. $outkey = $objp->idprodfournprice; // id in table of price
  2901. if (!$outkey && $alsoproductwithnosupplierprice) {
  2902. $outkey = 'idprod_'.$objp->rowid; // id of product
  2903. }
  2904. $outref = $objp->ref;
  2905. $outval = '';
  2906. $outbarcode = $objp->barcode;
  2907. $outqty = 1;
  2908. $outdiscount = 0;
  2909. $outtype = $objp->fk_product_type;
  2910. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2911. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2912. // Units
  2913. $outvalUnits = '';
  2914. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2915. if (!empty($objp->unit_short)) {
  2916. $outvalUnits .= ' - '.$objp->unit_short;
  2917. }
  2918. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2919. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2920. $outvalUnits .= ' - '.$unitToShow;
  2921. }
  2922. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2923. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2924. $outvalUnits .= ' - '.$unitToShow;
  2925. }
  2926. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2927. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2928. $outvalUnits .= ' - '.$unitToShow;
  2929. }
  2930. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2931. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2932. $outvalUnits .= ' - '.$unitToShow;
  2933. }
  2934. if ($outdurationvalue && $outdurationunit) {
  2935. $da = array(
  2936. 'h' => $langs->trans('Hour'),
  2937. 'd' => $langs->trans('Day'),
  2938. 'w' => $langs->trans('Week'),
  2939. 'm' => $langs->trans('Month'),
  2940. 'y' => $langs->trans('Year')
  2941. );
  2942. if (isset($da[$outdurationunit])) {
  2943. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2944. }
  2945. }
  2946. }
  2947. $objRef = $objp->ref;
  2948. if ($filterkey && $filterkey != '') {
  2949. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2950. }
  2951. $objRefFourn = $objp->ref_fourn;
  2952. if ($filterkey && $filterkey != '') {
  2953. $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  2954. }
  2955. $label = $objp->label;
  2956. if ($filterkey && $filterkey != '') {
  2957. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2958. }
  2959. $optlabel = $objp->ref;
  2960. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2961. $optlabel .= ' <span class="opacitymedium">('.$objp->ref_fourn.')</span>';
  2962. }
  2963. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2964. $optlabel .= ' ('.$outbarcode.')';
  2965. }
  2966. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2967. $outvallabel = $objRef;
  2968. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2969. $outvallabel .= ' ('.$objRefFourn.')';
  2970. }
  2971. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2972. $outvallabel .= ' ('.$outbarcode.')';
  2973. }
  2974. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2975. // Units
  2976. $optlabel .= $outvalUnits;
  2977. $outvallabel .= $outvalUnits;
  2978. if (!empty($objp->idprodfournprice)) {
  2979. $outqty = $objp->quantity;
  2980. $outdiscount = $objp->remise_percent;
  2981. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2982. $prod_supplier = new ProductFournisseur($this->db);
  2983. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2984. $prod_supplier->id = $objp->fk_product;
  2985. $prod_supplier->fourn_qty = $objp->quantity;
  2986. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2987. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2988. $priceparser = new PriceParser($this->db);
  2989. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2990. if ($price_result >= 0) {
  2991. $objp->fprice = $price_result;
  2992. if ($objp->quantity >= 1) {
  2993. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  2994. }
  2995. }
  2996. }
  2997. if ($objp->quantity == 1) {
  2998. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  2999. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  3000. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3001. $outvallabel .= $langs->transnoentities("Unit");
  3002. } else {
  3003. $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;
  3004. $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;
  3005. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3006. $outvallabel .= ' '.$langs->transnoentities("Units");
  3007. }
  3008. if ($objp->quantity > 1) {
  3009. $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
  3010. $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
  3011. }
  3012. if ($objp->remise_percent >= 1) {
  3013. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  3014. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  3015. }
  3016. if ($objp->duration) {
  3017. $optlabel .= " - ".$objp->duration;
  3018. $outvallabel .= " - ".$objp->duration;
  3019. }
  3020. if (!$socid) {
  3021. $optlabel .= " - ".dol_trunc($objp->name, 8);
  3022. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  3023. }
  3024. if ($objp->supplier_reputation) {
  3025. //TODO dictionary
  3026. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  3027. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  3028. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  3029. }
  3030. } else {
  3031. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3032. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3033. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3034. } else // No supplier price defined for product, even on other suppliers
  3035. {
  3036. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3037. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3038. }
  3039. }
  3040. if (!empty($conf->stock->enabled) && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3041. $novirtualstock = ($showstockinlist == 2);
  3042. if (!empty($user->rights->stock->lire)) {
  3043. $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  3044. if ($objp->stock > 0) {
  3045. $optlabel .= ' - <span class="product_line_stock_ok">';
  3046. } elseif ($objp->stock <= 0) {
  3047. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3048. }
  3049. $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
  3050. $optlabel .= '</span>';
  3051. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3052. $langs->load("stocks");
  3053. $tmpproduct = new Product($this->db);
  3054. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3055. $tmpproduct->load_virtual_stock();
  3056. $virtualstock = $tmpproduct->stock_theorique;
  3057. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  3058. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  3059. if ($virtualstock > 0) {
  3060. $optlabel .= '<span class="product_line_stock_ok">';
  3061. } elseif ($virtualstock <= 0) {
  3062. $optlabel .= '<span class="product_line_stock_too_low">';
  3063. }
  3064. $optlabel .= $virtualstock;
  3065. $optlabel .= '</span>';
  3066. unset($tmpproduct);
  3067. }
  3068. }
  3069. }
  3070. $opt = '<option value="'.$outkey.'"';
  3071. if ($selected && $selected == $objp->idprodfournprice) {
  3072. $opt .= ' selected';
  3073. }
  3074. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3075. $opt .= ' disabled';
  3076. }
  3077. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3078. $opt .= ' data-product-id="'.$objp->rowid.'" data-price-id="'.$objp->idprodfournprice.'" data-qty="'.$objp->quantity.'" data-up="'.$objp->unitprice.'" data-discount="'.$outdiscount.'"';
  3079. }
  3080. $opt .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
  3081. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  3082. $opt .= '>';
  3083. $opt .= $optlabel;
  3084. $outval .= $outvallabel;
  3085. $opt .= "</option>\n";
  3086. // Add new entry
  3087. // "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
  3088. // "label" value of json key array is used by jQuery automatically as text for combo box
  3089. $out .= $opt;
  3090. array_push(
  3091. $outarray,
  3092. array('key'=>$outkey,
  3093. 'value'=>$outref,
  3094. 'label'=>$outval,
  3095. 'qty'=>$outqty,
  3096. 'price_qty_ht'=>price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3097. 'price_unit_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3098. 'price_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3099. 'tva_tx'=>$objp->tva_tx,
  3100. 'default_vat_code'=>$objp->default_vat_code,
  3101. 'discount'=>$outdiscount,
  3102. 'type'=>$outtype,
  3103. 'duration_value'=>$outdurationvalue,
  3104. 'duration_unit'=>$outdurationunit,
  3105. 'disabled'=>(empty($objp->idprodfournprice) ? true : false),
  3106. 'description'=>$objp->description
  3107. )
  3108. );
  3109. // Exemple of var_dump $outarray
  3110. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3111. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3112. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3113. //}
  3114. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3115. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3116. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3117. $i++;
  3118. }
  3119. $out .= '</select>';
  3120. $this->db->free($result);
  3121. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  3122. $out .= ajax_combobox($htmlname);
  3123. if (empty($outputmode)) {
  3124. return $out;
  3125. }
  3126. return $outarray;
  3127. } else {
  3128. dol_print_error($this->db);
  3129. }
  3130. }
  3131. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3132. /**
  3133. * Return list of suppliers prices for a product
  3134. *
  3135. * @param int $productid Id of product
  3136. * @param string $htmlname Name of HTML field
  3137. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3138. * @return string
  3139. */
  3140. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3141. {
  3142. // phpcs:enable
  3143. global $langs, $conf;
  3144. $langs->load('stocks');
  3145. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3146. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3147. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3148. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  3149. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3150. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  3151. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  3152. $sql .= " AND p.tobuy = 1";
  3153. $sql .= " AND s.fournisseur = 1";
  3154. $sql .= " AND p.rowid = ".((int) $productid);
  3155. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3156. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  3157. $result = $this->db->query($sql);
  3158. if ($result) {
  3159. $num = $this->db->num_rows($result);
  3160. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3161. if (!$num) {
  3162. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  3163. } else {
  3164. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3165. $form .= '<option value="0">&nbsp;</option>';
  3166. $i = 0;
  3167. while ($i < $num) {
  3168. $objp = $this->db->fetch_object($result);
  3169. $opt = '<option value="'.$objp->idprodfournprice.'"';
  3170. //if there is only one supplier, preselect it
  3171. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  3172. $opt .= ' selected';
  3173. }
  3174. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  3175. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3176. $prod_supplier = new ProductFournisseur($this->db);
  3177. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3178. $prod_supplier->id = $productid;
  3179. $prod_supplier->fourn_qty = $objp->quantity;
  3180. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3181. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3182. $priceparser = new PriceParser($this->db);
  3183. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3184. if ($price_result >= 0) {
  3185. $objp->fprice = $price_result;
  3186. if ($objp->quantity >= 1) {
  3187. $objp->unitprice = $objp->fprice / $objp->quantity;
  3188. }
  3189. }
  3190. }
  3191. if ($objp->quantity == 1) {
  3192. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3193. }
  3194. $opt .= $objp->quantity.' ';
  3195. if ($objp->quantity == 1) {
  3196. $opt .= $langs->trans("Unit");
  3197. } else {
  3198. $opt .= $langs->trans("Units");
  3199. }
  3200. if ($objp->quantity > 1) {
  3201. $opt .= " - ";
  3202. $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");
  3203. }
  3204. if ($objp->duration) {
  3205. $opt .= " - ".$objp->duration;
  3206. }
  3207. $opt .= "</option>\n";
  3208. $form .= $opt;
  3209. $i++;
  3210. }
  3211. }
  3212. $form .= '</select>';
  3213. $this->db->free($result);
  3214. return $form;
  3215. } else {
  3216. dol_print_error($this->db);
  3217. }
  3218. }
  3219. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3220. /**
  3221. * Return list of delivery address
  3222. *
  3223. * @param string $selected Id contact pre-selectionn
  3224. * @param int $socid Id of company
  3225. * @param string $htmlname Name of HTML field
  3226. * @param int $showempty Add an empty field
  3227. * @return integer|null
  3228. */
  3229. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3230. {
  3231. // phpcs:enable
  3232. // looking for users
  3233. $sql = "SELECT a.rowid, a.label";
  3234. $sql .= " FROM ".MAIN_DB_PREFIX."societe_address as a";
  3235. $sql .= " WHERE a.fk_soc = ".((int) $socid);
  3236. $sql .= " ORDER BY a.label ASC";
  3237. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  3238. $resql = $this->db->query($sql);
  3239. if ($resql) {
  3240. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3241. if ($showempty) {
  3242. print '<option value="0">&nbsp;</option>';
  3243. }
  3244. $num = $this->db->num_rows($resql);
  3245. $i = 0;
  3246. if ($num) {
  3247. while ($i < $num) {
  3248. $obj = $this->db->fetch_object($resql);
  3249. if ($selected && $selected == $obj->rowid) {
  3250. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  3251. } else {
  3252. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  3253. }
  3254. $i++;
  3255. }
  3256. }
  3257. print '</select>';
  3258. return $num;
  3259. } else {
  3260. dol_print_error($this->db);
  3261. }
  3262. }
  3263. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3264. /**
  3265. * Load into cache list of payment terms
  3266. *
  3267. * @return int Nb of lines loaded, <0 if KO
  3268. */
  3269. public function load_cache_conditions_paiements()
  3270. {
  3271. // phpcs:enable
  3272. global $langs;
  3273. $num = count($this->cache_conditions_paiements);
  3274. if ($num > 0) {
  3275. return 0; // Cache already loaded
  3276. }
  3277. dol_syslog(__METHOD__, LOG_DEBUG);
  3278. $sql = "SELECT rowid, code, libelle as label";
  3279. $sql .= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  3280. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  3281. $sql .= " AND active > 0";
  3282. $sql .= " ORDER BY sortorder";
  3283. $resql = $this->db->query($sql);
  3284. if ($resql) {
  3285. $num = $this->db->num_rows($resql);
  3286. $i = 0;
  3287. while ($i < $num) {
  3288. $obj = $this->db->fetch_object($resql);
  3289. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3290. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3291. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3292. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3293. $i++;
  3294. }
  3295. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3296. return $num;
  3297. } else {
  3298. dol_print_error($this->db);
  3299. return -1;
  3300. }
  3301. }
  3302. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3303. /**
  3304. * Load int a cache property th elist of possible delivery delays.
  3305. *
  3306. * @return int Nb of lines loaded, <0 if KO
  3307. */
  3308. public function load_cache_availability()
  3309. {
  3310. // phpcs:enable
  3311. global $langs;
  3312. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3313. if ($num > 0) {
  3314. return 0; // Cache already loaded
  3315. }
  3316. dol_syslog(__METHOD__, LOG_DEBUG);
  3317. $langs->load('propal');
  3318. $sql = "SELECT rowid, code, label, position";
  3319. $sql .= " FROM ".MAIN_DB_PREFIX.'c_availability';
  3320. $sql .= " WHERE active > 0";
  3321. $resql = $this->db->query($sql);
  3322. if ($resql) {
  3323. $num = $this->db->num_rows($resql);
  3324. $i = 0;
  3325. while ($i < $num) {
  3326. $obj = $this->db->fetch_object($resql);
  3327. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3328. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3329. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3330. $this->cache_availability[$obj->rowid]['label'] = $label;
  3331. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3332. $i++;
  3333. }
  3334. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3335. return $num;
  3336. } else {
  3337. dol_print_error($this->db);
  3338. return -1;
  3339. }
  3340. }
  3341. /**
  3342. * Retourne la liste des types de delais de livraison possibles
  3343. *
  3344. * @param int $selected Id du type de delais pre-selectionne
  3345. * @param string $htmlname Nom de la zone select
  3346. * @param string $filtertype To add a filter
  3347. * @param int $addempty Add empty entry
  3348. * @param string $morecss More CSS
  3349. * @return void
  3350. */
  3351. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3352. {
  3353. global $langs, $user;
  3354. $this->load_cache_availability();
  3355. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3356. print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3357. if ($addempty) {
  3358. print '<option value="0">&nbsp;</option>';
  3359. }
  3360. foreach ($this->cache_availability as $id => $arrayavailability) {
  3361. if ($selected == $id) {
  3362. print '<option value="'.$id.'" selected>';
  3363. } else {
  3364. print '<option value="'.$id.'">';
  3365. }
  3366. print dol_escape_htmltag($arrayavailability['label']);
  3367. print '</option>';
  3368. }
  3369. print '</select>';
  3370. if ($user->admin) {
  3371. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3372. }
  3373. print ajax_combobox($htmlname);
  3374. }
  3375. /**
  3376. * Load into cache cache_demand_reason, array of input reasons
  3377. *
  3378. * @return int Nb of lines loaded, <0 if KO
  3379. */
  3380. public function loadCacheInputReason()
  3381. {
  3382. global $langs;
  3383. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3384. if ($num > 0) {
  3385. return 0; // Cache already loaded
  3386. }
  3387. $sql = "SELECT rowid, code, label";
  3388. $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  3389. $sql .= " WHERE active > 0";
  3390. $resql = $this->db->query($sql);
  3391. if ($resql) {
  3392. $num = $this->db->num_rows($resql);
  3393. $i = 0;
  3394. $tmparray = array();
  3395. while ($i < $num) {
  3396. $obj = $this->db->fetch_object($resql);
  3397. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3398. $label = ($obj->label != '-' ? $obj->label : '');
  3399. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
  3400. $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3401. }
  3402. if ($langs->trans($obj->code) != $obj->code) {
  3403. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3404. }
  3405. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3406. $tmparray[$obj->rowid]['code'] = $obj->code;
  3407. $tmparray[$obj->rowid]['label'] = $label;
  3408. $i++;
  3409. }
  3410. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3411. unset($tmparray);
  3412. return $num;
  3413. } else {
  3414. dol_print_error($this->db);
  3415. return -1;
  3416. }
  3417. }
  3418. /**
  3419. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3420. * List found into table c_input_reason loaded by loadCacheInputReason
  3421. *
  3422. * @param int $selected Id or code of type origin to select by default
  3423. * @param string $htmlname Nom de la zone select
  3424. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3425. * @param int $addempty Add an empty entry
  3426. * @param string $morecss Add more css to the HTML select component
  3427. * @param int $notooltip Do not show the tooltip for admin
  3428. * @return void
  3429. */
  3430. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3431. {
  3432. global $langs, $user;
  3433. $this->loadCacheInputReason();
  3434. print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3435. if ($addempty) {
  3436. print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3437. }
  3438. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3439. if ($arraydemandreason['code'] == $exclude) {
  3440. continue;
  3441. }
  3442. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3443. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3444. } else {
  3445. print '<option value="'.$arraydemandreason['id'].'">';
  3446. }
  3447. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3448. print $langs->trans($label);
  3449. print '</option>';
  3450. }
  3451. print '</select>';
  3452. if ($user->admin && empty($notooltip)) {
  3453. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3454. }
  3455. print ajax_combobox('select_'.$htmlname);
  3456. }
  3457. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3458. /**
  3459. * Charge dans cache la liste des types de paiements possibles
  3460. *
  3461. * @return int Nb of lines loaded, <0 if KO
  3462. */
  3463. public function load_cache_types_paiements()
  3464. {
  3465. // phpcs:enable
  3466. global $langs;
  3467. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3468. if ($num > 0) {
  3469. return $num; // Cache already loaded
  3470. }
  3471. dol_syslog(__METHOD__, LOG_DEBUG);
  3472. $this->cache_types_paiements = array();
  3473. $sql = "SELECT id, code, libelle as label, type, active";
  3474. $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement";
  3475. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3476. $resql = $this->db->query($sql);
  3477. if ($resql) {
  3478. $num = $this->db->num_rows($resql);
  3479. $i = 0;
  3480. while ($i < $num) {
  3481. $obj = $this->db->fetch_object($resql);
  3482. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3483. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3484. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3485. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3486. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3487. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3488. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3489. $i++;
  3490. }
  3491. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3492. return $num;
  3493. } else {
  3494. dol_print_error($this->db);
  3495. return -1;
  3496. }
  3497. }
  3498. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3499. /**
  3500. * Return list of payment modes.
  3501. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3502. * See instead to force the default value by the caller.
  3503. *
  3504. * @param int $selected Id of payment term to preselect by default
  3505. * @param string $htmlname Nom de la zone select
  3506. * @param int $filtertype Not used
  3507. * @param int $addempty Add an empty entry
  3508. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3509. * @param string $morecss Add more CSS on select tag
  3510. * @return void
  3511. */
  3512. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '')
  3513. {
  3514. // phpcs:enable
  3515. global $langs, $user, $conf;
  3516. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3517. $this->load_cache_conditions_paiements();
  3518. // Set default value if not already set by caller
  3519. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3520. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3521. }
  3522. print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3523. if ($addempty) {
  3524. print '<option value="0">&nbsp;</option>';
  3525. }
  3526. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3527. if ($selected == $id) {
  3528. print '<option value="'.$id.'" selected>';
  3529. } else {
  3530. print '<option value="'.$id.'">';
  3531. }
  3532. print $arrayconditions['label'];
  3533. print '</option>';
  3534. }
  3535. print '</select>';
  3536. if ($user->admin && empty($noinfoadmin)) {
  3537. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3538. }
  3539. print ajax_combobox($htmlname);
  3540. }
  3541. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3542. /**
  3543. * Return list of payment methods
  3544. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3545. *
  3546. * @param string $selected Id or code or preselected payment mode
  3547. * @param string $htmlname Name of select field
  3548. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3549. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3550. * @param int $empty 1=can be empty, 0 otherwise
  3551. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3552. * @param int $maxlength Max length of label
  3553. * @param int $active Active or not, -1 = all
  3554. * @param string $morecss Add more CSS on select tag
  3555. * @param int $nooutput 1=Return string, do not send to output
  3556. * @return void
  3557. */
  3558. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3559. {
  3560. // phpcs:enable
  3561. global $langs, $user, $conf;
  3562. $out = '';
  3563. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3564. $filterarray = array();
  3565. if ($filtertype == 'CRDT') {
  3566. $filterarray = array(0, 2, 3);
  3567. } elseif ($filtertype == 'DBIT') {
  3568. $filterarray = array(1, 2, 3);
  3569. } elseif ($filtertype != '' && $filtertype != '-1') {
  3570. $filterarray = explode(',', $filtertype);
  3571. }
  3572. $this->load_cache_types_paiements();
  3573. // Set default value if not already set by caller
  3574. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3575. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3576. }
  3577. $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3578. if ($empty) {
  3579. $out .= '<option value="">&nbsp;</option>';
  3580. }
  3581. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3582. // If not good status
  3583. if ($active >= 0 && $arraytypes['active'] != $active) {
  3584. continue;
  3585. }
  3586. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3587. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3588. continue;
  3589. }
  3590. // We discard empty line if showempty is on because an empty line has already been output.
  3591. if ($empty && empty($arraytypes['code'])) {
  3592. continue;
  3593. }
  3594. if ($format == 0) {
  3595. $out .= '<option value="'.$id.'"';
  3596. } elseif ($format == 1) {
  3597. $out .= '<option value="'.$arraytypes['code'].'"';
  3598. } elseif ($format == 2) {
  3599. $out .= '<option value="'.$arraytypes['code'].'"';
  3600. } elseif ($format == 3) {
  3601. $out .= '<option value="'.$id.'"';
  3602. }
  3603. // Print attribute selected or not
  3604. if ($format == 1 || $format == 2) {
  3605. if ($selected == $arraytypes['code']) {
  3606. $out .= ' selected';
  3607. }
  3608. } else {
  3609. if ($selected == $id) {
  3610. $out .= ' selected';
  3611. }
  3612. }
  3613. $out .= '>';
  3614. if ($format == 0) {
  3615. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3616. } elseif ($format == 1) {
  3617. $value = $arraytypes['code'];
  3618. } elseif ($format == 2) {
  3619. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3620. } elseif ($format == 3) {
  3621. $value = $arraytypes['code'];
  3622. }
  3623. $out .= $value ? $value : '&nbsp;';
  3624. $out .= '</option>';
  3625. }
  3626. $out .= '</select>';
  3627. if ($user->admin && !$noadmininfo) {
  3628. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3629. }
  3630. $out .= ajax_combobox('select'.$htmlname);
  3631. if (empty($nooutput)) {
  3632. print $out;
  3633. } else {
  3634. return $out;
  3635. }
  3636. }
  3637. /**
  3638. * Selection HT or TTC
  3639. *
  3640. * @param string $selected Id pre-selectionne
  3641. * @param string $htmlname Nom de la zone select
  3642. * @param string $addjscombo Add js combo
  3643. * @return string Code of HTML select to chose tax or not
  3644. */
  3645. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3646. {
  3647. global $langs;
  3648. $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3649. $options = array(
  3650. 'HT'=>$langs->trans("HT"),
  3651. 'TTC'=>$langs->trans("TTC")
  3652. );
  3653. foreach ($options as $id => $value) {
  3654. if ($selected == $id) {
  3655. $return .= '<option value="'.$id.'" selected>'.$value;
  3656. } else {
  3657. $return .= '<option value="'.$id.'">'.$value;
  3658. }
  3659. $return .= '</option>';
  3660. }
  3661. $return .= '</select>';
  3662. if ($addjscombo) {
  3663. $return .= ajax_combobox('select_'.$htmlname);
  3664. }
  3665. return $return;
  3666. }
  3667. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3668. /**
  3669. * Load in cache list of transport mode
  3670. *
  3671. * @return int Nb of lines loaded, <0 if KO
  3672. */
  3673. public function load_cache_transport_mode()
  3674. {
  3675. // phpcs:enable
  3676. global $langs;
  3677. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  3678. if ($num > 0) {
  3679. return $num; // Cache already loaded
  3680. }
  3681. dol_syslog(__METHOD__, LOG_DEBUG);
  3682. $this->cache_transport_mode = array();
  3683. $sql = "SELECT rowid, code, label, active";
  3684. $sql .= " FROM ".MAIN_DB_PREFIX."c_transport_mode";
  3685. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3686. $resql = $this->db->query($sql);
  3687. if ($resql) {
  3688. $num = $this->db->num_rows($resql);
  3689. $i = 0;
  3690. while ($i < $num) {
  3691. $obj = $this->db->fetch_object($resql);
  3692. // If traduction exist, we use it else we take the default label
  3693. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3694. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3695. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3696. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3697. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3698. $i++;
  3699. }
  3700. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3701. return $num;
  3702. } else {
  3703. dol_print_error($this->db);
  3704. return -1;
  3705. }
  3706. }
  3707. /**
  3708. * Return list of transport mode for intracomm report
  3709. *
  3710. * @param string $selected Id of the transport mode pre-selected
  3711. * @param string $htmlname Name of the select field
  3712. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3713. * @param int $empty 1=can be empty, 0 else
  3714. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3715. * @param int $maxlength Max length of label
  3716. * @param int $active Active or not, -1 = all
  3717. * @param string $morecss Add more CSS on select tag
  3718. * @return void
  3719. */
  3720. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3721. {
  3722. global $langs, $user;
  3723. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3724. $this->load_cache_transport_mode();
  3725. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3726. if ($empty) {
  3727. print '<option value="">&nbsp;</option>';
  3728. }
  3729. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3730. // If not good status
  3731. if ($active >= 0 && $arraytypes['active'] != $active) {
  3732. continue;
  3733. }
  3734. // We discard empty line if showempty is on because an empty line has already been output.
  3735. if ($empty && empty($arraytypes['code'])) {
  3736. continue;
  3737. }
  3738. if ($format == 0) {
  3739. print '<option value="'.$id.'"';
  3740. } elseif ($format == 1) {
  3741. print '<option value="'.$arraytypes['code'].'"';
  3742. } elseif ($format == 2) {
  3743. print '<option value="'.$arraytypes['code'].'"';
  3744. } elseif ($format == 3) {
  3745. print '<option value="'.$id.'"';
  3746. }
  3747. // If text is selected, we compare with code, else with id
  3748. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  3749. print ' selected';
  3750. } elseif ($selected == $id) {
  3751. print ' selected';
  3752. }
  3753. print '>';
  3754. if ($format == 0) {
  3755. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3756. } elseif ($format == 1) {
  3757. $value = $arraytypes['code'];
  3758. } elseif ($format == 2) {
  3759. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3760. } elseif ($format == 3) {
  3761. $value = $arraytypes['code'];
  3762. }
  3763. print $value ? $value : '&nbsp;';
  3764. print '</option>';
  3765. }
  3766. print '</select>';
  3767. if ($user->admin && !$noadmininfo) {
  3768. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3769. }
  3770. }
  3771. /**
  3772. * Return a HTML select list of shipping mode
  3773. *
  3774. * @param string $selected Id shipping mode pre-selected
  3775. * @param string $htmlname Name of select zone
  3776. * @param string $filtre To filter list. This parameter must not come from input of users
  3777. * @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.
  3778. * @param string $moreattrib To add more attribute on select
  3779. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3780. * @param string $morecss More CSS
  3781. * @return void
  3782. */
  3783. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  3784. {
  3785. global $langs, $conf, $user;
  3786. $langs->load("admin");
  3787. $langs->load("deliveries");
  3788. $sql = "SELECT rowid, code, libelle as label";
  3789. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
  3790. $sql .= " WHERE active > 0";
  3791. if ($filtre) {
  3792. $sql .= " AND ".$filtre;
  3793. }
  3794. $sql .= " ORDER BY libelle ASC";
  3795. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3796. $result = $this->db->query($sql);
  3797. if ($result) {
  3798. $num = $this->db->num_rows($result);
  3799. $i = 0;
  3800. if ($num) {
  3801. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3802. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3803. print '<option value="-1">&nbsp;</option>';
  3804. }
  3805. while ($i < $num) {
  3806. $obj = $this->db->fetch_object($result);
  3807. if ($selected == $obj->rowid) {
  3808. print '<option value="'.$obj->rowid.'" selected>';
  3809. } else {
  3810. print '<option value="'.$obj->rowid.'">';
  3811. }
  3812. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3813. print '</option>';
  3814. $i++;
  3815. }
  3816. print "</select>";
  3817. if ($user->admin && empty($noinfoadmin)) {
  3818. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3819. }
  3820. print ajax_combobox('select'.$htmlname);
  3821. } else {
  3822. print $langs->trans("NoShippingMethodDefined");
  3823. }
  3824. } else {
  3825. dol_print_error($this->db);
  3826. }
  3827. }
  3828. /**
  3829. * Display form to select shipping mode
  3830. *
  3831. * @param string $page Page
  3832. * @param int $selected Id of shipping mode
  3833. * @param string $htmlname Name of select html field
  3834. * @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.
  3835. * @return void
  3836. */
  3837. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  3838. {
  3839. global $langs, $db;
  3840. $langs->load("deliveries");
  3841. if ($htmlname != "none") {
  3842. print '<form method="POST" action="'.$page.'">';
  3843. print '<input type="hidden" name="action" value="setshippingmethod">';
  3844. print '<input type="hidden" name="token" value="'.newToken().'">';
  3845. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3846. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3847. print '</form>';
  3848. } else {
  3849. if ($selected) {
  3850. $code = $langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
  3851. print $langs->trans("SendingMethod".strtoupper($code));
  3852. } else {
  3853. print "&nbsp;";
  3854. }
  3855. }
  3856. }
  3857. /**
  3858. * Creates HTML last in cycle situation invoices selector
  3859. *
  3860. * @param string $selected Preselected ID
  3861. * @param int $socid Company ID
  3862. *
  3863. * @return string HTML select
  3864. */
  3865. public function selectSituationInvoices($selected = '', $socid = 0)
  3866. {
  3867. global $langs;
  3868. $langs->load('bills');
  3869. $opt = '<option value ="" selected></option>';
  3870. $sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc';
  3871. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture';
  3872. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  3873. $sql .= ' AND situation_counter >= 1';
  3874. $sql .= ' AND fk_soc = '.(int) $socid;
  3875. $sql .= ' AND type <> 2';
  3876. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  3877. $resql = $this->db->query($sql);
  3878. if ($resql && $this->db->num_rows($resql) > 0) {
  3879. // Last seen cycle
  3880. $ref = 0;
  3881. while ($obj = $this->db->fetch_object($resql)) {
  3882. //Same cycle ?
  3883. if ($obj->situation_cycle_ref != $ref) {
  3884. // Just seen this cycle
  3885. $ref = $obj->situation_cycle_ref;
  3886. //not final ?
  3887. if ($obj->situation_final != 1) {
  3888. //Not prov?
  3889. if (substr($obj->ref, 1, 4) != 'PROV') {
  3890. if ($selected == $obj->rowid) {
  3891. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  3892. } else {
  3893. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  3894. }
  3895. }
  3896. }
  3897. }
  3898. }
  3899. } else {
  3900. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  3901. }
  3902. if ($opt == '<option value ="" selected></option>') {
  3903. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  3904. }
  3905. return $opt;
  3906. }
  3907. /**
  3908. * Creates HTML units selector (code => label)
  3909. *
  3910. * @param string $selected Preselected Unit ID
  3911. * @param string $htmlname Select name
  3912. * @param int $showempty Add a nempty line
  3913. * @param string $unit_type Restrict to one given unit type
  3914. * @return string HTML select
  3915. */
  3916. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  3917. {
  3918. global $langs;
  3919. $langs->load('products');
  3920. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  3921. $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
  3922. $sql .= ' WHERE active > 0';
  3923. if (!empty($unit_type)) {
  3924. $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
  3925. }
  3926. $sql .= " ORDER BY sortorder";
  3927. $resql = $this->db->query($sql);
  3928. if ($resql && $this->db->num_rows($resql) > 0) {
  3929. if ($showempty) {
  3930. $return .= '<option value="none"></option>';
  3931. }
  3932. while ($res = $this->db->fetch_object($resql)) {
  3933. $unitLabel = $res->label;
  3934. if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
  3935. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  3936. }
  3937. if ($selected == $res->rowid) {
  3938. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  3939. } else {
  3940. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  3941. }
  3942. }
  3943. $return .= '</select>';
  3944. }
  3945. return $return;
  3946. }
  3947. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3948. /**
  3949. * Return a HTML select list of bank accounts
  3950. *
  3951. * @param string $selected Id account pre-selected
  3952. * @param string $htmlname Name of select zone
  3953. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  3954. * @param string $filtre To filter list. This parameter must not come from input of users
  3955. * @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.
  3956. * @param string $moreattrib To add more attribute on select
  3957. * @param int $showcurrency Show currency in label
  3958. * @param string $morecss More CSS
  3959. * @param int $nooutput 1=Return string, do not send to output
  3960. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  3961. */
  3962. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  3963. {
  3964. // phpcs:enable
  3965. global $langs, $conf;
  3966. $out = '';
  3967. $langs->load("admin");
  3968. $num = 0;
  3969. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  3970. $sql .= " FROM ".MAIN_DB_PREFIX."bank_account";
  3971. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  3972. if ($status != 2) {
  3973. $sql .= " AND clos = ".(int) $status;
  3974. }
  3975. if ($filtre) {
  3976. $sql .= " AND ".$filtre;
  3977. }
  3978. $sql .= " ORDER BY label";
  3979. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  3980. $result = $this->db->query($sql);
  3981. if ($result) {
  3982. $num = $this->db->num_rows($result);
  3983. $i = 0;
  3984. if ($num) {
  3985. $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3986. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3987. $out .= '<option value="-1">&nbsp;</option>';
  3988. }
  3989. while ($i < $num) {
  3990. $obj = $this->db->fetch_object($result);
  3991. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  3992. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
  3993. } else {
  3994. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
  3995. }
  3996. $out .= trim($obj->label);
  3997. if ($showcurrency) {
  3998. $out .= ' ('.$obj->currency_code.')';
  3999. }
  4000. if ($status == 2 && $obj->status == 1) {
  4001. $out .= ' ('.$langs->trans("Closed").')';
  4002. }
  4003. $out .= '</option>';
  4004. $i++;
  4005. }
  4006. $out .= "</select>";
  4007. $out .= ajax_combobox('select'.$htmlname);
  4008. } else {
  4009. if ($status == 0) {
  4010. $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  4011. } else {
  4012. $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  4013. }
  4014. }
  4015. } else {
  4016. dol_print_error($this->db);
  4017. }
  4018. // Output or return
  4019. if (empty($nooutput)) {
  4020. print $out;
  4021. } else {
  4022. return $out;
  4023. }
  4024. return $num;
  4025. }
  4026. /**
  4027. * Return a HTML select list of establishment
  4028. *
  4029. * @param string $selected Id establishment pre-selected
  4030. * @param string $htmlname Name of select zone
  4031. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4032. * @param string $filtre To filter list. This parameter must not come from input of users
  4033. * @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.
  4034. * @param string $moreattrib To add more attribute on select
  4035. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4036. */
  4037. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4038. {
  4039. global $langs, $conf;
  4040. $langs->load("admin");
  4041. $num = 0;
  4042. $sql = "SELECT rowid, name, fk_country, status, entity";
  4043. $sql .= " FROM ".MAIN_DB_PREFIX."establishment";
  4044. $sql .= " WHERE 1=1";
  4045. if ($status != 2) {
  4046. $sql .= " AND status = ".(int) $status;
  4047. }
  4048. if ($filtre) {
  4049. $sql .= " AND ".$filtre;
  4050. }
  4051. $sql .= " ORDER BY name";
  4052. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  4053. $result = $this->db->query($sql);
  4054. if ($result) {
  4055. $num = $this->db->num_rows($result);
  4056. $i = 0;
  4057. if ($num) {
  4058. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4059. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4060. print '<option value="-1">&nbsp;</option>';
  4061. }
  4062. while ($i < $num) {
  4063. $obj = $this->db->fetch_object($result);
  4064. if ($selected == $obj->rowid) {
  4065. print '<option value="'.$obj->rowid.'" selected>';
  4066. } else {
  4067. print '<option value="'.$obj->rowid.'">';
  4068. }
  4069. print trim($obj->name);
  4070. if ($status == 2 && $obj->status == 1) {
  4071. print ' ('.$langs->trans("Closed").')';
  4072. }
  4073. print '</option>';
  4074. $i++;
  4075. }
  4076. print "</select>";
  4077. } else {
  4078. if ($status == 0) {
  4079. print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  4080. } else {
  4081. print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  4082. }
  4083. }
  4084. } else {
  4085. dol_print_error($this->db);
  4086. }
  4087. }
  4088. /**
  4089. * Display form to select bank account
  4090. *
  4091. * @param string $page Page
  4092. * @param int $selected Id of bank account
  4093. * @param string $htmlname Name of select html field
  4094. * @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.
  4095. * @return void
  4096. */
  4097. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4098. {
  4099. global $langs;
  4100. if ($htmlname != "none") {
  4101. print '<form method="POST" action="'.$page.'">';
  4102. print '<input type="hidden" name="action" value="setbankaccount">';
  4103. print '<input type="hidden" name="token" value="'.newToken().'">';
  4104. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4105. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4106. if ($nbaccountfound > 0) {
  4107. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4108. }
  4109. print '</form>';
  4110. } else {
  4111. $langs->load('banks');
  4112. if ($selected) {
  4113. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  4114. $bankstatic = new Account($this->db);
  4115. $result = $bankstatic->fetch($selected);
  4116. if ($result) {
  4117. print $bankstatic->getNomUrl(1);
  4118. }
  4119. } else {
  4120. print "&nbsp;";
  4121. }
  4122. }
  4123. }
  4124. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4125. /**
  4126. * Return list of categories having choosed type
  4127. *
  4128. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4129. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4130. * @param string $htmlname HTML field name
  4131. * @param int $maxlength Maximum length for labels
  4132. * @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.
  4133. * $markafterid can be an :
  4134. * - int (id of category)
  4135. * - string (categories ids seprated by comma)
  4136. * - array (list of categories ids)
  4137. * @param int $outputmode 0=HTML select string, 1=Array
  4138. * @param int $include [=0] Removed or 1=Keep only
  4139. * @param string $morecss More CSS
  4140. * @return string
  4141. * @see select_categories()
  4142. */
  4143. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4144. {
  4145. // phpcs:enable
  4146. global $conf, $langs;
  4147. $langs->load("categories");
  4148. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4149. // For backward compatibility
  4150. if (is_numeric($type)) {
  4151. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4152. }
  4153. if ($type === Categorie::TYPE_BANK_LINE) {
  4154. // TODO Move this into common category feature
  4155. $cate_arbo = array();
  4156. $sql = "SELECT c.label, c.rowid";
  4157. $sql .= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
  4158. $sql .= " WHERE entity = ".$conf->entity;
  4159. $sql .= " ORDER BY c.label";
  4160. $result = $this->db->query($sql);
  4161. if ($result) {
  4162. $num = $this->db->num_rows($result);
  4163. $i = 0;
  4164. while ($i < $num) {
  4165. $objp = $this->db->fetch_object($result);
  4166. if ($objp) {
  4167. $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  4168. }
  4169. $i++;
  4170. }
  4171. $this->db->free($result);
  4172. } else {
  4173. dol_print_error($this->db);
  4174. }
  4175. } else {
  4176. $cat = new Categorie($this->db);
  4177. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4178. }
  4179. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  4180. $outarray = array();
  4181. if (is_array($cate_arbo)) {
  4182. if (!count($cate_arbo)) {
  4183. $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  4184. } else {
  4185. $output .= '<option value="-1">&nbsp;</option>';
  4186. foreach ($cate_arbo as $key => $value) {
  4187. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4188. $add = 'selected ';
  4189. } else {
  4190. $add = '';
  4191. }
  4192. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  4193. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4194. }
  4195. }
  4196. }
  4197. $output .= '</select>';
  4198. $output .= "\n";
  4199. if ($outputmode) {
  4200. return $outarray;
  4201. }
  4202. return $output;
  4203. }
  4204. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4205. /**
  4206. * Show a confirmation HTML form or AJAX popup
  4207. *
  4208. * @param string $page Url of page to call if confirmation is OK
  4209. * @param string $title Title
  4210. * @param string $question Question
  4211. * @param string $action Action
  4212. * @param array $formquestion An array with forms complementary inputs
  4213. * @param string $selectedchoice "" or "no" or "yes"
  4214. * @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
  4215. * @param int $height Force height of box
  4216. * @param int $width Force width of box
  4217. * @return void
  4218. * @deprecated
  4219. * @see formconfirm()
  4220. */
  4221. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4222. {
  4223. // phpcs:enable
  4224. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4225. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4226. }
  4227. /**
  4228. * Show a confirmation HTML form or AJAX popup.
  4229. * Easiest way to use this is with useajax=1.
  4230. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4231. * just after calling this method. For example:
  4232. * print '<script type="text/javascript">'."\n";
  4233. * print 'jQuery(document).ready(function() {'."\n";
  4234. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4235. * print '});'."\n";
  4236. * print '</script>'."\n";
  4237. *
  4238. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4239. * @param string $title Title
  4240. * @param string $question Question
  4241. * @param string $action Action
  4242. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>))
  4243. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', 'other' or 'onecolumn'...
  4244. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  4245. * @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
  4246. * @param int|string $height Force height of box (0 = auto)
  4247. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4248. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4249. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4250. */
  4251. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0)
  4252. {
  4253. global $langs, $conf;
  4254. $more = '<!-- formconfirm before calling page='.dol_escape_htmltag($page).' -->';
  4255. $formconfirm = '';
  4256. $inputok = array();
  4257. $inputko = array();
  4258. // Clean parameters
  4259. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4260. if ($conf->browser->layout == 'phone') {
  4261. $width = '95%';
  4262. }
  4263. // Set height automatically if not defined
  4264. if (empty($height)) {
  4265. $height = 220;
  4266. if (is_array($formquestion) && count($formquestion) > 2) {
  4267. $height += ((count($formquestion) - 2) * 24);
  4268. }
  4269. }
  4270. if (is_array($formquestion) && !empty($formquestion)) {
  4271. // First add hidden fields and value
  4272. foreach ($formquestion as $key => $input) {
  4273. if (is_array($input) && !empty($input)) {
  4274. if ($input['type'] == 'hidden') {
  4275. $more .= '<input type="hidden" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  4276. }
  4277. }
  4278. }
  4279. // Now add questions
  4280. $moreonecolumn = '';
  4281. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  4282. foreach ($formquestion as $key => $input) {
  4283. if (is_array($input) && !empty($input)) {
  4284. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
  4285. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4286. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4287. if ($input['type'] == 'text') {
  4288. $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";
  4289. } elseif ($input['type'] == 'password') {
  4290. $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";
  4291. } elseif ($input['type'] == 'textarea') {
  4292. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4293. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4294. $more .= $input['value'];
  4295. $more .= '</textarea>';
  4296. $more .= '</div></div>'."\n";*/
  4297. $moreonecolumn .= '<div class="margintoponly">';
  4298. $moreonecolumn .= $input['label'].'<br>';
  4299. $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
  4300. $moreonecolumn .= $input['value'];
  4301. $moreonecolumn .= '</textarea>';
  4302. $moreonecolumn .= '</div>';
  4303. } elseif ($input['type'] == 'select') {
  4304. if (empty($morecss)) {
  4305. $morecss = 'minwidth100';
  4306. }
  4307. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4308. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4309. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4310. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4311. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4312. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4313. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4314. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4315. if (!empty($input['label'])) {
  4316. $more .= $input['label'].'</div><div class="tagtd left">';
  4317. }
  4318. $more .= $this->selectarray($input['name'], $input['values'], $input['default'], $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4319. $more .= '</div></div>'."\n";
  4320. } elseif ($input['type'] == 'checkbox') {
  4321. $more .= '<div class="tagtr">';
  4322. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  4323. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
  4324. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') {
  4325. $more .= ' checked';
  4326. }
  4327. if (is_bool($input['value']) && $input['value']) {
  4328. $more .= ' checked';
  4329. }
  4330. if (isset($input['disabled'])) {
  4331. $more .= ' disabled';
  4332. }
  4333. $more .= ' /></div>';
  4334. $more .= '</div>'."\n";
  4335. } elseif ($input['type'] == 'radio') {
  4336. $i = 0;
  4337. foreach ($input['values'] as $selkey => $selval) {
  4338. $more .= '<div class="tagtr">';
  4339. if ($i == 0) {
  4340. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4341. } else {
  4342. $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  4343. }
  4344. $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;
  4345. if ($input['disabled']) {
  4346. $more .= ' disabled';
  4347. }
  4348. if (isset($input['default']) && $input['default'] === $selkey) {
  4349. $more .= ' checked="checked"';
  4350. }
  4351. $more .= ' /> ';
  4352. $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'">'.$selval.'</label>';
  4353. $more .= '</div></div>'."\n";
  4354. $i++;
  4355. }
  4356. } elseif ($input['type'] == 'date') {
  4357. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4358. $more .= '<div class="tagtd">';
  4359. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4360. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, $addnowlink);
  4361. $more .= '</div></div>'."\n";
  4362. $formquestion[] = array('name'=>$input['name'].'day');
  4363. $formquestion[] = array('name'=>$input['name'].'month');
  4364. $formquestion[] = array('name'=>$input['name'].'year');
  4365. $formquestion[] = array('name'=>$input['name'].'hour');
  4366. $formquestion[] = array('name'=>$input['name'].'min');
  4367. } elseif ($input['type'] == 'other') {
  4368. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4369. if (!empty($input['label'])) {
  4370. $more .= $input['label'].'</div><div class="tagtd">';
  4371. }
  4372. $more .= $input['value'];
  4373. $more .= '</div></div>'."\n";
  4374. } elseif ($input['type'] == 'onecolumn') {
  4375. $moreonecolumn .= '<div class="margintoponly">';
  4376. $moreonecolumn .= $input['value'];
  4377. $moreonecolumn .= '</div>'."\n";
  4378. } elseif ($input['type'] == 'hidden') {
  4379. // Do nothing more, already added by a previous loop
  4380. } else {
  4381. $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
  4382. }
  4383. }
  4384. }
  4385. $more .= '</div>'."\n";
  4386. $more .= $moreonecolumn;
  4387. }
  4388. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4389. // 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
  4390. // See page product/card.php for example
  4391. if (!empty($conf->dol_use_jmobile)) {
  4392. $useajax = 0;
  4393. }
  4394. if (empty($conf->use_javascript_ajax)) {
  4395. $useajax = 0;
  4396. }
  4397. if ($useajax) {
  4398. $autoOpen = true;
  4399. $dialogconfirm = 'dialog-confirm';
  4400. $button = '';
  4401. if (!is_numeric($useajax)) {
  4402. $button = $useajax;
  4403. $useajax = 1;
  4404. $autoOpen = false;
  4405. $dialogconfirm .= '-'.$button;
  4406. }
  4407. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.$action.'&confirm=yes';
  4408. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'confirm=no' : '');
  4409. // Add input fields into list of fields to read during submit (inputok and inputko)
  4410. if (is_array($formquestion)) {
  4411. foreach ($formquestion as $key => $input) {
  4412. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4413. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4414. if (is_array($input) && isset($input['name'])) {
  4415. if (strpos($input['name'], ',') > 0) {
  4416. $inputok = array_merge($inputok, explode(',', $input['name']));
  4417. } else {
  4418. array_push($inputok, $input['name']);
  4419. }
  4420. }
  4421. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4422. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4423. array_push($inputko, $input['name']);
  4424. }
  4425. }
  4426. }
  4427. // Show JQuery confirm box.
  4428. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  4429. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4430. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  4431. }
  4432. if (!empty($more)) {
  4433. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  4434. }
  4435. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  4436. $formconfirm .= '</div>'."\n";
  4437. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=".$page." -->\n";
  4438. $formconfirm .= '<script type="text/javascript">'."\n";
  4439. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4440. $formconfirm .= 'jQuery(document).ready(function() {
  4441. $(function() {
  4442. $( "#'.$dialogconfirm.'" ).dialog(
  4443. {
  4444. autoOpen: '.($autoOpen ? "true" : "false").',';
  4445. if ($newselectedchoice == 'no') {
  4446. $formconfirm .= '
  4447. open: function() {
  4448. $(this).parent().find("button.ui-button:eq(2)").focus();
  4449. },';
  4450. }
  4451. $formconfirm .= '
  4452. resizable: false,
  4453. height: "'.$height.'",
  4454. width: "'.$width.'",
  4455. modal: true,
  4456. closeOnEscape: false,
  4457. buttons: {
  4458. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  4459. var options = "&token='.urlencode(newToken()).'";
  4460. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  4461. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  4462. if (inputok.length>0) {
  4463. $.each(inputok, function(i, inputname) {
  4464. var more = "";
  4465. var inputvalue;
  4466. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4467. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4468. } else {
  4469. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4470. inputvalue = $("#" + inputname + more).val();
  4471. }
  4472. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4473. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4474. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4475. });
  4476. }
  4477. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  4478. if (pageyes.length > 0) { location.href = urljump; }
  4479. $(this).dialog("close");
  4480. },
  4481. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  4482. var options = "&token='.urlencode(newToken()).'";
  4483. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  4484. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  4485. if (inputko.length>0) {
  4486. $.each(inputko, function(i, inputname) {
  4487. var more = "";
  4488. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4489. var inputvalue = $("#" + inputname + more).val();
  4490. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4491. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4492. });
  4493. }
  4494. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  4495. //alert(urljump);
  4496. if (pageno.length > 0) { location.href = urljump; }
  4497. $(this).dialog("close");
  4498. }
  4499. }
  4500. }
  4501. );
  4502. var button = "'.$button.'";
  4503. if (button.length > 0) {
  4504. $( "#" + button ).click(function() {
  4505. $("#'.$dialogconfirm.'").dialog("open");
  4506. });
  4507. }
  4508. });
  4509. });
  4510. </script>';
  4511. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4512. } else {
  4513. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  4514. if (empty($disableformtag)) {
  4515. $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  4516. }
  4517. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  4518. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  4519. $formconfirm .= '<table class="valid centpercent">'."\n";
  4520. // Line title
  4521. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4522. $formconfirm .= img_picto('', 'recent').' '.$title;
  4523. $formconfirm .= '</td></tr>'."\n";
  4524. // Line text
  4525. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4526. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  4527. }
  4528. // Line form fields
  4529. if ($more) {
  4530. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
  4531. $formconfirm .= $more;
  4532. $formconfirm .= '</td></tr>'."\n";
  4533. }
  4534. // Line with question
  4535. $formconfirm .= '<tr class="valid">';
  4536. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4537. $formconfirm .= '<td class="valid center">';
  4538. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly');
  4539. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton" type="submit" value="'.$langs->trans("Validate").'">';
  4540. $formconfirm .= '</td>';
  4541. $formconfirm .= '</tr>'."\n";
  4542. $formconfirm .= '</table>'."\n";
  4543. if (empty($disableformtag)) {
  4544. $formconfirm .= "</form>\n";
  4545. }
  4546. $formconfirm .= '<br>';
  4547. if (!empty($conf->use_javascript_ajax)) {
  4548. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4549. $formconfirm .= '<script type="text/javascript">'."\n";
  4550. $formconfirm .= '
  4551. $(document).ready(function () {
  4552. $(".confirmvalidatebutton").on("click", function() {
  4553. console.log("We click on button");
  4554. $(this).attr("disabled", "disabled");
  4555. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4556. //console.log($(this).closest("form"));
  4557. $(this).closest("form").submit();
  4558. });
  4559. });
  4560. ';
  4561. $formconfirm .= '</script>'."\n";
  4562. }
  4563. $formconfirm .= "<!-- end formconfirm -->\n";
  4564. }
  4565. return $formconfirm;
  4566. }
  4567. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4568. /**
  4569. * Show a form to select a project
  4570. *
  4571. * @param int $page Page
  4572. * @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)
  4573. * @param int $selected Id pre-selected project
  4574. * @param string $htmlname Name of select field
  4575. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4576. * @param int $maxlength Max length
  4577. * @param int $forcefocus Force focus on field (works with javascript only)
  4578. * @param int $nooutput No print is done. String is returned.
  4579. * @return string Return html content
  4580. */
  4581. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  4582. {
  4583. // phpcs:enable
  4584. global $langs;
  4585. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4586. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4587. $out = '';
  4588. $formproject = new FormProjets($this->db);
  4589. $langs->load("project");
  4590. if ($htmlname != "none") {
  4591. $out .= "\n";
  4592. $out .= '<form method="post" action="'.$page.'">';
  4593. $out .= '<input type="hidden" name="action" value="classin">';
  4594. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4595. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  4596. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4597. $out .= '</form>';
  4598. } else {
  4599. if ($selected) {
  4600. $projet = new Project($this->db);
  4601. $projet->fetch($selected);
  4602. $out .= $projet->getNomUrl(1, '', 1);
  4603. } else {
  4604. $out .= "&nbsp;";
  4605. }
  4606. }
  4607. if (empty($nooutput)) {
  4608. print $out;
  4609. return '';
  4610. }
  4611. return $out;
  4612. }
  4613. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4614. /**
  4615. * Show a form to select payment conditions
  4616. *
  4617. * @param int $page Page
  4618. * @param string $selected Id condition pre-selectionne
  4619. * @param string $htmlname Name of select html field
  4620. * @param int $addempty Add empty entry
  4621. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4622. * @return void
  4623. */
  4624. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '')
  4625. {
  4626. // phpcs:enable
  4627. global $langs;
  4628. if ($htmlname != "none") {
  4629. print '<form method="POST" action="'.$page.'">';
  4630. print '<input type="hidden" name="action" value="setconditions">';
  4631. print '<input type="hidden" name="token" value="'.newToken().'">';
  4632. if ($type) {
  4633. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4634. }
  4635. $this->select_conditions_paiements($selected, $htmlname, -1, $addempty, 0, '');
  4636. print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4637. print '</form>';
  4638. } else {
  4639. if ($selected) {
  4640. $this->load_cache_conditions_paiements();
  4641. if (isset($this->cache_conditions_paiements[$selected])) {
  4642. print $this->cache_conditions_paiements[$selected]['label'];
  4643. } else {
  4644. $langs->load('errors');
  4645. print $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4646. }
  4647. } else {
  4648. print "&nbsp;";
  4649. }
  4650. }
  4651. }
  4652. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4653. /**
  4654. * Show a form to select a delivery delay
  4655. *
  4656. * @param int $page Page
  4657. * @param string $selected Id condition pre-selectionne
  4658. * @param string $htmlname Name of select html field
  4659. * @param int $addempty Ajoute entree vide
  4660. * @return void
  4661. */
  4662. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4663. {
  4664. // phpcs:enable
  4665. global $langs;
  4666. if ($htmlname != "none") {
  4667. print '<form method="post" action="'.$page.'">';
  4668. print '<input type="hidden" name="action" value="setavailability">';
  4669. print '<input type="hidden" name="token" value="'.newToken().'">';
  4670. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4671. print '<input type="submit" name="modify" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4672. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="'.$langs->trans("Cancel").'">';
  4673. print '</form>';
  4674. } else {
  4675. if ($selected) {
  4676. $this->load_cache_availability();
  4677. print $this->cache_availability[$selected]['label'];
  4678. } else {
  4679. print "&nbsp;";
  4680. }
  4681. }
  4682. }
  4683. /**
  4684. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  4685. * List found into table c_input_reason loaded by loadCacheInputReason
  4686. *
  4687. * @param string $page Page
  4688. * @param string $selected Id condition pre-selectionne
  4689. * @param string $htmlname Name of select html field
  4690. * @param int $addempty Add empty entry
  4691. * @return void
  4692. */
  4693. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  4694. {
  4695. global $langs;
  4696. if ($htmlname != "none") {
  4697. print '<form method="post" action="'.$page.'">';
  4698. print '<input type="hidden" name="action" value="setdemandreason">';
  4699. print '<input type="hidden" name="token" value="'.newToken().'">';
  4700. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  4701. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4702. print '</form>';
  4703. } else {
  4704. if ($selected) {
  4705. $this->loadCacheInputReason();
  4706. foreach ($this->cache_demand_reason as $key => $val) {
  4707. if ($val['id'] == $selected) {
  4708. print $val['label'];
  4709. break;
  4710. }
  4711. }
  4712. } else {
  4713. print "&nbsp;";
  4714. }
  4715. }
  4716. }
  4717. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4718. /**
  4719. * Show a form + html select a date
  4720. *
  4721. * @param string $page Page
  4722. * @param string $selected Date preselected
  4723. * @param string $htmlname Html name of date input fields or 'none'
  4724. * @param int $displayhour Display hour selector
  4725. * @param int $displaymin Display minutes selector
  4726. * @param int $nooutput 1=No print output, return string
  4727. * @param string $type 'direct-debit' or 'bank-transfer'
  4728. * @return string
  4729. * @see selectDate()
  4730. */
  4731. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  4732. {
  4733. // phpcs:enable
  4734. global $langs;
  4735. $ret = '';
  4736. if ($htmlname != "none") {
  4737. $ret .= '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4738. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4739. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4740. if ($type) {
  4741. $ret .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4742. }
  4743. $ret .= '<table class="nobordernopadding">';
  4744. $ret .= '<tr><td>';
  4745. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4746. $ret .= '</td>';
  4747. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  4748. $ret .= '</tr></table></form>';
  4749. } else {
  4750. if ($displayhour) {
  4751. $ret .= dol_print_date($selected, 'dayhour');
  4752. } else {
  4753. $ret .= dol_print_date($selected, 'day');
  4754. }
  4755. }
  4756. if (empty($nooutput)) {
  4757. print $ret;
  4758. }
  4759. return $ret;
  4760. }
  4761. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4762. /**
  4763. * Show a select form to choose a user
  4764. *
  4765. * @param string $page Page
  4766. * @param string $selected Id of user preselected
  4767. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4768. * @param array $exclude List of users id to exclude
  4769. * @param array $include List of users id to include
  4770. * @return void
  4771. */
  4772. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4773. {
  4774. // phpcs:enable
  4775. global $langs;
  4776. if ($htmlname != "none") {
  4777. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4778. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4779. print '<input type="hidden" name="token" value="'.newToken().'">';
  4780. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  4781. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4782. print '</form>';
  4783. } else {
  4784. if ($selected) {
  4785. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  4786. $theuser = new User($this->db);
  4787. $theuser->fetch($selected);
  4788. print $theuser->getNomUrl(1);
  4789. } else {
  4790. print "&nbsp;";
  4791. }
  4792. }
  4793. }
  4794. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4795. /**
  4796. * Show form with payment mode
  4797. *
  4798. * @param string $page Page
  4799. * @param int $selected Id mode pre-selectionne
  4800. * @param string $htmlname Name of select html field
  4801. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  4802. * @param int $active Active or not, -1 = all
  4803. * @param int $addempty 1=Add empty entry
  4804. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4805. * @return void
  4806. */
  4807. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '')
  4808. {
  4809. // phpcs:enable
  4810. global $langs;
  4811. if ($htmlname != "none") {
  4812. print '<form method="POST" action="'.$page.'">';
  4813. print '<input type="hidden" name="action" value="setmode">';
  4814. print '<input type="hidden" name="token" value="'.newToken().'">';
  4815. if ($type) {
  4816. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4817. }
  4818. print $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  4819. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4820. print '</form>';
  4821. } else {
  4822. if ($selected) {
  4823. $this->load_cache_types_paiements();
  4824. print $this->cache_types_paiements[$selected]['label'];
  4825. } else {
  4826. print "&nbsp;";
  4827. }
  4828. }
  4829. }
  4830. /**
  4831. * Show form with transport mode
  4832. *
  4833. * @param string $page Page
  4834. * @param int $selected Id mode pre-select
  4835. * @param string $htmlname Name of select html field
  4836. * @param int $active Active or not, -1 = all
  4837. * @param int $addempty 1=Add empty entry
  4838. * @return void
  4839. */
  4840. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  4841. {
  4842. global $langs;
  4843. if ($htmlname != "none") {
  4844. print '<form method="POST" action="'.$page.'">';
  4845. print '<input type="hidden" name="action" value="settransportmode">';
  4846. print '<input type="hidden" name="token" value="'.newToken().'">';
  4847. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  4848. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4849. print '</form>';
  4850. } else {
  4851. if ($selected) {
  4852. $this->load_cache_transport_mode();
  4853. print $this->cache_transport_mode[$selected]['label'];
  4854. } else {
  4855. print "&nbsp;";
  4856. }
  4857. }
  4858. }
  4859. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4860. /**
  4861. * Show form with multicurrency code
  4862. *
  4863. * @param string $page Page
  4864. * @param string $selected code pre-selectionne
  4865. * @param string $htmlname Name of select html field
  4866. * @return void
  4867. */
  4868. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  4869. {
  4870. // phpcs:enable
  4871. global $langs;
  4872. if ($htmlname != "none") {
  4873. print '<form method="POST" action="'.$page.'">';
  4874. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  4875. print '<input type="hidden" name="token" value="'.newToken().'">';
  4876. print $this->selectMultiCurrency($selected, $htmlname, 0);
  4877. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4878. print '</form>';
  4879. } else {
  4880. dol_include_once('/core/lib/company.lib.php');
  4881. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  4882. }
  4883. }
  4884. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4885. /**
  4886. * Show form with multicurrency rate
  4887. *
  4888. * @param string $page Page
  4889. * @param double $rate Current rate
  4890. * @param string $htmlname Name of select html field
  4891. * @param string $currency Currency code to explain the rate
  4892. * @return void
  4893. */
  4894. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  4895. {
  4896. // phpcs:enable
  4897. global $langs, $mysoc, $conf;
  4898. if ($htmlname != "none") {
  4899. print '<form method="POST" action="'.$page.'">';
  4900. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  4901. print '<input type="hidden" name="token" value="'.newToken().'">';
  4902. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
  4903. print '<select name="calculation_mode">';
  4904. print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
  4905. print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
  4906. print '</select> ';
  4907. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4908. print '</form>';
  4909. } else {
  4910. if (!empty($rate)) {
  4911. print price($rate, 1, $langs, 1, 0);
  4912. if ($currency && $rate != 1) {
  4913. print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  4914. }
  4915. } else {
  4916. print 1;
  4917. }
  4918. }
  4919. }
  4920. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4921. /**
  4922. * Show a select box with available absolute discounts
  4923. *
  4924. * @param string $page Page URL where form is shown
  4925. * @param int $selected Value pre-selected
  4926. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  4927. * @param int $socid Third party id
  4928. * @param float $amount Total amount available
  4929. * @param string $filter SQL filter on discounts
  4930. * @param int $maxvalue Max value for lines that can be selected
  4931. * @param string $more More string to add
  4932. * @param int $hidelist 1=Hide list
  4933. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  4934. * @return void
  4935. */
  4936. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  4937. {
  4938. // phpcs:enable
  4939. global $conf, $langs;
  4940. if ($htmlname != "none") {
  4941. print '<form method="post" action="'.$page.'">';
  4942. print '<input type="hidden" name="action" value="setabsolutediscount">';
  4943. print '<input type="hidden" name="token" value="'.newToken().'">';
  4944. print '<div class="inline-block">';
  4945. if (!empty($discount_type)) {
  4946. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  4947. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  4948. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4949. } else {
  4950. $translationKey = 'HasCreditNoteFromSupplier';
  4951. }
  4952. } else {
  4953. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  4954. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  4955. } else {
  4956. $translationKey = 'HasCreditNoteFromSupplier';
  4957. }
  4958. }
  4959. } else {
  4960. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  4961. if (!$filter || $filter == "fk_facture_source IS NULL") {
  4962. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4963. } else {
  4964. $translationKey = 'CompanyHasCreditNote';
  4965. }
  4966. } else {
  4967. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  4968. $translationKey = 'CompanyHasAbsoluteDiscount';
  4969. } else {
  4970. $translationKey = 'CompanyHasCreditNote';
  4971. }
  4972. }
  4973. }
  4974. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  4975. if (empty($hidelist)) {
  4976. print ' ';
  4977. }
  4978. print '</div>';
  4979. if (empty($hidelist)) {
  4980. print '<div class="inline-block" style="padding-right: 10px">';
  4981. $newfilter = 'discount_type='.intval($discount_type);
  4982. if (!empty($discount_type)) {
  4983. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  4984. } else {
  4985. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  4986. }
  4987. if ($filter) {
  4988. $newfilter .= ' AND ('.$filter.')';
  4989. }
  4990. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  4991. if ($nbqualifiedlines > 0) {
  4992. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  4993. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  4994. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4995. }
  4996. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  4997. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4998. }
  4999. print '>';
  5000. }
  5001. print '</div>';
  5002. }
  5003. if ($more) {
  5004. print '<div class="inline-block">';
  5005. print $more;
  5006. print '</div>';
  5007. }
  5008. print '</form>';
  5009. } else {
  5010. if ($selected) {
  5011. print $selected;
  5012. } else {
  5013. print "0";
  5014. }
  5015. }
  5016. }
  5017. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5018. /**
  5019. * Show forms to select a contact
  5020. *
  5021. * @param string $page Page
  5022. * @param Societe $societe Filter on third party
  5023. * @param int $selected Id contact pre-selectionne
  5024. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5025. * @return void
  5026. */
  5027. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5028. {
  5029. // phpcs:enable
  5030. global $langs, $conf;
  5031. if ($htmlname != "none") {
  5032. print '<form method="post" action="'.$page.'">';
  5033. print '<input type="hidden" name="action" value="set_contact">';
  5034. print '<input type="hidden" name="token" value="'.newToken().'">';
  5035. print '<table class="nobordernopadding">';
  5036. print '<tr><td>';
  5037. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5038. $num = $this->num;
  5039. if ($num == 0) {
  5040. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5041. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  5042. }
  5043. print '</td>';
  5044. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5045. print '</tr></table></form>';
  5046. } else {
  5047. if ($selected) {
  5048. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  5049. $contact = new Contact($this->db);
  5050. $contact->fetch($selected);
  5051. print $contact->getFullName($langs);
  5052. } else {
  5053. print "&nbsp;";
  5054. }
  5055. }
  5056. }
  5057. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5058. /**
  5059. * Output html select to select thirdparty
  5060. *
  5061. * @param string $page Page
  5062. * @param string $selected Id preselected
  5063. * @param string $htmlname Name of HTML select
  5064. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5065. * @param int $showempty Add an empty field
  5066. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5067. * @param int $forcecombo Force to use combo box
  5068. * @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')))
  5069. * @param int $nooutput No print output. Return it only.
  5070. * @param array $excludeids Exclude IDs from the select combo
  5071. * @return void|string
  5072. */
  5073. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array())
  5074. {
  5075. // phpcs:enable
  5076. global $langs;
  5077. $out = '';
  5078. if ($htmlname != "none") {
  5079. $out .= '<form method="post" action="'.$page.'">';
  5080. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5081. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5082. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5083. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5084. $out .= '</form>';
  5085. } else {
  5086. if ($selected) {
  5087. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  5088. $soc = new Societe($this->db);
  5089. $soc->fetch($selected);
  5090. $out .= $soc->getNomUrl($langs);
  5091. } else {
  5092. $out .= "&nbsp;";
  5093. }
  5094. }
  5095. if ($nooutput) {
  5096. return $out;
  5097. } else {
  5098. print $out;
  5099. }
  5100. }
  5101. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5102. /**
  5103. * Retourne la liste des devises, dans la langue de l'utilisateur
  5104. *
  5105. * @param string $selected preselected currency code
  5106. * @param string $htmlname name of HTML select list
  5107. * @deprecated
  5108. * @return void
  5109. */
  5110. public function select_currency($selected = '', $htmlname = 'currency_id')
  5111. {
  5112. // phpcs:enable
  5113. print $this->selectCurrency($selected, $htmlname);
  5114. }
  5115. /**
  5116. * Retourne la liste des devises, dans la langue de l'utilisateur
  5117. *
  5118. * @param string $selected preselected currency code
  5119. * @param string $htmlname name of HTML select list
  5120. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5121. * @return string
  5122. */
  5123. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0)
  5124. {
  5125. global $conf, $langs, $user;
  5126. $langs->loadCacheCurrencies('');
  5127. $out = '';
  5128. if ($selected == 'euro' || $selected == 'euros') {
  5129. $selected = 'EUR'; // Pour compatibilite
  5130. }
  5131. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  5132. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5133. $labeltoshow = $currency['label'];
  5134. if ($mode == 1) {
  5135. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  5136. } else {
  5137. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  5138. }
  5139. if ($selected && $selected == $code_iso) {
  5140. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5141. } else {
  5142. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5143. }
  5144. $out .= $labeltoshow;
  5145. $out .= '</option>';
  5146. }
  5147. $out .= '</select>';
  5148. if ($user->admin) {
  5149. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5150. }
  5151. // Make select dynamic
  5152. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5153. $out .= ajax_combobox($htmlname);
  5154. return $out;
  5155. }
  5156. /**
  5157. * Return array of currencies in user language
  5158. *
  5159. * @param string $selected preselected currency code
  5160. * @param string $htmlname name of HTML select list
  5161. * @param integer $useempty 1=Add empty line
  5162. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5163. * @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
  5164. * @return string
  5165. */
  5166. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false)
  5167. {
  5168. global $db, $conf, $langs, $user;
  5169. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5170. $TCurrency = array();
  5171. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
  5172. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  5173. if ($filter) {
  5174. $sql .= " AND ".$filter;
  5175. }
  5176. $resql = $this->db->query($sql);
  5177. if ($resql) {
  5178. while ($obj = $this->db->fetch_object($resql)) {
  5179. $TCurrency[$obj->code] = $obj->code;
  5180. }
  5181. }
  5182. $out = '';
  5183. $out .= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  5184. if ($useempty) {
  5185. $out .= '<option value="">&nbsp;</option>';
  5186. }
  5187. // If company current currency not in table, we add it into list. Should always be available.
  5188. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5189. $TCurrency[$conf->currency] = $conf->currency;
  5190. }
  5191. if (count($TCurrency) > 0) {
  5192. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5193. if (isset($TCurrency[$code_iso])) {
  5194. if (!empty($selected) && $selected == $code_iso) {
  5195. $out .= '<option value="'.$code_iso.'" selected="selected">';
  5196. } else {
  5197. $out .= '<option value="'.$code_iso.'">';
  5198. }
  5199. $out .= $currency['label'];
  5200. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  5201. $out .= '</option>';
  5202. }
  5203. }
  5204. }
  5205. $out .= '</select>';
  5206. // Make select dynamic
  5207. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5208. $out .= ajax_combobox($htmlname);
  5209. return $out;
  5210. }
  5211. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5212. /**
  5213. * Load into the cache vat rates of a country
  5214. *
  5215. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5216. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5217. */
  5218. public function load_cache_vatrates($country_code)
  5219. {
  5220. // phpcs:enable
  5221. global $langs;
  5222. $num = count($this->cache_vatrates);
  5223. if ($num > 0) {
  5224. return $num; // Cache already loaded
  5225. }
  5226. dol_syslog(__METHOD__, LOG_DEBUG);
  5227. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5228. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5229. $sql .= " WHERE t.fk_pays = c.rowid";
  5230. $sql .= " AND t.active > 0";
  5231. $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
  5232. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5233. $resql = $this->db->query($sql);
  5234. if ($resql) {
  5235. $num = $this->db->num_rows($resql);
  5236. if ($num) {
  5237. for ($i = 0; $i < $num; $i++) {
  5238. $obj = $this->db->fetch_object($resql);
  5239. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5240. $this->cache_vatrates[$i]['code'] = $obj->code;
  5241. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5242. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5243. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5244. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5245. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5246. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5247. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  5248. $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
  5249. $positiverates = '';
  5250. if ($obj->taux) {
  5251. $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  5252. }
  5253. if ($obj->localtax1) {
  5254. $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  5255. }
  5256. if ($obj->localtax2) {
  5257. $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  5258. }
  5259. if (empty($positiverates)) {
  5260. $positiverates = '0';
  5261. }
  5262. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5263. }
  5264. return $num;
  5265. } else {
  5266. $this->error = '<span class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</span>';
  5267. return -1;
  5268. }
  5269. } else {
  5270. $this->error = '<span class="error">'.$this->db->error().'</span>';
  5271. return -2;
  5272. }
  5273. }
  5274. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5275. /**
  5276. * Output an HTML select vat rate.
  5277. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5278. *
  5279. * @param string $htmlname Name of HTML select field
  5280. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5281. * @param Societe $societe_vendeuse Thirdparty seller
  5282. * @param Societe $societe_acheteuse Thirdparty buyer
  5283. * @param int $idprod Id product. O if unknown of NA.
  5284. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5285. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5286. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5287. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5288. * 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.
  5289. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5290. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5291. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5292. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5293. * @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
  5294. * @return string
  5295. */
  5296. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5297. {
  5298. // phpcs:enable
  5299. global $langs, $conf, $mysoc;
  5300. $langs->load('errors');
  5301. $return = '';
  5302. // Define defaultnpr, defaultttx and defaultcode
  5303. $defaultnpr = ($info_bits & 0x01);
  5304. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5305. $defaulttx = str_replace('*', '', $selectedrate);
  5306. $defaultcode = '';
  5307. $reg = array();
  5308. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5309. $defaultcode = $reg[1];
  5310. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5311. }
  5312. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5313. // Check parameters
  5314. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5315. if ($societe_vendeuse->id == $mysoc->id) {
  5316. $return .= '<span class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</span>';
  5317. } else {
  5318. $return .= '<span class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</span>';
  5319. }
  5320. return $return;
  5321. }
  5322. //var_dump($societe_acheteuse);
  5323. //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";
  5324. //exit;
  5325. // Define list of countries to use to search VAT rates to show
  5326. // First we defined code_country to use to find list
  5327. if (is_object($societe_vendeuse)) {
  5328. $code_country = "'".$societe_vendeuse->country_code."'";
  5329. } else {
  5330. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  5331. }
  5332. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5333. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5334. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5335. // We also add the buyer
  5336. if (is_numeric($type)) {
  5337. if ($type == 1) { // We know product is a service
  5338. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5339. }
  5340. } elseif (!$idprod) { // We don't know type of product
  5341. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5342. } else {
  5343. $prodstatic = new Product($this->db);
  5344. $prodstatic->fetch($idprod);
  5345. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5346. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5347. }
  5348. }
  5349. }
  5350. }
  5351. // Now we get list
  5352. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5353. if ($num > 0) {
  5354. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5355. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5356. $tmpthirdparty = new Societe($this->db);
  5357. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5358. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5359. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5360. $defaultcode = $reg[1];
  5361. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5362. }
  5363. if (empty($defaulttx)) {
  5364. $defaultnpr = 0;
  5365. }
  5366. }
  5367. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  5368. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  5369. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5370. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5371. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5372. } else {
  5373. $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  5374. }
  5375. }
  5376. // Disabled if seller is not subject to VAT
  5377. $disabled = false;
  5378. $title = '';
  5379. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5380. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5381. // of using supplier invoices (this is a very bad idea !)
  5382. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5383. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  5384. $disabled = true;
  5385. }
  5386. }
  5387. if (!$options_only) {
  5388. $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  5389. }
  5390. $selectedfound = false;
  5391. foreach ($this->cache_vatrates as $rate) {
  5392. // Keep only 0 if seller is not subject to VAT
  5393. if ($disabled && $rate['txtva'] != 0) {
  5394. continue;
  5395. }
  5396. // Define key to use into select list
  5397. $key = $rate['txtva'];
  5398. $key .= $rate['nprtva'] ? '*' : '';
  5399. if ($mode > 0 && $rate['code']) {
  5400. $key .= ' ('.$rate['code'].')';
  5401. }
  5402. if ($mode < 0) {
  5403. $key = $rate['rowid'];
  5404. }
  5405. $return .= '<option value="'.$key.'"';
  5406. if (!$selectedfound) {
  5407. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5408. if ($defaultcode == $rate['code']) {
  5409. $return .= ' selected';
  5410. $selectedfound = true;
  5411. }
  5412. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5413. $return .= ' selected';
  5414. $selectedfound = true;
  5415. }
  5416. }
  5417. $return .= '>';
  5418. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  5419. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5420. $return .= $rate['labelpositiverates'];
  5421. } else {
  5422. $return .= vatrate($rate['label']);
  5423. }
  5424. //$return.=($rate['code']?' '.$rate['code']:'');
  5425. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5426. $return .= '</option>';
  5427. }
  5428. if (!$options_only) {
  5429. $return .= '</select>';
  5430. }
  5431. } else {
  5432. $return .= $this->error;
  5433. }
  5434. $this->num = $num;
  5435. return $return;
  5436. }
  5437. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5438. /**
  5439. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5440. * Fields are preselected with :
  5441. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5442. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5443. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5444. *
  5445. * @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).
  5446. * @param string $prefix Prefix for fields name
  5447. * @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
  5448. * @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
  5449. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5450. * @param string $form_name Not used
  5451. * @param int $d 1=Show days, month, years
  5452. * @param int $addnowlink Add a link "Now"
  5453. * @param int $nooutput Do not output html string but return it
  5454. * @param int $disabled Disable input fields
  5455. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5456. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5457. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5458. * @return string|void Nothing or string if nooutput is 1
  5459. * @deprecated
  5460. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5461. */
  5462. 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 = '')
  5463. {
  5464. // phpcs:enable
  5465. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5466. if (!empty($nooutput)) {
  5467. return $retstring;
  5468. }
  5469. print $retstring;
  5470. return;
  5471. }
  5472. /**
  5473. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5474. * Fields are preselected with :
  5475. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5476. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5477. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5478. *
  5479. * @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).
  5480. * @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).
  5481. * @param string $prefix Prefix for fields name
  5482. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5483. * @return string Html for selectDate
  5484. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5485. */
  5486. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0)
  5487. {
  5488. global $langs;
  5489. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5490. $ret .= '<br>';
  5491. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5492. return $ret;
  5493. }
  5494. /**
  5495. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5496. * Fields are preselected with :
  5497. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5498. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5499. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5500. *
  5501. * @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).
  5502. * @param string $prefix Prefix for fields name
  5503. * @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
  5504. * @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
  5505. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5506. * @param string $form_name Not used
  5507. * @param int $d 1=Show days, month, years
  5508. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5509. * @param int $disabled Disable input fields
  5510. * @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')
  5511. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5512. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5513. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5514. * @param int $stepminutes Specify step for minutes between 1 and 30
  5515. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5516. * @param string $placeholder Placeholder
  5517. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5518. * @return string Html for selectDate
  5519. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5520. */
  5521. 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')
  5522. {
  5523. global $conf, $langs;
  5524. if ($gm === 'auto') {
  5525. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5526. }
  5527. $retstring = '';
  5528. if ($prefix == '') {
  5529. $prefix = 're';
  5530. }
  5531. if ($h == '') {
  5532. $h = 0;
  5533. }
  5534. if ($m == '') {
  5535. $m = 0;
  5536. }
  5537. $emptydate = 0;
  5538. $emptyhours = 0;
  5539. if ($stepminutes <= 0 || $stepminutes > 30) {
  5540. $stepminutes = 1;
  5541. }
  5542. if ($empty == 1) {
  5543. $emptydate = 1;
  5544. $emptyhours = 1;
  5545. }
  5546. if ($empty == 2) {
  5547. $emptydate = 0;
  5548. $emptyhours = 1;
  5549. }
  5550. $orig_set_time = $set_time;
  5551. if ($set_time === '' && $emptydate == 0) {
  5552. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5553. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5554. $set_time = dol_now($gm);
  5555. } else {
  5556. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5557. }
  5558. }
  5559. // Analysis of the pre-selection date
  5560. $reg = array();
  5561. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5562. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5563. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5564. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5565. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5566. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5567. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5568. } elseif (strval($set_time) != '' && $set_time != -1) {
  5569. // set_time est un timestamps (0 possible)
  5570. $syear = dol_print_date($set_time, "%Y", $gm);
  5571. $smonth = dol_print_date($set_time, "%m", $gm);
  5572. $sday = dol_print_date($set_time, "%d", $gm);
  5573. if ($orig_set_time != '') {
  5574. $shour = dol_print_date($set_time, "%H", $gm);
  5575. $smin = dol_print_date($set_time, "%M", $gm);
  5576. $ssec = dol_print_date($set_time, "%S", $gm);
  5577. } else {
  5578. $shour = '';
  5579. $smin = '';
  5580. $ssec = '';
  5581. }
  5582. } else {
  5583. // Date est '' ou vaut -1
  5584. $syear = '';
  5585. $smonth = '';
  5586. $sday = '';
  5587. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5588. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5589. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5590. }
  5591. if ($h == 3) {
  5592. $shour = '';
  5593. }
  5594. if ($m == 3) {
  5595. $smin = '';
  5596. }
  5597. $nowgmt = dol_now('gmt');
  5598. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5599. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5600. $usecalendar = 'combo';
  5601. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5602. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5603. }
  5604. if ($d) {
  5605. // Show date with popup
  5606. if ($usecalendar != 'combo') {
  5607. $formated_date = '';
  5608. //print "e".$set_time." t ".$conf->format_date_short;
  5609. if (strval($set_time) != '' && $set_time != -1) {
  5610. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5611. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5612. }
  5613. // Calendrier popup version eldy
  5614. if ($usecalendar == "eldy") {
  5615. // Input area to enter date manually
  5616. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5617. $retstring .= ($disabled ? ' disabled' : '');
  5618. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5619. $retstring .= '>';
  5620. // Icon calendar
  5621. $retstringbuttom = '';
  5622. if (!$disabled) {
  5623. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5624. $base = DOL_URL_ROOT.'/core/';
  5625. $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5626. $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5627. } else {
  5628. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5629. }
  5630. $retstring = $retstringbuttom.$retstring;
  5631. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5632. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5633. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5634. } elseif ($usecalendar == 'jquery') {
  5635. if (!$disabled) {
  5636. // Output javascript for datepicker
  5637. $retstring .= "<script type='text/javascript'>";
  5638. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5639. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5640. autoclose: true,
  5641. todayHighlight: true,";
  5642. if (!empty($conf->dol_use_jmobile)) {
  5643. $retstring .= "
  5644. beforeShow: function (input, datePicker) {
  5645. input.disabled = true;
  5646. },
  5647. onClose: function (dateText, datePicker) {
  5648. this.disabled = false;
  5649. },
  5650. ";
  5651. }
  5652. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  5653. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  5654. $retstring .= "
  5655. showOn: 'button', /* both has problem with autocompletion */
  5656. buttonImage: '".DOL_URL_ROOT."/theme/".dol_escape_js($conf->theme)."/img/object_calendarday.png',
  5657. buttonImageOnly: true";
  5658. }
  5659. $retstring .= "
  5660. }) });";
  5661. $retstring .= "</script>";
  5662. }
  5663. // Zone de saisie manuelle de la date
  5664. $retstring .= '<div class="nowrap inline-block divfordateinput">';
  5665. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5666. $retstring .= ($disabled ? ' disabled' : '');
  5667. $retstring .= ($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '');
  5668. $retstring .= ' onChange="dpChangeDay(\''.dol_escape_js($prefix).'\',\''.dol_escape_js($langs->trans("FormatDateShortJavaInput")).'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5669. $retstring .= '>';
  5670. // Icone calendrier
  5671. if (!$disabled) {
  5672. /* Not required. Managed by option buttonImage of jquery
  5673. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  5674. $retstring.="<script type='text/javascript'>";
  5675. $retstring.="jQuery(document).ready(function() {";
  5676. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  5677. $retstring.=" jQuery('#".$prefix."').focus();";
  5678. $retstring.=' });';
  5679. $retstring.='});';
  5680. $retstring.="</script>";*/
  5681. } else {
  5682. $retstringbutton = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5683. $retsring = $retstringbutton.$retstring;
  5684. }
  5685. $retstring .= '</div>';
  5686. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5687. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5688. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5689. } else {
  5690. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  5691. }
  5692. } else {
  5693. // Show date with combo selects
  5694. // Day
  5695. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  5696. if ($emptydate || $set_time == -1) {
  5697. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5698. }
  5699. for ($day = 1; $day <= 31; $day++) {
  5700. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  5701. }
  5702. $retstring .= "</select>";
  5703. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  5704. if ($emptydate || $set_time == -1) {
  5705. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5706. }
  5707. // Month
  5708. for ($month = 1; $month <= 12; $month++) {
  5709. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  5710. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  5711. $retstring .= "</option>";
  5712. }
  5713. $retstring .= "</select>";
  5714. // Year
  5715. if ($emptydate || $set_time == -1) {
  5716. $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.'">';
  5717. } else {
  5718. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  5719. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  5720. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  5721. }
  5722. $retstring .= "</select>\n";
  5723. }
  5724. }
  5725. }
  5726. if ($d && $h) {
  5727. $retstring .= ($h == 2 ? '<br>' : ' ');
  5728. $retstring .= '<span class="nowraponall">';
  5729. }
  5730. if ($h) {
  5731. $hourstart = 0;
  5732. $hourend = 24;
  5733. if ($openinghours != '') {
  5734. $openinghours = explode(',', $openinghours);
  5735. $hourstart = $openinghours[0];
  5736. $hourend = $openinghours[1];
  5737. if ($hourend < $hourstart) {
  5738. $hourend = $hourstart;
  5739. }
  5740. }
  5741. // Show hour
  5742. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  5743. if ($emptyhours) {
  5744. $retstring .= '<option value="-1">&nbsp;</option>';
  5745. }
  5746. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  5747. if (strlen($hour) < 2) {
  5748. $hour = "0".$hour;
  5749. }
  5750. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  5751. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  5752. $retstring .= '</option>';
  5753. }
  5754. $retstring .= '</select>';
  5755. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  5756. if ($m) {
  5757. $retstring .= ":";
  5758. }
  5759. }
  5760. if ($m) {
  5761. // Show minutes
  5762. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  5763. if ($emptyhours) {
  5764. $retstring .= '<option value="-1">&nbsp;</option>';
  5765. }
  5766. for ($min = 0; $min < 60; $min += $stepminutes) {
  5767. if (strlen($min) < 2) {
  5768. $min = "0".$min;
  5769. }
  5770. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  5771. }
  5772. $retstring .= '</select>';
  5773. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  5774. }
  5775. if ($d && $h) {
  5776. $retstring .= '</span>';
  5777. }
  5778. // Add a "Now" link
  5779. if ($conf->use_javascript_ajax && $addnowlink) {
  5780. // Script which will be inserted in the onClick of the "Now" link
  5781. $reset_scripts = "";
  5782. if ($addnowlink == 2) { // local computer time
  5783. // pad add leading 0 on numbers
  5784. $reset_scripts .= "Number.prototype.pad = function(size) {
  5785. var s = String(this);
  5786. while (s.length < (size || 2)) {s = '0' + s;}
  5787. return s;
  5788. };
  5789. var d = new Date();";
  5790. }
  5791. // Generate the date part, depending on the use or not of the javascript calendar
  5792. if ($addnowlink == 1) { // server time expressed in user time setup
  5793. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5794. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5795. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5796. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5797. } elseif ($addnowlink == 2) {
  5798. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  5799. * This break application for foreign languages.
  5800. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  5801. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  5802. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  5803. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  5804. */
  5805. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5806. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5807. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5808. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5809. }
  5810. /*if ($usecalendar == "eldy")
  5811. {
  5812. $base=DOL_URL_ROOT.'/core/';
  5813. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  5814. }
  5815. else
  5816. {
  5817. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  5818. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  5819. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  5820. }*/
  5821. // Update the hour part
  5822. if ($h) {
  5823. if ($fullday) {
  5824. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5825. }
  5826. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  5827. if ($addnowlink == 1) {
  5828. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  5829. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5830. } elseif ($addnowlink == 2) {
  5831. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  5832. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5833. }
  5834. if ($fullday) {
  5835. $reset_scripts .= ' } ';
  5836. }
  5837. }
  5838. // Update the minute part
  5839. if ($m) {
  5840. if ($fullday) {
  5841. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5842. }
  5843. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  5844. if ($addnowlink == 1) {
  5845. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  5846. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5847. } elseif ($addnowlink == 2) {
  5848. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  5849. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5850. }
  5851. if ($fullday) {
  5852. $reset_scripts .= ' } ';
  5853. }
  5854. }
  5855. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5856. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  5857. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  5858. $retstring .= $langs->trans("Now");
  5859. $retstring .= '</button> ';
  5860. }
  5861. }
  5862. // Add a "Plus one hour" link
  5863. if ($conf->use_javascript_ajax && $addplusone) {
  5864. // Script which will be inserted in the onClick of the "Add plusone" link
  5865. $reset_scripts = "";
  5866. // Generate the date part, depending on the use or not of the javascript calendar
  5867. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');';
  5868. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5869. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5870. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5871. // Update the hour part
  5872. if ($h) {
  5873. if ($fullday) {
  5874. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5875. }
  5876. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  5877. if ($fullday) {
  5878. $reset_scripts .= ' } ';
  5879. }
  5880. }
  5881. // Update the minute part
  5882. if ($m) {
  5883. if ($fullday) {
  5884. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5885. }
  5886. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  5887. if ($fullday) {
  5888. $reset_scripts .= ' } ';
  5889. }
  5890. }
  5891. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5892. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  5893. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  5894. $retstring .= $langs->trans("DateStartPlusOne");
  5895. $retstring .= '</button> ';
  5896. }
  5897. }
  5898. // Add a link to set data
  5899. if ($conf->use_javascript_ajax && $adddateof) {
  5900. $tmparray = dol_getdate($adddateof);
  5901. if (empty($labeladddateof)) {
  5902. $labeladddateof = $langs->trans("DateInvoice");
  5903. }
  5904. $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>';
  5905. }
  5906. return $retstring;
  5907. }
  5908. /**
  5909. * selectTypeDuration
  5910. *
  5911. * @param string $prefix Prefix
  5912. * @param string $selected Selected duration type
  5913. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  5914. * @return string HTML select string
  5915. */
  5916. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  5917. {
  5918. global $langs;
  5919. $TDurationTypes = array(
  5920. 'y'=>$langs->trans('Years'),
  5921. 'm'=>$langs->trans('Month'),
  5922. 'w'=>$langs->trans('Weeks'),
  5923. 'd'=>$langs->trans('Days'),
  5924. 'h'=>$langs->trans('Hours'),
  5925. 'i'=>$langs->trans('Minutes')
  5926. );
  5927. // Removed undesired duration types
  5928. foreach ($excludetypes as $value) {
  5929. unset($TDurationTypes[$value]);
  5930. }
  5931. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  5932. foreach ($TDurationTypes as $key => $typeduration) {
  5933. $retstring .= '<option value="'.$key.'"';
  5934. if ($key == $selected) {
  5935. $retstring .= " selected";
  5936. }
  5937. $retstring .= ">".$typeduration."</option>";
  5938. }
  5939. $retstring .= "</select>";
  5940. $retstring .= ajax_combobox('select_'.$prefix.'type_duration');
  5941. return $retstring;
  5942. }
  5943. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5944. /**
  5945. * Function to show a form to select a duration on a page
  5946. *
  5947. * @param string $prefix Prefix for input fields
  5948. * @param int $iSecond Default preselected duration (number of seconds or '')
  5949. * @param int $disabled Disable the combo box
  5950. * @param string $typehour If 'select' then input hour and input min is a combo,
  5951. * If 'text' input hour is in text and input min is a text,
  5952. * If 'textselect' input hour is in text and input min is a combo
  5953. * @param integer $minunderhours If 1, show minutes selection under the hours
  5954. * @param int $nooutput Do not output html string but return it
  5955. * @return string|void
  5956. */
  5957. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  5958. {
  5959. // phpcs:enable
  5960. global $langs;
  5961. $retstring = '';
  5962. $hourSelected = 0;
  5963. $minSelected = 0;
  5964. // Hours
  5965. if ($iSecond != '') {
  5966. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5967. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  5968. $minSelected = convertSecondToTime($iSecond, 'min');
  5969. }
  5970. if ($typehour == 'select') {
  5971. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  5972. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  5973. $retstring .= '<option value="'.$hour.'"';
  5974. if ($hourSelected == $hour) {
  5975. $retstring .= " selected";
  5976. }
  5977. $retstring .= ">".$hour."</option>";
  5978. }
  5979. $retstring .= "</select>";
  5980. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  5981. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  5982. } else {
  5983. return 'BadValueForParameterTypeHour';
  5984. }
  5985. if ($typehour != 'text') {
  5986. $retstring .= ' '.$langs->trans('HourShort');
  5987. } else {
  5988. $retstring .= '<span class="hideonsmartphone">:</span>';
  5989. }
  5990. // Minutes
  5991. if ($minunderhours) {
  5992. $retstring .= '<br>';
  5993. } else {
  5994. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  5995. }
  5996. if ($typehour == 'select' || $typehour == 'textselect') {
  5997. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  5998. for ($min = 0; $min <= 55; $min = $min + 5) {
  5999. $retstring .= '<option value="'.$min.'"';
  6000. if ($minSelected == $min) {
  6001. $retstring .= ' selected';
  6002. }
  6003. $retstring .= '>'.$min.'</option>';
  6004. }
  6005. $retstring .= "</select>";
  6006. } elseif ($typehour == 'text') {
  6007. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  6008. }
  6009. if ($typehour != 'text') {
  6010. $retstring .= ' '.$langs->trans('MinuteShort');
  6011. }
  6012. //$retstring.="&nbsp;";
  6013. if (!empty($nooutput)) {
  6014. return $retstring;
  6015. }
  6016. print $retstring;
  6017. return;
  6018. }
  6019. /**
  6020. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6021. *
  6022. * @param int $selected Preselected tickets
  6023. * @param string $htmlname Name of HTML select field (must be unique in page).
  6024. * @param string $filtertype To add a filter
  6025. * @param int $limit Limit on number of returned lines
  6026. * @param int $status Ticket status
  6027. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6028. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6029. * @param array $ajaxoptions Options for ajax_autocompleter
  6030. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6031. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6032. * @param int $forcecombo Force to use combo box
  6033. * @param string $morecss Add more css on select
  6034. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6035. * @param string $nooutput No print, return the output into a string
  6036. * @return void|string
  6037. */
  6038. 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)
  6039. {
  6040. global $langs, $conf;
  6041. $out = '';
  6042. // check parameters
  6043. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6044. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6045. $placeholder = '';
  6046. if ($selected && empty($selected_input_value)) {
  6047. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6048. $tickettmpselect = new Ticket($this->db);
  6049. $tickettmpselect->fetch($selected);
  6050. $selected_input_value = $tickettmpselect->ref;
  6051. unset($tickettmpselect);
  6052. }
  6053. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6054. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6055. elseif ($hidelabel > 1) {
  6056. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6057. if ($hidelabel == 2) {
  6058. $out .= img_picto($langs->trans("Search"), 'search');
  6059. }
  6060. }
  6061. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6062. if ($hidelabel == 3) {
  6063. $out .= img_picto($langs->trans("Search"), 'search');
  6064. }
  6065. } else {
  6066. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6067. }
  6068. if (empty($nooutput)) print $out;
  6069. else return $out;
  6070. }
  6071. /**
  6072. * Return list of tickets.
  6073. * Called by selectTickets.
  6074. *
  6075. * @param int $selected Preselected ticket
  6076. * @param string $htmlname Name of select html
  6077. * @param string $filtertype Filter on ticket type
  6078. * @param int $limit Limit on number of returned lines
  6079. * @param string $filterkey Filter on ticket ref or subject
  6080. * @param int $status Ticket status
  6081. * @param int $outputmode 0=HTML select string, 1=Array
  6082. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6083. * @param int $forcecombo Force to use combo box
  6084. * @param string $morecss Add more css on select
  6085. * @return array Array of keys for json
  6086. */
  6087. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6088. {
  6089. global $langs, $conf, $user, $db;
  6090. $out = '';
  6091. $outarray = array();
  6092. $selectFields = " p.rowid, p.ref, p.message";
  6093. $sql = "SELECT ";
  6094. $sql .= $selectFields;
  6095. $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
  6096. $sql .= ' WHERE p.entity IN ('.getEntity('ticket').')';
  6097. // Add criteria on ref/label
  6098. if ($filterkey != '') {
  6099. $sql .= ' AND (';
  6100. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6101. // For natural search
  6102. $scrit = explode(' ', $filterkey);
  6103. $i = 0;
  6104. if (count($scrit) > 1) $sql .= "(";
  6105. foreach ($scrit as $crit) {
  6106. if ($i > 0) $sql .= " AND ";
  6107. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.subject LIKE '".$this->db->escape($prefix.$crit)."%'";
  6108. $sql .= ")";
  6109. $i++;
  6110. }
  6111. if (count($scrit) > 1) $sql .= ")";
  6112. $sql .= ')';
  6113. }
  6114. $sql .= $this->db->plimit($limit, 0);
  6115. // Build output string
  6116. dol_syslog(get_class($this)."::selectTicketsList search tickets", LOG_DEBUG);
  6117. $result = $this->db->query($sql);
  6118. if ($result) {
  6119. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6120. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  6121. $num = $this->db->num_rows($result);
  6122. $events = null;
  6123. if (!$forcecombo) {
  6124. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6125. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6126. }
  6127. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6128. $textifempty = '';
  6129. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6130. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6131. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6132. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6133. else $textifempty .= $langs->trans("All");
  6134. } else {
  6135. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6136. }
  6137. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6138. $i = 0;
  6139. while ($num && $i < $num) {
  6140. $opt = '';
  6141. $optJson = array();
  6142. $objp = $this->db->fetch_object($result);
  6143. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6144. // Add new entry
  6145. // "key" value of json key array is used by jQuery automatically as selected value
  6146. // "label" value of json key array is used by jQuery automatically as text for combo box
  6147. $out .= $opt;
  6148. array_push($outarray, $optJson);
  6149. $i++;
  6150. }
  6151. $out .= '</select>';
  6152. $this->db->free($result);
  6153. if (empty($outputmode)) return $out;
  6154. return $outarray;
  6155. } else {
  6156. dol_print_error($db);
  6157. }
  6158. }
  6159. /**
  6160. * constructTicketListOption.
  6161. * This define value for &$opt and &$optJson.
  6162. *
  6163. * @param resource $objp Result set of fetch
  6164. * @param string $opt Option (var used for returned value in string option format)
  6165. * @param string $optJson Option (var used for returned value in json format)
  6166. * @param string $selected Preselected value
  6167. * @param string $filterkey Filter key to highlight
  6168. * @return void
  6169. */
  6170. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6171. {
  6172. global $langs, $conf, $user, $db;
  6173. $outkey = '';
  6174. $outval = '';
  6175. $outref = '';
  6176. $outlabel = '';
  6177. $outtype = '';
  6178. $label = $objp->label;
  6179. $outkey = $objp->rowid;
  6180. $outref = $objp->ref;
  6181. $outlabel = $objp->label;
  6182. $outtype = $objp->fk_product_type;
  6183. $opt = '<option value="'.$objp->rowid.'"';
  6184. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6185. $opt .= '>';
  6186. $opt .= $objp->ref;
  6187. $objRef = $objp->ref;
  6188. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6189. $outval .= $objRef;
  6190. $opt .= "</option>\n";
  6191. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtypem);
  6192. }
  6193. /**
  6194. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6195. *
  6196. * @param int $selected Preselected tickets
  6197. * @param string $htmlname Name of HTML select field (must be unique in page).
  6198. * @param string $filtertype To add a filter
  6199. * @param int $limit Limit on number of returned lines
  6200. * @param int $status Ticket status
  6201. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6202. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6203. * @param array $ajaxoptions Options for ajax_autocompleter
  6204. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6205. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6206. * @param int $forcecombo Force to use combo box
  6207. * @param string $morecss Add more css on select
  6208. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6209. * @param string $nooutput No print, return the output into a string
  6210. * @return void|string
  6211. */
  6212. 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)
  6213. {
  6214. global $langs, $conf;
  6215. $out = '';
  6216. // check parameters
  6217. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6218. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6219. $placeholder = '';
  6220. if ($selected && empty($selected_input_value)) {
  6221. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6222. $projecttmpselect = new Project($this->db);
  6223. $projecttmpselect->fetch($selected);
  6224. $selected_input_value = $projecttmpselect->ref;
  6225. unset($projecttmpselect);
  6226. }
  6227. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6228. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6229. elseif ($hidelabel > 1) {
  6230. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6231. if ($hidelabel == 2) {
  6232. $out .= img_picto($langs->trans("Search"), 'search');
  6233. }
  6234. }
  6235. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6236. if ($hidelabel == 3) {
  6237. $out .= img_picto($langs->trans("Search"), 'search');
  6238. }
  6239. } else {
  6240. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6241. }
  6242. if (empty($nooutput)) print $out;
  6243. else return $out;
  6244. }
  6245. /**
  6246. * Return list of projects.
  6247. * Called by selectProjects.
  6248. *
  6249. * @param int $selected Preselected project
  6250. * @param string $htmlname Name of select html
  6251. * @param string $filtertype Filter on project type
  6252. * @param int $limit Limit on number of returned lines
  6253. * @param string $filterkey Filter on project ref or subject
  6254. * @param int $status Ticket status
  6255. * @param int $outputmode 0=HTML select string, 1=Array
  6256. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6257. * @param int $forcecombo Force to use combo box
  6258. * @param string $morecss Add more css on select
  6259. * @return array Array of keys for json
  6260. */
  6261. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6262. {
  6263. global $langs, $conf, $user, $db;
  6264. $out = '';
  6265. $outarray = array();
  6266. $selectFields = " p.rowid, p.ref";
  6267. $sql = "SELECT ";
  6268. $sql .= $selectFields;
  6269. $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
  6270. $sql .= ' WHERE p.entity IN ('.getEntity('project').')';
  6271. // Add criteria on ref/label
  6272. if ($filterkey != '') {
  6273. $sql .= ' AND (';
  6274. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6275. // For natural search
  6276. $scrit = explode(' ', $filterkey);
  6277. $i = 0;
  6278. if (count($scrit) > 1) $sql .= "(";
  6279. foreach ($scrit as $crit) {
  6280. if ($i > 0) $sql .= " AND ";
  6281. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6282. $sql .= "";
  6283. $i++;
  6284. }
  6285. if (count($scrit) > 1) $sql .= ")";
  6286. $sql .= ')';
  6287. }
  6288. $sql .= $this->db->plimit($limit, 0);
  6289. // Build output string
  6290. dol_syslog(get_class($this)."::selectProjectsList search projects", LOG_DEBUG);
  6291. $result = $this->db->query($sql);
  6292. if ($result) {
  6293. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6294. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  6295. $num = $this->db->num_rows($result);
  6296. $events = null;
  6297. if (!$forcecombo) {
  6298. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6299. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6300. }
  6301. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6302. $textifempty = '';
  6303. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6304. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6305. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6306. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6307. else $textifempty .= $langs->trans("All");
  6308. } else {
  6309. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6310. }
  6311. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6312. $i = 0;
  6313. while ($num && $i < $num) {
  6314. $opt = '';
  6315. $optJson = array();
  6316. $objp = $this->db->fetch_object($result);
  6317. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6318. // Add new entry
  6319. // "key" value of json key array is used by jQuery automatically as selected value
  6320. // "label" value of json key array is used by jQuery automatically as text for combo box
  6321. $out .= $opt;
  6322. array_push($outarray, $optJson);
  6323. $i++;
  6324. }
  6325. $out .= '</select>';
  6326. $this->db->free($result);
  6327. if (empty($outputmode)) return $out;
  6328. return $outarray;
  6329. } else {
  6330. dol_print_error($db);
  6331. }
  6332. }
  6333. /**
  6334. * constructProjectListOption.
  6335. * This define value for &$opt and &$optJson.
  6336. *
  6337. * @param resource $objp Result set of fetch
  6338. * @param string $opt Option (var used for returned value in string option format)
  6339. * @param string $optJson Option (var used for returned value in json format)
  6340. * @param string $selected Preselected value
  6341. * @param string $filterkey Filter key to highlight
  6342. * @return void
  6343. */
  6344. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6345. {
  6346. global $langs, $conf, $user, $db;
  6347. $outkey = '';
  6348. $outval = '';
  6349. $outref = '';
  6350. $outlabel = '';
  6351. $outtype = '';
  6352. $label = $objp->label;
  6353. $outkey = $objp->rowid;
  6354. $outref = $objp->ref;
  6355. $outlabel = $objp->label;
  6356. $outtype = $objp->fk_product_type;
  6357. $opt = '<option value="'.$objp->rowid.'"';
  6358. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6359. $opt .= '>';
  6360. $opt .= $objp->ref;
  6361. $objRef = $objp->ref;
  6362. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6363. $outval .= $objRef;
  6364. $opt .= "</option>\n";
  6365. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtypem);
  6366. }
  6367. /**
  6368. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6369. *
  6370. * @param int $selected Preselected tickets
  6371. * @param string $htmlname Name of HTML select field (must be unique in page).
  6372. * @param string $filtertype To add a filter
  6373. * @param int $limit Limit on number of returned lines
  6374. * @param int $status Ticket status
  6375. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6376. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6377. * @param array $ajaxoptions Options for ajax_autocompleter
  6378. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6379. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6380. * @param int $forcecombo Force to use combo box
  6381. * @param string $morecss Add more css on select
  6382. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6383. * @param string $nooutput No print, return the output into a string
  6384. * @return void|string
  6385. */
  6386. 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)
  6387. {
  6388. global $langs, $conf;
  6389. $out = '';
  6390. // check parameters
  6391. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6392. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6393. $placeholder = '';
  6394. if ($selected && empty($selected_input_value)) {
  6395. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6396. $adherenttmpselect = new Member($this->db);
  6397. $adherenttmpselect->fetch($selected);
  6398. $selected_input_value = $adherenttmpselect->ref;
  6399. unset($adherenttmpselect);
  6400. }
  6401. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6402. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6403. elseif ($hidelabel > 1) {
  6404. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6405. if ($hidelabel == 2) {
  6406. $out .= img_picto($langs->trans("Search"), 'search');
  6407. }
  6408. }
  6409. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6410. if ($hidelabel == 3) {
  6411. $out .= img_picto($langs->trans("Search"), 'search');
  6412. }
  6413. } else {
  6414. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6415. }
  6416. if (empty($nooutput)) print $out;
  6417. else return $out;
  6418. }
  6419. /**
  6420. * Return list of adherents.
  6421. * Called by selectMembers.
  6422. *
  6423. * @param int $selected Preselected adherent
  6424. * @param string $htmlname Name of select html
  6425. * @param string $filtertype Filter on adherent type
  6426. * @param int $limit Limit on number of returned lines
  6427. * @param string $filterkey Filter on adherent ref or subject
  6428. * @param int $status Ticket status
  6429. * @param int $outputmode 0=HTML select string, 1=Array
  6430. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6431. * @param int $forcecombo Force to use combo box
  6432. * @param string $morecss Add more css on select
  6433. * @return array Array of keys for json
  6434. */
  6435. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6436. {
  6437. global $langs, $conf, $user, $db;
  6438. $out = '';
  6439. $outarray = array();
  6440. $selectFields = " p.rowid, p.ref";
  6441. $sql = "SELECT ";
  6442. $sql .= $selectFields;
  6443. $sql .= " FROM ".MAIN_DB_PREFIX."adherent as p";
  6444. $sql .= ' WHERE p.entity IN ('.getEntity('adherent').')';
  6445. // Add criteria on ref/label
  6446. if ($filterkey != '') {
  6447. $sql .= ' AND (';
  6448. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6449. // For natural search
  6450. $scrit = explode(' ', $filterkey);
  6451. $i = 0;
  6452. if (count($scrit) > 1) $sql .= "(";
  6453. foreach ($scrit as $crit) {
  6454. if ($i > 0) $sql .= " AND ";
  6455. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6456. $sql .= "";
  6457. $i++;
  6458. }
  6459. if (count($scrit) > 1) $sql .= ")";
  6460. $sql .= ')';
  6461. }
  6462. $sql .= $this->db->plimit($limit, 0);
  6463. // Build output string
  6464. dol_syslog(get_class($this)."::selectMembersList search adherents", LOG_DEBUG);
  6465. $result = $this->db->query($sql);
  6466. if ($result) {
  6467. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6468. require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
  6469. $num = $this->db->num_rows($result);
  6470. $events = null;
  6471. if (!$forcecombo) {
  6472. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6473. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6474. }
  6475. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6476. $textifempty = '';
  6477. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6478. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6479. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6480. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6481. else $textifempty .= $langs->trans("All");
  6482. } else {
  6483. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6484. }
  6485. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6486. $i = 0;
  6487. while ($num && $i < $num) {
  6488. $opt = '';
  6489. $optJson = array();
  6490. $objp = $this->db->fetch_object($result);
  6491. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6492. // Add new entry
  6493. // "key" value of json key array is used by jQuery automatically as selected value
  6494. // "label" value of json key array is used by jQuery automatically as text for combo box
  6495. $out .= $opt;
  6496. array_push($outarray, $optJson);
  6497. $i++;
  6498. }
  6499. $out .= '</select>';
  6500. $this->db->free($result);
  6501. if (empty($outputmode)) return $out;
  6502. return $outarray;
  6503. } else {
  6504. dol_print_error($db);
  6505. }
  6506. }
  6507. /**
  6508. * constructMemberListOption.
  6509. * This define value for &$opt and &$optJson.
  6510. *
  6511. * @param resource $objp Result set of fetch
  6512. * @param string $opt Option (var used for returned value in string option format)
  6513. * @param string $optJson Option (var used for returned value in json format)
  6514. * @param string $selected Preselected value
  6515. * @param string $filterkey Filter key to highlight
  6516. * @return void
  6517. */
  6518. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6519. {
  6520. global $langs, $conf, $user, $db;
  6521. $outkey = '';
  6522. $outval = '';
  6523. $outref = '';
  6524. $outlabel = '';
  6525. $outtype = '';
  6526. $label = $objp->label;
  6527. $outkey = $objp->rowid;
  6528. $outref = $objp->ref;
  6529. $outlabel = $objp->label;
  6530. $outtype = $objp->fk_product_type;
  6531. $opt = '<option value="'.$objp->rowid.'"';
  6532. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6533. $opt .= '>';
  6534. $opt .= $objp->ref;
  6535. $objRef = $objp->ref;
  6536. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6537. $outval .= $objRef;
  6538. $opt .= "</option>\n";
  6539. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtypem);
  6540. }
  6541. /**
  6542. * Generic method to select a component from a combo list.
  6543. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6544. * This is the generic method that will replace all specific existing methods.
  6545. *
  6546. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6547. * @param string $htmlname Name of HTML select component
  6548. * @param int $preselectedvalue Preselected value (ID of element)
  6549. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6550. * @param string $searchkey Search criteria
  6551. * @param string $placeholder Place holder
  6552. * @param string $morecss More CSS
  6553. * @param string $moreparams More params provided to ajax call
  6554. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6555. * @param int $disabled 1=Html component is disabled
  6556. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6557. * @return string Return HTML string
  6558. * @see selectForFormsList() select_thirdparty_list()
  6559. */
  6560. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6561. {
  6562. global $conf, $user;
  6563. $objecttmp = null;
  6564. $InfoFieldList = explode(":", $objectdesc);
  6565. $classname = $InfoFieldList[0];
  6566. $classpath = $InfoFieldList[1];
  6567. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6568. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6569. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6570. if (!empty($classpath)) {
  6571. dol_include_once($classpath);
  6572. if ($classname && class_exists($classname)) {
  6573. $objecttmp = new $classname($this->db);
  6574. // Make some replacement
  6575. $sharedentities = getEntity(strtolower($classname));
  6576. $objecttmp->filter = str_replace(
  6577. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6578. array($conf->entity, $sharedentities, $user->id),
  6579. $filter
  6580. );
  6581. }
  6582. }
  6583. if (!is_object($objecttmp)) {
  6584. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  6585. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  6586. }
  6587. //var_dump($objecttmp->filter);
  6588. $prefixforautocompletemode = $objecttmp->element;
  6589. if ($prefixforautocompletemode == 'societe') {
  6590. $prefixforautocompletemode = 'company';
  6591. }
  6592. if ($prefixforautocompletemode == 'product') {
  6593. $prefixforautocompletemode = 'produit';
  6594. }
  6595. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6596. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  6597. $out = '';
  6598. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6599. // No immediate load of all database
  6600. $placeholder = '';
  6601. if ($preselectedvalue && empty($selected_input_value)) {
  6602. $objecttmp->fetch($preselectedvalue);
  6603. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6604. //unset($objecttmp);
  6605. }
  6606. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  6607. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  6608. // No immediate load of all database
  6609. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&objectdesc='.urlencode($objectdesc).'&filter='.urlencode($objecttmp->filter).($sortfield ? '&sortfield='.urlencode($sortfield) : '');
  6610. // Activate the auto complete using ajax call.
  6611. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6612. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6613. $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).'"' : '') .' />';
  6614. } else {
  6615. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  6616. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield);
  6617. }
  6618. return $out;
  6619. }
  6620. /**
  6621. * Function to forge a SQL criteria
  6622. *
  6623. * @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"
  6624. * @return string Forged criteria. Example: "t.field like 'abc%'"
  6625. */
  6626. protected static function forgeCriteriaCallback($matches)
  6627. {
  6628. global $db;
  6629. //dol_syslog("Convert matches ".$matches[1]);
  6630. if (empty($matches[1])) {
  6631. return '';
  6632. }
  6633. $tmp = explode(':', $matches[1]);
  6634. if (count($tmp) < 3) {
  6635. return '';
  6636. }
  6637. $tmpescaped = $tmp[2];
  6638. $regbis = array();
  6639. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  6640. $tmpescaped = "'".$db->escape($regbis[1])."'";
  6641. } else {
  6642. $tmpescaped = $db->escape($tmpescaped);
  6643. }
  6644. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  6645. }
  6646. /**
  6647. * Output html form to select an object.
  6648. * Note, this function is called by selectForForms or by ajax selectobject.php
  6649. *
  6650. * @param Object $objecttmp Object to knwo the table to scan for combo.
  6651. * @param string $htmlname Name of HTML select component
  6652. * @param int $preselectedvalue Preselected value (ID of element)
  6653. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6654. * @param string $searchkey Search value
  6655. * @param string $placeholder Place holder
  6656. * @param string $morecss More CSS
  6657. * @param string $moreparams More params provided to ajax call
  6658. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6659. * @param int $outputmode 0=HTML select string, 1=Array
  6660. * @param int $disabled 1=Html component is disabled
  6661. * @param string $sortfield Sort field
  6662. * @return string|array Return HTML string
  6663. * @see selectForForms()
  6664. */
  6665. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '')
  6666. {
  6667. global $conf, $langs, $user, $hookmanager;
  6668. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  6669. $prefixforautocompletemode = $objecttmp->element;
  6670. if ($prefixforautocompletemode == 'societe') {
  6671. $prefixforautocompletemode = 'company';
  6672. }
  6673. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6674. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  6675. $tmpfieldstoshow = '';
  6676. foreach ($objecttmp->fields as $key => $val) {
  6677. if (!dol_eval($val['enabled'], 1, 1)) {
  6678. continue;
  6679. }
  6680. if (!empty($val['showoncombobox'])) {
  6681. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  6682. }
  6683. }
  6684. if ($tmpfieldstoshow) {
  6685. $fieldstoshow = $tmpfieldstoshow;
  6686. }
  6687. } else {
  6688. // For backward compatibility
  6689. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  6690. }
  6691. if (empty($fieldstoshow)) {
  6692. if (isset($objecttmp->fields['ref'])) {
  6693. $fieldstoshow = 't.ref';
  6694. } else {
  6695. $langs->load("errors");
  6696. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  6697. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  6698. }
  6699. }
  6700. $out = '';
  6701. $outarray = array();
  6702. $num = 0;
  6703. // Search data
  6704. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX.$objecttmp->table_element." as t";
  6705. if (isset($objecttmp->ismultientitymanaged)) {
  6706. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6707. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  6708. $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$tmparray[1]." as parenttable ON parenttable.rowid = t.".$tmparray[0];
  6709. }
  6710. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6711. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6712. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  6713. }
  6714. }
  6715. }
  6716. // Add where from hooks
  6717. $parameters = array();
  6718. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  6719. if (!empty($hookmanager->resPrint)) {
  6720. $sql .= $hookmanager->resPrint;
  6721. } else {
  6722. $sql .= " WHERE 1=1";
  6723. if (isset($objecttmp->ismultientitymanaged)) {
  6724. if ($objecttmp->ismultientitymanaged == 1) {
  6725. $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  6726. }
  6727. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6728. $sql .= " AND parenttable.entity = t.".$tmparray[0];
  6729. }
  6730. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  6731. if ($objecttmp->element == 'societe') {
  6732. $sql .= " AND t.rowid = ".((int) $user->socid);
  6733. } else {
  6734. $sql .= " AND t.fk_soc = ".((int) $user->socid);
  6735. }
  6736. }
  6737. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6738. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6739. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  6740. }
  6741. }
  6742. }
  6743. if ($searchkey != '') {
  6744. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  6745. }
  6746. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  6747. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  6748. {
  6749. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  6750. }*/
  6751. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  6752. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  6753. }
  6754. }
  6755. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  6756. //$sql.=$this->db->plimit($limit, 0);
  6757. //print $sql;
  6758. // Build output string
  6759. $resql = $this->db->query($sql);
  6760. if ($resql) {
  6761. // Construct $out and $outarray
  6762. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  6763. // 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
  6764. $textifempty = '&nbsp;';
  6765. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6766. if (!empty($conf->global->$confkeyforautocompletemode)) {
  6767. if ($showempty && !is_numeric($showempty)) {
  6768. $textifempty = $langs->trans($showempty);
  6769. } else {
  6770. $textifempty .= $langs->trans("All");
  6771. }
  6772. }
  6773. if ($showempty) {
  6774. $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  6775. }
  6776. $num = $this->db->num_rows($resql);
  6777. $i = 0;
  6778. if ($num) {
  6779. while ($i < $num) {
  6780. $obj = $this->db->fetch_object($resql);
  6781. $label = '';
  6782. $tmparray = explode(',', $fieldstoshow);
  6783. $oldvalueforshowoncombobox = 0;
  6784. foreach ($tmparray as $key => $val) {
  6785. $val = preg_replace('/t\./', '', $val);
  6786. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  6787. $label .= $obj->$val;
  6788. $oldvalueforshowoncombobox = $objecttmp->fields[$val]['showoncombobox'];
  6789. }
  6790. if (empty($outputmode)) {
  6791. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  6792. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  6793. } else {
  6794. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  6795. }
  6796. } else {
  6797. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  6798. }
  6799. $i++;
  6800. if (($i % 10) == 0) {
  6801. $out .= "\n";
  6802. }
  6803. }
  6804. }
  6805. $out .= '</select>'."\n";
  6806. if (!$forcecombo) {
  6807. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6808. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  6809. }
  6810. } else {
  6811. dol_print_error($this->db);
  6812. }
  6813. $this->result = array('nbofelement'=>$num);
  6814. if ($outputmode) {
  6815. return $outarray;
  6816. }
  6817. return $out;
  6818. }
  6819. /**
  6820. * Return a HTML select string, built from an array of key+value.
  6821. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  6822. *
  6823. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  6824. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  6825. * @param string|string[] $id Preselected key or preselected keys for multiselect
  6826. * @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.
  6827. * @param int $key_in_label 1 to show key into label with format "[key] value"
  6828. * @param int $value_as_key 1 to use value as key
  6829. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  6830. * @param int $translate 1=Translate and encode value
  6831. * @param int $maxlen Length maximum for labels
  6832. * @param int $disabled Html select box is disabled
  6833. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  6834. * @param string $morecss Add more class to css styles
  6835. * @param int $addjscombo Add js combo
  6836. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  6837. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  6838. * @param int $nohtmlescape No html escaping.
  6839. * @return string HTML select string.
  6840. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  6841. */
  6842. 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)
  6843. {
  6844. global $conf, $langs;
  6845. // Do we want a multiselect ?
  6846. //$jsbeautify = 0;
  6847. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  6848. $jsbeautify = 1;
  6849. if ($value_as_key) {
  6850. $array = array_combine($array, $array);
  6851. }
  6852. $out = '';
  6853. if ($addjscombo < 0) {
  6854. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6855. $addjscombo = 1;
  6856. } else {
  6857. $addjscombo = 0;
  6858. }
  6859. }
  6860. // Add code for jquery to use multiselect
  6861. if ($addjscombo && $jsbeautify) {
  6862. // Enhance with select2
  6863. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6864. $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', $show_empty < 0 ? (string) $show_empty : '-1');
  6865. }
  6866. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  6867. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  6868. $out .= '>';
  6869. if ($show_empty) {
  6870. $textforempty = ' ';
  6871. if (!empty($conf->use_javascript_ajax)) {
  6872. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  6873. }
  6874. if (!is_numeric($show_empty)) {
  6875. $textforempty = $show_empty;
  6876. }
  6877. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  6878. }
  6879. if (is_array($array)) {
  6880. // Translate
  6881. if ($translate) {
  6882. foreach ($array as $key => $value) {
  6883. if (!is_array($value)) {
  6884. $array[$key] = $langs->trans($value);
  6885. } else {
  6886. $array[$key]['label'] = $langs->trans($value['label']);
  6887. }
  6888. }
  6889. }
  6890. // Sort
  6891. if ($sort == 'ASC') {
  6892. asort($array);
  6893. } elseif ($sort == 'DESC') {
  6894. arsort($array);
  6895. }
  6896. foreach ($array as $key => $tmpvalue) {
  6897. if (is_array($tmpvalue)) {
  6898. $value = $tmpvalue['label'];
  6899. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  6900. $style = empty($tmpvalue['css']) ? ' class="'.$tmpvalue['css'].'"' : '';
  6901. } else {
  6902. $value = $tmpvalue;
  6903. $disabled = '';
  6904. $style = '';
  6905. }
  6906. if (!empty($disablebademail)) {
  6907. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  6908. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  6909. $disabled = ' disabled';
  6910. $style = ' class="warning"';
  6911. }
  6912. }
  6913. if ($key_in_label) {
  6914. if (empty($nohtmlescape)) {
  6915. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  6916. } else {
  6917. $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  6918. }
  6919. } else {
  6920. if (empty($nohtmlescape)) {
  6921. $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  6922. } else {
  6923. $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  6924. }
  6925. if ($value == '' || $value == '-') {
  6926. $selectOptionValue = '&nbsp;';
  6927. }
  6928. }
  6929. $out .= '<option value="'.$key.'"';
  6930. $out .= $style.$disabled;
  6931. if (is_array($id)) {
  6932. if (in_array($key, $id) && !$disabled) {
  6933. $out .= ' selected'; // To preselect a value
  6934. }
  6935. } else {
  6936. $id = (string) $id; // if $id = 0, then $id = '0'
  6937. if ($id != '' && $id == $key && !$disabled) {
  6938. $out .= ' selected'; // To preselect a value
  6939. }
  6940. }
  6941. if ($nohtmlescape) {
  6942. $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  6943. }
  6944. if (is_array($tmpvalue)) {
  6945. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  6946. if (preg_match('/^data-/', $keyforvalue)) {
  6947. $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  6948. }
  6949. }
  6950. }
  6951. $out .= '>';
  6952. //var_dump($selectOptionValue);
  6953. $out .= $selectOptionValue;
  6954. $out .= "</option>\n";
  6955. }
  6956. }
  6957. $out .= "</select>";
  6958. return $out;
  6959. }
  6960. /**
  6961. * 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.
  6962. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  6963. *
  6964. * @param string $htmlname Name of html select area
  6965. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  6966. * @param string $id Preselected key
  6967. * @param string $moreparam Add more parameters onto the select tag
  6968. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  6969. * @param int $disabled Html select box is disabled
  6970. * @param int $minimumInputLength Minimum Input Length
  6971. * @param string $morecss Add more class to css styles
  6972. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  6973. * @param string $placeholder String to use as placeholder
  6974. * @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)
  6975. * @return string HTML select string
  6976. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  6977. */
  6978. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  6979. {
  6980. global $conf, $langs;
  6981. global $delayedhtmlcontent; // Will be used later outside of this function
  6982. // TODO Use an internal dolibarr component instead of select2
  6983. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  6984. return '';
  6985. }
  6986. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  6987. $outdelayed = '';
  6988. if (!empty($conf->use_javascript_ajax)) {
  6989. $tmpplugin = 'select2';
  6990. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  6991. <script>
  6992. $(document).ready(function () {
  6993. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  6994. $(".'.$htmlname.'").select2({
  6995. ajax: {
  6996. dir: "ltr",
  6997. url: "'.$url.'",
  6998. dataType: \'json\',
  6999. delay: 250,
  7000. data: function (params) {
  7001. return {
  7002. q: params.term, // search term
  7003. page: params.page
  7004. };
  7005. },
  7006. processResults: function (data) {
  7007. // parse the results into the format expected by Select2.
  7008. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7009. //console.log(data);
  7010. saveRemoteData = data;
  7011. /* format json result for select2 */
  7012. result = []
  7013. $.each( data, function( key, value ) {
  7014. result.push({id: key, text: value.text});
  7015. });
  7016. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7017. //console.log(result);
  7018. return {results: result, more: false}
  7019. },
  7020. cache: true
  7021. },
  7022. language: select2arrayoflanguage,
  7023. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7024. placeholder: "'.dol_escape_js($placeholder).'",
  7025. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7026. minimumInputLength: '.$minimumInputLength.',
  7027. formatResult: function(result, container, query, escapeMarkup) {
  7028. return escapeMarkup(result.text);
  7029. },
  7030. });
  7031. '.($callurlonselect ? '
  7032. /* Code to execute a GET when we select a value */
  7033. $(".'.$htmlname.'").change(function() {
  7034. var selected = $(".'.$htmlname.'").val();
  7035. console.log("We select in selectArrayAjax the entry "+selected)
  7036. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7037. $.each( saveRemoteData, function( key, value ) {
  7038. if (key == selected)
  7039. {
  7040. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7041. location.assign(value.url);
  7042. }
  7043. });
  7044. });' : '').'
  7045. });
  7046. </script>';
  7047. }
  7048. if ($acceptdelayedhtml) {
  7049. $delayedhtmlcontent .= $outdelayed;
  7050. } else {
  7051. $out .= $outdelayed;
  7052. }
  7053. return $out;
  7054. }
  7055. /**
  7056. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7057. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7058. *
  7059. * @param string $htmlname Name of html select area
  7060. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7061. * @param string $id Preselected key
  7062. * @param string $moreparam Add more parameters onto the select tag
  7063. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7064. * @param int $disabled Html select box is disabled
  7065. * @param int $minimumInputLength Minimum Input Length
  7066. * @param string $morecss Add more class to css styles
  7067. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7068. * @param string $placeholder String to use as placeholder
  7069. * @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)
  7070. * @return string HTML select string
  7071. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7072. */
  7073. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7074. {
  7075. global $conf, $langs;
  7076. global $delayedhtmlcontent; // Will be used later outside of this function
  7077. // TODO Use an internal dolibarr component instead of select2
  7078. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7079. return '';
  7080. }
  7081. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  7082. $formattedarrayresult = array();
  7083. foreach ($array as $key => $value) {
  7084. $o = new stdClass();
  7085. $o->id = $key;
  7086. $o->text = $value['text'];
  7087. $o->url = $value['url'];
  7088. $formattedarrayresult[] = $o;
  7089. }
  7090. $outdelayed = '';
  7091. if (!empty($conf->use_javascript_ajax)) {
  7092. $tmpplugin = 'select2';
  7093. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7094. <script>
  7095. $(document).ready(function () {
  7096. var data = '.json_encode($formattedarrayresult).';
  7097. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  7098. $(".'.$htmlname.'").select2({
  7099. data: data,
  7100. language: select2arrayoflanguage,
  7101. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7102. placeholder: "'.dol_escape_js($placeholder).'",
  7103. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7104. minimumInputLength: '.$minimumInputLength.',
  7105. formatResult: function(result, container, query, escapeMarkup) {
  7106. return escapeMarkup(result.text);
  7107. },
  7108. matcher: function (params, data) {
  7109. if(! data.id) return null;';
  7110. if ($callurlonselect) {
  7111. $outdelayed .= '
  7112. var urlBase = data.url;
  7113. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7114. /* console.log("params.term="+params.term); */
  7115. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7116. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7117. }
  7118. if (!$disableFiltering) {
  7119. $outdelayed .= '
  7120. if(data.text.match(new RegExp(params.term))) {
  7121. return data;
  7122. }
  7123. return null;';
  7124. } else {
  7125. $outdelayed .= '
  7126. return data;';
  7127. }
  7128. $outdelayed .= '
  7129. }
  7130. });
  7131. '.($callurlonselect ? '
  7132. /* Code to execute a GET when we select a value */
  7133. $(".'.$htmlname.'").change(function() {
  7134. var selected = $(".'.$htmlname.'").val();
  7135. console.log("We select "+selected)
  7136. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7137. $.each( saveRemoteData, function( key, value ) {
  7138. if (key == selected)
  7139. {
  7140. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7141. location.assign(value.url);
  7142. }
  7143. });
  7144. });' : '').'
  7145. });
  7146. </script>';
  7147. }
  7148. if ($acceptdelayedhtml) {
  7149. $delayedhtmlcontent .= $outdelayed;
  7150. } else {
  7151. $out .= $outdelayed;
  7152. }
  7153. return $out;
  7154. }
  7155. /**
  7156. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7157. *
  7158. * @param string $htmlname Name of select
  7159. * @param array $array Array with key+value
  7160. * @param array $selected Array with key+value preselected
  7161. * @param int $key_in_label 1 to show key like in "[key] value"
  7162. * @param int $value_as_key 1 to use value as key
  7163. * @param string $morecss Add more css style
  7164. * @param int $translate Translate and encode value
  7165. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7166. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7167. * @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.
  7168. * @param string $placeholder String to use as placeholder
  7169. * @param int $addjscombo Add js combo
  7170. * @return string HTML multiselect string
  7171. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7172. */
  7173. 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)
  7174. {
  7175. global $conf, $langs;
  7176. $out = '';
  7177. if ($addjscombo < 0) {
  7178. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7179. $addjscombo = 1;
  7180. } else {
  7181. $addjscombo = 0;
  7182. }
  7183. }
  7184. // Try also magic suggest
  7185. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  7186. if (is_array($array) && !empty($array)) {
  7187. if ($value_as_key) {
  7188. $array = array_combine($array, $array);
  7189. }
  7190. if (!empty($array)) {
  7191. foreach ($array as $key => $value) {
  7192. $newval = ($translate ? $langs->trans($value) : $value);
  7193. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  7194. $out .= '<option value="'.$key.'"';
  7195. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != '')) {
  7196. $out .= ' selected';
  7197. }
  7198. $out .= ' data-html="'.dol_escape_htmltag($newval).'"';
  7199. $out .= '>';
  7200. $out .= dol_htmlentitiesbr($newval);
  7201. $out .= '</option>'."\n";
  7202. }
  7203. }
  7204. }
  7205. $out .= '</select>'."\n";
  7206. // Add code for jquery to use multiselect
  7207. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7208. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.', addjscombo='.$addjscombo.' -->';
  7209. $out .= "\n".'<script>'."\n";
  7210. if ($addjscombo == 1) {
  7211. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7212. $out .= 'function formatResult(record) {'."\n";
  7213. if ($elemtype == 'category') {
  7214. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7215. } else {
  7216. $out .= 'return record.text;';
  7217. }
  7218. $out .= '};'."\n";
  7219. $out .= 'function formatSelection(record) {'."\n";
  7220. if ($elemtype == 'category') {
  7221. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7222. } else {
  7223. $out .= 'return record.text;';
  7224. }
  7225. $out .= '};'."\n";
  7226. $out .= '$(document).ready(function () {
  7227. $(\'#'.$htmlname.'\').'.$tmpplugin.'({
  7228. dir: \'ltr\',
  7229. // Specify format function for dropdown item
  7230. formatResult: formatResult,
  7231. templateResult: formatResult, /* For 4.0 */
  7232. // Specify format function for selected item
  7233. formatSelection: formatSelection,
  7234. templateSelection: formatSelection /* For 4.0 */
  7235. });
  7236. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7237. the size only if component is not hidden by default on load */
  7238. $(\'#'.$htmlname.' + .select2\').addClass(\''.$morecss.'\');
  7239. });'."\n";
  7240. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7241. // Add other js lib
  7242. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7243. // ...
  7244. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  7245. $out .= '$(document).ready(function () {
  7246. $(\'#'.$htmlname.'\').multiSelect({
  7247. containerHTML: \'<div class="multi-select-container">\',
  7248. menuHTML: \'<div class="multi-select-menu">\',
  7249. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  7250. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7251. activeClass: \'multi-select-container--open\',
  7252. noneText: \''.$placeholder.'\'
  7253. });
  7254. })';
  7255. }
  7256. $out .= '</script>';
  7257. }
  7258. return $out;
  7259. }
  7260. /**
  7261. * 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.
  7262. *
  7263. * @param string $htmlname Name of HTML field
  7264. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7265. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7266. * @return string HTML multiselect string
  7267. * @see selectarray()
  7268. */
  7269. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  7270. {
  7271. global $conf, $langs, $user, $extrafields;
  7272. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7273. return '';
  7274. }
  7275. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved selected fields to show
  7276. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7277. $tmparray = explode(',', $user->conf->$tmpvar);
  7278. foreach ($array as $key => $val) {
  7279. //var_dump($key);
  7280. //var_dump($tmparray);
  7281. if (in_array($key, $tmparray)) {
  7282. $array[$key]['checked'] = 1;
  7283. } else {
  7284. $array[$key]['checked'] = 0;
  7285. }
  7286. }
  7287. } else { // There is no list of fields already customized for user
  7288. foreach ($array as $key => $val) {
  7289. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7290. $array[$key]['checked'] = 0;
  7291. }
  7292. }
  7293. }
  7294. $listoffieldsforselection = '';
  7295. $listcheckedstring = '';
  7296. foreach ($array as $key => $val) {
  7297. /* var_dump($val);
  7298. var_dump(array_key_exists('enabled', $val));
  7299. var_dump(!$val['enabled']);*/
  7300. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7301. unset($array[$key]); // We don't want this field
  7302. continue;
  7303. }
  7304. if (!empty($val['type']) && $val['type'] == 'separate') {
  7305. // Field remains in array but we don't add it into $listoffieldsforselection
  7306. //$listoffieldsforselection .= '<li>-----</li>';
  7307. continue;
  7308. }
  7309. if ($val['label']) {
  7310. if (!empty($val['langfile']) && is_object($langs)) {
  7311. $langs->load($val['langfile']);
  7312. }
  7313. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7314. $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>';
  7315. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  7316. }
  7317. }
  7318. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  7319. <dl class="dropdown">
  7320. <dt>
  7321. <a href="#'.$htmlname.'">
  7322. '.img_picto('', 'list').'
  7323. </a>
  7324. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  7325. </dt>
  7326. <dd class="dropdowndd">
  7327. <div class="multiselectcheckbox'.$htmlname.'">
  7328. <ul class="ul'.$htmlname.'">
  7329. '.$listoffieldsforselection.'
  7330. </ul>
  7331. </div>
  7332. </dd>
  7333. </dl>
  7334. <script type="text/javascript">
  7335. jQuery(document).ready(function () {
  7336. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  7337. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7338. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7339. var title = $(this).val() + ",";
  7340. if ($(this).is(\':checked\')) {
  7341. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  7342. }
  7343. else {
  7344. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  7345. }
  7346. // Now, we submit page
  7347. //$(this).parents(\'form:first\').submit();
  7348. });
  7349. });
  7350. </script>
  7351. ';
  7352. return $out;
  7353. }
  7354. /**
  7355. * Render list of categories linked to object with id $id and type $type
  7356. *
  7357. * @param int $id Id of object
  7358. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7359. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7360. * @param int $nolink 1=Do not add html links
  7361. * @return string String with categories
  7362. */
  7363. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7364. {
  7365. global $db;
  7366. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7367. $cat = new Categorie($db);
  7368. $categories = $cat->containing($id, $type);
  7369. if ($rendermode == 1) {
  7370. $toprint = array();
  7371. foreach ($categories as $c) {
  7372. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7373. foreach ($ways as $way) {
  7374. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  7375. }
  7376. }
  7377. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  7378. }
  7379. if ($rendermode == 0) {
  7380. $arrayselected = array();
  7381. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7382. foreach ($categories as $c) {
  7383. $arrayselected[] = $c->id;
  7384. }
  7385. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7386. }
  7387. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7388. }
  7389. /**
  7390. * Show linked object block.
  7391. *
  7392. * @param CommonObject $object Object we want to show links to
  7393. * @param string $morehtmlright More html to show on right of title
  7394. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7395. * @return int <0 if KO, >=0 if OK
  7396. */
  7397. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
  7398. {
  7399. global $conf, $langs, $hookmanager;
  7400. global $bc, $action;
  7401. $object->fetchObjectLinked();
  7402. // Bypass the default method
  7403. $hookmanager->initHooks(array('commonobject'));
  7404. $parameters = array(
  7405. 'morehtmlright' => $morehtmlright,
  7406. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7407. );
  7408. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7409. if (empty($reshook)) {
  7410. $nbofdifferenttypes = count($object->linkedObjects);
  7411. print '<!-- showLinkedObjectBlock -->';
  7412. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7413. print '<div class="div-table-responsive-no-min">';
  7414. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  7415. print '<tr class="liste_titre">';
  7416. print '<td>'.$langs->trans("Type").'</td>';
  7417. print '<td>'.$langs->trans("Ref").'</td>';
  7418. print '<td class="center"></td>';
  7419. print '<td class="center">'.$langs->trans("Date").'</td>';
  7420. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7421. print '<td class="right">'.$langs->trans("Status").'</td>';
  7422. print '<td></td>';
  7423. print '</tr>';
  7424. $nboftypesoutput = 0;
  7425. foreach ($object->linkedObjects as $objecttype => $objects) {
  7426. $tplpath = $element = $subelement = $objecttype;
  7427. // to display inport button on tpl
  7428. $showImportButton = false;
  7429. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7430. $showImportButton = true;
  7431. }
  7432. $regs = array();
  7433. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7434. $element = $regs[1];
  7435. $subelement = $regs[2];
  7436. $tplpath = $element.'/'.$subelement;
  7437. }
  7438. $tplname = 'linkedobjectblock';
  7439. // To work with non standard path
  7440. if ($objecttype == 'facture') {
  7441. $tplpath = 'compta/'.$element;
  7442. if (empty($conf->facture->enabled)) {
  7443. continue; // Do not show if module disabled
  7444. }
  7445. } elseif ($objecttype == 'facturerec') {
  7446. $tplpath = 'compta/facture';
  7447. $tplname = 'linkedobjectblockForRec';
  7448. if (empty($conf->facture->enabled)) {
  7449. continue; // Do not show if module disabled
  7450. }
  7451. } elseif ($objecttype == 'propal') {
  7452. $tplpath = 'comm/'.$element;
  7453. if (empty($conf->propal->enabled)) {
  7454. continue; // Do not show if module disabled
  7455. }
  7456. } elseif ($objecttype == 'supplier_proposal') {
  7457. if (empty($conf->supplier_proposal->enabled)) {
  7458. continue; // Do not show if module disabled
  7459. }
  7460. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  7461. $tplpath = 'expedition';
  7462. if (empty($conf->expedition->enabled)) {
  7463. continue; // Do not show if module disabled
  7464. }
  7465. } elseif ($objecttype == 'reception') {
  7466. $tplpath = 'reception';
  7467. if (empty($conf->reception->enabled)) {
  7468. continue; // Do not show if module disabled
  7469. }
  7470. } elseif ($objecttype == 'delivery') {
  7471. $tplpath = 'delivery';
  7472. if (empty($conf->expedition->enabled)) {
  7473. continue; // Do not show if module disabled
  7474. }
  7475. } elseif ($objecttype == 'mo') {
  7476. $tplpath = 'mrp/mo';
  7477. if (empty($conf->mrp->enabled)) {
  7478. continue; // Do not show if module disabled
  7479. }
  7480. } elseif ($objecttype == 'ficheinter') {
  7481. $tplpath = 'fichinter';
  7482. if (empty($conf->ficheinter->enabled)) {
  7483. continue; // Do not show if module disabled
  7484. }
  7485. } elseif ($objecttype == 'invoice_supplier') {
  7486. $tplpath = 'fourn/facture';
  7487. } elseif ($objecttype == 'order_supplier') {
  7488. $tplpath = 'fourn/commande';
  7489. } elseif ($objecttype == 'expensereport') {
  7490. $tplpath = 'expensereport';
  7491. } elseif ($objecttype == 'subscription') {
  7492. $tplpath = 'adherents';
  7493. } elseif ($objecttype == 'conferenceorbooth') {
  7494. $tplpath = 'eventorganization';
  7495. } elseif ($objecttype == 'conferenceorboothattendee') {
  7496. $tplpath = 'eventorganization';
  7497. } elseif ($objecttype == 'mo') {
  7498. $tplpath = 'mrp';
  7499. if (empty($conf->mrp->enabled)) {
  7500. continue; // Do not show if module disabled
  7501. }
  7502. }
  7503. global $linkedObjectBlock;
  7504. $linkedObjectBlock = $objects;
  7505. // Output template part (modules that overwrite templates must declare this into descriptor)
  7506. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  7507. foreach ($dirtpls as $reldir) {
  7508. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7509. global $noMoreLinkedObjectBlockAfter;
  7510. $noMoreLinkedObjectBlockAfter = 1;
  7511. }
  7512. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  7513. if ($res) {
  7514. $nboftypesoutput++;
  7515. break;
  7516. }
  7517. }
  7518. }
  7519. if (!$nboftypesoutput) {
  7520. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  7521. }
  7522. print '</table>';
  7523. if (!empty($compatibleImportElementsList)) {
  7524. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  7525. }
  7526. print '</div>';
  7527. return $nbofdifferenttypes;
  7528. }
  7529. }
  7530. /**
  7531. * Show block with links to link to other objects.
  7532. *
  7533. * @param CommonObject $object Object we want to show links to
  7534. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7535. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7536. * @return string <0 if KO, >0 if OK
  7537. */
  7538. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7539. {
  7540. global $conf, $langs, $hookmanager;
  7541. global $bc, $action;
  7542. $linktoelem = '';
  7543. $linktoelemlist = '';
  7544. $listofidcompanytoscan = '';
  7545. if (!is_object($object->thirdparty)) {
  7546. $object->fetch_thirdparty();
  7547. }
  7548. $possiblelinks = array();
  7549. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7550. $listofidcompanytoscan = $object->thirdparty->id;
  7551. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7552. $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  7553. }
  7554. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7555. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7556. $tmpproject = new Project($this->db);
  7557. $tmpproject->fetch($object->fk_project);
  7558. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7559. $listofidcompanytoscan .= ','.$tmpproject->socid;
  7560. }
  7561. unset($tmpproject);
  7562. }
  7563. $possiblelinks = array(
  7564. '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 ".MAIN_DB_PREFIX."societe as s, ".MAIN_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').')'),
  7565. '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 ".MAIN_DB_PREFIX."societe as s, ".MAIN_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').')'),
  7566. '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 ".MAIN_DB_PREFIX."societe as s, ".MAIN_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').')'),
  7567. '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 ".MAIN_DB_PREFIX."societe as s, ".MAIN_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').')'),
  7568. 'contrat'=>array(
  7569. 'enabled'=>$conf->contrat->enabled,
  7570. 'perms'=>1,
  7571. 'label'=>'LinkToContract',
  7572. '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 FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t, ".MAIN_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'
  7573. ),
  7574. '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 ".MAIN_DB_PREFIX."societe as s, ".MAIN_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').')'),
  7575. '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 ".MAIN_DB_PREFIX."societe as s, ".MAIN_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').')'),
  7576. '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 ".MAIN_DB_PREFIX."societe as s, ".MAIN_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').')'),
  7577. '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 ".MAIN_DB_PREFIX."societe as s, ".MAIN_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').')'),
  7578. '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 ".MAIN_DB_PREFIX."societe as s, ".MAIN_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').')'),
  7579. '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 ".MAIN_DB_PREFIX."societe as s INNER JOIN ".MAIN_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').')')
  7580. );
  7581. }
  7582. // Can complete the possiblelink array
  7583. $hookmanager->initHooks(array('commonobject'));
  7584. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan);
  7585. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  7586. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7587. }
  7588. if (empty($reshook)) {
  7589. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7590. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  7591. }
  7592. } elseif ($reshook > 0) {
  7593. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7594. $possiblelinks = $hookmanager->resArray;
  7595. }
  7596. }
  7597. foreach ($possiblelinks as $key => $possiblelink) {
  7598. $num = 0;
  7599. if (empty($possiblelink['enabled'])) {
  7600. continue;
  7601. }
  7602. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  7603. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  7604. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7605. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  7606. print '<input type="hidden" name="id" value="' . $object->id . '">';
  7607. print '<input type="hidden" name="action" value="addlinkbyref">';
  7608. print '<input type="hidden" name="addlink" value="' . $key . '">';
  7609. print '<table class="noborder">';
  7610. print '<tr>';
  7611. print '<td>' . $langs->trans("Ref") . '</td>';
  7612. 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>';
  7613. print '</tr>';
  7614. print '</table>';
  7615. print '</form>';
  7616. }
  7617. $sql = $possiblelink['sql'];
  7618. $resqllist = $this->db->query($sql);
  7619. if ($resqllist) {
  7620. $num = $this->db->num_rows($resqllist);
  7621. $i = 0;
  7622. print '<br>';
  7623. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  7624. print '<input type="hidden" name="action" value="addlink">';
  7625. print '<input type="hidden" name="token" value="'.newToken().'">';
  7626. print '<input type="hidden" name="id" value="'.$object->id.'">';
  7627. print '<input type="hidden" name="addlink" value="'.$key.'">';
  7628. print '<table class="noborder">';
  7629. print '<tr class="liste_titre">';
  7630. print '<td class="nowrap"></td>';
  7631. print '<td class="center">'.$langs->trans("Ref").'</td>';
  7632. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  7633. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7634. print '<td class="left">'.$langs->trans("Company").'</td>';
  7635. print '</tr>';
  7636. while ($i < $num) {
  7637. $objp = $this->db->fetch_object($resqllist);
  7638. print '<tr class="oddeven">';
  7639. print '<td class="left">';
  7640. print '<input type="radio" name="idtolinkto" id="'.$key.'_'.$objp->rowid.'" value="'.$objp->rowid.'">';
  7641. print '</td>';
  7642. print '<td class="center"><label for="'.$key.'_'.$objp->rowid.'">'.$objp->ref.'</label></td>';
  7643. print '<td>'.(!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')).'</td>';
  7644. print '<td class="right">';
  7645. if ($possiblelink['label'] == 'LinkToContract') {
  7646. $form = new Form($this->db);
  7647. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' ';
  7648. }
  7649. print '<span class="amount">'.price($objp->total_ht).'</span>';
  7650. print '</td>';
  7651. print '<td>'.$objp->name.'</td>';
  7652. print '</tr>';
  7653. $i++;
  7654. }
  7655. print '</table>';
  7656. print '<div class="center">';
  7657. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="'.$langs->trans('ToLink').'">';
  7658. if (empty($conf->use_javascript_ajax)) {
  7659. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7660. } else {
  7661. 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>';
  7662. }
  7663. print '</form>';
  7664. $this->db->free($resqllist);
  7665. } else {
  7666. dol_print_error($this->db);
  7667. }
  7668. print '</div>';
  7669. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  7670. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7671. $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  7672. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  7673. } else {
  7674. $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  7675. }
  7676. }
  7677. }
  7678. if ($linktoelemlist) {
  7679. $linktoelem = '
  7680. <dl class="dropdown" id="linktoobjectname">
  7681. ';
  7682. if (!empty($conf->use_javascript_ajax)) {
  7683. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>'.$langs->trans("LinkTo").'...</a></dt>';
  7684. }
  7685. $linktoelem .= '<dd>
  7686. <div class="multiselectlinkto">
  7687. <ul class="ulselectedfields">'.$linktoelemlist.'
  7688. </ul>
  7689. </div>
  7690. </dd>
  7691. </dl>';
  7692. } else {
  7693. $linktoelem = '';
  7694. }
  7695. if (!empty($conf->use_javascript_ajax)) {
  7696. print '<!-- Add js to show linkto box -->
  7697. <script>
  7698. jQuery(document).ready(function() {
  7699. jQuery(".linkto").click(function() {
  7700. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  7701. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  7702. });
  7703. });
  7704. </script>
  7705. ';
  7706. }
  7707. return $linktoelem;
  7708. }
  7709. /**
  7710. * Return an html string with a select combo box to choose yes or no
  7711. *
  7712. * @param string $htmlname Name of html select field
  7713. * @param string $value Pre-selected value
  7714. * @param int $option 0 return yes/no, 1 return 1/0
  7715. * @param bool $disabled true or false
  7716. * @param int $useempty 1=Add empty line
  7717. * @param int $addjscombo 1=Add js beautifier on combo box
  7718. * @param string $morecss More CSS
  7719. * @return string See option
  7720. */
  7721. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '')
  7722. {
  7723. global $langs;
  7724. $yes = "yes";
  7725. $no = "no";
  7726. if ($option) {
  7727. $yes = "1";
  7728. $no = "0";
  7729. }
  7730. $disabled = ($disabled ? ' disabled' : '');
  7731. $resultyesno = '<select class="flat width75'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  7732. if ($useempty) {
  7733. $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  7734. }
  7735. if (("$value" == 'yes') || ($value == 1)) {
  7736. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  7737. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  7738. } else {
  7739. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  7740. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  7741. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  7742. }
  7743. $resultyesno .= '</select>'."\n";
  7744. if ($addjscombo) {
  7745. $resultyesno .= ajax_combobox($htmlname);
  7746. }
  7747. return $resultyesno;
  7748. }
  7749. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7750. /**
  7751. * Return list of export templates
  7752. *
  7753. * @param string $selected Id modele pre-selectionne
  7754. * @param string $htmlname Name of HTML select
  7755. * @param string $type Type of searched templates
  7756. * @param int $useempty Affiche valeur vide dans liste
  7757. * @return void
  7758. */
  7759. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  7760. {
  7761. // phpcs:enable
  7762. $sql = "SELECT rowid, label";
  7763. $sql .= " FROM ".MAIN_DB_PREFIX."export_model";
  7764. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  7765. $sql .= " ORDER BY rowid";
  7766. $result = $this->db->query($sql);
  7767. if ($result) {
  7768. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  7769. if ($useempty) {
  7770. print '<option value="-1">&nbsp;</option>';
  7771. }
  7772. $num = $this->db->num_rows($result);
  7773. $i = 0;
  7774. while ($i < $num) {
  7775. $obj = $this->db->fetch_object($result);
  7776. if ($selected == $obj->rowid) {
  7777. print '<option value="'.$obj->rowid.'" selected>';
  7778. } else {
  7779. print '<option value="'.$obj->rowid.'">';
  7780. }
  7781. print $obj->label;
  7782. print '</option>';
  7783. $i++;
  7784. }
  7785. print "</select>";
  7786. } else {
  7787. dol_print_error($this->db);
  7788. }
  7789. }
  7790. /**
  7791. * Return a HTML area with the reference of object and a navigation bar for a business object
  7792. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  7793. *
  7794. * @param object $object Object to show.
  7795. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  7796. * @param string $morehtml More html content to output just before the nav bar.
  7797. * @param int $shownav Show Condition (navigation is shown if value is 1).
  7798. * @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.
  7799. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  7800. * @param string $morehtmlref More html to show after ref.
  7801. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  7802. * @param int $nodbprefix Do not include DB prefix to forge table name.
  7803. * @param string $morehtmlleft More html code to show before ref.
  7804. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  7805. * @param string $morehtmlright More html code to show after ref.
  7806. * @return string Portion HTML with ref + navigation buttons
  7807. */
  7808. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  7809. {
  7810. global $conf, $langs, $hookmanager, $extralanguages;
  7811. $ret = '';
  7812. if (empty($fieldid)) {
  7813. $fieldid = 'rowid';
  7814. }
  7815. if (empty($fieldref)) {
  7816. $fieldref = 'ref';
  7817. }
  7818. // Preparing gender's display if there is one
  7819. $addgendertxt = '';
  7820. if (property_exists($object, 'gender') && !empty($object->gender)) {
  7821. $addgendertxt = ' ';
  7822. switch ($object->gender) {
  7823. case 'man':
  7824. $addgendertxt .= '<i class="fas fa-mars"></i>';
  7825. break;
  7826. case 'woman':
  7827. $addgendertxt .= '<i class="fas fa-venus"></i>';
  7828. break;
  7829. case 'other':
  7830. $addgendertxt .= '<i class="fas fa-genderless"></i>';
  7831. break;
  7832. }
  7833. }
  7834. /*
  7835. $addadmin = '';
  7836. if (property_exists($object, 'admin')) {
  7837. if (!empty($conf->multicompany->enabled) && !empty($object->admin) && empty($object->entity)) {
  7838. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  7839. } elseif (!empty($object->admin)) {
  7840. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  7841. }
  7842. }*/
  7843. // Add where from hooks
  7844. if (is_object($hookmanager)) {
  7845. $parameters = array();
  7846. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  7847. $object->next_prev_filter .= $hookmanager->resPrint;
  7848. }
  7849. $previous_ref = $next_ref = '';
  7850. if ($shownav) {
  7851. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  7852. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  7853. $navurl = $_SERVER["PHP_SELF"];
  7854. // Special case for project/task page
  7855. if ($paramid == 'project_ref') {
  7856. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  7857. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  7858. $paramid = 'ref';
  7859. }
  7860. }
  7861. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  7862. // accesskey is for Mac: CTRL + key for all browsers
  7863. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  7864. if ($conf->browser->name == 'chrome') {
  7865. $stringforfirstkey .= ' ALT +';
  7866. } elseif ($conf->browser->name == 'firefox') {
  7867. $stringforfirstkey .= ' ALT + SHIFT +';
  7868. } else {
  7869. $stringforfirstkey .= ' CTL +';
  7870. }
  7871. $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>';
  7872. $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>';
  7873. }
  7874. //print "xx".$previous_ref."x".$next_ref;
  7875. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  7876. // Right part of banner
  7877. if ($morehtmlright) {
  7878. $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  7879. }
  7880. if ($previous_ref || $next_ref || $morehtml) {
  7881. $ret .= '<div class="pagination paginationref"><ul class="right">';
  7882. }
  7883. if ($morehtml) {
  7884. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  7885. }
  7886. if ($shownav && ($previous_ref || $next_ref)) {
  7887. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  7888. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  7889. }
  7890. if ($previous_ref || $next_ref || $morehtml) {
  7891. $ret .= '</ul></div>';
  7892. }
  7893. $parameters = array();
  7894. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  7895. if (empty($reshook)) {
  7896. $morehtmlstatus .= $hookmanager->resPrint;
  7897. } else {
  7898. $morehtmlstatus = $hookmanager->resPrint;
  7899. }
  7900. if ($morehtmlstatus) {
  7901. $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  7902. }
  7903. $parameters = array();
  7904. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  7905. if (empty($reshook)) {
  7906. $morehtmlref .= $hookmanager->resPrint;
  7907. } elseif ($reshook > 0) {
  7908. $morehtmlref = $hookmanager->resPrint;
  7909. }
  7910. // Left part of banner
  7911. if ($morehtmlleft) {
  7912. if ($conf->browser->layout == 'phone') {
  7913. $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  7914. } else {
  7915. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  7916. }
  7917. }
  7918. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  7919. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  7920. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  7921. if ($object->element == 'societe') {
  7922. $ret .= dol_htmlentities($object->name);
  7923. // List of extra languages
  7924. $arrayoflangcode = array();
  7925. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  7926. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  7927. }
  7928. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  7929. if (!is_object($extralanguages)) {
  7930. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  7931. $extralanguages = new ExtraLanguages($this->db);
  7932. }
  7933. $extralanguages->fetch_name_extralanguages('societe');
  7934. if (!empty($extralanguages->attributes['societe']['name'])) {
  7935. $object->fetchValuesForExtraLanguages();
  7936. $htmltext = '';
  7937. // If there is extra languages
  7938. foreach ($arrayoflangcode as $extralangcode) {
  7939. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  7940. if ($object->array_languages['name'][$extralangcode]) {
  7941. $htmltext .= $object->array_languages['name'][$extralangcode];
  7942. } else {
  7943. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  7944. }
  7945. }
  7946. $ret .= '<!-- Show translations of name -->'."\n";
  7947. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  7948. }
  7949. }
  7950. } elseif ($object->element == 'member') {
  7951. $ret .= $object->ref.'<br>';
  7952. $fullname = $object->getFullName($langs);
  7953. if ($object->morphy == 'mor' && $object->societe) {
  7954. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).$addgendertxt.')' : '');
  7955. } else {
  7956. $ret .= dol_htmlentities($fullname).$addgendertxt.((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  7957. }
  7958. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  7959. $ret .= dol_htmlentities($object->getFullName($langs));
  7960. } elseif (in_array($object->element, array('action', 'agenda'))) {
  7961. $ret .= $object->ref.'<br>'.$object->label;
  7962. } elseif (in_array($object->element, array('adherent_type'))) {
  7963. $ret .= $object->label;
  7964. } elseif ($object->element == 'ecm_directories') {
  7965. $ret .= '';
  7966. } elseif ($fieldref != 'none') {
  7967. $ret .= dol_htmlentities($object->$fieldref);
  7968. }
  7969. if ($morehtmlref) {
  7970. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  7971. if (substr($morehtmlref, 0, 4) != '<div') {
  7972. $ret .= ' ';
  7973. }
  7974. $ret .= $morehtmlref;
  7975. }
  7976. $ret .= '</div>';
  7977. $ret .= '</div><!-- End banner content -->';
  7978. return $ret;
  7979. }
  7980. /**
  7981. * Return HTML code to output a barcode
  7982. *
  7983. * @param Object $object Object containing data to retrieve file name
  7984. * @param int $width Width of photo
  7985. * @param string $morecss More CSS on img of barcode
  7986. * @return string HTML code to output barcode
  7987. */
  7988. public function showbarcode(&$object, $width = 100, $morecss = '')
  7989. {
  7990. global $conf;
  7991. //Check if barcode is filled in the card
  7992. if (empty($object->barcode)) {
  7993. return '';
  7994. }
  7995. // Complete object if not complete
  7996. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  7997. $result = $object->fetch_barcode();
  7998. //Check if fetch_barcode() failed
  7999. if ($result < 1) {
  8000. return '<!-- ErrorFetchBarcode -->';
  8001. }
  8002. }
  8003. // Barcode image
  8004. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  8005. $out = '<!-- url barcode = '.$url.' -->';
  8006. $out .= '<img src="'.$url.'"'.($morecss ? ' class="'.$morecss.'"' : '').'>';
  8007. return $out;
  8008. }
  8009. /**
  8010. * Return HTML code to output a photo
  8011. *
  8012. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8013. * @param object $object Object containing data to retrieve file name
  8014. * @param int $width Width of photo
  8015. * @param int $height Height of photo (auto if 0)
  8016. * @param int $caneditfield Add edit fields
  8017. * @param string $cssclass CSS name to use on img for photo
  8018. * @param string $imagesize 'mini', 'small' or '' (original)
  8019. * @param int $addlinktofullsize Add link to fullsize image
  8020. * @param int $cache 1=Accept to use image in cache
  8021. * @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 ''.
  8022. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8023. * @return string HTML code to output photo
  8024. */
  8025. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8026. {
  8027. global $conf, $langs;
  8028. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8029. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8030. $ret = '';
  8031. $dir = '';
  8032. $file = '';
  8033. $originalfile = '';
  8034. $altfile = '';
  8035. $email = '';
  8036. $capture = '';
  8037. if ($modulepart == 'societe') {
  8038. $dir = $conf->societe->multidir_output[$entity];
  8039. if (!empty($object->logo)) {
  8040. if (dolIsAllowedForPreview($object->logo)) {
  8041. if ((string) $imagesize == 'mini') {
  8042. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8043. } elseif ((string) $imagesize == 'small') {
  8044. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_small');
  8045. } else {
  8046. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8047. }
  8048. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8049. }
  8050. }
  8051. $email = $object->email;
  8052. } elseif ($modulepart == 'contact') {
  8053. $dir = $conf->societe->multidir_output[$entity].'/contact';
  8054. if (!empty($object->photo)) {
  8055. if (dolIsAllowedForPreview($object->photo)) {
  8056. if ((string) $imagesize == 'mini') {
  8057. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8058. } elseif ((string) $imagesize == 'small') {
  8059. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8060. } else {
  8061. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8062. }
  8063. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8064. }
  8065. }
  8066. $email = $object->email;
  8067. $capture = 'user';
  8068. } elseif ($modulepart == 'userphoto') {
  8069. $dir = $conf->user->dir_output;
  8070. if (!empty($object->photo)) {
  8071. if (dolIsAllowedForPreview($object->photo)) {
  8072. if ((string) $imagesize == 'mini') {
  8073. $file = get_exdir(0, 0, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_mini');
  8074. } elseif ((string) $imagesize == 'small') {
  8075. $file = get_exdir(0, 0, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_small');
  8076. } else {
  8077. $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->photo;
  8078. }
  8079. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').$object->photo;
  8080. }
  8081. }
  8082. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8083. $altfile = $object->id.".jpg"; // For backward compatibility
  8084. }
  8085. $email = $object->email;
  8086. $capture = 'user';
  8087. } elseif ($modulepart == 'memberphoto') {
  8088. $dir = $conf->adherent->dir_output;
  8089. if (!empty($object->photo)) {
  8090. if (dolIsAllowedForPreview($object->photo)) {
  8091. if ((string) $imagesize == 'mini') {
  8092. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8093. } elseif ((string) $imagesize == 'small') {
  8094. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8095. } else {
  8096. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8097. }
  8098. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8099. }
  8100. }
  8101. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8102. $altfile = $object->id.".jpg"; // For backward compatibility
  8103. }
  8104. $email = $object->email;
  8105. $capture = 'user';
  8106. } else {
  8107. // Generic case to show photos
  8108. $dir = $conf->$modulepart->dir_output;
  8109. if (!empty($object->photo)) {
  8110. if (dolIsAllowedForPreview($object->photo)) {
  8111. if ((string) $imagesize == 'mini') {
  8112. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8113. } elseif ((string) $imagesize == 'small') {
  8114. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  8115. } else {
  8116. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8117. }
  8118. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8119. }
  8120. }
  8121. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8122. $altfile = $object->id.".jpg"; // For backward compatibility
  8123. }
  8124. $email = $object->email;
  8125. }
  8126. if ($forcecapture) {
  8127. $capture = $forcecapture;
  8128. }
  8129. if ($dir) {
  8130. if ($file && file_exists($dir."/".$file)) {
  8131. if ($addlinktofullsize) {
  8132. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8133. if ($urladvanced) {
  8134. $ret .= '<a href="'.$urladvanced.'">';
  8135. } else {
  8136. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8137. }
  8138. }
  8139. $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.'">';
  8140. if ($addlinktofullsize) {
  8141. $ret .= '</a>';
  8142. }
  8143. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  8144. if ($addlinktofullsize) {
  8145. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8146. if ($urladvanced) {
  8147. $ret .= '<a href="'.$urladvanced.'">';
  8148. } else {
  8149. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8150. }
  8151. }
  8152. $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.'">';
  8153. if ($addlinktofullsize) {
  8154. $ret .= '</a>';
  8155. }
  8156. } else {
  8157. $nophoto = '/public/theme/common/nophoto.png';
  8158. $defaultimg = 'identicon'; // For gravatar
  8159. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8160. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8161. $nophoto = 'company';
  8162. } else {
  8163. $nophoto = '/public/theme/common/user_anonymous.png';
  8164. if (!empty($object->gender) && $object->gender == 'man') {
  8165. $nophoto = '/public/theme/common/user_man.png';
  8166. }
  8167. if (!empty($object->gender) && $object->gender == 'woman') {
  8168. $nophoto = '/public/theme/common/user_woman.png';
  8169. }
  8170. }
  8171. }
  8172. if (!empty($conf->gravatar->enabled) && $email && empty($noexternsourceoverwrite)) {
  8173. // see https://gravatar.com/site/implement/images/php/
  8174. $ret .= '<!-- Put link to gravatar -->';
  8175. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="Gravatar avatar" 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
  8176. } else {
  8177. if ($nophoto == 'company') {
  8178. $ret .= '<div class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'">'.img_picto('', 'company').'</div>';
  8179. } else {
  8180. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  8181. }
  8182. }
  8183. }
  8184. if ($caneditfield) {
  8185. if ($object->photo) {
  8186. $ret .= "<br>\n";
  8187. }
  8188. $ret .= '<table class="nobordernopadding centpercent">';
  8189. if ($object->photo) {
  8190. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">'.$langs->trans("Delete").'</label><br><br></td></tr>';
  8191. }
  8192. $ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
  8193. $ret .= '</table>';
  8194. }
  8195. } else {
  8196. dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  8197. }
  8198. return $ret;
  8199. }
  8200. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8201. /**
  8202. * Return select list of groups
  8203. *
  8204. * @param string $selected Id group preselected
  8205. * @param string $htmlname Field name in form
  8206. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8207. * @param string $exclude Array list of groups id to exclude
  8208. * @param int $disabled If select list must be disabled
  8209. * @param string $include Array list of groups id to include
  8210. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8211. * @param string $force_entity '0' or Ids of environment to force
  8212. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8213. * @param string $morecss More css to add to html component
  8214. * @return string
  8215. * @see select_dolusers()
  8216. */
  8217. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8218. {
  8219. // phpcs:enable
  8220. global $conf, $user, $langs;
  8221. // Permettre l'exclusion de groupes
  8222. if (is_array($exclude)) {
  8223. $excludeGroups = implode(",", $exclude);
  8224. }
  8225. // Permettre l'inclusion de groupes
  8226. if (is_array($include)) {
  8227. $includeGroups = implode(",", $include);
  8228. }
  8229. if (!is_array($selected)) {
  8230. $selected = array($selected);
  8231. }
  8232. $out = '';
  8233. // On recherche les groupes
  8234. $sql = "SELECT ug.rowid, ug.nom as name";
  8235. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8236. $sql .= ", e.label";
  8237. }
  8238. $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  8239. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8240. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
  8241. if ($force_entity) {
  8242. $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  8243. } else {
  8244. $sql .= " WHERE ug.entity IS NOT NULL";
  8245. }
  8246. } else {
  8247. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  8248. }
  8249. if (is_array($exclude) && $excludeGroups) {
  8250. $sql .= " AND ug.rowid NOT IN (".$this->db->sanitize($excludeGroups).")";
  8251. }
  8252. if (is_array($include) && $includeGroups) {
  8253. $sql .= " AND ug.rowid IN (".$this->db->sanitize($includeGroups).")";
  8254. }
  8255. $sql .= " ORDER BY ug.nom ASC";
  8256. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  8257. $resql = $this->db->query($sql);
  8258. if ($resql) {
  8259. // Enhance with select2
  8260. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8261. $out .= ajax_combobox($htmlname);
  8262. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  8263. $num = $this->db->num_rows($resql);
  8264. $i = 0;
  8265. if ($num) {
  8266. if ($show_empty && !$multiple) {
  8267. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8268. }
  8269. while ($i < $num) {
  8270. $obj = $this->db->fetch_object($resql);
  8271. $disableline = 0;
  8272. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8273. $disableline = 1;
  8274. }
  8275. $out .= '<option value="'.$obj->rowid.'"';
  8276. if ($disableline) {
  8277. $out .= ' disabled';
  8278. }
  8279. if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (!is_object($selected[0]) && in_array($obj->rowid, $selected))) {
  8280. $out .= ' selected';
  8281. }
  8282. $out .= '>';
  8283. $out .= $obj->name;
  8284. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8285. $out .= " (".$obj->label.")";
  8286. }
  8287. $out .= '</option>';
  8288. $i++;
  8289. }
  8290. } else {
  8291. if ($show_empty) {
  8292. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  8293. }
  8294. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  8295. }
  8296. $out .= '</select>';
  8297. } else {
  8298. dol_print_error($this->db);
  8299. }
  8300. return $out;
  8301. }
  8302. /**
  8303. * Return HTML to show the search and clear seach button
  8304. *
  8305. * @return string
  8306. */
  8307. public function showFilterButtons()
  8308. {
  8309. $out = '<div class="nowraponall">';
  8310. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8311. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8312. $out .= '</div>';
  8313. return $out;
  8314. }
  8315. /**
  8316. * Return HTML to show the search and clear search button
  8317. *
  8318. * @param string $cssclass CSS class
  8319. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8320. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8321. * @return string
  8322. */
  8323. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8324. {
  8325. global $conf, $langs;
  8326. $out = '';
  8327. if (!empty($conf->use_javascript_ajax)) {
  8328. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  8329. }
  8330. $out .= '<script>
  8331. $(document).ready(function() {
  8332. $("#' . $cssclass.'s").click(function() {
  8333. if($(this).is(\':checked\')){
  8334. console.log("We check all '.$cssclass.' and trigger the change method");
  8335. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  8336. }
  8337. else
  8338. {
  8339. console.log("We uncheck all");
  8340. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  8341. }'."\n";
  8342. if ($calljsfunction) {
  8343. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8344. }
  8345. $out .= ' });
  8346. $(".' . $cssclass.'").change(function() {
  8347. $(this).closest("tr").toggleClass("highlight", this.checked);
  8348. });
  8349. });
  8350. </script>';
  8351. return $out;
  8352. }
  8353. /**
  8354. * Return HTML to show the search and clear seach button
  8355. *
  8356. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8357. * @param string $cssclass CSS class
  8358. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8359. * @param string $massactionname Mass action name
  8360. * @return string
  8361. */
  8362. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8363. {
  8364. $out = $this->showFilterButtons();
  8365. if ($addcheckuncheckall) {
  8366. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8367. }
  8368. return $out;
  8369. }
  8370. /**
  8371. * Return HTML to show the select of expense categories
  8372. *
  8373. * @param string $selected preselected category
  8374. * @param string $htmlname name of HTML select list
  8375. * @param integer $useempty 1=Add empty line
  8376. * @param array $excludeid id to exclude
  8377. * @param string $target htmlname of target select to bind event
  8378. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8379. * @param array $params param to give
  8380. * @param int $info_admin Show the tooltip help picto to setup list
  8381. * @return string
  8382. */
  8383. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8384. {
  8385. global $db, $langs, $user;
  8386. $out = '';
  8387. $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
  8388. $sql .= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
  8389. if (!empty($excludeid)) {
  8390. $sql .= ' AND rowid NOT IN ('.$this->db->sanitize(implode(',', $excludeid)).')';
  8391. }
  8392. $sql .= ' ORDER BY label';
  8393. $resql = $db->query($sql);
  8394. if ($resql) {
  8395. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  8396. if ($useempty) {
  8397. $out .= '<option value="0">&nbsp;</option>';
  8398. }
  8399. while ($obj = $db->fetch_object($resql)) {
  8400. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  8401. }
  8402. $out .= '</select>';
  8403. $out .= ajax_combobox('select_'.$htmlname);
  8404. if (!empty($htmlname) && $user->admin && $info_admin) {
  8405. $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8406. }
  8407. if (!empty($target)) {
  8408. $sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8409. $resql = $db->query($sql);
  8410. if ($resql) {
  8411. if ($db->num_rows($resql) > 0) {
  8412. $obj = $db->fetch_object($resql);
  8413. $out .= '<script>
  8414. $(function() {
  8415. $("select[name='.$target.']").on("change", function() {
  8416. var current_val = $(this).val();
  8417. if (current_val == '.$obj->id.') {';
  8418. if (!empty($default_selected) || !empty($selected)) {
  8419. $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  8420. }
  8421. $out .= '
  8422. $("select[name='.$htmlname.']").change();
  8423. }
  8424. });
  8425. $("select[name='.$htmlname.']").change(function() {
  8426. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  8427. // get price of kilometer to fill the unit price
  8428. $.ajax({
  8429. method: "POST",
  8430. dataType: "json",
  8431. data: { fk_c_exp_tax_cat: $(this).val(), token: \''.currentToken().'\' },
  8432. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php?'.$params).'",
  8433. }).done(function( data, textStatus, jqXHR ) {
  8434. console.log(data);
  8435. if (typeof data.up != "undefined") {
  8436. $("input[name=value_unit]").val(data.up);
  8437. $("select[name='.$htmlname.']").attr("title", data.title);
  8438. } else {
  8439. $("input[name=value_unit]").val("");
  8440. $("select[name='.$htmlname.']").attr("title", "");
  8441. }
  8442. });
  8443. }
  8444. });
  8445. });
  8446. </script>';
  8447. }
  8448. }
  8449. }
  8450. } else {
  8451. dol_print_error($db);
  8452. }
  8453. return $out;
  8454. }
  8455. /**
  8456. * Return HTML to show the select ranges of expense range
  8457. *
  8458. * @param string $selected preselected category
  8459. * @param string $htmlname name of HTML select list
  8460. * @param integer $useempty 1=Add empty line
  8461. * @return string
  8462. */
  8463. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8464. {
  8465. global $db, $conf, $langs;
  8466. $out = '';
  8467. $sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
  8468. $sql .= ' WHERE entity = '.$conf->entity.' AND active = 1';
  8469. $resql = $db->query($sql);
  8470. if ($resql) {
  8471. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8472. if ($useempty) {
  8473. $out .= '<option value="0"></option>';
  8474. }
  8475. while ($obj = $db->fetch_object($resql)) {
  8476. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  8477. }
  8478. $out .= '</select>';
  8479. } else {
  8480. dol_print_error($db);
  8481. }
  8482. return $out;
  8483. }
  8484. /**
  8485. * Return HTML to show a select of expense
  8486. *
  8487. * @param string $selected preselected category
  8488. * @param string $htmlname name of HTML select list
  8489. * @param integer $useempty 1=Add empty choice
  8490. * @param integer $allchoice 1=Add all choice
  8491. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8492. * @return string
  8493. */
  8494. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8495. {
  8496. global $db, $langs;
  8497. $out = '';
  8498. $sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
  8499. $sql .= ' WHERE active = 1';
  8500. $resql = $db->query($sql);
  8501. if ($resql) {
  8502. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8503. if ($useempty) {
  8504. $out .= '<option value="0"></option>';
  8505. }
  8506. if ($allchoice) {
  8507. $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  8508. }
  8509. $field = 'code';
  8510. if ($useid) {
  8511. $field = 'id';
  8512. }
  8513. while ($obj = $db->fetch_object($resql)) {
  8514. $key = $langs->trans($obj->code);
  8515. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  8516. }
  8517. $out .= '</select>';
  8518. } else {
  8519. dol_print_error($db);
  8520. }
  8521. return $out;
  8522. }
  8523. /**
  8524. * Output a combo list with invoices qualified for a third party
  8525. *
  8526. * @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)
  8527. * @param int $selected Id invoice preselected
  8528. * @param string $htmlname Name of HTML select
  8529. * @param int $maxlength Maximum length of label
  8530. * @param int $option_only Return only html options lines without the select tag
  8531. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8532. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8533. * @param int $forcefocus Force focus on field (works with javascript only)
  8534. * @param int $disabled Disabled
  8535. * @param string $morecss More css added to the select component
  8536. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  8537. * @param string $showproject 'all' = Show project info, ''=Hide project info
  8538. * @param User $usertofilter User object to use for filtering
  8539. * @return int Nbr of project if OK, <0 if KO
  8540. */
  8541. 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)
  8542. {
  8543. global $user, $conf, $langs;
  8544. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  8545. if (is_null($usertofilter)) {
  8546. $usertofilter = $user;
  8547. }
  8548. $out = '';
  8549. $hideunselectables = false;
  8550. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  8551. $hideunselectables = true;
  8552. }
  8553. if (empty($projectsListId)) {
  8554. if (empty($usertofilter->rights->projet->all->lire)) {
  8555. $projectstatic = new Project($this->db);
  8556. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  8557. }
  8558. }
  8559. // Search all projects
  8560. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  8561. p.title, p.fk_soc, p.fk_statut, p.public,";
  8562. $sql .= ' s.nom as name';
  8563. $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as p';
  8564. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,';
  8565. $sql .= ' '.MAIN_DB_PREFIX.'facture as f';
  8566. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  8567. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  8568. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  8569. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  8570. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  8571. $sql .= " ORDER BY p.ref, f.ref ASC";
  8572. $resql = $this->db->query($sql);
  8573. if ($resql) {
  8574. // Use select2 selector
  8575. if (!empty($conf->use_javascript_ajax)) {
  8576. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8577. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8578. $out .= $comboenhancement;
  8579. $morecss = 'minwidth200imp maxwidth500';
  8580. }
  8581. if (empty($option_only)) {
  8582. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  8583. }
  8584. if (!empty($show_empty)) {
  8585. $out .= '<option value="0" class="optiongrey">';
  8586. if (!is_numeric($show_empty)) {
  8587. $out .= $show_empty;
  8588. } else {
  8589. $out .= '&nbsp;';
  8590. }
  8591. $out .= '</option>';
  8592. }
  8593. $num = $this->db->num_rows($resql);
  8594. $i = 0;
  8595. if ($num) {
  8596. while ($i < $num) {
  8597. $obj = $this->db->fetch_object($resql);
  8598. // 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.
  8599. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  8600. // Do nothing
  8601. } else {
  8602. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  8603. $i++;
  8604. continue;
  8605. }
  8606. $labeltoshow = '';
  8607. if ($showproject == 'all') {
  8608. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  8609. if ($obj->name) {
  8610. $labeltoshow .= ' - '.$obj->name; // Soc name
  8611. }
  8612. $disabled = 0;
  8613. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  8614. $disabled = 1;
  8615. $labeltoshow .= ' - '.$langs->trans("Draft");
  8616. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  8617. if ($discard_closed == 2) {
  8618. $disabled = 1;
  8619. }
  8620. $labeltoshow .= ' - '.$langs->trans("Closed");
  8621. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  8622. $disabled = 1;
  8623. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  8624. }
  8625. }
  8626. if (!empty($selected) && $selected == $obj->rowid) {
  8627. $out .= '<option value="'.$obj->rowid.'" selected';
  8628. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8629. $out .= '>'.$labeltoshow.'</option>';
  8630. } else {
  8631. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  8632. $resultat = '';
  8633. } else {
  8634. $resultat = '<option value="'.$obj->rowid.'"';
  8635. if ($disabled) {
  8636. $resultat .= ' disabled';
  8637. }
  8638. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  8639. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  8640. $resultat .= '>';
  8641. $resultat .= $labeltoshow;
  8642. $resultat .= '</option>';
  8643. }
  8644. $out .= $resultat;
  8645. }
  8646. }
  8647. $i++;
  8648. }
  8649. }
  8650. if (empty($option_only)) {
  8651. $out .= '</select>';
  8652. }
  8653. print $out;
  8654. $this->db->free($resql);
  8655. return $num;
  8656. } else {
  8657. dol_print_error($this->db);
  8658. return -1;
  8659. }
  8660. }
  8661. /**
  8662. * Output the component to make advanced search criteries
  8663. *
  8664. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  8665. * @param array $search_component_params Array of selected search criterias
  8666. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  8667. * @param string $search_component_params_hidden String with $search_component_params criterias
  8668. * @return string HTML component for advanced search
  8669. */
  8670. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  8671. {
  8672. global $langs;
  8673. $ret = '';
  8674. $ret .= '<div class="nowrap centpercent">';
  8675. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8676. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor paddingright">';
  8677. $ret .= '<span class="fas fa-filter linkobject boxfilter" title="Filter" id="idsubimgproductdistribution"></span>';
  8678. $ret .= $langs->trans("Filters");
  8679. $ret .= '</a>';
  8680. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8681. $ret .= '<div name="search_component_params" class="search_component_params inline-block minwidth500 maxwidth300onsmartphone valignmiddle">';
  8682. $texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  8683. $ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  8684. $ret .= '</div>';
  8685. $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";
  8686. if (GETPOST('show_search_component_params_hidden', 'int')) {
  8687. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  8688. }
  8689. $ret .= '<input type="'.(GETPOST('show_search_component_params_hidden', 'int') ? 'text' : 'hidden').'" name="search_component_params_hidden" class="search_component_params_hidden marginleftonly" value="'.$search_component_params_hidden.'">';
  8690. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  8691. foreach ($arrayofcriterias as $criterias) {
  8692. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  8693. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  8694. continue;
  8695. }
  8696. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  8697. continue;
  8698. }
  8699. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  8700. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  8701. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  8702. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  8703. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  8704. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  8705. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  8706. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  8707. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  8708. } else {
  8709. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  8710. }
  8711. }
  8712. }
  8713. $ret .= '</div>';
  8714. return $ret;
  8715. }
  8716. /**
  8717. * selectModelMail
  8718. *
  8719. * @param string $prefix Prefix
  8720. * @param string $modelType Model type
  8721. * @param int $default 1=Show also Default mail template
  8722. * @param int $addjscombo Add js combobox
  8723. * @return string HTML select string
  8724. */
  8725. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  8726. {
  8727. global $langs, $db, $user;
  8728. $retstring = '';
  8729. $TModels = array();
  8730. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  8731. $formmail = new FormMail($db);
  8732. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  8733. if ($default) {
  8734. $TModels[0] = $langs->trans('DefaultMailModel');
  8735. }
  8736. if ($result > 0) {
  8737. foreach ($formmail->lines_model as $model) {
  8738. $TModels[$model->id] = $model->label;
  8739. }
  8740. }
  8741. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  8742. foreach ($TModels as $id_model => $label_model) {
  8743. $retstring .= '<option value="'.$id_model.'"';
  8744. $retstring .= ">".$label_model."</option>";
  8745. }
  8746. $retstring .= "</select>";
  8747. if ($addjscombo) {
  8748. $retstring .= ajax_combobox('select_'.$prefix.'model_mail');
  8749. }
  8750. return $retstring;
  8751. }
  8752. /**
  8753. * Output the buttons to submit a creation/edit form
  8754. *
  8755. * @param string $save_label Alternative label for save button
  8756. * @param string $cancel_label Alternative label for cancel button
  8757. * @param array $morebuttons Add additional buttons between save and cancel
  8758. * @param bool $withoutdiv Option to remove enclosing centered div
  8759. * @param string $morecss More CSS
  8760. * @return string Html code with the buttons
  8761. */
  8762. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '')
  8763. {
  8764. global $langs;
  8765. $buttons = array();
  8766. $save = array(
  8767. 'name' => 'save',
  8768. 'label_key' => $save_label,
  8769. );
  8770. if ($save_label == 'Create' || $save_label == 'Add' ) {
  8771. $save['name'] = 'add';
  8772. } elseif ($save_label == 'Modify') {
  8773. $save['name'] = 'edit';
  8774. }
  8775. $cancel = array(
  8776. 'name' => 'cancel',
  8777. 'label_key' => 'Cancel',
  8778. );
  8779. !empty($save_label) ? $buttons[] = $save : '';
  8780. if (!empty($morebuttons)) {
  8781. $buttons[] = $morebuttons;
  8782. }
  8783. !empty($cancel_label) ? $buttons[] = $cancel : '';
  8784. $retstring = $withoutdiv ? '': '<div class="center">';
  8785. foreach ($buttons as $button) {
  8786. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  8787. $retstring .= '<input type="submit" class="button button-'.$button['name'].($morecss ? ' '.$morecss : '').' '.$addclass.'" name="'.$button['name'].'" value="'.dol_escape_htmltag($langs->trans($button['label_key'])).'">';
  8788. }
  8789. $retstring .= $withoutdiv ? '': '</div>';
  8790. return $retstring;
  8791. }
  8792. }