html.form.class.php 353 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268
  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-2019 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 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018-2019 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), '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. {
  104. if (!empty($perm))
  105. {
  106. $tmp = explode(':', $typeofdata);
  107. $ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  108. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  109. if ($help) {
  110. $ret .= $this->textwithpicto($langs->trans($text), $help);
  111. } else {
  112. $ret .= $langs->trans($text);
  113. }
  114. if ($fieldrequired) $ret .= '</span>';
  115. $ret .= '</div>'."\n";
  116. } else {
  117. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  118. if ($help) {
  119. $ret .= $this->textwithpicto($langs->trans($text), $help);
  120. } else {
  121. $ret .= $langs->trans($text);
  122. }
  123. if ($fieldrequired) $ret .= '</span>';
  124. }
  125. } else {
  126. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  127. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  128. if ($help) {
  129. $ret .= $this->textwithpicto($langs->trans($text), $help);
  130. } else {
  131. $ret .= $langs->trans($text);
  132. }
  133. if ($fieldrequired) $ret .= '</span>';
  134. if (!empty($notabletag)) $ret .= ' ';
  135. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</td>';
  136. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<td class="right">';
  137. if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  138. if (!empty($notabletag) && $notabletag == 1) $ret .= ' : ';
  139. if (!empty($notabletag) && $notabletag == 3) $ret .= ' ';
  140. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</td>';
  141. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</tr></table>';
  142. }
  143. return $ret;
  144. }
  145. /**
  146. * Output value of a field for an editable field
  147. *
  148. * @param string $text Text of label (not used in this function)
  149. * @param string $htmlname Name of select field
  150. * @param string $value Value to show/edit
  151. * @param object $object Object
  152. * @param boolean $perm Permission to allow button to edit parameter
  153. * @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,...')
  154. * @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 value). Use '' to use same than $value
  155. * @param object $extObject External object
  156. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  157. * @param string $moreparam More param to add on the form action href URL
  158. * @param int $notabletag Do no output table tags
  159. * @param string $formatfunc Call a specific function to output field
  160. * @param string $paramid Key of parameter for id ('id', 'socid')
  161. * @return string HTML edit field
  162. */
  163. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id')
  164. {
  165. global $conf, $langs, $db;
  166. $ret = '';
  167. // Check parameters
  168. if (empty($typeofdata)) return 'ErrorBadParameter';
  169. // When option to edit inline is activated
  170. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|datehourpicker/', $typeofdata)) // TODO add jquery timepicker and support select
  171. {
  172. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  173. } else {
  174. $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
  175. if ($editmode)
  176. {
  177. $ret .= "\n";
  178. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  179. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  180. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  181. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  182. if (empty($notabletag)) $ret .= '<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
  183. if (empty($notabletag)) $ret .= '<tr><td>';
  184. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata))
  185. {
  186. $tmp = explode(':', $typeofdata);
  187. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  188. } elseif (preg_match('/^(numeric|amount)/', $typeofdata))
  189. {
  190. $tmp = explode(':', $typeofdata);
  191. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  192. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ?price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  193. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) // if wysiwyg is enabled $typeofdata = 'ckeditor'
  194. {
  195. $tmp = explode(':', $typeofdata);
  196. $cols = $tmp[2];
  197. $morealt = '';
  198. if (preg_match('/%/', $cols))
  199. {
  200. $morealt = ' style="width: '.$cols.'"';
  201. $cols = '';
  202. }
  203. $valuetoshow = ($editvalue ? $editvalue : $value);
  204. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  205. // textarea convert automatically entities chars into simple chars.
  206. // 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.
  207. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  208. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  209. $ret .= '</textarea>';
  210. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker')
  211. {
  212. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0);
  213. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
  214. {
  215. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0);
  216. } elseif (preg_match('/^select;/', $typeofdata))
  217. {
  218. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  219. $arraylist = array();
  220. foreach ($arraydata as $val)
  221. {
  222. $tmp = explode(':', $val);
  223. $tmpkey = str_replace('|', ':', $tmp[0]);
  224. $arraylist[$tmpkey] = $tmp[1];
  225. }
  226. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  227. } elseif (preg_match('/^ckeditor/', $typeofdata))
  228. {
  229. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  230. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  231. $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'));
  232. $ret .= $doleditor->Create(1);
  233. }
  234. if (empty($notabletag)) $ret .= '</td>';
  235. if (empty($notabletag)) $ret .= '<td class="left">';
  236. //else $ret.='<div class="clearboth"></div>';
  237. $ret .= '<input type="submit" class="button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  238. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) $ret .= '<br>'."\n";
  239. $ret .= '<input type="submit" class="button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  240. if (empty($notabletag)) $ret .= '</td>';
  241. if (empty($notabletag)) $ret .= '</tr></table>'."\n";
  242. $ret .= '</form>'."\n";
  243. } else {
  244. if (preg_match('/^(email)/', $typeofdata)) $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  245. elseif (preg_match('/^(amount|numeric)/', $typeofdata)) $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  246. elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) $ret .= dol_htmlentitiesbr($value);
  247. elseif (preg_match('/^safehtmlstring/', $typeofdata)) $ret .= dol_string_onlythesehtmltags($value);
  248. elseif (preg_match('/^restricthtml/', $typeofdata)) $ret .= dol_string_onlythesehtmltags($value);
  249. elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret .= '<span class="valuedate">'.dol_print_date($value, 'day').'</span>';
  250. elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour').'</span>';
  251. elseif (preg_match('/^select;/', $typeofdata))
  252. {
  253. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  254. $arraylist = array();
  255. foreach ($arraydata as $val)
  256. {
  257. $tmp = explode(':', $val);
  258. $arraylist[$tmp[0]] = $tmp[1];
  259. }
  260. $ret .= $arraylist[$value];
  261. } elseif (preg_match('/^ckeditor/', $typeofdata))
  262. {
  263. $tmpcontent = dol_htmlentitiesbr($value);
  264. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB))
  265. {
  266. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  267. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  268. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  269. }
  270. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  271. // clean data from some dangerous html
  272. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  273. } else {
  274. $ret .= dol_escape_htmltag($value);
  275. }
  276. if ($formatfunc && method_exists($object, $formatfunc))
  277. {
  278. $ret = $object->$formatfunc($ret);
  279. }
  280. }
  281. }
  282. return $ret;
  283. }
  284. /**
  285. * Output edit in place form
  286. *
  287. * @param string $fieldname Name of the field
  288. * @param object $object Object
  289. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  290. * @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]'...)
  291. * @param string $check Same coe than $check parameter of GETPOST()
  292. * @param string $morecss More CSS
  293. * @return string HTML code for the edit of alternative language
  294. */
  295. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  296. {
  297. global $conf, $langs, $extralanguages;
  298. $result = '';
  299. // List of extra languages
  300. $arrayoflangcode = array();
  301. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  302. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  303. if (!is_object($extralanguages)) {
  304. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  305. $extralanguages = new ExtraLanguages($this->db);
  306. }
  307. $extralanguages->fetch_name_extralanguages('societe');
  308. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  309. return ''; // No extralang field to show
  310. }
  311. $result .= '<!-- Widget for translation -->'."\n";
  312. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  313. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  314. $result .= $s;
  315. $result .= '</div>';
  316. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  317. $resultforextrlang = '';
  318. foreach ($arrayoflangcode as $langcode)
  319. {
  320. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  321. if (empty($valuetoshow)) {
  322. $object->fetchValuesForExtraLanguages();
  323. //var_dump($object->array_languages);
  324. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  325. }
  326. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  327. $resultforextrlang .= $s;
  328. // TODO Use the showInputField() method of ExtraLanguages object
  329. if ($typeofdata == 'textarea') {
  330. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  331. $resultforextrlang .= $valuetoshow;
  332. $resultforextrlang .= '</textarea>';
  333. } else {
  334. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  335. }
  336. }
  337. $result .= $resultforextrlang;
  338. $result .= '</div>';
  339. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  340. }
  341. return $result;
  342. }
  343. /**
  344. * Output edit in place form
  345. *
  346. * @param object $object Object
  347. * @param string $value Value to show/edit
  348. * @param string $htmlname DIV ID (field name)
  349. * @param int $condition Condition to edit
  350. * @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')
  351. * @param string $editvalue When in edit mode, use this value as $value instead of value
  352. * @param object $extObject External object
  353. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  354. * @return string HTML edit in place
  355. */
  356. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  357. {
  358. global $conf;
  359. $out = '';
  360. // Check parameters
  361. if (preg_match('/^text/', $inputType)) $value = dol_nl2br($value);
  362. elseif (preg_match('/^numeric/', $inputType)) $value = price($value);
  363. elseif ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
  364. if ($condition)
  365. {
  366. $element = false;
  367. $table_element = false;
  368. $fk_element = false;
  369. $loadmethod = false;
  370. $savemethod = false;
  371. $ext_element = false;
  372. $button_only = false;
  373. $inputOption = '';
  374. if (is_object($object))
  375. {
  376. $element = $object->element;
  377. $table_element = $object->table_element;
  378. $fk_element = $object->id;
  379. }
  380. if (is_object($extObject))
  381. {
  382. $ext_element = $extObject->element;
  383. }
  384. if (preg_match('/^(string|email|numeric)/', $inputType))
  385. {
  386. $tmp = explode(':', $inputType);
  387. $inputType = $tmp[0];
  388. if (!empty($tmp[1])) $inputOption = $tmp[1];
  389. if (!empty($tmp[2])) $savemethod = $tmp[2];
  390. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  391. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType)))
  392. {
  393. $tmp = explode(':', $inputType);
  394. $inputType = $tmp[0];
  395. if (!empty($tmp[1])) $inputOption = $tmp[1];
  396. if (!empty($tmp[2])) $savemethod = $tmp[2];
  397. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  398. } elseif (preg_match('/^(select|autocomplete)/', $inputType))
  399. {
  400. $tmp = explode(':', $inputType);
  401. $inputType = $tmp[0]; $loadmethod = $tmp[1];
  402. if (!empty($tmp[2])) $savemethod = $tmp[2];
  403. if (!empty($tmp[3])) $button_only = true;
  404. } elseif (preg_match('/^textarea/', $inputType))
  405. {
  406. $tmp = explode(':', $inputType);
  407. $inputType = $tmp[0];
  408. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  409. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  410. } elseif (preg_match('/^ckeditor/', $inputType))
  411. {
  412. $tmp = explode(':', $inputType);
  413. $inputType = $tmp[0]; $toolbar = $tmp[1];
  414. if (!empty($tmp[2])) $width = $tmp[2];
  415. if (!empty($tmp[3])) $heigth = $tmp[3];
  416. if (!empty($tmp[4])) $savemethod = $tmp[4];
  417. if (!empty($conf->fckeditor->enabled))
  418. {
  419. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  420. } else {
  421. $inputType = 'textarea';
  422. }
  423. }
  424. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  425. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  426. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  427. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  428. if (!empty($savemethod)) $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  429. if (!empty($ext_element)) $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  430. if (!empty($custommsg))
  431. {
  432. if (is_array($custommsg))
  433. {
  434. if (!empty($custommsg['success']))
  435. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  436. if (!empty($custommsg['error']))
  437. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  438. } else $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  439. }
  440. if ($inputType == 'textarea') {
  441. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  442. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  443. }
  444. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  445. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  446. } else {
  447. $out = $value;
  448. }
  449. return $out;
  450. }
  451. /**
  452. * Show a text and picto with tooltip on text or picto.
  453. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  454. *
  455. * @param string $text Text to show
  456. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  457. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  458. * @param int $direction -1=image is before, 0=no image, 1=image is after
  459. * @param string $img Html code for image (use img_xxx() function to get it)
  460. * @param string $extracss Add a CSS style to td tags
  461. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  462. * @param string $incbefore Include code before the text
  463. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  464. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  465. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  466. * @return string Code html du tooltip (texte+picto)
  467. * @see textwithpicto() Use thisfunction if you can.
  468. */
  469. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  470. {
  471. if ($incbefore) $text = $incbefore.$text;
  472. if (!$htmltext) return $text;
  473. $tag = 'td';
  474. if ($notabs == 2) $tag = 'div';
  475. if ($notabs == 3) $tag = 'span';
  476. // Sanitize tooltip
  477. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  478. $extrastyle = '';
  479. if ($direction < 0) { $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : ''); $extrastyle = 'padding: 0px; padding-left: 3px !important;'; }
  480. if ($direction > 0) { $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : ''); $extrastyle = 'padding: 0px; padding-right: 3px !important;'; }
  481. $classfortooltip = 'classfortooltip';
  482. $s = ''; $textfordialog = '';
  483. if ($tooltiptrigger == '')
  484. {
  485. $htmltext = str_replace('"', '&quot;', $htmltext);
  486. } else {
  487. $classfortooltip = 'classfortooltiponclick';
  488. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  489. }
  490. if ($tooltipon == 2 || $tooltipon == 3)
  491. {
  492. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  493. if ($tooltiptrigger == '') $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  494. else $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  495. } else $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  496. if ($tooltipon == 1 || $tooltipon == 3)
  497. {
  498. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  499. if ($tooltiptrigger == '') $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  500. else $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  501. } else $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  502. if (empty($notabs)) $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  503. elseif ($notabs == 2) $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  504. // Define value if value is before
  505. if ($direction < 0) {
  506. $s .= '<'.$tag.$paramfortooltipimg;
  507. if ($tag == 'td') {
  508. $s .= ' class=valigntop" width="14"';
  509. }
  510. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  511. }
  512. // Use another method to help avoid having a space in value in order to use this value with jquery
  513. // Define label
  514. if ((string) $text != '') $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  515. // Define value if value is after
  516. if ($direction > 0) {
  517. $s .= '<'.$tag.$paramfortooltipimg;
  518. if ($tag == 'td') $s .= ' class="valignmiddle" width="14"';
  519. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  520. }
  521. if (empty($notabs)) $s .= '</tr></table>';
  522. elseif ($notabs == 2) $s .= '</div>';
  523. return $s;
  524. }
  525. /**
  526. * Show a text with a picto and a tooltip on picto
  527. *
  528. * @param string $text Text to show
  529. * @param string $htmltext Content of tooltip
  530. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  531. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  532. * @param string $extracss Add a CSS style to td, div or span tag
  533. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  534. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  535. * @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')
  536. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  537. * @return string HTML code of text, picto, tooltip
  538. */
  539. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  540. {
  541. global $conf, $langs;
  542. $alt = '';
  543. if ($tooltiptrigger) $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  544. //For backwards compatibility
  545. if ($type == '0') $type = 'info';
  546. elseif ($type == '1') $type = 'help';
  547. // If info or help with no javascript, show only text
  548. if (empty($conf->use_javascript_ajax))
  549. {
  550. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') return $text;
  551. else {
  552. $alt = $htmltext;
  553. $htmltext = '';
  554. }
  555. }
  556. // If info or help with smartphone, show only text (tooltip hover can't works)
  557. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
  558. {
  559. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') return $text;
  560. }
  561. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  562. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  563. //{
  564. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  565. //}
  566. $img = '';
  567. if ($type == 'info') $img = img_help(0, $alt);
  568. elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  569. elseif ($type == 'helpclickable') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  570. elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
  571. elseif ($type == 'admin') $img = img_picto($alt, 'star');
  572. elseif ($type == 'warning') $img = img_warning($alt);
  573. elseif ($type != 'none') $img = img_picto($alt, $type); // $type can be an image path
  574. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  575. }
  576. /**
  577. * Generate select HTML to choose massaction
  578. *
  579. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  580. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  581. * @param int $alwaysvisible 1=select button always visible
  582. * @param string $name Name for massaction
  583. * @param string $cssclass CSS class used to check for select
  584. * @return string|void Select list
  585. */
  586. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  587. {
  588. global $conf, $langs, $hookmanager;
  589. $disabled = 0;
  590. $ret = '<div class="centpercent center">';
  591. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  592. // 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.
  593. $parameters = array();
  594. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  595. // check if there is a mass action
  596. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) return;
  597. if (empty($reshook))
  598. {
  599. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  600. foreach ($arrayofaction as $code => $label)
  601. {
  602. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  603. }
  604. }
  605. $ret .= $hookmanager->resPrint;
  606. $ret .= '</select>';
  607. if (empty($conf->dol_optimize_smallscreen)) $ret .= ajax_combobox('.'.$name.'select');
  608. // 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
  609. $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.
  610. $ret .= '<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'confirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  611. $ret .= '</div>';
  612. if (!empty($conf->use_javascript_ajax))
  613. {
  614. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  615. <script>
  616. 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 */
  617. {
  618. atleastoneselected=0;
  619. jQuery("."+cssclass).each(function( index ) {
  620. /* console.log( index + ": " + $( this ).text() ); */
  621. if ($(this).is(\':checked\')) atleastoneselected++;
  622. });
  623. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  624. if (atleastoneselected || '.$alwaysvisible.')
  625. {
  626. jQuery("."+name).show();
  627. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  628. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  629. }
  630. else
  631. {
  632. jQuery("."+name).hide();
  633. jQuery("."+name+"other").hide();
  634. }
  635. }
  636. jQuery(document).ready(function () {
  637. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  638. jQuery(".' . $cssclass.'").click(function() {
  639. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  640. });
  641. jQuery(".' . $name.'select").change(function() {
  642. var massaction = $( this ).val();
  643. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  644. if (massaction == "builddoc")
  645. {
  646. urlform = urlform + "#show_files";
  647. }
  648. $( this ).closest("form").attr("action", urlform);
  649. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  650. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  651. if ($(this).val() != \'0\')
  652. {
  653. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  654. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  655. jQuery(".' . $name.'"+massaction).show();
  656. }
  657. else
  658. {
  659. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  660. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  661. }
  662. });
  663. });
  664. </script>
  665. ';
  666. }
  667. return $ret;
  668. }
  669. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  670. /**
  671. * Return combo list of activated countries, into language of user
  672. *
  673. * @param string $selected Id or Code or Label of preselected country
  674. * @param string $htmlname Name of html select object
  675. * @param string $htmloption More html options on select object
  676. * @param integer $maxlength Max length for labels (0=no limit)
  677. * @param string $morecss More css class
  678. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  679. * @param int $showempty Show empty choice
  680. * @param int $disablefavorites 1=Disable favorites,
  681. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  682. * @param array $exclude_country_code Array of country code (iso2) to exclude
  683. * @return string HTML string with select
  684. */
  685. public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array())
  686. {
  687. // phpcs:enable
  688. global $conf, $langs, $mysoc;
  689. $langs->load("dict");
  690. $out = '';
  691. $countryArray = array();
  692. $favorite = array();
  693. $label = array();
  694. $atleastonefavorite = 0;
  695. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
  696. $sql .= " FROM ".MAIN_DB_PREFIX."c_country";
  697. $sql .= " WHERE active > 0";
  698. //$sql.= " ORDER BY code ASC";
  699. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  700. $resql = $this->db->query($sql);
  701. if ($resql)
  702. {
  703. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  704. $num = $this->db->num_rows($resql);
  705. $i = 0;
  706. if ($num)
  707. {
  708. while ($i < $num)
  709. {
  710. $obj = $this->db->fetch_object($resql);
  711. $countryArray[$i]['rowid'] = $obj->rowid;
  712. $countryArray[$i]['code_iso'] = $obj->code_iso;
  713. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  714. $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 : ''));
  715. $countryArray[$i]['favorite'] = $obj->favorite;
  716. $favorite[$i] = $obj->favorite;
  717. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  718. $i++;
  719. }
  720. if (empty($disablefavorites)) array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  721. else $countryArray = dol_sort_array($countryArray, 'label');
  722. if ($showempty)
  723. {
  724. $out .= '<option value="">&nbsp;</option>'."\n";
  725. }
  726. if ($addspecialentries) // Add dedicated entries for groups of countries
  727. {
  728. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  729. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  730. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  731. if ($mysoc->isInEEC()) $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  732. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  733. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  734. }
  735. foreach ($countryArray as $row)
  736. {
  737. //if (empty($showempty) && empty($row['rowid'])) continue;
  738. if (empty($row['rowid'])) continue;
  739. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) continue; // exclude some countries
  740. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
  741. if (empty($row['favorite']) && $atleastonefavorite)
  742. {
  743. $atleastonefavorite = 0;
  744. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  745. }
  746. $labeltoshow = '';
  747. if ($row['label']) $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  748. else $labeltoshow .= '&nbsp;';
  749. if ($row['code_iso']) {
  750. $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
  751. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium marginrightonly"');
  752. $labeltoshow = $tmpflag.' '.$labeltoshow;
  753. }
  754. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  755. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  756. } else {
  757. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  758. }
  759. $out .= $labeltoshow;
  760. $out .= '</option>';
  761. }
  762. }
  763. $out .= '</select>';
  764. } else {
  765. dol_print_error($this->db);
  766. }
  767. // Make select dynamic
  768. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  769. $out .= ajax_combobox('select'.$htmlname);
  770. return $out;
  771. }
  772. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  773. /**
  774. * Return select list of incoterms
  775. *
  776. * @param string $selected Id or Code of preselected incoterm
  777. * @param string $location_incoterms Value of input location
  778. * @param string $page Defined the form action
  779. * @param string $htmlname Name of html select object
  780. * @param string $htmloption Options html on select object
  781. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  782. * @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')))
  783. * @return string HTML string with select and input
  784. */
  785. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
  786. {
  787. // phpcs:enable
  788. global $conf, $langs;
  789. $langs->load("dict");
  790. $out = '';
  791. $incotermArray = array();
  792. $sql = "SELECT rowid, code";
  793. $sql .= " FROM ".MAIN_DB_PREFIX."c_incoterms";
  794. $sql .= " WHERE active > 0";
  795. $sql .= " ORDER BY code ASC";
  796. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  797. $resql = $this->db->query($sql);
  798. if ($resql)
  799. {
  800. if ($conf->use_javascript_ajax && !$forcecombo)
  801. {
  802. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  803. $out .= ajax_combobox($htmlname, $events);
  804. }
  805. if (!empty($page))
  806. {
  807. $out .= '<form method="post" action="'.$page.'">';
  808. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  809. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  810. }
  811. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
  812. $out .= '<option value="0">&nbsp;</option>';
  813. $num = $this->db->num_rows($resql);
  814. $i = 0;
  815. if ($num)
  816. {
  817. $foundselected = false;
  818. while ($i < $num)
  819. {
  820. $obj = $this->db->fetch_object($resql);
  821. $incotermArray[$i]['rowid'] = $obj->rowid;
  822. $incotermArray[$i]['code'] = $obj->code;
  823. $i++;
  824. }
  825. foreach ($incotermArray as $row)
  826. {
  827. if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
  828. {
  829. $out .= '<option value="'.$row['rowid'].'" selected>';
  830. } else {
  831. $out .= '<option value="'.$row['rowid'].'">';
  832. }
  833. if ($row['code']) $out .= $row['code'];
  834. $out .= '</option>';
  835. }
  836. }
  837. $out .= '</select>';
  838. $out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
  839. if (!empty($page))
  840. {
  841. $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
  842. }
  843. } else {
  844. dol_print_error($this->db);
  845. }
  846. return $out;
  847. }
  848. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  849. /**
  850. * Return list of types of lines (product or service)
  851. * Example: 0=product, 1=service, 9=other (for external module)
  852. *
  853. * @param string $selected Preselected type
  854. * @param string $htmlname Name of field in html form
  855. * @param int $showempty Add an empty field
  856. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  857. * @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')
  858. * @return void
  859. */
  860. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  861. {
  862. // phpcs:enable
  863. global $db, $langs, $user, $conf;
  864. // If product & services are enabled or both disabled.
  865. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  866. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)))
  867. {
  868. if (empty($hidetext)) print $langs->trans("Type").': ';
  869. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  870. if ($showempty)
  871. {
  872. print '<option value="-1"';
  873. if ($selected == -1) print ' selected';
  874. print '>&nbsp;</option>';
  875. }
  876. print '<option value="0"';
  877. if (0 == $selected) print ' selected';
  878. print '>'.$langs->trans("Product");
  879. print '<option value="1"';
  880. if (1 == $selected) print ' selected';
  881. print '>'.$langs->trans("Service");
  882. print '</select>';
  883. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  884. }
  885. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3)
  886. {
  887. print $langs->trans("Service");
  888. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  889. }
  890. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2)
  891. {
  892. print $langs->trans("Product");
  893. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  894. }
  895. if ($forceall < 0) // This should happened only for contracts when both predefined product and service are disabled.
  896. {
  897. 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
  898. }
  899. }
  900. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  901. /**
  902. * Load into cache cache_types_fees, array of types of fees
  903. *
  904. * @return int Nb of lines loaded, <0 if KO
  905. */
  906. public function load_cache_types_fees()
  907. {
  908. // phpcs:enable
  909. global $langs;
  910. $num = count($this->cache_types_fees);
  911. if ($num > 0) return 0; // Cache already loaded
  912. dol_syslog(__METHOD__, LOG_DEBUG);
  913. $langs->load("trips");
  914. $sql = "SELECT c.code, c.label";
  915. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  916. $sql .= " WHERE active > 0";
  917. $resql = $this->db->query($sql);
  918. if ($resql)
  919. {
  920. $num = $this->db->num_rows($resql);
  921. $i = 0;
  922. while ($i < $num)
  923. {
  924. $obj = $this->db->fetch_object($resql);
  925. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  926. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  927. $this->cache_types_fees[$obj->code] = $label;
  928. $i++;
  929. }
  930. asort($this->cache_types_fees);
  931. return $num;
  932. } else {
  933. dol_print_error($this->db);
  934. return -1;
  935. }
  936. }
  937. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  938. /**
  939. * Return list of types of notes
  940. *
  941. * @param string $selected Preselected type
  942. * @param string $htmlname Name of field in form
  943. * @param int $showempty Add an empty field
  944. * @return void
  945. */
  946. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  947. {
  948. // phpcs:enable
  949. global $user, $langs;
  950. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  951. $this->load_cache_types_fees();
  952. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  953. if ($showempty)
  954. {
  955. print '<option value="-1"';
  956. if ($selected == -1) print ' selected';
  957. print '>&nbsp;</option>';
  958. }
  959. foreach ($this->cache_types_fees as $key => $value)
  960. {
  961. print '<option value="'.$key.'"';
  962. if ($key == $selected) print ' selected';
  963. print '>';
  964. print $value;
  965. print '</option>';
  966. }
  967. print '</select>';
  968. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  969. }
  970. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  971. /**
  972. * Output html form to select a third party
  973. *
  974. * @param string $selected Preselected type
  975. * @param string $htmlname Name of field in form
  976. * @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)')
  977. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  978. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  979. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  980. * @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')))
  981. * @param int $limit Maximum number of elements
  982. * @param string $morecss Add more css styles to the SELECT component
  983. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  984. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  985. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  986. * @param array $ajaxoptions Options for ajax_autocompleter
  987. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  988. * @return string HTML string with select box for thirdparty.
  989. */
  990. 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)
  991. {
  992. // phpcs:enable
  993. global $conf, $user, $langs;
  994. $out = '';
  995. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo)
  996. {
  997. // No immediate load of all database
  998. $placeholder = '';
  999. if ($selected && empty($selected_input_value))
  1000. {
  1001. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1002. $societetmp = new Societe($this->db);
  1003. $societetmp->fetch($selected);
  1004. $selected_input_value = $societetmp->name;
  1005. unset($societetmp);
  1006. }
  1007. // mode 1
  1008. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&filter='.urlencode($filter).($showtype ? '&showtype='.urlencode($showtype) : '');
  1009. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1010. $out .= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
  1011. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  1012. elseif ($hidelabel > 1) {
  1013. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  1014. if ($hidelabel == 2) {
  1015. $out .= img_picto($langs->trans("Search"), 'search');
  1016. }
  1017. }
  1018. $out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1019. if ($hidelabel == 3) {
  1020. $out .= img_picto($langs->trans("Search"), 'search');
  1021. }
  1022. } else {
  1023. // Immediate load of all database
  1024. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
  1025. }
  1026. return $out;
  1027. }
  1028. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1029. /**
  1030. * Output html form to select a third party.
  1031. * 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.
  1032. *
  1033. * @param string $selected Preselected type
  1034. * @param string $htmlname Name of field in form
  1035. * @param string $filter Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
  1036. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1037. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1038. * @param int $forcecombo Force to use standard HTML select component without beautification
  1039. * @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')))
  1040. * @param string $filterkey Filter on key value
  1041. * @param int $outputmode 0=HTML select string, 1=Array
  1042. * @param int $limit Limit number of answers
  1043. * @param string $morecss Add more css styles to the SELECT component
  1044. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1045. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1046. * @return string HTML string with
  1047. */
  1048. 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)
  1049. {
  1050. // phpcs:enable
  1051. global $conf, $user, $langs;
  1052. $out = '';
  1053. $num = 0;
  1054. $outarray = array();
  1055. if ($selected === '') $selected = array();
  1056. elseif (!is_array($selected)) $selected = array($selected);
  1057. // Clean $filter that may contains sql conditions so sql code
  1058. if (function_exists('testSqlAndScriptInject')) {
  1059. if (testSqlAndScriptInject($filter, 3) > 0) {
  1060. $filter = '';
  1061. }
  1062. }
  1063. // We search companies
  1064. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1065. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1066. $sql .= ", s.address, s.zip, s.town";
  1067. $sql .= ", dictp.code as country_code";
  1068. }
  1069. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  1070. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1071. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid = s.fk_pays";
  1072. }
  1073. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1074. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1075. if (!empty($user->socid)) $sql .= " AND s.rowid = ".$user->socid;
  1076. if ($filter) $sql .= " AND (".$filter.")";
  1077. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
  1078. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql .= " AND s.status <> 0";
  1079. // Add criteria
  1080. if ($filterkey && $filterkey != '')
  1081. {
  1082. $sql .= " AND (";
  1083. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1084. // For natural search
  1085. $scrit = explode(' ', $filterkey);
  1086. $i = 0;
  1087. if (count($scrit) > 1) $sql .= "(";
  1088. foreach ($scrit as $crit) {
  1089. if ($i > 0) $sql .= " AND ";
  1090. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1091. $i++;
  1092. }
  1093. if (count($scrit) > 1) $sql .= ")";
  1094. if (!empty($conf->barcode->enabled))
  1095. {
  1096. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1097. }
  1098. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1099. $sql .= ")";
  1100. }
  1101. $sql .= $this->db->order("nom", "ASC");
  1102. $sql .= $this->db->plimit($limit, 0);
  1103. // Build output string
  1104. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1105. $resql = $this->db->query($sql);
  1106. if ($resql)
  1107. {
  1108. if (!$forcecombo)
  1109. {
  1110. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1111. $out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
  1112. }
  1113. // Construct $out and $outarray
  1114. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1115. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1116. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
  1117. {
  1118. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1119. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1120. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  1121. else $textifempty .= $langs->trans("All");
  1122. }
  1123. if ($showempty) $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.$textifempty.'</span>').'">'.$textifempty.'</option>'."\n";
  1124. $num = $this->db->num_rows($resql);
  1125. $i = 0;
  1126. if ($num)
  1127. {
  1128. while ($i < $num)
  1129. {
  1130. $obj = $this->db->fetch_object($resql);
  1131. $label = '';
  1132. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1133. if (($obj->client) && (!empty($obj->code_client))) {
  1134. $label = $obj->code_client.' - ';
  1135. }
  1136. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1137. $label .= $obj->code_fournisseur.' - ';
  1138. }
  1139. $label .= ' '.$obj->name;
  1140. } else {
  1141. $label = $obj->name;
  1142. }
  1143. if (!empty($obj->name_alias)) {
  1144. $label .= ' ('.$obj->name_alias.')';
  1145. }
  1146. if ($showtype)
  1147. {
  1148. if ($obj->client || $obj->fournisseur) $label .= ' (';
  1149. if ($obj->client == 1 || $obj->client == 3) $label .= $langs->trans("Customer");
  1150. if ($obj->client == 2 || $obj->client == 3) $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1151. if ($obj->fournisseur) $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1152. if ($obj->client || $obj->fournisseur) $label .= ')';
  1153. }
  1154. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1155. $label .= ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1156. if (!empty($obj->country_code)) {
  1157. $label .= ', '.$langs->trans('Country'.$obj->country_code);
  1158. }
  1159. }
  1160. if (empty($outputmode))
  1161. {
  1162. if (in_array($obj->rowid, $selected))
  1163. {
  1164. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1165. } else {
  1166. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1167. }
  1168. } else {
  1169. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1170. }
  1171. $i++;
  1172. if (($i % 10) == 0) $out .= "\n";
  1173. }
  1174. }
  1175. $out .= '</select>'."\n";
  1176. } else {
  1177. dol_print_error($this->db);
  1178. }
  1179. $this->result = array('nbofthirdparties'=>$num);
  1180. if ($outputmode) return $outarray;
  1181. return $out;
  1182. }
  1183. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1184. /**
  1185. * Return HTML combo list of absolute discounts
  1186. *
  1187. * @param string $selected Id remise fixe pre-selectionnee
  1188. * @param string $htmlname Nom champ formulaire
  1189. * @param string $filter Criteres optionnels de filtre
  1190. * @param int $socid Id of thirdparty
  1191. * @param int $maxvalue Max value for lines that can be selected
  1192. * @return int Return number of qualifed lines in list
  1193. */
  1194. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1195. {
  1196. // phpcs:enable
  1197. global $langs, $conf;
  1198. // On recherche les remises
  1199. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1200. $sql .= " re.description, re.fk_facture_source";
  1201. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  1202. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1203. $sql .= " AND re.entity = ".$conf->entity;
  1204. if ($filter) $sql .= " AND ".$filter;
  1205. $sql .= " ORDER BY re.description ASC";
  1206. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1207. $resql = $this->db->query($sql);
  1208. if ($resql)
  1209. {
  1210. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1211. $num = $this->db->num_rows($resql);
  1212. $qualifiedlines = $num;
  1213. $i = 0;
  1214. if ($num)
  1215. {
  1216. print '<option value="0">&nbsp;</option>';
  1217. while ($i < $num)
  1218. {
  1219. $obj = $this->db->fetch_object($resql);
  1220. $desc = dol_trunc($obj->description, 40);
  1221. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1222. if (preg_match('/\(DEPOSIT\)/', $desc)) $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1223. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1224. if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1225. $selectstring = '';
  1226. if ($selected > 0 && $selected == $obj->rowid) $selectstring = ' selected';
  1227. $disabled = '';
  1228. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
  1229. {
  1230. $qualifiedlines--;
  1231. $disabled = ' disabled';
  1232. }
  1233. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
  1234. {
  1235. $tmpfac = new Facture($this->db);
  1236. if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc = $desc.' - '.$tmpfac->ref;
  1237. }
  1238. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1239. $i++;
  1240. }
  1241. }
  1242. print '</select>';
  1243. return $qualifiedlines;
  1244. } else {
  1245. dol_print_error($this->db);
  1246. return -1;
  1247. }
  1248. }
  1249. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1250. /**
  1251. * Return list of all contacts (for a third party or all)
  1252. *
  1253. * @param int $socid Id ot third party or 0 for all
  1254. * @param string $selected Id contact pre-selectionne
  1255. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1256. * @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
  1257. * @param string $exclude List of contacts id to exclude
  1258. * @param string $limitto Disable answers that are not id in this array list
  1259. * @param integer $showfunction Add function into label
  1260. * @param string $moreclass Add more class to class style
  1261. * @param integer $showsoc Add company into label
  1262. * @param int $forcecombo Force to use combo box
  1263. * @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')))
  1264. * @param bool $options_only Return options only (for ajax treatment)
  1265. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1266. * @param string $htmlid Html id to use instead of htmlname
  1267. * @return int <0 if KO, Nb of contact in list if OK
  1268. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1269. */
  1270. 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 = '')
  1271. {
  1272. // phpcs:enable
  1273. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1274. return $this->num;
  1275. }
  1276. /**
  1277. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1278. * This also set the number of contacts found into $this->num
  1279. *
  1280. * @since 9.0 Add afterSelectContactOptions hook
  1281. *
  1282. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1283. * @param array|int $selected Array of ID of pre-selected contact id
  1284. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1285. * @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
  1286. * @param string $exclude List of contacts id to exclude
  1287. * @param string $limitto Disable answers that are not id in this array list
  1288. * @param integer $showfunction Add function into label
  1289. * @param string $moreclass Add more class to class style
  1290. * @param bool $options_only Return options only (for ajax treatment)
  1291. * @param integer $showsoc Add company into label
  1292. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1293. * @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')))
  1294. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1295. * @param string $htmlid Html id to use instead of htmlname
  1296. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1297. * @return int <0 if KO, Nb of contact in list if OK
  1298. */
  1299. 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)
  1300. {
  1301. global $conf, $langs, $hookmanager, $action;
  1302. $langs->load('companies');
  1303. if (empty($htmlid)) $htmlid = $htmlname;
  1304. $num = 0;
  1305. if ($selected === '') $selected = array();
  1306. elseif (!is_array($selected)) $selected = array($selected);
  1307. $out = '';
  1308. if (!is_object($hookmanager))
  1309. {
  1310. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1311. $hookmanager = new HookManager($this->db);
  1312. }
  1313. // We search third parties
  1314. $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";
  1315. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) $sql .= ", s.nom as company, s.town AS company_town";
  1316. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
  1317. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=sp.fk_soc";
  1318. $sql .= " WHERE sp.entity IN (".getEntity('socpeople').")";
  1319. if ($socid > 0 || $socid == -1) $sql .= " AND sp.fk_soc=".$socid;
  1320. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql .= " AND sp.statut <> 0";
  1321. $sql .= " ORDER BY sp.lastname ASC";
  1322. dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
  1323. $resql = $this->db->query($sql);
  1324. if ($resql)
  1325. {
  1326. $num = $this->db->num_rows($resql);
  1327. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only)
  1328. {
  1329. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1330. $out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
  1331. }
  1332. if ($htmlname != 'none' && !$options_only) $out .= '<select class="flat'.($moreclass ? ' '.$moreclass : '').'"'.($num?'':' disabled').' id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1333. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1334. if ($showempty == 2) $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1335. $i = 0;
  1336. if ($num)
  1337. {
  1338. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1339. $contactstatic = new Contact($this->db);
  1340. while ($i < $num)
  1341. {
  1342. $obj = $this->db->fetch_object($resql);
  1343. // Set email (or phones) and town extended infos
  1344. $extendedInfos = '';
  1345. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1346. $extendedInfos = array();
  1347. $email = trim($obj->email);
  1348. if (!empty($email)) $extendedInfos[] = $email;
  1349. else {
  1350. $phone = trim($obj->phone);
  1351. $phone_perso = trim($obj->phone_perso);
  1352. $phone_mobile = trim($obj->phone_mobile);
  1353. if (!empty($phone)) $extendedInfos[] = $phone;
  1354. if (!empty($phone_perso)) $extendedInfos[] = $phone_perso;
  1355. if (!empty($phone_mobile)) $extendedInfos[] = $phone_mobile;
  1356. }
  1357. $contact_town = trim($obj->contact_town);
  1358. $company_town = trim($obj->company_town);
  1359. if (!empty($contact_town)) $extendedInfos[] = $contact_town;
  1360. elseif (!empty($company_town)) $extendedInfos[] = $company_town;
  1361. $extendedInfos = implode(' - ', $extendedInfos);
  1362. if (!empty($extendedInfos)) $extendedInfos = ' - ' . $extendedInfos;
  1363. }
  1364. $contactstatic->id = $obj->rowid;
  1365. $contactstatic->lastname = $obj->lastname;
  1366. $contactstatic->firstname = $obj->firstname;
  1367. if ($obj->statut == 1) {
  1368. if ($htmlname != 'none')
  1369. {
  1370. $disabled = 0;
  1371. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) $disabled = 1;
  1372. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) $disabled = 1;
  1373. if (!empty($selected) && in_array($obj->rowid, $selected))
  1374. {
  1375. $out .= '<option value="'.$obj->rowid.'"';
  1376. if ($disabled) $out .= ' disabled';
  1377. $out .= ' selected>';
  1378. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1379. if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
  1380. if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
  1381. $out .= '</option>';
  1382. } else {
  1383. $out .= '<option value="'.$obj->rowid.'"';
  1384. if ($disabled) $out .= ' disabled';
  1385. $out .= '>';
  1386. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1387. if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
  1388. if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
  1389. $out .= '</option>';
  1390. }
  1391. } else {
  1392. if (in_array($obj->rowid, $selected))
  1393. {
  1394. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1395. if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
  1396. if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
  1397. }
  1398. }
  1399. }
  1400. $i++;
  1401. }
  1402. } else {
  1403. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1404. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1405. $out .= $labeltoshow;
  1406. $out .= '</option>';
  1407. }
  1408. $parameters = array(
  1409. 'socid'=>$socid,
  1410. 'htmlname'=>$htmlname,
  1411. 'resql'=>$resql,
  1412. 'out'=>&$out,
  1413. 'showfunction'=>$showfunction,
  1414. 'showsoc'=>$showsoc,
  1415. );
  1416. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1417. if ($htmlname != 'none' && !$options_only)
  1418. {
  1419. $out .= '</select>';
  1420. }
  1421. $this->num = $num;
  1422. return $out;
  1423. } else {
  1424. dol_print_error($this->db);
  1425. return -1;
  1426. }
  1427. }
  1428. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1429. /**
  1430. * Return the HTML select list of users
  1431. *
  1432. * @param string $selected Id user preselected
  1433. * @param string $htmlname Field name in form
  1434. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1435. * @param array $exclude Array list of users id to exclude
  1436. * @param int $disabled If select list must be disabled
  1437. * @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
  1438. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1439. * @param string $force_entity '0' or Ids of environment to force
  1440. * @return void
  1441. * @deprecated Use select_dolusers instead
  1442. * @see select_dolusers()
  1443. */
  1444. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1445. {
  1446. // phpcs:enable
  1447. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1448. }
  1449. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1450. /**
  1451. * Return select list of users
  1452. *
  1453. * @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)
  1454. * @param string $htmlname Field name in form
  1455. * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list
  1456. * @param array $exclude Array list of users id to exclude
  1457. * @param int $disabled If select list must be disabled
  1458. * @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
  1459. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1460. * @param string $force_entity '0' or Ids of environment to force
  1461. * @param int $maxlength Maximum length of string into list (0=no limit)
  1462. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1463. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1')
  1464. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1465. * @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.
  1466. * @param string $morecss More css
  1467. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1468. * @param int $outputmode 0=HTML select string, 1=Array
  1469. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1470. * @return string HTML select string
  1471. * @see select_dolgroups()
  1472. */
  1473. 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)
  1474. {
  1475. // phpcs:enable
  1476. global $conf, $user, $langs, $hookmanager;
  1477. // If no preselected user defined, we take current user
  1478. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected = $user->id;
  1479. if ($selected === '') $selected = array();
  1480. elseif (!is_array($selected)) $selected = array($selected);
  1481. $excludeUsers = null;
  1482. $includeUsers = null;
  1483. // Permettre l'exclusion d'utilisateurs
  1484. if (is_array($exclude)) $excludeUsers = implode(",", $exclude);
  1485. // Permettre l'inclusion d'utilisateurs
  1486. if (is_array($include)) $includeUsers = implode(",", $include);
  1487. elseif ($include == 'hierarchy')
  1488. {
  1489. // Build list includeUsers to have only hierarchy
  1490. $includeUsers = implode(",", $user->getAllChildIds(0));
  1491. } elseif ($include == 'hierarchyme')
  1492. {
  1493. // Build list includeUsers to have only hierarchy and current user
  1494. $includeUsers = implode(",", $user->getAllChildIds(1));
  1495. }
  1496. $out = '';
  1497. $outarray = array();
  1498. // Forge request to select users
  1499. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1500. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  1501. {
  1502. $sql .= ", e.label";
  1503. }
  1504. $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
  1505. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  1506. {
  1507. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=u.entity";
  1508. if ($force_entity) $sql .= " WHERE u.entity IN (0,".$force_entity.")";
  1509. else $sql .= " WHERE u.entity IS NOT NULL";
  1510. } else {
  1511. if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
  1512. {
  1513. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
  1514. $sql .= " ON ug.fk_user = u.rowid";
  1515. $sql .= " WHERE ug.entity = ".$conf->entity;
  1516. } else {
  1517. $sql .= " WHERE u.entity IN (0,".$conf->entity.")";
  1518. }
  1519. }
  1520. if (!empty($user->socid)) $sql .= " AND u.fk_soc = ".$user->socid;
  1521. if (is_array($exclude) && $excludeUsers) $sql .= " AND u.rowid NOT IN (".$excludeUsers.")";
  1522. if ($includeUsers) $sql .= " AND u.rowid IN (".$includeUsers.")";
  1523. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql .= " AND u.statut <> 0";
  1524. if (!empty($morefilter)) $sql .= " ".$morefilter;
  1525. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1526. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1527. if (!empty($reshook)) $sql .= $hookmanager->resPrint;
  1528. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1529. {
  1530. $sql .= " ORDER BY u.firstname ASC";
  1531. } else {
  1532. $sql .= " ORDER BY u.lastname ASC";
  1533. }
  1534. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1535. $resql = $this->db->query($sql);
  1536. if ($resql)
  1537. {
  1538. $num = $this->db->num_rows($resql);
  1539. $i = 0;
  1540. if ($num)
  1541. {
  1542. // Enhance with select2
  1543. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1544. $out .= ajax_combobox($htmlname);
  1545. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1546. $out .= '<select class="flat'.($morecss ? ' minwidth100imp '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1547. if ($show_empty && !$multiple) $out .= '<option value="-1"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>&nbsp;</option>'."\n";
  1548. if ($show_every) $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1549. $userstatic = new User($this->db);
  1550. while ($i < $num)
  1551. {
  1552. $obj = $this->db->fetch_object($resql);
  1553. $userstatic->id = $obj->rowid;
  1554. $userstatic->lastname = $obj->lastname;
  1555. $userstatic->firstname = $obj->firstname;
  1556. $userstatic->photo = $obj->photo;
  1557. $userstatic->statut = $obj->status;
  1558. $userstatic->entity = $obj->entity;
  1559. $userstatic->admin = $obj->admin;
  1560. $disableline = '';
  1561. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) $disableline = ($enableonlytext ? $enableonlytext : '1');
  1562. $labeltoshow = '';
  1563. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1564. $fullNameMode = 0;
  1565. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))
  1566. {
  1567. $fullNameMode = 1; //Firstname+lastname
  1568. }
  1569. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1570. if (empty($obj->firstname) && empty($obj->lastname)) $labeltoshow .= $obj->login;
  1571. // Complete name with more info
  1572. $moreinfo = '';
  1573. if (!empty($conf->global->MAIN_SHOW_LOGIN))
  1574. {
  1575. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1576. }
  1577. if ($showstatus >= 0)
  1578. {
  1579. if ($obj->status == 1 && $showstatus == 1)
  1580. {
  1581. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1582. }
  1583. if ($obj->status == 0 && $showstatus == 1)
  1584. {
  1585. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1586. }
  1587. }
  1588. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity)
  1589. {
  1590. if (!$obj->entity)
  1591. {
  1592. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1593. } else {
  1594. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1595. }
  1596. }
  1597. $moreinfo .= ($moreinfo ? ')' : '');
  1598. if ($disableline && $disableline != '1')
  1599. {
  1600. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1601. }
  1602. $labeltoshow .= $moreinfo;
  1603. $out .= '<option value="'.$obj->rowid.'"';
  1604. if ($disableline) $out .= ' disabled';
  1605. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1606. $out .= ' selected';
  1607. }
  1608. $out .= ' data-html="';
  1609. $outhtml = '';
  1610. if (!empty($obj->photo))
  1611. {
  1612. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1613. }
  1614. if ($showstatus >= 0 && $obj->status == 0) $outhtml .= '<strike class="opacitymediumxxx">';
  1615. $outhtml .= $labeltoshow;
  1616. if ($showstatus >= 0 && $obj->status == 0) $outhtml .= '</strike>';
  1617. $out .= dol_escape_htmltag($outhtml);
  1618. $out .= '">';
  1619. $out .= $labeltoshow;
  1620. $out .= '</option>';
  1621. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1622. $i++;
  1623. }
  1624. } else {
  1625. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1626. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1627. }
  1628. $out .= '</select>';
  1629. } else {
  1630. dol_print_error($this->db);
  1631. }
  1632. if ($outputmode) return $outarray;
  1633. return $out;
  1634. }
  1635. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1636. /**
  1637. * Return select list of users. Selected users are stored into session.
  1638. * List of users are provided into $_SESSION['assignedtouser'].
  1639. *
  1640. * @param string $action Value for $action
  1641. * @param string $htmlname Field name in form
  1642. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1643. * @param array $exclude Array list of users id to exclude
  1644. * @param int $disabled If select list must be disabled
  1645. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1646. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1647. * @param int $force_entity '0' or Ids of environment to force
  1648. * @param int $maxlength Maximum length of string into list (0=no limit)
  1649. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1650. * @param string $morefilter Add more filters into sql request
  1651. * @param int $showproperties Show properties of each attendees
  1652. * @param array $listofuserid Array with properties of each user
  1653. * @param array $listofcontactid Array with properties of each contact
  1654. * @param array $listofotherid Array with properties of each other contact
  1655. * @return string HTML select string
  1656. * @see select_dolgroups()
  1657. */
  1658. 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())
  1659. {
  1660. // phpcs:enable
  1661. global $conf, $user, $langs;
  1662. $userstatic = new User($this->db);
  1663. $out = '';
  1664. $assignedtouser = array();
  1665. if (!empty($_SESSION['assignedtouser']))
  1666. {
  1667. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1668. }
  1669. $nbassignetouser = count($assignedtouser);
  1670. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1671. if ($nbassignetouser) $out .= '<ul class="attendees">';
  1672. $i = 0; $ownerid = 0;
  1673. foreach ($assignedtouser as $key => $value)
  1674. {
  1675. if ($value['id'] == $ownerid) continue;
  1676. $out .= '<li>';
  1677. $userstatic->fetch($value['id']);
  1678. $out .= $userstatic->getNomUrl(-1);
  1679. if ($i == 0) { $ownerid = $value['id']; $out .= ' ('.$langs->trans("Owner").')'; }
  1680. if ($nbassignetouser > 1 && $action != 'view')
  1681. {
  1682. $out .= ' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
  1683. }
  1684. // Show my availability
  1685. if ($showproperties)
  1686. {
  1687. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))
  1688. {
  1689. $out .= '<div class="myavailability inline-block">';
  1690. $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>';
  1691. $out .= '</div>';
  1692. }
  1693. }
  1694. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1695. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1696. $out .= '</li>';
  1697. $i++;
  1698. }
  1699. if ($nbassignetouser) $out .= '</ul>';
  1700. // Method with no ajax
  1701. if ($action != 'view')
  1702. {
  1703. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1704. $out .= '<script type="text/javascript" language="javascript">jQuery(document).ready(function () {';
  1705. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  1706. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  1707. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  1708. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  1709. $out .= '});';
  1710. $out .= '})</script>';
  1711. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1712. $out .= ' <input type="submit" disabled class="button valignmiddle" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1713. $out .= '<br>';
  1714. }
  1715. return $out;
  1716. }
  1717. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1718. /**
  1719. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1720. *
  1721. * @param int $selected Preselected products
  1722. * @param string $htmlname Name of HTML select field (must be unique in page)
  1723. * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1724. * @param int $limit Limit on number of returned lines
  1725. * @param int $price_level Level of price to show
  1726. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1727. * @param int $finished 2=all, 1=finished, 0=raw material
  1728. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1729. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1730. * @param array $ajaxoptions Options for ajax_autocompleter
  1731. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1732. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1733. * @param int $forcecombo Force to use combo box
  1734. * @param string $morecss Add more css on select
  1735. * @param int $hidepriceinlabel 1=Hide prices in label
  1736. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  1737. * 'warehouseopen' = count products from open warehouses,
  1738. * 'warehouseclosed' = count products from closed warehouses,
  1739. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  1740. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  1741. * @param string $nooutput No print, return the output into a string
  1742. * @return void|string
  1743. */
  1744. public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $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 = array(), $nooutput = 0)
  1745. {
  1746. // phpcs:enable
  1747. global $langs, $conf;
  1748. $out = '';
  1749. // check parameters
  1750. $price_level = (!empty($price_level) ? $price_level : 0);
  1751. if (is_null($ajaxoptions)) $ajaxoptions = array();
  1752. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  1753. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  1754. $filtertype = '0';
  1755. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  1756. $filtertype = '1';
  1757. }
  1758. }
  1759. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1760. {
  1761. $placeholder = '';
  1762. if ($selected && empty($selected_input_value))
  1763. {
  1764. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1765. $producttmpselect = new Product($this->db);
  1766. $producttmpselect->fetch($selected);
  1767. $selected_input_value = $producttmpselect->ref;
  1768. unset($producttmpselect);
  1769. }
  1770. // handle case where product or service module is disabled + no filter specified
  1771. if ($filtertype == '')
  1772. {
  1773. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  1774. $filtertype = 1;
  1775. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  1776. $filtertype = 0;
  1777. }
  1778. }
  1779. // mode=1 means customers products
  1780. $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  1781. //Price by customer
  1782. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1783. $urloption .= '&socid='.$socid;
  1784. }
  1785. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1786. if (!empty($conf->variants->enabled)) {
  1787. $out .= '
  1788. <script>
  1789. selected = '.json_encode($selected_combinations).';
  1790. combvalues = {};
  1791. jQuery(document).ready(function () {
  1792. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  1793. if (jQuery(this).val() == \'free\') {
  1794. jQuery(\'div#attributes_box\').empty();
  1795. }
  1796. });
  1797. jQuery("input#'.$htmlname.'").change(function () {
  1798. if (!jQuery(this).val()) {
  1799. jQuery(\'div#attributes_box\').empty();
  1800. return;
  1801. }
  1802. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  1803. id: jQuery(this).val()
  1804. }, function (data) {
  1805. jQuery(\'div#attributes_box\').empty();
  1806. jQuery.each(data, function (key, val) {
  1807. combvalues[val.id] = val.values;
  1808. var span = jQuery(document.createElement(\'div\')).css({
  1809. \'display\': \'table-row\'
  1810. });
  1811. span.append(
  1812. jQuery(document.createElement(\'div\')).text(val.label).css({
  1813. \'font-weight\': \'bold\',
  1814. \'display\': \'table-cell\',
  1815. \'text-align\': \'right\'
  1816. })
  1817. );
  1818. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  1819. \'margin-left\': \'15px\',
  1820. \'white-space\': \'pre\'
  1821. }).append(
  1822. jQuery(document.createElement(\'option\')).val(\'\')
  1823. );
  1824. jQuery.each(combvalues[val.id], function (key, val) {
  1825. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  1826. if (selected[val.fk_product_attribute] == val.id) {
  1827. tag.attr(\'selected\', \'selected\');
  1828. }
  1829. html.append(tag);
  1830. });
  1831. span.append(html);
  1832. jQuery(\'div#attributes_box\').append(span);
  1833. });
  1834. })
  1835. });
  1836. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  1837. });
  1838. </script>
  1839. ';
  1840. }
  1841. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  1842. elseif ($hidelabel > 1) {
  1843. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  1844. if ($hidelabel == 2) {
  1845. $out .= img_picto($langs->trans("Search"), 'search');
  1846. }
  1847. }
  1848. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1849. if ($hidelabel == 3) {
  1850. $out .= img_picto($langs->trans("Search"), 'search');
  1851. }
  1852. } else {
  1853. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus);
  1854. }
  1855. if (empty($nooutput)) print $out;
  1856. else return $out;
  1857. }
  1858. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1859. /**
  1860. * Return list of products for a customer.
  1861. * Called by select_produits.
  1862. *
  1863. * @param int $selected Preselected product
  1864. * @param string $htmlname Name of select html
  1865. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1866. * @param int $limit Limit on number of returned lines
  1867. * @param int $price_level Level of price to show
  1868. * @param string $filterkey Filter on product
  1869. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1870. * @param int $finished Filter on finished field: 2=No filter
  1871. * @param int $outputmode 0=HTML select string, 1=Array
  1872. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1873. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1874. * @param int $forcecombo Force to use combo box
  1875. * @param string $morecss Add more css on select
  1876. * @param int $hidepriceinlabel 1=Hide prices in label
  1877. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  1878. * 'warehouseopen' = count products from open warehouses,
  1879. * 'warehouseclosed' = count products from closed warehouses,
  1880. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  1881. * @return array Array of keys for json
  1882. */
  1883. 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 = '')
  1884. {
  1885. // phpcs:enable
  1886. global $langs, $conf, $user, $db;
  1887. $out = '';
  1888. $outarray = array();
  1889. // Units
  1890. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1891. $langs->load('other');
  1892. }
  1893. $warehouseStatusArray = array();
  1894. if (!empty($warehouseStatus))
  1895. {
  1896. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  1897. if (preg_match('/warehouseclosed/', $warehouseStatus))
  1898. {
  1899. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  1900. }
  1901. if (preg_match('/warehouseopen/', $warehouseStatus))
  1902. {
  1903. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  1904. }
  1905. if (preg_match('/warehouseinternal/', $warehouseStatus))
  1906. {
  1907. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  1908. }
  1909. }
  1910. $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.duration, p.fk_price_expression";
  1911. if (count($warehouseStatusArray))
  1912. {
  1913. $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
  1914. } else {
  1915. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  1916. }
  1917. $sql = "SELECT ";
  1918. $sql .= $selectFields.$selectFieldsGrouped;
  1919. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
  1920. {
  1921. //Product category
  1922. $sql .= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
  1923. FROM ".MAIN_DB_PREFIX."categorie_product
  1924. WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
  1925. LIMIT 1
  1926. ) AS categorie_product_id ";
  1927. }
  1928. //Price by customer
  1929. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
  1930. {
  1931. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  1932. $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
  1933. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
  1934. }
  1935. // Units
  1936. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1937. $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";
  1938. $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';
  1939. }
  1940. // Multilang : we add translation
  1941. if (!empty($conf->global->MAIN_MULTILANGS))
  1942. {
  1943. $sql .= ", pl.label as label_translated";
  1944. $selectFields .= ", label_translated";
  1945. }
  1946. // Price by quantity
  1947. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
  1948. {
  1949. $sql .= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1950. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level;
  1951. $sql .= " ORDER BY date_price";
  1952. $sql .= " DESC LIMIT 1) as price_rowid";
  1953. $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
  1954. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level;
  1955. $sql .= " ORDER BY date_price";
  1956. $sql .= " DESC LIMIT 1) as price_by_qty";
  1957. $selectFields .= ", price_rowid, price_by_qty";
  1958. }
  1959. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  1960. if (count($warehouseStatusArray))
  1961. {
  1962. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
  1963. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  1964. $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.
  1965. }
  1966. // include search in supplier ref
  1967. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
  1968. {
  1969. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  1970. }
  1971. //Price by customer
  1972. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1973. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
  1974. }
  1975. // Units
  1976. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1977. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  1978. }
  1979. // Multilang : we add translation
  1980. if (!empty($conf->global->MAIN_MULTILANGS))
  1981. {
  1982. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='".$this->db->escape($langs->getDefaultLang())."'";
  1983. }
  1984. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1985. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  1986. }
  1987. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  1988. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1989. $sql .= " AND pac.rowid IS NULL";
  1990. }
  1991. if ($finished == 0)
  1992. {
  1993. $sql .= " AND p.finished = ".$finished;
  1994. } elseif ($finished == 1)
  1995. {
  1996. $sql .= " AND p.finished = ".$finished;
  1997. if ($status >= 0) $sql .= " AND p.tosell = ".$status;
  1998. } elseif ($status >= 0)
  1999. {
  2000. $sql .= " AND p.tosell = ".$status;
  2001. }
  2002. // Filter by product type
  2003. if (strval($filtertype) != '') $sql .= " AND p.fk_product_type = ".$filtertype;
  2004. elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2005. $sql .= " AND p.fk_product_type = 1";
  2006. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2007. $sql .= " AND p.fk_product_type = 0";
  2008. }
  2009. // Add criteria on ref/label
  2010. if ($filterkey != '')
  2011. {
  2012. $sql .= ' AND (';
  2013. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2014. // For natural search
  2015. $scrit = explode(' ', $filterkey);
  2016. $i = 0;
  2017. if (count($scrit) > 1) $sql .= "(";
  2018. foreach ($scrit as $crit)
  2019. {
  2020. if ($i > 0) $sql .= " AND ";
  2021. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2022. if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2023. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION))
  2024. {
  2025. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2026. if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2027. }
  2028. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2029. $sql .= ")";
  2030. $i++;
  2031. }
  2032. if (count($scrit) > 1) $sql .= ")";
  2033. if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2034. $sql .= ')';
  2035. }
  2036. if (count($warehouseStatusArray))
  2037. {
  2038. $sql .= ' GROUP BY'.$selectFields;
  2039. }
  2040. //Sort by category
  2041. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
  2042. {
  2043. $sql .= " ORDER BY categorie_product_id ";
  2044. //ASC OR DESC order
  2045. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2046. } else {
  2047. $sql .= $this->db->order("p.ref");
  2048. }
  2049. $sql .= $this->db->plimit($limit, 0);
  2050. // Build output string
  2051. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2052. $result = $this->db->query($sql);
  2053. if ($result)
  2054. {
  2055. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2056. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2057. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2058. $num = $this->db->num_rows($result);
  2059. $events = null;
  2060. if (!$forcecombo)
  2061. {
  2062. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2063. $out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
  2064. }
  2065. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2066. $textifempty = '';
  2067. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2068. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2069. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  2070. {
  2071. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  2072. else $textifempty .= $langs->trans("All");
  2073. } else {
  2074. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  2075. }
  2076. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  2077. $i = 0;
  2078. while ($num && $i < $num)
  2079. {
  2080. $opt = '';
  2081. $optJson = array();
  2082. $objp = $this->db->fetch_object($result);
  2083. 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)
  2084. { // Price by quantity will return many prices for the same product
  2085. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2086. $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
  2087. $sql .= " WHERE fk_product_price=".$objp->price_rowid;
  2088. $sql .= " ORDER BY quantity ASC";
  2089. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2090. $result2 = $this->db->query($sql);
  2091. if ($result2)
  2092. {
  2093. $nb_prices = $this->db->num_rows($result2);
  2094. $j = 0;
  2095. while ($nb_prices && $j < $nb_prices) {
  2096. $objp2 = $this->db->fetch_object($result2);
  2097. $objp->price_by_qty_rowid = $objp2->rowid;
  2098. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2099. $objp->price_by_qty_quantity = $objp2->quantity;
  2100. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2101. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2102. // For backward compatibility
  2103. $objp->quantity = $objp2->quantity;
  2104. $objp->price = $objp2->price;
  2105. $objp->unitprice = $objp2->unitprice;
  2106. $objp->remise_percent = $objp2->remise_percent;
  2107. $objp->remise = $objp2->remise;
  2108. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2109. $j++;
  2110. // Add new entry
  2111. // "key" value of json key array is used by jQuery automatically as selected value
  2112. // "label" value of json key array is used by jQuery automatically as text for combo box
  2113. $out .= $opt;
  2114. array_push($outarray, $optJson);
  2115. }
  2116. }
  2117. } else {
  2118. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2119. $price_product = new Product($this->db);
  2120. $price_product->fetch($objp->rowid, '', '', 1);
  2121. $priceparser = new PriceParser($this->db);
  2122. $price_result = $priceparser->parseProduct($price_product);
  2123. if ($price_result >= 0) {
  2124. $objp->price = $price_result;
  2125. $objp->unitprice = $price_result;
  2126. //Calculate the VAT
  2127. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2128. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2129. }
  2130. }
  2131. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2132. // Add new entry
  2133. // "key" value of json key array is used by jQuery automatically as selected value
  2134. // "label" value of json key array is used by jQuery automatically as text for combo box
  2135. $out .= $opt;
  2136. array_push($outarray, $optJson);
  2137. }
  2138. $i++;
  2139. }
  2140. $out .= '</select>';
  2141. $this->db->free($result);
  2142. if (empty($outputmode)) return $out;
  2143. return $outarray;
  2144. } else {
  2145. dol_print_error($db);
  2146. }
  2147. }
  2148. /**
  2149. * constructProductListOption.
  2150. * This define value for &$opt and &$optJson.
  2151. *
  2152. * @param resource $objp Resultset of fetch
  2153. * @param string $opt Option (var used for returned value in string option format)
  2154. * @param string $optJson Option (var used for returned value in json format)
  2155. * @param int $price_level Price level
  2156. * @param string $selected Preselected value
  2157. * @param int $hidepriceinlabel Hide price in label
  2158. * @param string $filterkey Filter key to highlight
  2159. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2160. * @return void
  2161. */
  2162. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2163. {
  2164. global $langs, $conf, $user, $db;
  2165. $outkey = '';
  2166. $outval = '';
  2167. $outref = '';
  2168. $outlabel = '';
  2169. $outdesc = '';
  2170. $outbarcode = '';
  2171. $outorigin = '';
  2172. $outtype = '';
  2173. $outprice_ht = '';
  2174. $outprice_ttc = '';
  2175. $outpricebasetype = '';
  2176. $outtva_tx = '';
  2177. $outqty = 1;
  2178. $outdiscount = 0;
  2179. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2180. $label = $objp->label;
  2181. if (!empty($objp->label_translated)) $label = $objp->label_translated;
  2182. if (!empty($filterkey) && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2183. $outkey = $objp->rowid;
  2184. $outref = $objp->ref;
  2185. $outlabel = $objp->label;
  2186. $outdesc = $objp->description;
  2187. $outbarcode = $objp->barcode;
  2188. $outorigin = $objp->fk_country;
  2189. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2190. $outtype = $objp->fk_product_type;
  2191. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2192. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2193. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2194. // Units
  2195. $outvalUnits = '';
  2196. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2197. if (!empty($objp->unit_short)) {
  2198. $outvalUnits .= ' - '.$objp->unit_short;
  2199. }
  2200. }
  2201. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2202. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2203. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2204. $outvalUnits .= ' - '.$unitToShow;
  2205. }
  2206. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2207. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2208. $outvalUnits .= ' - '.$unitToShow;
  2209. }
  2210. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2211. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2212. $outvalUnits .= ' - '.$unitToShow;
  2213. }
  2214. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2215. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2216. $outvalUnits .= ' - '.$unitToShow;
  2217. }
  2218. }
  2219. if ($outdurationvalue && $outdurationunit) {
  2220. $da = array(
  2221. 'h' => $langs->trans('Hour'),
  2222. 'd' => $langs->trans('Day'),
  2223. 'w' => $langs->trans('Week'),
  2224. 'm' => $langs->trans('Month'),
  2225. 'y' => $langs->trans('Year')
  2226. );
  2227. if (isset($da[$outdurationunit])) {
  2228. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2229. }
  2230. }
  2231. $opt = '<option value="'.$objp->rowid.'"';
  2232. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2233. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)
  2234. {
  2235. $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.'"';
  2236. }
  2237. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)))
  2238. {
  2239. if (!empty($user->rights->stock->lire)) {
  2240. if ($objp->stock > 0) $opt .= ' class="product_line_stock_ok"';
  2241. elseif ($objp->stock <= 0) $opt .= ' class="product_line_stock_too_low"';
  2242. }
  2243. }
  2244. $opt .= '>';
  2245. $opt .= $objp->ref;
  2246. if ($outbarcode) $opt .= ' ('.$outbarcode.')';
  2247. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2248. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) $opt .= ' ('.getCountry($outorigin, 1).')';
  2249. $objRef = $objp->ref;
  2250. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2251. $outval .= $objRef;
  2252. if ($outbarcode) $outval .= ' ('.$outbarcode.')';
  2253. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2254. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) $outval .= ' ('.getCountry($outorigin, 1).')';
  2255. // Units
  2256. $opt .= $outvalUnits;
  2257. $outval .= $outvalUnits;
  2258. $found = 0;
  2259. // Multiprice
  2260. // If we need a particular price level (from 1 to 6)
  2261. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
  2262. {
  2263. $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
  2264. $sql .= " FROM ".MAIN_DB_PREFIX."product_price";
  2265. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2266. $sql .= " AND entity IN (".getEntity('productprice').")";
  2267. $sql .= " AND price_level = ".((int) $price_level);
  2268. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2269. $sql .= " LIMIT 1";
  2270. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2271. $result2 = $this->db->query($sql);
  2272. if ($result2)
  2273. {
  2274. $objp2 = $this->db->fetch_object($result2);
  2275. if ($objp2)
  2276. {
  2277. $found = 1;
  2278. if ($objp2->price_base_type == 'HT')
  2279. {
  2280. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2281. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2282. } else {
  2283. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2284. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2285. }
  2286. $outprice_ht = price($objp2->price);
  2287. $outprice_ttc = price($objp2->price_ttc);
  2288. $outpricebasetype = $objp2->price_base_type;
  2289. $outtva_tx = $objp2->tva_tx;
  2290. }
  2291. } else {
  2292. dol_print_error($this->db);
  2293. }
  2294. }
  2295. // Price by quantity
  2296. 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)))
  2297. {
  2298. $found = 1;
  2299. $outqty = $objp->quantity;
  2300. $outdiscount = $objp->remise_percent;
  2301. if ($objp->quantity == 1)
  2302. {
  2303. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2304. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2305. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2306. $outval .= $langs->transnoentities("Unit");
  2307. } else {
  2308. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2309. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2310. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2311. $outval .= $langs->transnoentities("Units");
  2312. }
  2313. $outprice_ht = price($objp->unitprice);
  2314. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2315. $outpricebasetype = $objp->price_base_type;
  2316. $outtva_tx = $objp->tva_tx;
  2317. }
  2318. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
  2319. {
  2320. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2321. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2322. }
  2323. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
  2324. {
  2325. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2326. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2327. }
  2328. // Price by customer
  2329. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  2330. {
  2331. if (!empty($objp->idprodcustprice))
  2332. {
  2333. $found = 1;
  2334. if ($objp->custprice_base_type == 'HT')
  2335. {
  2336. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2337. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2338. } else {
  2339. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2340. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2341. }
  2342. $outprice_ht = price($objp->custprice);
  2343. $outprice_ttc = price($objp->custprice_ttc);
  2344. $outpricebasetype = $objp->custprice_base_type;
  2345. $outtva_tx = $objp->custtva_tx;
  2346. }
  2347. }
  2348. // If level no defined or multiprice not found, we used the default price
  2349. if (empty($hidepriceinlabel) && !$found)
  2350. {
  2351. if ($objp->price_base_type == 'HT')
  2352. {
  2353. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2354. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2355. } else {
  2356. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2357. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2358. }
  2359. $outprice_ht = price($objp->price);
  2360. $outprice_ttc = price($objp->price_ttc);
  2361. $outpricebasetype = $objp->price_base_type;
  2362. $outtva_tx = $objp->tva_tx;
  2363. }
  2364. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)))
  2365. {
  2366. if (!empty($user->rights->stock->lire)) {
  2367. $opt .= ' - '.$langs->trans("Stock").':'.$objp->stock;
  2368. if ($objp->stock > 0) {
  2369. $outval .= ' - <span class="product_line_stock_ok">';
  2370. } elseif ($objp->stock <= 0) {
  2371. $outval .= ' - <span class="product_line_stock_too_low">';
  2372. }
  2373. $outval .= $langs->transnoentities("Stock").':'.$objp->stock;
  2374. $outval .= '</span>';
  2375. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) // Warning, this option may slow down combo list generation
  2376. {
  2377. $langs->load("stocks");
  2378. $tmpproduct = new Product($this->db);
  2379. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2380. $tmpproduct->load_virtual_stock();
  2381. $virtualstock = $tmpproduct->stock_theorique;
  2382. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2383. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2384. if ($virtualstock > 0) {
  2385. $outval .= '<span class="product_line_stock_ok">';
  2386. } elseif ($virtualstock <= 0) {
  2387. $outval .= '<span class="product_line_stock_too_low">';
  2388. }
  2389. $outval .= $virtualstock;
  2390. $outval .= '</span>';
  2391. unset($tmpproduct);
  2392. }
  2393. }
  2394. }
  2395. $opt .= "</option>\n";
  2396. $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>price2num($outprice_ht), 'price_ttc'=>price2num($outprice_ttc), 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'pbq'=>$outpbq);
  2397. }
  2398. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2399. /**
  2400. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2401. *
  2402. * @param int $socid Id third party
  2403. * @param string $selected Preselected product
  2404. * @param string $htmlname Name of HTML Select
  2405. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2406. * @param string $filtre For a SQL filter
  2407. * @param array $ajaxoptions Options for ajax_autocompleter
  2408. * @param int $hidelabel Hide label (0=no, 1=yes)
  2409. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2410. * @param string $morecss More CSS
  2411. * @return void
  2412. */
  2413. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '')
  2414. {
  2415. // phpcs:enable
  2416. global $langs, $conf;
  2417. global $price_level, $status, $finished;
  2418. $selected_input_value = '';
  2419. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  2420. {
  2421. if ($selected > 0)
  2422. {
  2423. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2424. $producttmpselect = new Product($this->db);
  2425. $producttmpselect->fetch($selected);
  2426. $selected_input_value = $producttmpselect->ref;
  2427. unset($producttmpselect);
  2428. }
  2429. // mode=2 means suppliers products
  2430. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2431. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2432. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
  2433. } else {
  2434. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', -1, 0, 0, $alsoproductwithnosupplierprice, $morecss);
  2435. }
  2436. }
  2437. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2438. /**
  2439. * Return list of suppliers products
  2440. *
  2441. * @param int $socid Id societe fournisseur (0 pour aucun filtre)
  2442. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2443. * @param string $htmlname Nom de la zone select
  2444. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2445. * @param string $filtre Pour filtre sql
  2446. * @param string $filterkey Filtre des produits
  2447. * @param int $statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)
  2448. * @param int $outputmode 0=HTML select string, 1=Array
  2449. * @param int $limit Limit of line number
  2450. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2451. * @param string $morecss Add more CSS
  2452. * @param int $showstockinlist Show stock information (slower).
  2453. * @return array Array of keys for json
  2454. */
  2455. public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '', $showstockinlist = 0)
  2456. {
  2457. // phpcs:enable
  2458. global $langs, $conf, $db, $user;
  2459. $out = '';
  2460. $outarray = array();
  2461. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2462. $langs->load('stocks');
  2463. // Units
  2464. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2465. $langs->load('other');
  2466. }
  2467. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock,";
  2468. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2469. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
  2470. $sql .= " pfp.supplier_reputation";
  2471. // Units
  2472. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2473. $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";
  2474. }
  2475. if (!empty($conf->barcode->enabled)) $sql .= ", pfp.barcode";
  2476. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2477. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2478. if ($socid) $sql .= " AND pfp.fk_soc = ".$socid;
  2479. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2480. // Units
  2481. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2482. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  2483. }
  2484. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2485. $sql .= " AND p.tobuy = 1";
  2486. if (strval($filtertype) != '') $sql .= " AND p.fk_product_type=".$this->db->escape($filtertype);
  2487. if (!empty($filtre)) $sql .= " ".$filtre;
  2488. // Add criteria on ref/label
  2489. if ($filterkey != '')
  2490. {
  2491. $sql .= ' AND (';
  2492. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2493. // For natural search
  2494. $scrit = explode(' ', $filterkey);
  2495. $i = 0;
  2496. if (count($scrit) > 1) $sql .= "(";
  2497. foreach ($scrit as $crit)
  2498. {
  2499. if ($i > 0) $sql .= " AND ";
  2500. $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)."%')";
  2501. $i++;
  2502. }
  2503. if (count($scrit) > 1) $sql .= ")";
  2504. if (!empty($conf->barcode->enabled)) {
  2505. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2506. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2507. }
  2508. $sql .= ')';
  2509. }
  2510. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2511. $sql .= $this->db->plimit($limit, 0);
  2512. // Build output string
  2513. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2514. $result = $this->db->query($sql);
  2515. if ($result)
  2516. {
  2517. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2518. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2519. $num = $this->db->num_rows($result);
  2520. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2521. $out .= '<select class="flat maxwidthonsmartphone'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2522. if (!$selected) $out .= '<option value="0" selected>&nbsp;</option>';
  2523. else $out .= '<option value="0">&nbsp;</option>';
  2524. $i = 0;
  2525. while ($i < $num)
  2526. {
  2527. $objp = $this->db->fetch_object($result);
  2528. $outkey = $objp->idprodfournprice; // id in table of price
  2529. if (!$outkey && $alsoproductwithnosupplierprice) $outkey = 'idprod_'.$objp->rowid; // id of product
  2530. $outref = $objp->ref;
  2531. $outval = '';
  2532. $outbarcode = $objp->barcode;
  2533. $outqty = 1;
  2534. $outdiscount = 0;
  2535. $outtype = $objp->fk_product_type;
  2536. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2537. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2538. // Units
  2539. $outvalUnits = '';
  2540. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2541. if (!empty($objp->unit_short)) {
  2542. $outvalUnits .= ' - '.$objp->unit_short;
  2543. }
  2544. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2545. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2546. $outvalUnits .= ' - '.$unitToShow;
  2547. }
  2548. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2549. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2550. $outvalUnits .= ' - '.$unitToShow;
  2551. }
  2552. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2553. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2554. $outvalUnits .= ' - '.$unitToShow;
  2555. }
  2556. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2557. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2558. $outvalUnits .= ' - '.$unitToShow;
  2559. }
  2560. if ($outdurationvalue && $outdurationunit) {
  2561. $da = array(
  2562. 'h' => $langs->trans('Hour'),
  2563. 'd' => $langs->trans('Day'),
  2564. 'w' => $langs->trans('Week'),
  2565. 'm' => $langs->trans('Month'),
  2566. 'y' => $langs->trans('Year')
  2567. );
  2568. if (isset($da[$outdurationunit])) {
  2569. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2570. }
  2571. }
  2572. }
  2573. $objRef = $objp->ref;
  2574. if ($filterkey && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2575. $objRefFourn = $objp->ref_fourn;
  2576. if ($filterkey && $filterkey != '') $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  2577. $label = $objp->label;
  2578. if ($filterkey && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2579. $optlabel = $objp->ref;
  2580. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2581. $optlabel .= ' <span class=\'opacitymedium\'>('.$objp->ref_fourn.')</span>';
  2582. }
  2583. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2584. $optlabel .= ' ('.$outbarcode.')';
  2585. }
  2586. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2587. $outvallabel = $objRef;
  2588. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2589. $outvallabel .= ' ('.$objRefFourn.')';
  2590. }
  2591. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2592. $outvallabel .= ' ('.$outbarcode.')';
  2593. }
  2594. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2595. // Units
  2596. $optlabel .= $outvalUnits;
  2597. $outvallabel .= $outvalUnits;
  2598. if (!empty($objp->idprodfournprice))
  2599. {
  2600. $outqty = $objp->quantity;
  2601. $outdiscount = $objp->remise_percent;
  2602. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2603. $prod_supplier = new ProductFournisseur($this->db);
  2604. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2605. $prod_supplier->id = $objp->fk_product;
  2606. $prod_supplier->fourn_qty = $objp->quantity;
  2607. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2608. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2609. $priceparser = new PriceParser($this->db);
  2610. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2611. if ($price_result >= 0) {
  2612. $objp->fprice = $price_result;
  2613. if ($objp->quantity >= 1)
  2614. {
  2615. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  2616. }
  2617. }
  2618. }
  2619. if ($objp->quantity == 1)
  2620. {
  2621. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  2622. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  2623. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2624. $outvallabel .= $langs->transnoentities("Unit");
  2625. } else {
  2626. $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;
  2627. $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;
  2628. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2629. $outvallabel .= ' '.$langs->transnoentities("Units");
  2630. }
  2631. if ($objp->quantity > 1)
  2632. {
  2633. $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
  2634. $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
  2635. }
  2636. if ($objp->remise_percent >= 1)
  2637. {
  2638. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2639. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2640. }
  2641. if ($objp->duration)
  2642. {
  2643. $optlabel .= " - ".$objp->duration;
  2644. $outvallabel .= " - ".$objp->duration;
  2645. }
  2646. if (!$socid)
  2647. {
  2648. $optlabel .= " - ".dol_trunc($objp->name, 8);
  2649. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  2650. }
  2651. if ($objp->supplier_reputation)
  2652. {
  2653. //TODO dictionary
  2654. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  2655. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  2656. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  2657. }
  2658. } else {
  2659. if (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier
  2660. {
  2661. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  2662. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2663. } else // No supplier price defined for product, even on other suppliers
  2664. {
  2665. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  2666. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2667. }
  2668. }
  2669. if (!empty($conf->stock->enabled) && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)))
  2670. {
  2671. $novirtualstock = ($showstockinlist == 2);
  2672. if (!empty($user->rights->stock->lire)) {
  2673. $outvallabel .= ' - '.$langs->trans("Stock").':'.$objp->stock;
  2674. if ($objp->stock > 0) {
  2675. $optlabel .= ' - <span class="product_line_stock_ok">';
  2676. } elseif ($objp->stock <= 0) {
  2677. $optlabel .= ' - <span class="product_line_stock_too_low">';
  2678. }
  2679. $optlabel .= $langs->transnoentities("Stock").':'.$objp->stock;
  2680. $optlabel .= '</span>';
  2681. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) // Warning, this option may slow down combo list generation
  2682. {
  2683. $langs->load("stocks");
  2684. $tmpproduct = new Product($this->db);
  2685. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2686. $tmpproduct->load_virtual_stock();
  2687. $virtualstock = $tmpproduct->stock_theorique;
  2688. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2689. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  2690. if ($virtualstock > 0) {
  2691. $optlabel .= '<span class="product_line_stock_ok">';
  2692. } elseif ($virtualstock <= 0) {
  2693. $optlabel .= '<span class="product_line_stock_too_low">';
  2694. }
  2695. $optlabel .= $virtualstock;
  2696. $optlabel .= '</span>';
  2697. unset($tmpproduct);
  2698. }
  2699. }
  2700. }
  2701. $opt = '<option value="'.$outkey.'"';
  2702. if ($selected && $selected == $objp->idprodfournprice) $opt .= ' selected';
  2703. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt .= ' disabled';
  2704. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
  2705. {
  2706. $opt .= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqup="'.$objp->unitprice.'" data-pbqpercent="'.$objp->remise_percent.'"';
  2707. }
  2708. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  2709. $opt .= '>';
  2710. $opt .= $optlabel;
  2711. $outval .= $outvallabel;
  2712. $opt .= "</option>\n";
  2713. // Add new entry
  2714. // "key" value of json key array is used by jQuery automatically as selected value
  2715. // "label" value of json key array is used by jQuery automatically as text for combo box
  2716. $out .= $opt;
  2717. array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'up'=>$objp->unitprice, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice) ?true:false)));
  2718. // Exemple of var_dump $outarray
  2719. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  2720. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  2721. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  2722. //}
  2723. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2724. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  2725. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2726. $i++;
  2727. }
  2728. $out .= '</select>';
  2729. $this->db->free($result);
  2730. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2731. $out .= ajax_combobox($htmlname);
  2732. if (empty($outputmode)) return $out;
  2733. return $outarray;
  2734. } else {
  2735. dol_print_error($this->db);
  2736. }
  2737. }
  2738. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2739. /**
  2740. * Return list of suppliers prices for a product
  2741. *
  2742. * @param int $productid Id of product
  2743. * @param string $htmlname Name of HTML field
  2744. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  2745. * @return string
  2746. */
  2747. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  2748. {
  2749. // phpcs:enable
  2750. global $langs, $conf;
  2751. $langs->load('stocks');
  2752. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  2753. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  2754. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  2755. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2756. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2757. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2758. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  2759. $sql .= " AND p.tobuy = 1";
  2760. $sql .= " AND s.fournisseur = 1";
  2761. $sql .= " AND p.rowid = ".$productid;
  2762. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  2763. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  2764. $result = $this->db->query($sql);
  2765. if ($result)
  2766. {
  2767. $num = $this->db->num_rows($result);
  2768. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  2769. if (!$num)
  2770. {
  2771. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  2772. } else {
  2773. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2774. $form .= '<option value="0">&nbsp;</option>';
  2775. $i = 0;
  2776. while ($i < $num)
  2777. {
  2778. $objp = $this->db->fetch_object($result);
  2779. $opt = '<option value="'.$objp->idprodfournprice.'"';
  2780. //if there is only one supplier, preselect it
  2781. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  2782. $opt .= ' selected';
  2783. }
  2784. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  2785. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2786. $prod_supplier = new ProductFournisseur($this->db);
  2787. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2788. $prod_supplier->id = $productid;
  2789. $prod_supplier->fourn_qty = $objp->quantity;
  2790. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2791. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2792. $priceparser = new PriceParser($this->db);
  2793. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2794. if ($price_result >= 0) {
  2795. $objp->fprice = $price_result;
  2796. if ($objp->quantity >= 1)
  2797. {
  2798. $objp->unitprice = $objp->fprice / $objp->quantity;
  2799. }
  2800. }
  2801. }
  2802. if ($objp->quantity == 1)
  2803. {
  2804. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  2805. }
  2806. $opt .= $objp->quantity.' ';
  2807. if ($objp->quantity == 1)
  2808. {
  2809. $opt .= $langs->trans("Unit");
  2810. } else {
  2811. $opt .= $langs->trans("Units");
  2812. }
  2813. if ($objp->quantity > 1)
  2814. {
  2815. $opt .= " - ";
  2816. $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");
  2817. }
  2818. if ($objp->duration) $opt .= " - ".$objp->duration;
  2819. $opt .= "</option>\n";
  2820. $form .= $opt;
  2821. $i++;
  2822. }
  2823. }
  2824. $form .= '</select>';
  2825. $this->db->free($result);
  2826. return $form;
  2827. } else {
  2828. dol_print_error($this->db);
  2829. }
  2830. }
  2831. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2832. /**
  2833. * Return list of delivery address
  2834. *
  2835. * @param string $selected Id contact pre-selectionn
  2836. * @param int $socid Id of company
  2837. * @param string $htmlname Name of HTML field
  2838. * @param int $showempty Add an empty field
  2839. * @return integer|null
  2840. */
  2841. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  2842. {
  2843. // phpcs:enable
  2844. // looking for users
  2845. $sql = "SELECT a.rowid, a.label";
  2846. $sql .= " FROM ".MAIN_DB_PREFIX."societe_address as a";
  2847. $sql .= " WHERE a.fk_soc = ".$socid;
  2848. $sql .= " ORDER BY a.label ASC";
  2849. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  2850. $resql = $this->db->query($sql);
  2851. if ($resql)
  2852. {
  2853. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  2854. if ($showempty) print '<option value="0">&nbsp;</option>';
  2855. $num = $this->db->num_rows($resql);
  2856. $i = 0;
  2857. if ($num)
  2858. {
  2859. while ($i < $num)
  2860. {
  2861. $obj = $this->db->fetch_object($resql);
  2862. if ($selected && $selected == $obj->rowid)
  2863. {
  2864. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  2865. } else {
  2866. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  2867. }
  2868. $i++;
  2869. }
  2870. }
  2871. print '</select>';
  2872. return $num;
  2873. } else {
  2874. dol_print_error($this->db);
  2875. }
  2876. }
  2877. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2878. /**
  2879. * Load into cache list of payment terms
  2880. *
  2881. * @return int Nb of lines loaded, <0 if KO
  2882. */
  2883. public function load_cache_conditions_paiements()
  2884. {
  2885. // phpcs:enable
  2886. global $langs;
  2887. $num = count($this->cache_conditions_paiements);
  2888. if ($num > 0) return 0; // Cache already loaded
  2889. dol_syslog(__METHOD__, LOG_DEBUG);
  2890. $sql = "SELECT rowid, code, libelle as label";
  2891. $sql .= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  2892. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  2893. $sql .= " AND active > 0";
  2894. $sql .= " ORDER BY sortorder";
  2895. $resql = $this->db->query($sql);
  2896. if ($resql)
  2897. {
  2898. $num = $this->db->num_rows($resql);
  2899. $i = 0;
  2900. while ($i < $num)
  2901. {
  2902. $obj = $this->db->fetch_object($resql);
  2903. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2904. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  2905. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  2906. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  2907. $i++;
  2908. }
  2909. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  2910. return $num;
  2911. } else {
  2912. dol_print_error($this->db);
  2913. return -1;
  2914. }
  2915. }
  2916. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2917. /**
  2918. * Charge dans cache la liste des délais de livraison possibles
  2919. *
  2920. * @return int Nb of lines loaded, <0 if KO
  2921. */
  2922. public function load_cache_availability()
  2923. {
  2924. // phpcs:enable
  2925. global $langs;
  2926. $num = count($this->cache_availability);
  2927. if ($num > 0) return 0; // Cache already loaded
  2928. dol_syslog(__METHOD__, LOG_DEBUG);
  2929. $langs->load('propal');
  2930. $sql = "SELECT rowid, code, label";
  2931. $sql .= " FROM ".MAIN_DB_PREFIX.'c_availability';
  2932. $sql .= " WHERE active > 0";
  2933. $resql = $this->db->query($sql);
  2934. if ($resql)
  2935. {
  2936. $num = $this->db->num_rows($resql);
  2937. $i = 0;
  2938. while ($i < $num)
  2939. {
  2940. $obj = $this->db->fetch_object($resql);
  2941. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2942. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  2943. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  2944. $this->cache_availability[$obj->rowid]['label'] = $label;
  2945. $i++;
  2946. }
  2947. $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
  2948. return $num;
  2949. } else {
  2950. dol_print_error($this->db);
  2951. return -1;
  2952. }
  2953. }
  2954. /**
  2955. * Retourne la liste des types de delais de livraison possibles
  2956. *
  2957. * @param int $selected Id du type de delais pre-selectionne
  2958. * @param string $htmlname Nom de la zone select
  2959. * @param string $filtertype To add a filter
  2960. * @param int $addempty Add empty entry
  2961. * @return void
  2962. */
  2963. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0)
  2964. {
  2965. global $langs, $user;
  2966. $this->load_cache_availability();
  2967. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2968. print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  2969. if ($addempty) print '<option value="0">&nbsp;</option>';
  2970. foreach ($this->cache_availability as $id => $arrayavailability)
  2971. {
  2972. if ($selected == $id)
  2973. {
  2974. print '<option value="'.$id.'" selected>';
  2975. } else {
  2976. print '<option value="'.$id.'">';
  2977. }
  2978. print $arrayavailability['label'];
  2979. print '</option>';
  2980. }
  2981. print '</select>';
  2982. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  2983. print ajax_combobox($htmlname);
  2984. }
  2985. /**
  2986. * Load into cache cache_demand_reason, array of input reasons
  2987. *
  2988. * @return int Nb of lines loaded, <0 if KO
  2989. */
  2990. public function loadCacheInputReason()
  2991. {
  2992. global $langs;
  2993. $num = count($this->cache_demand_reason);
  2994. if ($num > 0) return 0; // Cache already loaded
  2995. $sql = "SELECT rowid, code, label";
  2996. $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  2997. $sql .= " WHERE active > 0";
  2998. $resql = $this->db->query($sql);
  2999. if ($resql)
  3000. {
  3001. $num = $this->db->num_rows($resql);
  3002. $i = 0;
  3003. $tmparray = array();
  3004. while ($i < $num)
  3005. {
  3006. $obj = $this->db->fetch_object($resql);
  3007. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3008. $label = ($obj->label != '-' ? $obj->label : '');
  3009. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3010. if ($langs->trans($obj->code) != $obj->code) $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3011. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3012. $tmparray[$obj->rowid]['code'] = $obj->code;
  3013. $tmparray[$obj->rowid]['label'] = $label;
  3014. $i++;
  3015. }
  3016. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3017. unset($tmparray);
  3018. return $num;
  3019. } else {
  3020. dol_print_error($this->db);
  3021. return -1;
  3022. }
  3023. }
  3024. /**
  3025. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3026. * List found into table c_input_reason loaded by loadCacheInputReason
  3027. *
  3028. * @param int $selected Id or code of type origin to select by default
  3029. * @param string $htmlname Nom de la zone select
  3030. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3031. * @param int $addempty Add an empty entry
  3032. * @return void
  3033. */
  3034. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0)
  3035. {
  3036. global $langs, $user;
  3037. $this->loadCacheInputReason();
  3038. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3039. if ($addempty) print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3040. foreach ($this->cache_demand_reason as $id => $arraydemandreason)
  3041. {
  3042. if ($arraydemandreason['code'] == $exclude) continue;
  3043. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
  3044. {
  3045. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3046. } else {
  3047. print '<option value="'.$arraydemandreason['id'].'">';
  3048. }
  3049. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3050. print $langs->trans($label);
  3051. print '</option>';
  3052. }
  3053. print '</select>';
  3054. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3055. print ajax_combobox('select_'.$htmlname);
  3056. }
  3057. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3058. /**
  3059. * Charge dans cache la liste des types de paiements possibles
  3060. *
  3061. * @return int Nb of lines loaded, <0 if KO
  3062. */
  3063. public function load_cache_types_paiements()
  3064. {
  3065. // phpcs:enable
  3066. global $langs;
  3067. $num = count($this->cache_types_paiements);
  3068. if ($num > 0) return $num; // Cache already loaded
  3069. dol_syslog(__METHOD__, LOG_DEBUG);
  3070. $this->cache_types_paiements = array();
  3071. $sql = "SELECT id, code, libelle as label, type, active";
  3072. $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement";
  3073. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3074. //if ($active >= 0) $sql.= " AND active = ".$active;
  3075. $resql = $this->db->query($sql);
  3076. if ($resql)
  3077. {
  3078. $num = $this->db->num_rows($resql);
  3079. $i = 0;
  3080. while ($i < $num)
  3081. {
  3082. $obj = $this->db->fetch_object($resql);
  3083. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3084. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3085. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3086. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3087. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3088. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3089. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3090. $i++;
  3091. }
  3092. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3093. return $num;
  3094. } else {
  3095. dol_print_error($this->db);
  3096. return -1;
  3097. }
  3098. }
  3099. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3100. /**
  3101. * Return list of payment modes.
  3102. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3103. * See instead to force the default value by the caller.
  3104. *
  3105. * @param int $selected Id of payment term to preselect by default
  3106. * @param string $htmlname Nom de la zone select
  3107. * @param int $filtertype Not used
  3108. * @param int $addempty Add an empty entry
  3109. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3110. * @param string $morecss Add more CSS on select tag
  3111. * @return void
  3112. */
  3113. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '')
  3114. {
  3115. // phpcs:enable
  3116. global $langs, $user, $conf;
  3117. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3118. $this->load_cache_conditions_paiements();
  3119. // Set default value if not already set by caller
  3120. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3121. print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3122. if ($addempty) print '<option value="0">&nbsp;</option>';
  3123. foreach ($this->cache_conditions_paiements as $id => $arrayconditions)
  3124. {
  3125. if ($selected == $id)
  3126. {
  3127. print '<option value="'.$id.'" selected>';
  3128. } else {
  3129. print '<option value="'.$id.'">';
  3130. }
  3131. print $arrayconditions['label'];
  3132. print '</option>';
  3133. }
  3134. print '</select>';
  3135. if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3136. print ajax_combobox($htmlname);
  3137. }
  3138. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3139. /**
  3140. * Return list of payment methods
  3141. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3142. *
  3143. * @param string $selected Id or code or preselected payment mode
  3144. * @param string $htmlname Name of select field
  3145. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3146. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3147. * @param int $empty 1=can be empty, 0 otherwise
  3148. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3149. * @param int $maxlength Max length of label
  3150. * @param int $active Active or not, -1 = all
  3151. * @param string $morecss Add more CSS on select tag
  3152. * @return void
  3153. */
  3154. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3155. {
  3156. // phpcs:enable
  3157. global $langs, $user, $conf;
  3158. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3159. $filterarray = array();
  3160. if ($filtertype == 'CRDT') $filterarray = array(0, 2, 3);
  3161. elseif ($filtertype == 'DBIT') $filterarray = array(1, 2, 3);
  3162. elseif ($filtertype != '' && $filtertype != '-1') $filterarray = explode(',', $filtertype);
  3163. $this->load_cache_types_paiements();
  3164. // Set default value if not already set by caller
  3165. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3166. print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3167. if ($empty) print '<option value="">&nbsp;</option>';
  3168. foreach ($this->cache_types_paiements as $id => $arraytypes)
  3169. {
  3170. // If not good status
  3171. if ($active >= 0 && $arraytypes['active'] != $active) continue;
  3172. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3173. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) continue;
  3174. // We discard empty line if showempty is on because an empty line has already been output.
  3175. if ($empty && empty($arraytypes['code'])) continue;
  3176. if ($format == 0) print '<option value="'.$id.'"';
  3177. elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
  3178. elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
  3179. elseif ($format == 3) print '<option value="'.$id.'"';
  3180. // Print attribute selected or not
  3181. if ($format == 1 || $format == 2) {
  3182. if ($selected == $arraytypes['code']) print ' selected';
  3183. } else {
  3184. if ($selected == $id) print ' selected';
  3185. }
  3186. print '>';
  3187. if ($format == 0) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3188. elseif ($format == 1) $value = $arraytypes['code'];
  3189. elseif ($format == 2) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3190. elseif ($format == 3) $value = $arraytypes['code'];
  3191. print $value ? $value : '&nbsp;';
  3192. print '</option>';
  3193. }
  3194. print '</select>';
  3195. if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3196. print ajax_combobox('select'.$htmlname);
  3197. }
  3198. /**
  3199. * Selection HT or TTC
  3200. *
  3201. * @param string $selected Id pre-selectionne
  3202. * @param string $htmlname Nom de la zone select
  3203. * @return string Code of HTML select to chose tax or not
  3204. */
  3205. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type')
  3206. {
  3207. global $langs;
  3208. $return = '';
  3209. $return .= '<select class="flat maxwidth75" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3210. $options = array(
  3211. 'HT'=>$langs->trans("HT"),
  3212. 'TTC'=>$langs->trans("TTC")
  3213. );
  3214. foreach ($options as $id => $value)
  3215. {
  3216. if ($selected == $id)
  3217. {
  3218. $return .= '<option value="'.$id.'" selected>'.$value;
  3219. } else {
  3220. $return .= '<option value="'.$id.'">'.$value;
  3221. }
  3222. $return .= '</option>';
  3223. }
  3224. $return .= '</select>';
  3225. return $return;
  3226. }
  3227. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3228. /**
  3229. * Load in cache list of transport mode
  3230. *
  3231. * @return int Nb of lines loaded, <0 if KO
  3232. */
  3233. public function load_cache_transport_mode()
  3234. {
  3235. // phpcs:enable
  3236. global $langs;
  3237. $num = count($this->cache_transport_mode);
  3238. if ($num > 0) return $num; // Cache already loaded
  3239. dol_syslog(__METHOD__, LOG_DEBUG);
  3240. $this->cache_transport_mode = array();
  3241. $sql = "SELECT rowid, code, label, active";
  3242. $sql .= " FROM ".MAIN_DB_PREFIX."c_transport_mode";
  3243. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3244. //if ($active >= 0) $sql.= " AND active = ".$active;
  3245. $resql = $this->db->query($sql);
  3246. if ($resql)
  3247. {
  3248. $num = $this->db->num_rows($resql);
  3249. $i = 0;
  3250. while ($i < $num)
  3251. {
  3252. $obj = $this->db->fetch_object($resql);
  3253. // If traduction exist, we use it else we take the default label
  3254. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3255. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3256. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3257. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3258. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3259. $i++;
  3260. }
  3261. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3262. return $num;
  3263. }
  3264. else {
  3265. dol_print_error($this->db);
  3266. return -1;
  3267. }
  3268. }
  3269. /**
  3270. * Return list of transport mode for intracomm report
  3271. *
  3272. * @param string $selected Id of the transport mode pre-selected
  3273. * @param string $htmlname Name of the select field
  3274. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3275. * @param int $empty 1=can be empty, 0 else
  3276. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3277. * @param int $maxlength Max length of label
  3278. * @param int $active Active or not, -1 = all
  3279. * @param string $morecss Add more CSS on select tag
  3280. * @return void
  3281. */
  3282. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3283. {
  3284. global $langs, $user;
  3285. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3286. $this->load_cache_transport_mode();
  3287. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3288. if ($empty) print '<option value="">&nbsp;</option>';
  3289. foreach ($this->cache_transport_mode as $id => $arraytypes)
  3290. {
  3291. // If not good status
  3292. if ($active >= 0 && $arraytypes['active'] != $active) continue;
  3293. // We discard empty line if showempty is on because an empty line has already been output.
  3294. if ($empty && empty($arraytypes['code'])) continue;
  3295. if ($format == 0) print '<option value="'.$id.'"';
  3296. elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
  3297. elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
  3298. elseif ($format == 3) print '<option value="'.$id.'"';
  3299. // If text is selected, we compare with code, else with id
  3300. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
  3301. elseif ($selected == $id) print ' selected';
  3302. print '>';
  3303. if ($format == 0) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3304. elseif ($format == 1) $value = $arraytypes['code'];
  3305. elseif ($format == 2) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3306. elseif ($format == 3) $value = $arraytypes['code'];
  3307. print $value ? $value : '&nbsp;';
  3308. print '</option>';
  3309. }
  3310. print '</select>';
  3311. if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3312. }
  3313. /**
  3314. * Return a HTML select list of shipping mode
  3315. *
  3316. * @param string $selected Id shipping mode pre-selected
  3317. * @param string $htmlname Name of select zone
  3318. * @param string $filtre To filter list
  3319. * @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.
  3320. * @param string $moreattrib To add more attribute on select
  3321. * @return void
  3322. */
  3323. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '')
  3324. {
  3325. global $langs, $conf, $user;
  3326. $langs->load("admin");
  3327. $langs->load("deliveries");
  3328. $sql = "SELECT rowid, code, libelle as label";
  3329. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
  3330. $sql .= " WHERE active > 0";
  3331. if ($filtre) $sql .= " AND ".$filtre;
  3332. $sql .= " ORDER BY libelle ASC";
  3333. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3334. $result = $this->db->query($sql);
  3335. if ($result) {
  3336. $num = $this->db->num_rows($result);
  3337. $i = 0;
  3338. if ($num) {
  3339. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3340. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3341. print '<option value="-1">&nbsp;</option>';
  3342. }
  3343. while ($i < $num) {
  3344. $obj = $this->db->fetch_object($result);
  3345. if ($selected == $obj->rowid) {
  3346. print '<option value="'.$obj->rowid.'" selected>';
  3347. } else {
  3348. print '<option value="'.$obj->rowid.'">';
  3349. }
  3350. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3351. print '</option>';
  3352. $i++;
  3353. }
  3354. print "</select>";
  3355. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3356. print ajax_combobox('select'.$htmlname);
  3357. } else {
  3358. print $langs->trans("NoShippingMethodDefined");
  3359. }
  3360. } else {
  3361. dol_print_error($this->db);
  3362. }
  3363. }
  3364. /**
  3365. * Display form to select shipping mode
  3366. *
  3367. * @param string $page Page
  3368. * @param int $selected Id of shipping mode
  3369. * @param string $htmlname Name of select html field
  3370. * @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.
  3371. * @return void
  3372. */
  3373. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  3374. {
  3375. global $langs, $db;
  3376. $langs->load("deliveries");
  3377. if ($htmlname != "none") {
  3378. print '<form method="POST" action="'.$page.'">';
  3379. print '<input type="hidden" name="action" value="setshippingmethod">';
  3380. print '<input type="hidden" name="token" value="'.newToken().'">';
  3381. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3382. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3383. print '</form>';
  3384. } else {
  3385. if ($selected) {
  3386. $code = $langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
  3387. print $langs->trans("SendingMethod".strtoupper($code));
  3388. } else {
  3389. print "&nbsp;";
  3390. }
  3391. }
  3392. }
  3393. /**
  3394. * Creates HTML last in cycle situation invoices selector
  3395. *
  3396. * @param string $selected Preselected ID
  3397. * @param int $socid Company ID
  3398. *
  3399. * @return string HTML select
  3400. */
  3401. public function selectSituationInvoices($selected = '', $socid = 0)
  3402. {
  3403. global $langs;
  3404. $langs->load('bills');
  3405. $opt = '<option value ="" selected></option>';
  3406. $sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc';
  3407. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture';
  3408. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  3409. $sql .= ' AND situation_counter >= 1';
  3410. $sql .= ' AND fk_soc = '.(int) $socid;
  3411. $sql .= ' AND type <> 2';
  3412. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  3413. $resql = $this->db->query($sql);
  3414. if ($resql && $this->db->num_rows($resql) > 0) {
  3415. // Last seen cycle
  3416. $ref = 0;
  3417. while ($obj = $this->db->fetch_object($resql)) {
  3418. //Same cycle ?
  3419. if ($obj->situation_cycle_ref != $ref) {
  3420. // Just seen this cycle
  3421. $ref = $obj->situation_cycle_ref;
  3422. //not final ?
  3423. if ($obj->situation_final != 1) {
  3424. //Not prov?
  3425. if (substr($obj->ref, 1, 4) != 'PROV') {
  3426. if ($selected == $obj->rowid) {
  3427. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  3428. } else {
  3429. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  3430. }
  3431. }
  3432. }
  3433. }
  3434. }
  3435. } else {
  3436. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  3437. }
  3438. if ($opt == '<option value ="" selected></option>')
  3439. {
  3440. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  3441. }
  3442. return $opt;
  3443. }
  3444. /**
  3445. * Creates HTML units selector (code => label)
  3446. *
  3447. * @param string $selected Preselected Unit ID
  3448. * @param string $htmlname Select name
  3449. * @param int $showempty Add a nempty line
  3450. * @return string HTML select
  3451. */
  3452. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0)
  3453. {
  3454. global $langs;
  3455. $langs->load('products');
  3456. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  3457. $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
  3458. $sql .= ' WHERE active > 0';
  3459. $resql = $this->db->query($sql);
  3460. if ($resql && $this->db->num_rows($resql) > 0)
  3461. {
  3462. if ($showempty) $return .= '<option value="none"></option>';
  3463. while ($res = $this->db->fetch_object($resql))
  3464. {
  3465. $unitLabel = $res->label;
  3466. if (!empty($langs->tab_translate['unit'.$res->code])) // check if Translation is available before
  3467. {
  3468. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  3469. }
  3470. if ($selected == $res->rowid)
  3471. {
  3472. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  3473. } else {
  3474. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  3475. }
  3476. }
  3477. $return .= '</select>';
  3478. }
  3479. return $return;
  3480. }
  3481. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3482. /**
  3483. * Return a HTML select list of bank accounts
  3484. *
  3485. * @param string $selected Id account pre-selected
  3486. * @param string $htmlname Name of select zone
  3487. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  3488. * @param string $filtre To filter list
  3489. * @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.
  3490. * @param string $moreattrib To add more attribute on select
  3491. * @param int $showcurrency Show currency in label
  3492. * @param string $morecss More CSS
  3493. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  3494. */
  3495. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '')
  3496. {
  3497. // phpcs:enable
  3498. global $langs, $conf;
  3499. $langs->load("admin");
  3500. $num = 0;
  3501. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  3502. $sql .= " FROM ".MAIN_DB_PREFIX."bank_account";
  3503. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  3504. if ($status != 2) $sql .= " AND clos = ".(int) $status;
  3505. if ($filtre) $sql .= " AND ".$filtre;
  3506. $sql .= " ORDER BY label";
  3507. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  3508. $result = $this->db->query($sql);
  3509. if ($result)
  3510. {
  3511. $num = $this->db->num_rows($result);
  3512. $i = 0;
  3513. if ($num)
  3514. {
  3515. print '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3516. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  3517. {
  3518. print '<option value="-1">&nbsp;</option>';
  3519. }
  3520. while ($i < $num)
  3521. {
  3522. $obj = $this->db->fetch_object($result);
  3523. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected)))
  3524. {
  3525. print '<option value="'.$obj->rowid.'" selected>';
  3526. } else {
  3527. print '<option value="'.$obj->rowid.'">';
  3528. }
  3529. print trim($obj->label);
  3530. if ($showcurrency) print ' ('.$obj->currency_code.')';
  3531. if ($status == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  3532. print '</option>';
  3533. $i++;
  3534. }
  3535. print "</select>";
  3536. print ajax_combobox('select'.$htmlname);
  3537. } else {
  3538. if ($status == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  3539. else print '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  3540. }
  3541. } else {
  3542. dol_print_error($this->db);
  3543. }
  3544. return $num;
  3545. }
  3546. /**
  3547. * Return a HTML select list of establishment
  3548. *
  3549. * @param string $selected Id establishment pre-selected
  3550. * @param string $htmlname Name of select zone
  3551. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  3552. * @param string $filtre To filter list
  3553. * @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.
  3554. * @param string $moreattrib To add more attribute on select
  3555. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  3556. */
  3557. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  3558. {
  3559. // phpcs:enable
  3560. global $langs, $conf;
  3561. $langs->load("admin");
  3562. $num = 0;
  3563. $sql = "SELECT rowid, name, fk_country, status, entity";
  3564. $sql .= " FROM ".MAIN_DB_PREFIX."establishment";
  3565. $sql .= " WHERE 1=1";
  3566. if ($status != 2) $sql .= " AND status = ".(int) $status;
  3567. if ($filtre) $sql .= " AND ".$filtre;
  3568. $sql .= " ORDER BY name";
  3569. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  3570. $result = $this->db->query($sql);
  3571. if ($result)
  3572. {
  3573. $num = $this->db->num_rows($result);
  3574. $i = 0;
  3575. if ($num)
  3576. {
  3577. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3578. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  3579. {
  3580. print '<option value="-1">&nbsp;</option>';
  3581. }
  3582. while ($i < $num)
  3583. {
  3584. $obj = $this->db->fetch_object($result);
  3585. if ($selected == $obj->rowid)
  3586. {
  3587. print '<option value="'.$obj->rowid.'" selected>';
  3588. } else {
  3589. print '<option value="'.$obj->rowid.'">';
  3590. }
  3591. print trim($obj->name);
  3592. if ($status == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  3593. print '</option>';
  3594. $i++;
  3595. }
  3596. print "</select>";
  3597. } else {
  3598. if ($status == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  3599. else print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  3600. }
  3601. } else {
  3602. dol_print_error($this->db);
  3603. }
  3604. }
  3605. /**
  3606. * Display form to select bank account
  3607. *
  3608. * @param string $page Page
  3609. * @param int $selected Id of bank account
  3610. * @param string $htmlname Name of select html field
  3611. * @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.
  3612. * @return void
  3613. */
  3614. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  3615. {
  3616. global $langs;
  3617. if ($htmlname != "none") {
  3618. print '<form method="POST" action="'.$page.'">';
  3619. print '<input type="hidden" name="action" value="setbankaccount">';
  3620. print '<input type="hidden" name="token" value="'.newToken().'">';
  3621. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  3622. if ($nbaccountfound > 0) print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3623. print '</form>';
  3624. } else {
  3625. $langs->load('banks');
  3626. if ($selected) {
  3627. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  3628. $bankstatic = new Account($this->db);
  3629. $result = $bankstatic->fetch($selected);
  3630. if ($result) print $bankstatic->getNomUrl(1);
  3631. } else {
  3632. print "&nbsp;";
  3633. }
  3634. }
  3635. }
  3636. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3637. /**
  3638. * Return list of categories having choosed type
  3639. *
  3640. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  3641. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  3642. * @param string $htmlname HTML field name
  3643. * @param int $maxlength Maximum length for labels
  3644. * @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.
  3645. * $markafterid can be an :
  3646. * - int (id of category)
  3647. * - string (categories ids seprated by comma)
  3648. * - array (list of categories ids)
  3649. * @param int $outputmode 0=HTML select string, 1=Array
  3650. * @param int $include [=0] Removed or 1=Keep only
  3651. * @param string $morecss More CSS
  3652. * @return string
  3653. * @see select_categories()
  3654. */
  3655. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  3656. {
  3657. // phpcs:enable
  3658. global $conf, $langs;
  3659. $langs->load("categories");
  3660. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  3661. // For backward compatibility
  3662. if (is_numeric($type))
  3663. {
  3664. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  3665. }
  3666. if ($type === Categorie::TYPE_BANK_LINE)
  3667. {
  3668. // TODO Move this into common category feature
  3669. $cate_arbo = array();
  3670. $sql = "SELECT c.label, c.rowid";
  3671. $sql .= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
  3672. $sql .= " WHERE entity = ".$conf->entity;
  3673. $sql .= " ORDER BY c.label";
  3674. $result = $this->db->query($sql);
  3675. if ($result)
  3676. {
  3677. $num = $this->db->num_rows($result);
  3678. $i = 0;
  3679. while ($i < $num)
  3680. {
  3681. $objp = $this->db->fetch_object($result);
  3682. if ($objp) $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  3683. $i++;
  3684. }
  3685. $this->db->free($result);
  3686. } else dol_print_error($this->db);
  3687. } else {
  3688. $cat = new Categorie($this->db);
  3689. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  3690. }
  3691. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  3692. $outarray = array();
  3693. if (is_array($cate_arbo))
  3694. {
  3695. if (!count($cate_arbo)) $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  3696. else {
  3697. $output .= '<option value="-1">&nbsp;</option>';
  3698. foreach ($cate_arbo as $key => $value)
  3699. {
  3700. if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
  3701. {
  3702. $add = 'selected ';
  3703. } else {
  3704. $add = '';
  3705. }
  3706. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  3707. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  3708. }
  3709. }
  3710. }
  3711. $output .= '</select>';
  3712. $output .= "\n";
  3713. if ($outputmode) return $outarray;
  3714. return $output;
  3715. }
  3716. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3717. /**
  3718. * Show a confirmation HTML form or AJAX popup
  3719. *
  3720. * @param string $page Url of page to call if confirmation is OK
  3721. * @param string $title Title
  3722. * @param string $question Question
  3723. * @param string $action Action
  3724. * @param array $formquestion An array with forms complementary inputs
  3725. * @param string $selectedchoice "" or "no" or "yes"
  3726. * @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
  3727. * @param int $height Force height of box
  3728. * @param int $width Force width of box
  3729. * @return void
  3730. * @deprecated
  3731. * @see formconfirm()
  3732. */
  3733. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  3734. {
  3735. // phpcs:enable
  3736. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  3737. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  3738. }
  3739. /**
  3740. * Show a confirmation HTML form or AJAX popup.
  3741. * Easiest way to use this is with useajax=1.
  3742. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  3743. * just after calling this method. For example:
  3744. * print '<script type="text/javascript">'."\n";
  3745. * print 'jQuery(document).ready(function() {'."\n";
  3746. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  3747. * print '});'."\n";
  3748. * print '</script>'."\n";
  3749. *
  3750. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  3751. * @param string $title Title
  3752. * @param string $question Question
  3753. * @param string $action Action
  3754. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
  3755. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', ...
  3756. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  3757. * @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
  3758. * @param int|string $height Force height of box (0 = auto)
  3759. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  3760. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  3761. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  3762. */
  3763. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0)
  3764. {
  3765. global $langs, $conf;
  3766. $more = '<!-- formconfirm for page='.dol_escape_htmltag($page).' -->';
  3767. $formconfirm = '';
  3768. $inputok = array();
  3769. $inputko = array();
  3770. // Clean parameters
  3771. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  3772. if ($conf->browser->layout == 'phone') $width = '95%';
  3773. // Set height automatically if not defined
  3774. if (empty($height)) {
  3775. $height = 220;
  3776. if (is_array($formquestion) && count($formquestion) > 2) {
  3777. $height += ((count($formquestion) - 2) * 24);
  3778. }
  3779. }
  3780. if (is_array($formquestion) && !empty($formquestion))
  3781. {
  3782. // First add hidden fields and value
  3783. foreach ($formquestion as $key => $input)
  3784. {
  3785. if (is_array($input) && !empty($input))
  3786. {
  3787. if ($input['type'] == 'hidden')
  3788. {
  3789. $more .= '<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  3790. }
  3791. }
  3792. }
  3793. // Now add questions
  3794. $moreonecolumn = '';
  3795. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  3796. foreach ($formquestion as $key => $input)
  3797. {
  3798. if (is_array($input) && !empty($input))
  3799. {
  3800. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : '');
  3801. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  3802. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  3803. if ($input['type'] == 'text')
  3804. {
  3805. $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="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  3806. } elseif ($input['type'] == 'password')
  3807. {
  3808. $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="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  3809. } elseif ($input['type'] == 'select')
  3810. {
  3811. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  3812. if (!empty($input['label'])) $more .= $input['label'].'</div><div class="tagtd left">';
  3813. $more .= $this->selectarray($input['name'], $input['values'], $input['default'], 1, 0, 0, $moreattr, 0, 0, 0, '', $morecss);
  3814. $more .= '</div></div>'."\n";
  3815. } elseif ($input['type'] == 'checkbox')
  3816. {
  3817. $more .= '<div class="tagtr">';
  3818. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  3819. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
  3820. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more .= ' checked';
  3821. if (is_bool($input['value']) && $input['value']) $more .= ' checked';
  3822. if (isset($input['disabled'])) $more .= ' disabled';
  3823. $more .= ' /></div>';
  3824. $more .= '</div>'."\n";
  3825. } elseif ($input['type'] == 'radio')
  3826. {
  3827. $i = 0;
  3828. foreach ($input['values'] as $selkey => $selval)
  3829. {
  3830. $more .= '<div class="tagtr">';
  3831. if ($i == 0) $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  3832. else $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  3833. $more .= '<div class="tagtd'.($i == 0 ? ' tdtop' : '').'"><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].$selkey.'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
  3834. if ($input['disabled']) $more .= ' disabled';
  3835. if (isset($input['default']) && $input['default'] === $selkey) $more .= ' checked="checked"';
  3836. $more .= ' /> ';
  3837. $more .= '<label for="'.$input['name'].$selkey.'">'.$selval.'</label>';
  3838. $more .= '</div></div>'."\n";
  3839. $i++;
  3840. }
  3841. } elseif ($input['type'] == 'date')
  3842. {
  3843. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  3844. $more .= '<div class="tagtd">';
  3845. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, 0);
  3846. $more .= '</div></div>'."\n";
  3847. $formquestion[] = array('name'=>$input['name'].'day');
  3848. $formquestion[] = array('name'=>$input['name'].'month');
  3849. $formquestion[] = array('name'=>$input['name'].'year');
  3850. $formquestion[] = array('name'=>$input['name'].'hour');
  3851. $formquestion[] = array('name'=>$input['name'].'min');
  3852. } elseif ($input['type'] == 'other')
  3853. {
  3854. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  3855. if (!empty($input['label'])) $more .= $input['label'].'</div><div class="tagtd">';
  3856. $more .= $input['value'];
  3857. $more .= '</div></div>'."\n";
  3858. } elseif ($input['type'] == 'onecolumn')
  3859. {
  3860. $moreonecolumn .= '<div class="margintoponly">';
  3861. $moreonecolumn .= $input['value'];
  3862. $moreonecolumn .= '</div>'."\n";
  3863. }
  3864. }
  3865. }
  3866. $more .= '</div>'."\n";
  3867. $more .= $moreonecolumn;
  3868. }
  3869. // JQUI method dialog is broken with jmobile, we use standard HTML.
  3870. // 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
  3871. // See page product/card.php for example
  3872. if (!empty($conf->dol_use_jmobile)) $useajax = 0;
  3873. if (empty($conf->use_javascript_ajax)) $useajax = 0;
  3874. if ($useajax)
  3875. {
  3876. $autoOpen = true;
  3877. $dialogconfirm = 'dialog-confirm';
  3878. $button = '';
  3879. if (!is_numeric($useajax))
  3880. {
  3881. $button = $useajax;
  3882. $useajax = 1;
  3883. $autoOpen = false;
  3884. $dialogconfirm .= '-'.$button;
  3885. }
  3886. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.$action.'&confirm=yes';
  3887. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'confirm=no' : '');
  3888. // Add input fields into list of fields to read during submit (inputok and inputko)
  3889. if (is_array($formquestion))
  3890. {
  3891. foreach ($formquestion as $key => $input)
  3892. {
  3893. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  3894. if (is_array($input) && isset($input['name'])) array_push($inputok, $input['name']);
  3895. if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko, $input['name']);
  3896. }
  3897. }
  3898. // Show JQuery confirm box.
  3899. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  3900. if (is_array($formquestion) && !empty($formquestion['text'])) {
  3901. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  3902. }
  3903. if (!empty($more)) {
  3904. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  3905. }
  3906. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  3907. $formconfirm .= '</div>'."\n";
  3908. $formconfirm .= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
  3909. $formconfirm .= '<script type="text/javascript">'."\n";
  3910. $formconfirm .= 'jQuery(document).ready(function() {
  3911. $(function() {
  3912. $( "#'.$dialogconfirm.'" ).dialog(
  3913. {
  3914. autoOpen: '.($autoOpen ? "true" : "false").',';
  3915. if ($newselectedchoice == 'no')
  3916. {
  3917. $formconfirm .= '
  3918. open: function() {
  3919. $(this).parent().find("button.ui-button:eq(2)").focus();
  3920. },';
  3921. }
  3922. $formconfirm .= '
  3923. resizable: false,
  3924. height: "'.$height.'",
  3925. width: "'.$width.'",
  3926. modal: true,
  3927. closeOnEscape: false,
  3928. buttons: {
  3929. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  3930. var options = "&token='.urlencode(newToken()).'";
  3931. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  3932. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  3933. if (inputok.length>0) {
  3934. $.each(inputok, function(i, inputname) {
  3935. var more = "";
  3936. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3937. if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
  3938. var inputvalue = $("#" + inputname + more).val();
  3939. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3940. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  3941. });
  3942. }
  3943. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  3944. if (pageyes.length > 0) { location.href = urljump; }
  3945. $(this).dialog("close");
  3946. },
  3947. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  3948. var options = "&token='.urlencode(newToken()).'";
  3949. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  3950. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  3951. if (inputko.length>0) {
  3952. $.each(inputko, function(i, inputname) {
  3953. var more = "";
  3954. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3955. var inputvalue = $("#" + inputname + more).val();
  3956. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3957. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  3958. });
  3959. }
  3960. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  3961. //alert(urljump);
  3962. if (pageno.length > 0) { location.href = urljump; }
  3963. $(this).dialog("close");
  3964. }
  3965. }
  3966. }
  3967. );
  3968. var button = "'.$button.'";
  3969. if (button.length > 0) {
  3970. $( "#" + button ).click(function() {
  3971. $("#'.$dialogconfirm.'").dialog("open");
  3972. });
  3973. }
  3974. });
  3975. });
  3976. </script>';
  3977. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  3978. } else {
  3979. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  3980. if (empty($disableformtag)) $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  3981. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  3982. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  3983. $formconfirm .= '<table class="valid centpercent">'."\n";
  3984. // Line title
  3985. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('', 'recent').' '.$title.'</td></tr>'."\n";
  3986. // Line text
  3987. if (is_array($formquestion) && !empty($formquestion['text'])) {
  3988. $formconfirm .= '<tr class="valid"><td class="valid" colspan="3">'.$formquestion['text'].'</td></tr>'."\n";
  3989. }
  3990. // Line form fields
  3991. if ($more)
  3992. {
  3993. $formconfirm .= '<tr class="valid"><td class="valid" colspan="3">'."\n";
  3994. $formconfirm .= $more;
  3995. $formconfirm .= '</td></tr>'."\n";
  3996. }
  3997. // Line with question
  3998. $formconfirm .= '<tr class="valid">';
  3999. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4000. $formconfirm .= '<td class="valid">';
  4001. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice);
  4002. $formconfirm .= '</td>';
  4003. $formconfirm .= '<td class="valid center"><input class="button valignmiddle confirmvalidatebutton" type="submit" value="'.$langs->trans("Validate").'"></td>';
  4004. $formconfirm .= '</tr>'."\n";
  4005. $formconfirm .= '</table>'."\n";
  4006. if (empty($disableformtag)) $formconfirm .= "</form>\n";
  4007. $formconfirm .= '<br>';
  4008. if (empty($conf->use_javascript_ajax)) {
  4009. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4010. $formconfirm .= '<script type="text/javascript">'."\n";
  4011. $formconfirm .= '
  4012. $(document).ready(function () {
  4013. $(".confirmvalidatebutton").on("click", function() {
  4014. console.log("We click on button");
  4015. $(this).attr("disabled", "disabled");
  4016. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4017. //console.log($(this).closest("form"));
  4018. $(this).closest("form").submit();
  4019. });
  4020. });
  4021. ';
  4022. $formconfirm .= '</script>'."\n";
  4023. }
  4024. $formconfirm .= "<!-- end formconfirm -->\n";
  4025. }
  4026. return $formconfirm;
  4027. }
  4028. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4029. /**
  4030. * Show a form to select a project
  4031. *
  4032. * @param int $page Page
  4033. * @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)
  4034. * @param int $selected Id pre-selected project
  4035. * @param string $htmlname Name of select field
  4036. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4037. * @param int $maxlength Max length
  4038. * @param int $forcefocus Force focus on field (works with javascript only)
  4039. * @param int $nooutput No print is done. String is returned.
  4040. * @return string Return html content
  4041. */
  4042. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  4043. {
  4044. // phpcs:enable
  4045. global $langs;
  4046. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4047. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4048. $out = '';
  4049. $formproject = new FormProjets($this->db);
  4050. $langs->load("project");
  4051. if ($htmlname != "none")
  4052. {
  4053. $out .= "\n";
  4054. $out .= '<form method="post" action="'.$page.'">';
  4055. $out .= '<input type="hidden" name="action" value="classin">';
  4056. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4057. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  4058. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4059. $out .= '</form>';
  4060. } else {
  4061. if ($selected)
  4062. {
  4063. $projet = new Project($this->db);
  4064. $projet->fetch($selected);
  4065. //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
  4066. $out .= $projet->getNomUrl(0, '', 1);
  4067. } else {
  4068. $out .= "&nbsp;";
  4069. }
  4070. }
  4071. if (empty($nooutput))
  4072. {
  4073. print $out;
  4074. return '';
  4075. }
  4076. return $out;
  4077. }
  4078. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4079. /**
  4080. * Show a form to select payment conditions
  4081. *
  4082. * @param int $page Page
  4083. * @param string $selected Id condition pre-selectionne
  4084. * @param string $htmlname Name of select html field
  4085. * @param int $addempty Add empty entry
  4086. * @return void
  4087. */
  4088. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0)
  4089. {
  4090. // phpcs:enable
  4091. global $langs;
  4092. if ($htmlname != "none")
  4093. {
  4094. print '<form method="post" action="'.$page.'">';
  4095. print '<input type="hidden" name="action" value="setconditions">';
  4096. print '<input type="hidden" name="token" value="'.newToken().'">';
  4097. $this->select_conditions_paiements($selected, $htmlname, -1, $addempty);
  4098. print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4099. print '</form>';
  4100. } else {
  4101. if ($selected)
  4102. {
  4103. $this->load_cache_conditions_paiements();
  4104. print $this->cache_conditions_paiements[$selected]['label'];
  4105. } else {
  4106. print "&nbsp;";
  4107. }
  4108. }
  4109. }
  4110. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4111. /**
  4112. * Show a form to select a delivery delay
  4113. *
  4114. * @param int $page Page
  4115. * @param string $selected Id condition pre-selectionne
  4116. * @param string $htmlname Name of select html field
  4117. * @param int $addempty Ajoute entree vide
  4118. * @return void
  4119. */
  4120. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4121. {
  4122. // phpcs:enable
  4123. global $langs;
  4124. if ($htmlname != "none")
  4125. {
  4126. print '<form method="post" action="'.$page.'">';
  4127. print '<input type="hidden" name="action" value="setavailability">';
  4128. print '<input type="hidden" name="token" value="'.newToken().'">';
  4129. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4130. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4131. print '</form>';
  4132. } else {
  4133. if ($selected)
  4134. {
  4135. $this->load_cache_availability();
  4136. print $this->cache_availability[$selected]['label'];
  4137. } else {
  4138. print "&nbsp;";
  4139. }
  4140. }
  4141. }
  4142. /**
  4143. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  4144. * List found into table c_input_reason loaded by loadCacheInputReason
  4145. *
  4146. * @param string $page Page
  4147. * @param string $selected Id condition pre-selectionne
  4148. * @param string $htmlname Name of select html field
  4149. * @param int $addempty Add empty entry
  4150. * @return void
  4151. */
  4152. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  4153. {
  4154. global $langs;
  4155. if ($htmlname != "none")
  4156. {
  4157. print '<form method="post" action="'.$page.'">';
  4158. print '<input type="hidden" name="action" value="setdemandreason">';
  4159. print '<input type="hidden" name="token" value="'.newToken().'">';
  4160. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  4161. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4162. print '</form>';
  4163. } else {
  4164. if ($selected)
  4165. {
  4166. $this->loadCacheInputReason();
  4167. foreach ($this->cache_demand_reason as $key => $val)
  4168. {
  4169. if ($val['id'] == $selected)
  4170. {
  4171. print $val['label'];
  4172. break;
  4173. }
  4174. }
  4175. } else {
  4176. print "&nbsp;";
  4177. }
  4178. }
  4179. }
  4180. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4181. /**
  4182. * Show a form + html select a date
  4183. *
  4184. * @param string $page Page
  4185. * @param string $selected Date preselected
  4186. * @param string $htmlname Html name of date input fields or 'none'
  4187. * @param int $displayhour Display hour selector
  4188. * @param int $displaymin Display minutes selector
  4189. * @param int $nooutput 1=No print output, return string
  4190. * @return string
  4191. * @see selectDate()
  4192. */
  4193. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0)
  4194. {
  4195. // phpcs:enable
  4196. global $langs;
  4197. $ret = '';
  4198. if ($htmlname != "none")
  4199. {
  4200. $ret .= '<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
  4201. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4202. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4203. $ret .= '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  4204. $ret .= '<tr><td>';
  4205. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4206. $ret .= '</td>';
  4207. $ret .= '<td class="left"><input type="submit smallpaddingimp" class="button" value="'.$langs->trans("Modify").'"></td>';
  4208. $ret .= '</tr></table></form>';
  4209. } else {
  4210. if ($displayhour) $ret .= dol_print_date($selected, 'dayhour');
  4211. else $ret .= dol_print_date($selected, 'day');
  4212. }
  4213. if (empty($nooutput)) print $ret;
  4214. return $ret;
  4215. }
  4216. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4217. /**
  4218. * Show a select form to choose a user
  4219. *
  4220. * @param string $page Page
  4221. * @param string $selected Id of user preselected
  4222. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4223. * @param array $exclude List of users id to exclude
  4224. * @param array $include List of users id to include
  4225. * @return void
  4226. */
  4227. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4228. {
  4229. // phpcs:enable
  4230. global $langs;
  4231. if ($htmlname != "none")
  4232. {
  4233. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4234. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4235. print '<input type="hidden" name="token" value="'.newToken().'">';
  4236. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  4237. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4238. print '</form>';
  4239. } else {
  4240. if ($selected)
  4241. {
  4242. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  4243. $theuser = new User($this->db);
  4244. $theuser->fetch($selected);
  4245. print $theuser->getNomUrl(1);
  4246. } else {
  4247. print "&nbsp;";
  4248. }
  4249. }
  4250. }
  4251. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4252. /**
  4253. * Show form with payment mode
  4254. *
  4255. * @param string $page Page
  4256. * @param int $selected Id mode pre-selectionne
  4257. * @param string $htmlname Name of select html field
  4258. * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
  4259. * @param int $active Active or not, -1 = all
  4260. * @param int $addempty 1=Add empty entry
  4261. * @return void
  4262. */
  4263. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0)
  4264. {
  4265. // phpcs:enable
  4266. global $langs;
  4267. if ($htmlname != "none")
  4268. {
  4269. print '<form method="POST" action="'.$page.'">';
  4270. print '<input type="hidden" name="action" value="setmode">';
  4271. print '<input type="hidden" name="token" value="'.newToken().'">';
  4272. $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active);
  4273. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4274. print '</form>';
  4275. } else {
  4276. if ($selected)
  4277. {
  4278. $this->load_cache_types_paiements();
  4279. print $this->cache_types_paiements[$selected]['label'];
  4280. } else {
  4281. print "&nbsp;";
  4282. }
  4283. }
  4284. }
  4285. /**
  4286. * Show form with transport mode
  4287. *
  4288. * @param string $page Page
  4289. * @param int $selected Id mode pre-select
  4290. * @param string $htmlname Name of select html field
  4291. * @param int $active Active or not, -1 = all
  4292. * @param int $addempty 1=Add empty entry
  4293. * @return void
  4294. */
  4295. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  4296. {
  4297. global $langs;
  4298. if ($htmlname != "none")
  4299. {
  4300. print '<form method="POST" action="'.$page.'">';
  4301. print '<input type="hidden" name="action" value="setmode">';
  4302. print '<input type="hidden" name="token" value="'.newToken().'">';
  4303. $this->selectTransportMode($selected, $htmlname, 2, $addempty, 0, 0, $active);
  4304. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4305. print '</form>';
  4306. }
  4307. else {
  4308. if ($selected)
  4309. {
  4310. $this->load_cache_transport_mode();
  4311. print $this->cache_transport_mode[$selected]['label'];
  4312. } else {
  4313. print "&nbsp;";
  4314. }
  4315. }
  4316. }
  4317. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4318. /**
  4319. * Show form with multicurrency code
  4320. *
  4321. * @param string $page Page
  4322. * @param string $selected code pre-selectionne
  4323. * @param string $htmlname Name of select html field
  4324. * @return void
  4325. */
  4326. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  4327. {
  4328. // phpcs:enable
  4329. global $langs;
  4330. if ($htmlname != "none")
  4331. {
  4332. print '<form method="POST" action="'.$page.'">';
  4333. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  4334. print '<input type="hidden" name="token" value="'.newToken().'">';
  4335. print $this->selectMultiCurrency($selected, $htmlname, 0);
  4336. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4337. print '</form>';
  4338. } else {
  4339. dol_include_once('/core/lib/company.lib.php');
  4340. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  4341. }
  4342. }
  4343. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4344. /**
  4345. * Show form with multicurrency rate
  4346. *
  4347. * @param string $page Page
  4348. * @param double $rate Current rate
  4349. * @param string $htmlname Name of select html field
  4350. * @param string $currency Currency code to explain the rate
  4351. * @return void
  4352. */
  4353. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  4354. {
  4355. // phpcs:enable
  4356. global $langs, $mysoc, $conf;
  4357. if ($htmlname != "none")
  4358. {
  4359. print '<form method="POST" action="'.$page.'">';
  4360. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  4361. print '<input type="hidden" name="token" value="'.newToken().'">';
  4362. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CR')) : 1).'" /> ';
  4363. print '<select name="calculation_mode">';
  4364. print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
  4365. print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
  4366. print '</select> ';
  4367. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4368. print '</form>';
  4369. } else {
  4370. if (!empty($rate))
  4371. {
  4372. print price($rate, 1, $langs, 1, 0);
  4373. if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  4374. } else {
  4375. print 1;
  4376. }
  4377. }
  4378. }
  4379. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4380. /**
  4381. * Show a select box with available absolute discounts
  4382. *
  4383. * @param string $page Page URL where form is shown
  4384. * @param int $selected Value pre-selected
  4385. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  4386. * @param int $socid Third party id
  4387. * @param float $amount Total amount available
  4388. * @param string $filter SQL filter on discounts
  4389. * @param int $maxvalue Max value for lines that can be selected
  4390. * @param string $more More string to add
  4391. * @param int $hidelist 1=Hide list
  4392. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  4393. * @return void
  4394. */
  4395. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  4396. {
  4397. // phpcs:enable
  4398. global $conf, $langs;
  4399. if ($htmlname != "none")
  4400. {
  4401. print '<form method="post" action="'.$page.'">';
  4402. print '<input type="hidden" name="action" value="setabsolutediscount">';
  4403. print '<input type="hidden" name="token" value="'.newToken().'">';
  4404. print '<div class="inline-block">';
  4405. if (!empty($discount_type)) {
  4406. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  4407. {
  4408. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4409. else $translationKey = 'HasCreditNoteFromSupplier';
  4410. } else {
  4411. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
  4412. else $translationKey = 'HasCreditNoteFromSupplier';
  4413. }
  4414. } else {
  4415. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  4416. {
  4417. if (!$filter || $filter == "fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4418. else $translationKey = 'CompanyHasCreditNote';
  4419. } else {
  4420. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
  4421. else $translationKey = 'CompanyHasCreditNote';
  4422. }
  4423. }
  4424. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  4425. if (empty($hidelist)) print ': ';
  4426. print '</div>';
  4427. if (empty($hidelist))
  4428. {
  4429. print '<div class="inline-block" style="padding-right: 10px">';
  4430. $newfilter = 'discount_type='.intval($discount_type);
  4431. if (!empty($discount_type)) {
  4432. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  4433. } else {
  4434. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  4435. }
  4436. if ($filter) $newfilter .= ' AND ('.$filter.')';
  4437. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  4438. if ($nbqualifiedlines > 0)
  4439. {
  4440. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  4441. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
  4442. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4443. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
  4444. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4445. print '>';
  4446. }
  4447. print '</div>';
  4448. }
  4449. if ($more)
  4450. {
  4451. print '<div class="inline-block">';
  4452. print $more;
  4453. print '</div>';
  4454. }
  4455. print '</form>';
  4456. } else {
  4457. if ($selected)
  4458. {
  4459. print $selected;
  4460. } else {
  4461. print "0";
  4462. }
  4463. }
  4464. }
  4465. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4466. /**
  4467. * Show forms to select a contact
  4468. *
  4469. * @param string $page Page
  4470. * @param Societe $societe Filter on third party
  4471. * @param int $selected Id contact pre-selectionne
  4472. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  4473. * @return void
  4474. */
  4475. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  4476. {
  4477. // phpcs:enable
  4478. global $langs, $conf;
  4479. if ($htmlname != "none")
  4480. {
  4481. print '<form method="post" action="'.$page.'">';
  4482. print '<input type="hidden" name="action" value="set_contact">';
  4483. print '<input type="hidden" name="token" value="'.newToken().'">';
  4484. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  4485. print '<tr><td>';
  4486. print $this->selectcontacts($societe->id, $selected, $htmlname);
  4487. $num = $this->num;
  4488. if ($num == 0)
  4489. {
  4490. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  4491. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  4492. }
  4493. print '</td>';
  4494. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  4495. print '</tr></table></form>';
  4496. } else {
  4497. if ($selected)
  4498. {
  4499. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  4500. $contact = new Contact($this->db);
  4501. $contact->fetch($selected);
  4502. print $contact->getFullName($langs);
  4503. } else {
  4504. print "&nbsp;";
  4505. }
  4506. }
  4507. }
  4508. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4509. /**
  4510. * Output html select to select thirdparty
  4511. *
  4512. * @param string $page Page
  4513. * @param string $selected Id preselected
  4514. * @param string $htmlname Name of HTML select
  4515. * @param string $filter optional filters criteras
  4516. * @param int $showempty Add an empty field
  4517. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  4518. * @param int $forcecombo Force to use combo box
  4519. * @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')))
  4520. * @param int $nooutput No print output. Return it only.
  4521. * @return void|string
  4522. */
  4523. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0)
  4524. {
  4525. // phpcs:enable
  4526. global $langs;
  4527. $out = '';
  4528. if ($htmlname != "none")
  4529. {
  4530. $out .= '<form method="post" action="'.$page.'">';
  4531. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  4532. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4533. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
  4534. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4535. $out .= '</form>';
  4536. } else {
  4537. if ($selected)
  4538. {
  4539. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  4540. $soc = new Societe($this->db);
  4541. $soc->fetch($selected);
  4542. $out .= $soc->getNomUrl($langs);
  4543. } else {
  4544. $out .= "&nbsp;";
  4545. }
  4546. }
  4547. if ($nooutput) return $out;
  4548. else print $out;
  4549. }
  4550. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4551. /**
  4552. * Retourne la liste des devises, dans la langue de l'utilisateur
  4553. *
  4554. * @param string $selected preselected currency code
  4555. * @param string $htmlname name of HTML select list
  4556. * @deprecated
  4557. * @return void
  4558. */
  4559. public function select_currency($selected = '', $htmlname = 'currency_id')
  4560. {
  4561. // phpcs:enable
  4562. print $this->selectCurrency($selected, $htmlname);
  4563. }
  4564. /**
  4565. * Retourne la liste des devises, dans la langue de l'utilisateur
  4566. *
  4567. * @param string $selected preselected currency code
  4568. * @param string $htmlname name of HTML select list
  4569. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  4570. * @return string
  4571. */
  4572. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0)
  4573. {
  4574. global $conf, $langs, $user;
  4575. $langs->loadCacheCurrencies('');
  4576. $out = '';
  4577. if ($selected == 'euro' || $selected == 'euros') $selected = 'EUR'; // Pour compatibilite
  4578. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  4579. foreach ($langs->cache_currencies as $code_iso => $currency)
  4580. {
  4581. $labeltoshow = $currency['label'];
  4582. if ($mode == 1)
  4583. {
  4584. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  4585. } else {
  4586. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  4587. }
  4588. if ($selected && $selected == $code_iso)
  4589. {
  4590. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  4591. } else {
  4592. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  4593. }
  4594. $out .= $labeltoshow;
  4595. $out .= '</option>';
  4596. }
  4597. $out .= '</select>';
  4598. if ($user->admin) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4599. // Make select dynamic
  4600. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  4601. $out .= ajax_combobox($htmlname);
  4602. return $out;
  4603. }
  4604. /**
  4605. * Return array of currencies in user language
  4606. *
  4607. * @param string $selected preselected currency code
  4608. * @param string $htmlname name of HTML select list
  4609. * @param integer $useempty 1=Add empty line
  4610. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  4611. * @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
  4612. * @return string
  4613. */
  4614. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false)
  4615. {
  4616. global $db, $conf, $langs, $user;
  4617. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  4618. $TCurrency = array();
  4619. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
  4620. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  4621. if ($filter) $sql .= " AND ".$filter;
  4622. $resql = $this->db->query($sql);
  4623. if ($resql)
  4624. {
  4625. while ($obj = $this->db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
  4626. }
  4627. $out = '';
  4628. $out .= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  4629. if ($useempty) $out .= '<option value="">&nbsp;</option>';
  4630. // If company current currency not in table, we add it into list. Should always be available.
  4631. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency)
  4632. {
  4633. $TCurrency[$conf->currency] = $conf->currency;
  4634. }
  4635. if (count($TCurrency) > 0)
  4636. {
  4637. foreach ($langs->cache_currencies as $code_iso => $currency)
  4638. {
  4639. if (isset($TCurrency[$code_iso]))
  4640. {
  4641. if (!empty($selected) && $selected == $code_iso) $out .= '<option value="'.$code_iso.'" selected="selected">';
  4642. else $out .= '<option value="'.$code_iso.'">';
  4643. $out .= $currency['label'];
  4644. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  4645. $out .= '</option>';
  4646. }
  4647. }
  4648. }
  4649. $out .= '</select>';
  4650. // Make select dynamic
  4651. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  4652. $out .= ajax_combobox($htmlname);
  4653. return $out;
  4654. }
  4655. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4656. /**
  4657. * Load into the cache vat rates of a country
  4658. *
  4659. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  4660. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  4661. */
  4662. public function load_cache_vatrates($country_code)
  4663. {
  4664. // phpcs:enable
  4665. global $langs;
  4666. $num = count($this->cache_vatrates);
  4667. if ($num > 0) return $num; // Cache already loaded
  4668. dol_syslog(__METHOD__, LOG_DEBUG);
  4669. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  4670. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4671. $sql .= " WHERE t.fk_pays = c.rowid";
  4672. $sql .= " AND t.active > 0";
  4673. $sql .= " AND c.code IN (".$country_code.")";
  4674. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  4675. $resql = $this->db->query($sql);
  4676. if ($resql)
  4677. {
  4678. $num = $this->db->num_rows($resql);
  4679. if ($num)
  4680. {
  4681. for ($i = 0; $i < $num; $i++)
  4682. {
  4683. $obj = $this->db->fetch_object($resql);
  4684. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  4685. $this->cache_vatrates[$i]['code'] = $obj->code;
  4686. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  4687. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  4688. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  4689. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  4690. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  4691. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  4692. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  4693. $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
  4694. $positiverates = '';
  4695. if ($obj->taux) $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  4696. if ($obj->localtax1) $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  4697. if ($obj->localtax2) $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  4698. if (empty($positiverates)) $positiverates = '0';
  4699. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  4700. }
  4701. return $num;
  4702. } else {
  4703. $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</font>';
  4704. return -1;
  4705. }
  4706. } else {
  4707. $this->error = '<font class="error">'.$this->db->error().'</font>';
  4708. return -2;
  4709. }
  4710. }
  4711. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4712. /**
  4713. * Output an HTML select vat rate.
  4714. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  4715. *
  4716. * @param string $htmlname Name of HTML select field
  4717. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  4718. * @param Societe $societe_vendeuse Thirdparty seller
  4719. * @param Societe $societe_acheteuse Thirdparty buyer
  4720. * @param int $idprod Id product. O if unknown of NA.
  4721. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  4722. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  4723. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4724. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4725. * 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.
  4726. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  4727. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  4728. * Sinon la TVA proposee par defaut=0. Fin de regle.
  4729. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  4730. * @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
  4731. * @return string
  4732. */
  4733. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  4734. {
  4735. // phpcs:enable
  4736. global $langs, $conf, $mysoc;
  4737. $langs->load('errors');
  4738. $return = '';
  4739. // Define defaultnpr, defaultttx and defaultcode
  4740. $defaultnpr = ($info_bits & 0x01);
  4741. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  4742. $defaulttx = str_replace('*', '', $selectedrate);
  4743. $defaultcode = '';
  4744. if (preg_match('/\((.*)\)/', $defaulttx, $reg))
  4745. {
  4746. $defaultcode = $reg[1];
  4747. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  4748. }
  4749. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  4750. // Check parameters
  4751. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code)
  4752. {
  4753. if ($societe_vendeuse->id == $mysoc->id)
  4754. {
  4755. $return .= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</font>';
  4756. } else {
  4757. $return .= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</font>';
  4758. }
  4759. return $return;
  4760. }
  4761. //var_dump($societe_acheteuse);
  4762. //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";
  4763. //exit;
  4764. // Define list of countries to use to search VAT rates to show
  4765. // First we defined code_country to use to find list
  4766. if (is_object($societe_vendeuse))
  4767. {
  4768. $code_country = "'".$societe_vendeuse->country_code."'";
  4769. } else {
  4770. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  4771. }
  4772. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on
  4773. {
  4774. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4775. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany())))
  4776. {
  4777. // We also add the buyer
  4778. if (is_numeric($type))
  4779. {
  4780. if ($type == 1) // We know product is a service
  4781. {
  4782. $code_country .= ",'".$societe_acheteuse->country_code."'";
  4783. }
  4784. } elseif (!$idprod) // We don't know type of product
  4785. {
  4786. $code_country .= ",'".$societe_acheteuse->country_code."'";
  4787. } else {
  4788. $prodstatic = new Product($this->db);
  4789. $prodstatic->fetch($idprod);
  4790. if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service
  4791. {
  4792. $code_country .= ",'".$societe_acheteuse->country_code."'";
  4793. }
  4794. }
  4795. }
  4796. }
  4797. // Now we get list
  4798. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  4799. if ($num > 0)
  4800. {
  4801. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  4802. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4803. {
  4804. $tmpthirdparty = new Societe($this->db);
  4805. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  4806. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  4807. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  4808. $defaultcode = $reg[1];
  4809. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  4810. }
  4811. if (empty($defaulttx)) $defaultnpr = 0;
  4812. }
  4813. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  4814. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  4815. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4816. {
  4817. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  4818. else $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  4819. }
  4820. // Disabled if seller is not subject to VAT
  4821. $disabled = false; $title = '';
  4822. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
  4823. {
  4824. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  4825. // of using supplier invoices (this is a very bad idea !)
  4826. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT))
  4827. {
  4828. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  4829. $disabled = true;
  4830. }
  4831. }
  4832. if (!$options_only) $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  4833. $selectedfound = false;
  4834. foreach ($this->cache_vatrates as $rate)
  4835. {
  4836. // Keep only 0 if seller is not subject to VAT
  4837. if ($disabled && $rate['txtva'] != 0) continue;
  4838. // Define key to use into select list
  4839. $key = $rate['txtva'];
  4840. $key .= $rate['nprtva'] ? '*' : '';
  4841. if ($mode > 0 && $rate['code']) $key .= ' ('.$rate['code'].')';
  4842. if ($mode < 0) $key = $rate['rowid'];
  4843. $return .= '<option value="'.$key.'"';
  4844. if (!$selectedfound)
  4845. {
  4846. if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  4847. {
  4848. if ($defaultcode == $rate['code'])
  4849. {
  4850. $return .= ' selected';
  4851. $selectedfound = true;
  4852. }
  4853. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
  4854. {
  4855. $return .= ' selected';
  4856. $selectedfound = true;
  4857. }
  4858. }
  4859. $return .= '>';
  4860. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  4861. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
  4862. {
  4863. $return .= $rate['labelpositiverates'];
  4864. } else {
  4865. $return .= vatrate($rate['label']);
  4866. }
  4867. //$return.=($rate['code']?' '.$rate['code']:'');
  4868. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  4869. $return .= '</option>';
  4870. }
  4871. if (!$options_only) $return .= '</select>';
  4872. } else {
  4873. $return .= $this->error;
  4874. }
  4875. $this->num = $num;
  4876. return $return;
  4877. }
  4878. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4879. /**
  4880. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4881. * Fields are preselected with :
  4882. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4883. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4884. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4885. *
  4886. * @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).
  4887. * @param string $prefix Prefix for fields name
  4888. * @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
  4889. * @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
  4890. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4891. * @param string $form_name Not used
  4892. * @param int $d 1=Show days, month, years
  4893. * @param int $addnowlink Add a link "Now"
  4894. * @param int $nooutput Do not output html string but return it
  4895. * @param int $disabled Disable input fields
  4896. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  4897. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  4898. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  4899. * @return string|void Nothing or string if nooutput is 1
  4900. * @deprecated
  4901. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  4902. */
  4903. 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 = '')
  4904. {
  4905. // phpcs:enable
  4906. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  4907. if (!empty($nooutput)) {
  4908. return $retstring;
  4909. }
  4910. print $retstring;
  4911. return;
  4912. }
  4913. /**
  4914. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4915. * Fields are preselected with :
  4916. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4917. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4918. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4919. *
  4920. * @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).
  4921. * @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).
  4922. * @param string $prefix Prefix for fields name
  4923. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4924. * @return string Html for selectDate
  4925. * @see form_date(), select_month(), select_year(), select_dayofweek()
  4926. */
  4927. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0)
  4928. {
  4929. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty);
  4930. $ret .= '<br/>';
  4931. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty);
  4932. return $ret;
  4933. }
  4934. /**
  4935. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4936. * Fields are preselected with :
  4937. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4938. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4939. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4940. *
  4941. * @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).
  4942. * @param string $prefix Prefix for fields name
  4943. * @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
  4944. * @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
  4945. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4946. * @param string $form_name Not used
  4947. * @param int $d 1=Show days, month, years
  4948. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  4949. * @param int $disabled Disable input fields
  4950. * @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')
  4951. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  4952. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  4953. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  4954. * @param int $stepminutes Specify step for minutes between 1 and 30
  4955. * @param string $labeladddateof Label to use for the $adddateof parameter.
  4956. * @param string $placeholder Placeholder
  4957. * @return string Html for selectDate
  4958. * @see form_date(), select_month(), select_year(), select_dayofweek()
  4959. */
  4960. 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 = '')
  4961. {
  4962. global $conf, $langs;
  4963. $retstring = '';
  4964. if ($prefix == '') $prefix = 're';
  4965. if ($h == '') $h = 0;
  4966. if ($m == '') $m = 0;
  4967. $emptydate = 0;
  4968. $emptyhours = 0;
  4969. if ($stepminutes <= 0 || $stepminutes > 30) $stepminutes = 1;
  4970. if ($empty == 1) { $emptydate = 1; $emptyhours = 1; }
  4971. if ($empty == 2) { $emptydate = 0; $emptyhours = 1; }
  4972. $orig_set_time = $set_time;
  4973. if ($set_time === '' && $emptydate == 0)
  4974. {
  4975. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4976. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  4977. }
  4978. // Analysis of the pre-selection date
  4979. $reg = array();
  4980. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) // deprecated usage
  4981. {
  4982. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  4983. $syear = (!empty($reg[1]) ? $reg[1] : '');
  4984. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  4985. $sday = (!empty($reg[3]) ? $reg[3] : '');
  4986. $shour = (!empty($reg[4]) ? $reg[4] : '');
  4987. $smin = (!empty($reg[5]) ? $reg[5] : '');
  4988. } elseif (strval($set_time) != '' && $set_time != -1)
  4989. {
  4990. // set_time est un timestamps (0 possible)
  4991. $syear = dol_print_date($set_time, "%Y");
  4992. $smonth = dol_print_date($set_time, "%m");
  4993. $sday = dol_print_date($set_time, "%d");
  4994. if ($orig_set_time != '')
  4995. {
  4996. $shour = dol_print_date($set_time, "%H");
  4997. $smin = dol_print_date($set_time, "%M");
  4998. $ssec = dol_print_date($set_time, "%S");
  4999. } else {
  5000. $shour = '';
  5001. $smin = '';
  5002. $ssec = '';
  5003. }
  5004. } else {
  5005. // Date est '' ou vaut -1
  5006. $syear = '';
  5007. $smonth = '';
  5008. $sday = '';
  5009. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5010. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5011. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5012. }
  5013. if ($h == 3) $shour = '';
  5014. if ($m == 3) $smin = '';
  5015. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5016. $usecalendar = 'combo';
  5017. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5018. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5019. }
  5020. if ($d)
  5021. {
  5022. // Show date with popup
  5023. if ($usecalendar != 'combo')
  5024. {
  5025. $formated_date = '';
  5026. //print "e".$set_time." t ".$conf->format_date_short;
  5027. if (strval($set_time) != '' && $set_time != -1)
  5028. {
  5029. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5030. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5031. }
  5032. // Calendrier popup version eldy
  5033. if ($usecalendar == "eldy")
  5034. {
  5035. // Zone de saisie manuelle de la date
  5036. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5037. $retstring .= ($disabled ? ' disabled' : '');
  5038. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5039. $retstring .= '>';
  5040. // Icone calendrier
  5041. if (!$disabled)
  5042. {
  5043. $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5044. $base = DOL_URL_ROOT.'/core/';
  5045. $retstring .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5046. $retstring .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5047. } else $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5048. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5049. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5050. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5051. } elseif ($usecalendar == 'jquery')
  5052. {
  5053. if (!$disabled)
  5054. {
  5055. // Output javascript for datepicker
  5056. $retstring .= "<script type='text/javascript'>";
  5057. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5058. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5059. autoclose: true,
  5060. todayHighlight: true,";
  5061. if (!empty($conf->dol_use_jmobile))
  5062. {
  5063. $retstring .= "
  5064. beforeShow: function (input, datePicker) {
  5065. input.disabled = true;
  5066. },
  5067. onClose: function (dateText, datePicker) {
  5068. this.disabled = false;
  5069. },
  5070. ";
  5071. }
  5072. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  5073. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))
  5074. {
  5075. $retstring .= "
  5076. showOn: 'button',
  5077. buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
  5078. buttonImageOnly: true";
  5079. }
  5080. $retstring .= "
  5081. }) });";
  5082. $retstring .= "</script>";
  5083. }
  5084. // Zone de saisie manuelle de la date
  5085. $retstring .= '<div class="nowrap inline-block">';
  5086. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5087. $retstring .= ($disabled ? ' disabled' : '');
  5088. $retstring .= ($placeholder ? ' placeholder="'.$placeholder.'"' : '');
  5089. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5090. $retstring .= '>';
  5091. // Icone calendrier
  5092. if (!$disabled)
  5093. {
  5094. /* Not required. Managed by option buttonImage of jquery
  5095. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  5096. $retstring.="<script type='text/javascript'>";
  5097. $retstring.="jQuery(document).ready(function() {";
  5098. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  5099. $retstring.=" jQuery('#".$prefix."').focus();";
  5100. $retstring.=' });';
  5101. $retstring.='});';
  5102. $retstring.="</script>";*/
  5103. } else {
  5104. $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5105. }
  5106. $retstring .= '</div>';
  5107. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5108. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5109. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5110. } else {
  5111. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  5112. }
  5113. }
  5114. // Show date with combo selects
  5115. else {
  5116. // Day
  5117. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  5118. if ($emptydate || $set_time == -1)
  5119. {
  5120. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5121. }
  5122. for ($day = 1; $day <= 31; $day++)
  5123. {
  5124. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  5125. }
  5126. $retstring .= "</select>";
  5127. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  5128. if ($emptydate || $set_time == -1)
  5129. {
  5130. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5131. }
  5132. // Month
  5133. for ($month = 1; $month <= 12; $month++)
  5134. {
  5135. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  5136. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  5137. $retstring .= "</option>";
  5138. }
  5139. $retstring .= "</select>";
  5140. // Year
  5141. if ($emptydate || $set_time == -1)
  5142. {
  5143. $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.'">';
  5144. } else {
  5145. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  5146. for ($year = $syear - 10; $year < $syear + 10; $year++)
  5147. {
  5148. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  5149. }
  5150. $retstring .= "</select>\n";
  5151. }
  5152. }
  5153. }
  5154. if ($d && $h) {
  5155. $retstring .= ($h == 2 ? '<br>' : ' ');
  5156. $retstring .= '<span class="nowraponall">';
  5157. }
  5158. if ($h)
  5159. {
  5160. $hourstart = 0;
  5161. $hourend = 24;
  5162. if ($openinghours != '') {
  5163. $openinghours = explode(',', $openinghours);
  5164. $hourstart = $openinghours[0];
  5165. $hourend = $openinghours[1];
  5166. if ($hourend < $hourstart) $hourend = $hourstart;
  5167. }
  5168. // Show hour
  5169. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  5170. if ($emptyhours) $retstring .= '<option value="-1">&nbsp;</option>';
  5171. for ($hour = $hourstart; $hour < $hourend; $hour++)
  5172. {
  5173. if (strlen($hour) < 2) $hour = "0".$hour;
  5174. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  5175. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  5176. $retstring .= '</option>';
  5177. }
  5178. $retstring .= '</select>';
  5179. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  5180. if ($m) $retstring .= ":";
  5181. }
  5182. if ($m)
  5183. {
  5184. // Show minutes
  5185. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  5186. if ($emptyhours) $retstring .= '<option value="-1">&nbsp;</option>';
  5187. for ($min = 0; $min < 60; $min += $stepminutes)
  5188. {
  5189. if (strlen($min) < 2) $min = "0".$min;
  5190. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  5191. }
  5192. $retstring .= '</select>';
  5193. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  5194. }
  5195. if ($d && $h) {
  5196. $retstring .= '</span>';
  5197. }
  5198. // Add a "Now" link
  5199. if ($conf->use_javascript_ajax && $addnowlink)
  5200. {
  5201. // Script which will be inserted in the onClick of the "Now" link
  5202. $reset_scripts = "";
  5203. if ($addnowlink == 2) // local computer time
  5204. {
  5205. // pad add leading 0 on numbers
  5206. $reset_scripts .= "Number.prototype.pad = function(size) {
  5207. var s = String(this);
  5208. while (s.length < (size || 2)) {s = '0' + s;}
  5209. return s;
  5210. };
  5211. var d = new Date();";
  5212. }
  5213. // Generate the date part, depending on the use or not of the javascript calendar
  5214. if ($addnowlink == 1) // server time expressed in user time setup
  5215. {
  5216. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');';
  5217. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');';
  5218. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');';
  5219. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');';
  5220. } elseif ($addnowlink == 2)
  5221. {
  5222. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  5223. * This break application for foreign languages.
  5224. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  5225. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  5226. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  5227. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  5228. */
  5229. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');';
  5230. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');';
  5231. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');';
  5232. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');';
  5233. }
  5234. /*if ($usecalendar == "eldy")
  5235. {
  5236. $base=DOL_URL_ROOT.'/core/';
  5237. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  5238. }
  5239. else
  5240. {
  5241. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  5242. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  5243. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  5244. }*/
  5245. // Update the hour part
  5246. if ($h)
  5247. {
  5248. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5249. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  5250. if ($addnowlink == 1)
  5251. {
  5252. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H', 'tzuser').'\');';
  5253. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5254. } elseif ($addnowlink == 2)
  5255. {
  5256. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  5257. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5258. }
  5259. if ($fullday) $reset_scripts .= ' } ';
  5260. }
  5261. // Update the minute part
  5262. if ($m)
  5263. {
  5264. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5265. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  5266. if ($addnowlink == 1)
  5267. {
  5268. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M', 'tzuser').'\');';
  5269. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5270. } elseif ($addnowlink == 2)
  5271. {
  5272. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  5273. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5274. }
  5275. if ($fullday) $reset_scripts .= ' } ';
  5276. }
  5277. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5278. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  5279. {
  5280. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  5281. $retstring .= $langs->trans("Now");
  5282. $retstring .= '</button> ';
  5283. }
  5284. }
  5285. // Add a "Plus one hour" link
  5286. if ($conf->use_javascript_ajax && $addplusone)
  5287. {
  5288. // Script which will be inserted in the onClick of the "Add plusone" link
  5289. $reset_scripts = "";
  5290. // Generate the date part, depending on the use or not of the javascript calendar
  5291. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day').'\');';
  5292. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d').'\');';
  5293. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m').'\');';
  5294. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y').'\');';
  5295. // Update the hour part
  5296. if ($h)
  5297. {
  5298. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5299. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H').'\');';
  5300. if ($fullday) $reset_scripts .= ' } ';
  5301. }
  5302. // Update the minute part
  5303. if ($m)
  5304. {
  5305. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5306. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M').'\');';
  5307. if ($fullday) $reset_scripts .= ' } ';
  5308. }
  5309. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5310. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  5311. {
  5312. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  5313. $retstring .= $langs->trans("DateStartPlusOne");
  5314. $retstring .= '</button> ';
  5315. }
  5316. }
  5317. // Add a "Plus one hour" link
  5318. if ($conf->use_javascript_ajax && $adddateof)
  5319. {
  5320. $tmparray = dol_getdate($adddateof);
  5321. if (empty($labeladddateof)) $labeladddateof = $langs->trans("DateInvoice");
  5322. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$labeladddateof.'</a>';
  5323. }
  5324. return $retstring;
  5325. }
  5326. /**
  5327. * selectTypeDuration
  5328. *
  5329. * @param string $prefix Prefix
  5330. * @param string $selected Selected type
  5331. * @return string HTML select string
  5332. */
  5333. public function selectTypeDuration($prefix, $selected = 'i')
  5334. {
  5335. global $langs;
  5336. $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month'), 'w'=>$langs->trans('Weeks'), 'd'=>$langs->trans('Days'), 'h'=>$langs->trans('Hours'), 'i'=>$langs->trans('Minutes'));
  5337. $retstring = '<select class="flat" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  5338. foreach ($TDurationTypes as $key=>$typeduration) {
  5339. $retstring .= '<option value="'.$key.'"';
  5340. if ($key == $selected) {
  5341. $retstring .= " selected";
  5342. }
  5343. $retstring .= ">".$typeduration."</option>";
  5344. }
  5345. $retstring .= "</select>";
  5346. return $retstring;
  5347. }
  5348. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5349. /**
  5350. * Function to show a form to select a duration on a page
  5351. *
  5352. * @param string $prefix Prefix for input fields
  5353. * @param int $iSecond Default preselected duration (number of seconds or '')
  5354. * @param int $disabled Disable the combo box
  5355. * @param string $typehour If 'select' then input hour and input min is a combo,
  5356. * If 'text' input hour is in text and input min is a text,
  5357. * If 'textselect' input hour is in text and input min is a combo
  5358. * @param integer $minunderhours If 1, show minutes selection under the hours
  5359. * @param int $nooutput Do not output html string but return it
  5360. * @return string|void
  5361. */
  5362. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  5363. {
  5364. // phpcs:enable
  5365. global $langs;
  5366. $retstring = '';
  5367. $hourSelected = 0; $minSelected = 0;
  5368. // Hours
  5369. if ($iSecond != '')
  5370. {
  5371. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5372. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  5373. $minSelected = convertSecondToTime($iSecond, 'min');
  5374. }
  5375. if ($typehour == 'select') {
  5376. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  5377. for ($hour = 0; $hour < 25; $hour++) // For a duration, we allow 24 hours
  5378. {
  5379. $retstring .= '<option value="'.$hour.'"';
  5380. if ($hourSelected == $hour)
  5381. {
  5382. $retstring .= " selected";
  5383. }
  5384. $retstring .= ">".$hour."</option>";
  5385. }
  5386. $retstring .= "</select>";
  5387. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  5388. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  5389. } else {
  5390. return 'BadValueForParameterTypeHour';
  5391. }
  5392. if ($typehour != 'text') $retstring .= ' '.$langs->trans('HourShort');
  5393. else $retstring .= '<span class="hideonsmartphone">:</span>';
  5394. // Minutes
  5395. if ($minunderhours) $retstring .= '<br>';
  5396. else $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  5397. if ($typehour == 'select' || $typehour == 'textselect')
  5398. {
  5399. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  5400. for ($min = 0; $min <= 55; $min = $min + 5)
  5401. {
  5402. $retstring .= '<option value="'.$min.'"';
  5403. if ($minSelected == $min) $retstring .= ' selected';
  5404. $retstring .= '>'.$min.'</option>';
  5405. }
  5406. $retstring .= "</select>";
  5407. } elseif ($typehour == 'text')
  5408. {
  5409. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  5410. }
  5411. if ($typehour != 'text') $retstring .= ' '.$langs->trans('MinuteShort');
  5412. //$retstring.="&nbsp;";
  5413. if (!empty($nooutput)) return $retstring;
  5414. print $retstring;
  5415. return;
  5416. }
  5417. /**
  5418. * Generic method to select a component from a combo list.
  5419. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  5420. * This is the generic method that will replace all specific existing methods.
  5421. *
  5422. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]
  5423. * @param string $htmlname Name of HTML select component
  5424. * @param int $preselectedvalue Preselected value (ID of element)
  5425. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  5426. * @param string $searchkey Search criteria
  5427. * @param string $placeholder Place holder
  5428. * @param string $morecss More CSS
  5429. * @param string $moreparams More params provided to ajax call
  5430. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  5431. * @param int $disabled 1=Html component is disabled
  5432. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  5433. * @return string Return HTML string
  5434. * @see selectForFormsList() select_thirdparty_list()
  5435. */
  5436. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  5437. {
  5438. global $conf, $user;
  5439. $objecttmp = null;
  5440. $InfoFieldList = explode(":", $objectdesc);
  5441. $classname = $InfoFieldList[0];
  5442. $classpath = $InfoFieldList[1];
  5443. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  5444. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  5445. if (!empty($classpath))
  5446. {
  5447. dol_include_once($classpath);
  5448. if ($classname && class_exists($classname))
  5449. {
  5450. $objecttmp = new $classname($this->db);
  5451. // Make some replacement
  5452. $sharedentities = getEntity(strtolower($classname));
  5453. $objecttmp->filter = str_replace(
  5454. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  5455. array($conf->entity, $sharedentities, $user->id),
  5456. $filter);
  5457. }
  5458. }
  5459. if (!is_object($objecttmp))
  5460. {
  5461. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  5462. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  5463. }
  5464. //var_dump($objecttmp->filter);
  5465. $prefixforautocompletemode = $objecttmp->element;
  5466. if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode = 'company';
  5467. if ($prefixforautocompletemode == 'product') $prefixforautocompletemode = 'produit';
  5468. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  5469. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  5470. $out = '';
  5471. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo)
  5472. {
  5473. // No immediate load of all database
  5474. $placeholder = '';
  5475. if ($preselectedvalue && empty($selected_input_value))
  5476. {
  5477. $objecttmp->fetch($preselectedvalue);
  5478. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  5479. //unset($objecttmp);
  5480. }
  5481. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  5482. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  5483. // No immediate load of all database
  5484. $urloption = 'htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.'&filter='.urlencode($objecttmp->filter);
  5485. // Activate the auto complete using ajax call.
  5486. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  5487. $out .= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
  5488. if ($placeholder) $placeholder = ' placeholder="'.$placeholder.'"';
  5489. $out .= '<input type="text" class="'.$morecss.'"'.($disabled ? ' disabled="disabled"' : '').' name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
  5490. } else {
  5491. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  5492. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled);
  5493. }
  5494. return $out;
  5495. }
  5496. /**
  5497. * Function to forge a SQL criteria
  5498. *
  5499. * @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"
  5500. * @return string Forged criteria. Example: "t.field like 'abc%'"
  5501. */
  5502. protected static function forgeCriteriaCallback($matches)
  5503. {
  5504. global $db;
  5505. //dol_syslog("Convert matches ".$matches[1]);
  5506. if (empty($matches[1])) return '';
  5507. $tmp = explode(':', $matches[1]);
  5508. if (count($tmp) < 3) return '';
  5509. $tmpescaped = $tmp[2];
  5510. $regbis = array();
  5511. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis))
  5512. {
  5513. $tmpescaped = "'".$db->escape($regbis[1])."'";
  5514. } else {
  5515. $tmpescaped = $db->escape($tmpescaped);
  5516. }
  5517. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  5518. }
  5519. /**
  5520. * Output html form to select an object.
  5521. * Note, this function is called by selectForForms or by ajax selectobject.php
  5522. *
  5523. * @param Object $objecttmp Object to knwo the table to scan for combo.
  5524. * @param string $htmlname Name of HTML select component
  5525. * @param int $preselectedvalue Preselected value (ID of element)
  5526. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  5527. * @param string $searchkey Search value
  5528. * @param string $placeholder Place holder
  5529. * @param string $morecss More CSS
  5530. * @param string $moreparams More params provided to ajax call
  5531. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  5532. * @param int $outputmode 0=HTML select string, 1=Array
  5533. * @param int $disabled 1=Html component is disabled
  5534. * @return string|array Return HTML string
  5535. * @see selectForForms()
  5536. */
  5537. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0)
  5538. {
  5539. global $conf, $langs, $user;
  5540. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  5541. $prefixforautocompletemode = $objecttmp->element;
  5542. if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode = 'company';
  5543. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  5544. if (!empty($objecttmp->fields)) // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  5545. {
  5546. $tmpfieldstoshow = '';
  5547. foreach ($objecttmp->fields as $key => $val)
  5548. {
  5549. if ($val['showoncombobox']) $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  5550. }
  5551. if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
  5552. } else {
  5553. // For backward compatibility
  5554. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  5555. }
  5556. if (empty($fieldstoshow))
  5557. {
  5558. if (isset($objecttmp->fields['ref'])) {
  5559. $fieldstoshow = 't.ref';
  5560. } else {
  5561. $langs->load("errors");
  5562. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  5563. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  5564. }
  5565. }
  5566. $out = '';
  5567. $outarray = array();
  5568. $num = 0;
  5569. // Search data
  5570. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX.$objecttmp->table_element." as t";
  5571. if (isset($objecttmp->ismultientitymanaged) && !is_numeric($objecttmp->ismultientitymanaged)) {
  5572. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  5573. $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.$tmparray[1].' as parenttable ON parenttable.rowid = t.'.$tmparray[0];
  5574. }
  5575. if ($objecttmp->ismultientitymanaged == 'fk_soc@societe')
  5576. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  5577. $sql .= " WHERE 1=1";
  5578. if (isset($objecttmp->ismultientitymanaged) && $objecttmp->ismultientitymanaged == 1) $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  5579. if (isset($objecttmp->ismultientitymanaged) && !is_numeric($objecttmp->ismultientitymanaged)) {
  5580. $sql .= ' AND parenttable.entity = t.'.$tmparray[0];
  5581. }
  5582. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  5583. if ($objecttmp->element == 'societe') $sql .= " AND t.rowid = ".$user->socid;
  5584. else $sql .= " AND t.fk_soc = ".$user->socid;
  5585. }
  5586. if ($searchkey != '') $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  5587. if ($objecttmp->ismultientitymanaged == 'fk_soc@societe') {
  5588. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
  5589. }
  5590. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  5591. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  5592. {
  5593. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  5594. }*/
  5595. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  5596. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  5597. }
  5598. $sql .= $this->db->order($fieldstoshow, "ASC");
  5599. //$sql.=$this->db->plimit($limit, 0);
  5600. //print $sql;
  5601. // Build output string
  5602. $resql = $this->db->query($sql);
  5603. if ($resql)
  5604. {
  5605. if (!$forcecombo)
  5606. {
  5607. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5608. $out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);
  5609. }
  5610. // Construct $out and $outarray
  5611. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  5612. // 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
  5613. $textifempty = '&nbsp;';
  5614. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  5615. if (!empty($conf->global->$confkeyforautocompletemode))
  5616. {
  5617. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  5618. else $textifempty .= $langs->trans("All");
  5619. }
  5620. if ($showempty) $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  5621. $num = $this->db->num_rows($resql);
  5622. $i = 0;
  5623. if ($num)
  5624. {
  5625. while ($i < $num)
  5626. {
  5627. $obj = $this->db->fetch_object($resql);
  5628. $label = '';
  5629. $tmparray = explode(',', $fieldstoshow);
  5630. foreach ($tmparray as $key => $val)
  5631. {
  5632. $val = preg_replace('/t\./', '', $val);
  5633. $label .= (($label && $obj->$val) ? ' - ' : '').$obj->$val;
  5634. }
  5635. if (empty($outputmode))
  5636. {
  5637. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
  5638. {
  5639. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  5640. } else {
  5641. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  5642. }
  5643. } else {
  5644. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  5645. }
  5646. $i++;
  5647. if (($i % 10) == 0) $out .= "\n";
  5648. }
  5649. }
  5650. $out .= '</select>'."\n";
  5651. } else {
  5652. dol_print_error($this->db);
  5653. }
  5654. $this->result = array('nbofelement'=>$num);
  5655. if ($outputmode) return $outarray;
  5656. return $out;
  5657. }
  5658. /**
  5659. * Return a HTML select string, built from an array of key+value.
  5660. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  5661. *
  5662. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  5663. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  5664. * @param string|string[] $id Preselected key or preselected keys for multiselect
  5665. * @param int|string $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.
  5666. * @param int $key_in_label 1 to show key into label with format "[key] value"
  5667. * @param int $value_as_key 1 to use value as key
  5668. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  5669. * @param int $translate 1=Translate and encode value
  5670. * @param int $maxlen Length maximum for labels
  5671. * @param int $disabled Html select box is disabled
  5672. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  5673. * @param string $morecss Add more class to css styles
  5674. * @param int $addjscombo Add js combo
  5675. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  5676. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  5677. * @param int $nohtmlescape No html escaping.
  5678. * @return string HTML select string.
  5679. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  5680. */
  5681. 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 = 0, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  5682. {
  5683. global $conf, $langs;
  5684. // Do we want a multiselect ?
  5685. //$jsbeautify = 0;
  5686. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  5687. $jsbeautify = 1;
  5688. if ($value_as_key) $array = array_combine($array, $array);
  5689. $out = '';
  5690. // Add code for jquery to use multiselect
  5691. if ($addjscombo && $jsbeautify)
  5692. {
  5693. $minLengthToAutocomplete = 0;
  5694. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ? (constant('REQUIRE_JQUERY_MULTISELECT') ?constant('REQUIRE_JQUERY_MULTISELECT') : 'select2') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  5695. // Enhance with select2
  5696. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5697. $out .= ajax_combobox($htmlname);
  5698. }
  5699. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  5700. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  5701. $out .= '>';
  5702. if ($show_empty)
  5703. {
  5704. $textforempty = ' ';
  5705. if (!empty($conf->use_javascript_ajax)) $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  5706. if (!is_numeric($show_empty)) $textforempty = $show_empty;
  5707. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  5708. }
  5709. if (is_array($array))
  5710. {
  5711. // Translate
  5712. if ($translate)
  5713. {
  5714. foreach ($array as $key => $value)
  5715. {
  5716. if (!is_array($value)) $array[$key] = $langs->trans($value);
  5717. else $array[$key]['label'] = $langs->trans($value['label']);
  5718. }
  5719. }
  5720. // Sort
  5721. if ($sort == 'ASC') asort($array);
  5722. elseif ($sort == 'DESC') arsort($array);
  5723. foreach ($array as $key => $tmpvalue)
  5724. {
  5725. if (is_array($tmpvalue)) {
  5726. $value = $tmpvalue['label'];
  5727. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  5728. $style = empty($tmpvalue['css']) ? ' class="'.$tmpvalue['css'].'"' : '';
  5729. } else {
  5730. $value = $tmpvalue;
  5731. $disabled = ''; $style = '';
  5732. }
  5733. if (!empty($disablebademail))
  5734. {
  5735. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  5736. || ($disablebademail == 2 && preg_match('/---/', $value)))
  5737. {
  5738. $disabled = ' disabled';
  5739. $style = ' class="warning"';
  5740. }
  5741. }
  5742. if ($key_in_label)
  5743. {
  5744. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  5745. else $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  5746. } else {
  5747. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  5748. else $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  5749. if ($value == '' || $value == '-') $selectOptionValue = '&nbsp;';
  5750. }
  5751. $out .= '<option value="'.$key.'"';
  5752. $out .= $style.$disabled;
  5753. if (is_array($id)) {
  5754. if (in_array($key, $id) && !$disabled) $out .= ' selected'; // To preselect a value
  5755. } else {
  5756. $id = (string) $id; // if $id = 0, then $id = '0'
  5757. if ($id != '' && $id == $key && !$disabled) $out .= ' selected'; // To preselect a value
  5758. }
  5759. if ($nohtmlescape) $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  5760. if (is_array($tmpvalue))
  5761. {
  5762. foreach ($tmpvalue as $keyforvalue => $valueforvalue)
  5763. {
  5764. if (preg_match('/^data-/', $keyforvalue)) $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  5765. }
  5766. }
  5767. $out .= '>';
  5768. //var_dump($selectOptionValue);
  5769. $out .= $selectOptionValue;
  5770. $out .= "</option>\n";
  5771. }
  5772. }
  5773. $out .= "</select>";
  5774. return $out;
  5775. }
  5776. /**
  5777. * 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.
  5778. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  5779. *
  5780. * @param string $htmlname Name of html select area
  5781. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  5782. * @param string $id Preselected key
  5783. * @param string $moreparam Add more parameters onto the select tag
  5784. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  5785. * @param int $disabled Html select box is disabled
  5786. * @param int $minimumInputLength Minimum Input Length
  5787. * @param string $morecss Add more class to css styles
  5788. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  5789. * @param string $placeholder String to use as placeholder
  5790. * @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)
  5791. * @return string HTML select string
  5792. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  5793. */
  5794. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  5795. {
  5796. global $conf, $langs;
  5797. global $delayedhtmlcontent;
  5798. // TODO Use an internal dolibarr component instead of select2
  5799. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return '';
  5800. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  5801. $tmpplugin = 'select2';
  5802. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  5803. <script>
  5804. $(document).ready(function () {
  5805. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  5806. $(".'.$htmlname.'").select2({
  5807. ajax: {
  5808. dir: "ltr",
  5809. url: "'.$url.'",
  5810. dataType: \'json\',
  5811. delay: 250,
  5812. data: function (params) {
  5813. return {
  5814. q: params.term, // search term
  5815. page: params.page
  5816. };
  5817. },
  5818. processResults: function (data) {
  5819. // parse the results into the format expected by Select2.
  5820. // since we are using custom formatting functions we do not need to alter the remote JSON data
  5821. //console.log(data);
  5822. saveRemoteData = data;
  5823. /* format json result for select2 */
  5824. result = []
  5825. $.each( data, function( key, value ) {
  5826. result.push({id: key, text: value.text});
  5827. });
  5828. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  5829. //console.log(result);
  5830. return {results: result, more: false}
  5831. },
  5832. cache: true
  5833. },
  5834. language: select2arrayoflanguage,
  5835. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  5836. placeholder: "'.dol_escape_js($placeholder).'",
  5837. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  5838. minimumInputLength: '.$minimumInputLength.',
  5839. formatResult: function(result, container, query, escapeMarkup) {
  5840. return escapeMarkup(result.text);
  5841. },
  5842. });
  5843. '.($callurlonselect ? '
  5844. /* Code to execute a GET when we select a value */
  5845. $(".'.$htmlname.'").change(function() {
  5846. var selected = $(".'.$htmlname.'").val();
  5847. console.log("We select in selectArrayAjax the entry "+selected)
  5848. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  5849. $.each( saveRemoteData, function( key, value ) {
  5850. if (key == selected)
  5851. {
  5852. console.log("selectArrayAjax - Do a redirect to "+value.url)
  5853. location.assign(value.url);
  5854. }
  5855. });
  5856. });' : '').'
  5857. });
  5858. </script>';
  5859. if ($acceptdelayedhtml)
  5860. {
  5861. $delayedhtmlcontent .= $outdelayed;
  5862. } else {
  5863. $out .= $outdelayed;
  5864. }
  5865. return $out;
  5866. }
  5867. /**
  5868. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  5869. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  5870. *
  5871. * @param string $htmlname Name of html select area
  5872. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  5873. * @param string $id Preselected key
  5874. * @param string $moreparam Add more parameters onto the select tag
  5875. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  5876. * @param int $disabled Html select box is disabled
  5877. * @param int $minimumInputLength Minimum Input Length
  5878. * @param string $morecss Add more class to css styles
  5879. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  5880. * @param string $placeholder String to use as placeholder
  5881. * @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)
  5882. * @return string HTML select string
  5883. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  5884. */
  5885. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  5886. {
  5887. global $conf, $langs;
  5888. global $delayedhtmlcontent;
  5889. // TODO Use an internal dolibarr component instead of select2
  5890. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return '';
  5891. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  5892. $formattedarrayresult = array();
  5893. foreach ($array as $key => $value) {
  5894. $o = new stdClass();
  5895. $o->id = $key;
  5896. $o->text = $value['text'];
  5897. $o->url = $value['url'];
  5898. $formattedarrayresult[] = $o;
  5899. }
  5900. $tmpplugin = 'select2';
  5901. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  5902. <script>
  5903. $(document).ready(function () {
  5904. var data = '.json_encode($formattedarrayresult).';
  5905. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  5906. $(".'.$htmlname.'").select2({
  5907. data: data,
  5908. language: select2arrayoflanguage,
  5909. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  5910. placeholder: "'.dol_escape_js($placeholder).'",
  5911. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  5912. minimumInputLength: '.$minimumInputLength.',
  5913. formatResult: function(result, container, query, escapeMarkup) {
  5914. return escapeMarkup(result.text);
  5915. },
  5916. matcher: function (params, data) {
  5917. if(! data.id) return null;';
  5918. if ($callurlonselect) {
  5919. $outdelayed .= '
  5920. var urlBase = data.url;
  5921. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  5922. /* console.log("params.term="+params.term); */
  5923. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  5924. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  5925. }
  5926. if (!$disableFiltering) {
  5927. $outdelayed .= '
  5928. if(data.text.match(new RegExp(params.term))) {
  5929. return data;
  5930. }
  5931. return null;';
  5932. } else {
  5933. $outdelayed .= '
  5934. return data;';
  5935. }
  5936. $outdelayed .= '
  5937. }
  5938. });
  5939. '.($callurlonselect ? '
  5940. /* Code to execute a GET when we select a value */
  5941. $(".'.$htmlname.'").change(function() {
  5942. var selected = $(".'.$htmlname.'").val();
  5943. console.log("We select "+selected)
  5944. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  5945. $.each( saveRemoteData, function( key, value ) {
  5946. if (key == selected)
  5947. {
  5948. console.log("selectArrayFilter - Do a redirect to "+value.url)
  5949. location.assign(value.url);
  5950. }
  5951. });
  5952. });' : '').'
  5953. });
  5954. </script>';
  5955. if ($acceptdelayedhtml)
  5956. {
  5957. $delayedhtmlcontent .= $outdelayed;
  5958. } else {
  5959. $out .= $outdelayed;
  5960. }
  5961. return $out;
  5962. }
  5963. /**
  5964. * Show a multiselect form from an array.
  5965. *
  5966. * @param string $htmlname Name of select
  5967. * @param array $array Array with key+value
  5968. * @param array $selected Array with key+value preselected
  5969. * @param int $key_in_label 1 to show key like in "[key] value"
  5970. * @param int $value_as_key 1 to use value as key
  5971. * @param string $morecss Add more css style
  5972. * @param int $translate Translate and encode value
  5973. * @param int $width Force width of select box. May be used only when using jquery couch. Example: 250, 95%
  5974. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  5975. * @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.
  5976. * @param string $placeholder String to use as placeholder
  5977. * @param int $addjscombo Add js combo
  5978. * @return string HTML multiselect string
  5979. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  5980. */
  5981. 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)
  5982. {
  5983. global $conf, $langs;
  5984. $out = '';
  5985. if ($addjscombo < 0) {
  5986. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $addjscombo = 1;
  5987. else $addjscombo = 0;
  5988. }
  5989. // Add code for jquery to use multiselect
  5990. if (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
  5991. {
  5992. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.' -->
  5993. <script>'."\n";
  5994. if ($addjscombo == 1)
  5995. {
  5996. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  5997. $out .= 'function formatResult(record) {'."\n";
  5998. if ($elemtype == 'category')
  5999. {
  6000. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  6001. } else {
  6002. $out .= 'return record.text;';
  6003. }
  6004. $out .= '};'."\n";
  6005. $out .= 'function formatSelection(record) {'."\n";
  6006. if ($elemtype == 'category')
  6007. {
  6008. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  6009. } else {
  6010. $out .= 'return record.text;';
  6011. }
  6012. $out .= '};'."\n";
  6013. $out .= '$(document).ready(function () {
  6014. $(\'#'.$htmlname.'\').'.$tmpplugin.'({
  6015. dir: \'ltr\',
  6016. // Specify format function for dropdown item
  6017. formatResult: formatResult,
  6018. templateResult: formatResult, /* For 4.0 */
  6019. // Specify format function for selected item
  6020. formatSelection: formatSelection,
  6021. templateSelection: formatSelection /* For 4.0 */
  6022. });
  6023. });'."\n";
  6024. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT'))
  6025. {
  6026. // Add other js lib
  6027. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  6028. // ...
  6029. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  6030. $out .= '$(document).ready(function () {
  6031. $(\'#'.$htmlname.'\').multiSelect({
  6032. containerHTML: \'<div class="multi-select-container">\',
  6033. menuHTML: \'<div class="multi-select-menu">\',
  6034. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  6035. menuItemHTML: \'<label class="multi-select-menuitem">\',
  6036. activeClass: \'multi-select-container--open\',
  6037. noneText: \''.$placeholder.'\'
  6038. });
  6039. })';
  6040. }
  6041. $out .= '</script>';
  6042. }
  6043. // Try also magic suggest
  6044. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  6045. if (is_array($array) && !empty($array))
  6046. {
  6047. if ($value_as_key) $array = array_combine($array, $array);
  6048. if (!empty($array))
  6049. {
  6050. foreach ($array as $key => $value)
  6051. {
  6052. $newval = ($translate ? $langs->trans($value) : $value);
  6053. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  6054. $out .= '<option value="'.$key.'"';
  6055. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != ''))
  6056. {
  6057. $out .= ' selected';
  6058. }
  6059. $out .= ' data-html="'.$newval.'"';
  6060. $out .= '>';
  6061. $out .= dol_htmlentitiesbr($newval);
  6062. $out .= '</option>'."\n";
  6063. }
  6064. }
  6065. }
  6066. $out .= '</select>'."\n";
  6067. return $out;
  6068. }
  6069. /**
  6070. * Show a multiselect dropbox from an array.
  6071. *
  6072. * @param string $htmlname Name of HTML field
  6073. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  6074. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  6075. * @return string HTML multiselect string
  6076. * @see selectarray()
  6077. */
  6078. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  6079. {
  6080. global $conf, $langs, $user, $extrafields;
  6081. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
  6082. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved seleteced properties
  6083. if (!empty($user->conf->$tmpvar))
  6084. {
  6085. $tmparray = explode(',', $user->conf->$tmpvar);
  6086. foreach ($array as $key => $val)
  6087. {
  6088. //var_dump($key);
  6089. //var_dump($tmparray);
  6090. if (in_array($key, $tmparray)) $array[$key]['checked'] = 1;
  6091. else $array[$key]['checked'] = 0;
  6092. }
  6093. }
  6094. $lis = '';
  6095. $listcheckedstring = '';
  6096. foreach ($array as $key => $val)
  6097. {
  6098. /* var_dump($val);
  6099. var_dump(array_key_exists('enabled', $val));
  6100. var_dump(!$val['enabled']);*/
  6101. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled'])
  6102. {
  6103. unset($array[$key]); // We don't want this field
  6104. continue;
  6105. }
  6106. if ($val['label'])
  6107. {
  6108. if (!empty($val['langfile']) && is_object($langs)) {
  6109. $langs->load($val['langfile']);
  6110. }
  6111. $lis .= '<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked']) ? '' : ' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
  6112. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  6113. }
  6114. }
  6115. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  6116. <dl class="dropdown">
  6117. <dt>
  6118. <a href="#'.$htmlname.'">
  6119. '.img_picto('', 'list').'
  6120. </a>
  6121. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  6122. </dt>
  6123. <dd class="dropdowndd">
  6124. <div class="multiselectcheckbox'.$htmlname.'">
  6125. <ul class="ul'.$htmlname.'">
  6126. '.$lis.'
  6127. </ul>
  6128. </div>
  6129. </dd>
  6130. </dl>
  6131. <script type="text/javascript">
  6132. jQuery(document).ready(function () {
  6133. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  6134. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  6135. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  6136. var title = $(this).val() + ",";
  6137. if ($(this).is(\':checked\')) {
  6138. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  6139. }
  6140. else {
  6141. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  6142. }
  6143. // Now, we submit page
  6144. //$(this).parents(\'form:first\').submit();
  6145. });
  6146. });
  6147. </script>
  6148. ';
  6149. return $out;
  6150. }
  6151. /**
  6152. * Render list of categories linked to object with id $id and type $type
  6153. *
  6154. * @param int $id Id of object
  6155. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  6156. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  6157. * @param int $nolink 1=Do not add html links
  6158. * @return string String with categories
  6159. */
  6160. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  6161. {
  6162. global $db;
  6163. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6164. $cat = new Categorie($db);
  6165. $categories = $cat->containing($id, $type);
  6166. if ($rendermode == 1)
  6167. {
  6168. $toprint = array();
  6169. foreach ($categories as $c)
  6170. {
  6171. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  6172. foreach ($ways as $way)
  6173. {
  6174. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  6175. }
  6176. }
  6177. return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6178. }
  6179. if ($rendermode == 0)
  6180. {
  6181. $arrayselected = array();
  6182. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  6183. foreach ($categories as $c) {
  6184. $arrayselected[] = $c->id;
  6185. }
  6186. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  6187. }
  6188. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  6189. }
  6190. /**
  6191. * Show linked object block.
  6192. *
  6193. * @param CommonObject $object Object we want to show links to
  6194. * @param string $morehtmlright More html to show on right of title
  6195. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  6196. * @return int <0 if KO, >=0 if OK
  6197. */
  6198. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
  6199. {
  6200. global $conf, $langs, $hookmanager;
  6201. global $bc, $action;
  6202. $object->fetchObjectLinked();
  6203. // Bypass the default method
  6204. $hookmanager->initHooks(array('commonobject'));
  6205. $parameters = array(
  6206. 'morehtmlright' => $morehtmlright,
  6207. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  6208. );
  6209. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  6210. if (empty($reshook))
  6211. {
  6212. $nbofdifferenttypes = count($object->linkedObjects);
  6213. print '<!-- showLinkedObjectBlock -->';
  6214. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  6215. print '<div class="div-table-responsive-no-min">';
  6216. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  6217. print '<tr class="liste_titre">';
  6218. print '<td>'.$langs->trans("Type").'</td>';
  6219. print '<td>'.$langs->trans("Ref").'</td>';
  6220. print '<td class="center"></td>';
  6221. print '<td class="center">'.$langs->trans("Date").'</td>';
  6222. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  6223. print '<td class="right">'.$langs->trans("Status").'</td>';
  6224. print '<td></td>';
  6225. print '</tr>';
  6226. $nboftypesoutput = 0;
  6227. foreach ($object->linkedObjects as $objecttype => $objects)
  6228. {
  6229. $tplpath = $element = $subelement = $objecttype;
  6230. // to display inport button on tpl
  6231. $showImportButton = false;
  6232. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  6233. $showImportButton = true;
  6234. }
  6235. $regs = array();
  6236. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
  6237. {
  6238. $element = $regs[1];
  6239. $subelement = $regs[2];
  6240. $tplpath = $element.'/'.$subelement;
  6241. }
  6242. $tplname = 'linkedobjectblock';
  6243. // To work with non standard path
  6244. if ($objecttype == 'facture') {
  6245. $tplpath = 'compta/'.$element;
  6246. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  6247. } elseif ($objecttype == 'facturerec') {
  6248. $tplpath = 'compta/facture';
  6249. $tplname = 'linkedobjectblockForRec';
  6250. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  6251. } elseif ($objecttype == 'propal') {
  6252. $tplpath = 'comm/'.$element;
  6253. if (empty($conf->propal->enabled)) continue; // Do not show if module disabled
  6254. } elseif ($objecttype == 'supplier_proposal') {
  6255. if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled
  6256. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  6257. $tplpath = 'expedition';
  6258. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  6259. } elseif ($objecttype == 'reception') {
  6260. $tplpath = 'reception';
  6261. if (empty($conf->reception->enabled)) continue; // Do not show if module disabled
  6262. } elseif ($objecttype == 'delivery') {
  6263. $tplpath = 'delivery';
  6264. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  6265. } elseif ($objecttype == 'invoice_supplier') {
  6266. $tplpath = 'fourn/facture';
  6267. } elseif ($objecttype == 'order_supplier') {
  6268. $tplpath = 'fourn/commande';
  6269. } elseif ($objecttype == 'expensereport') {
  6270. $tplpath = 'expensereport';
  6271. } elseif ($objecttype == 'subscription') {
  6272. $tplpath = 'adherents';
  6273. }
  6274. global $linkedObjectBlock;
  6275. $linkedObjectBlock = $objects;
  6276. // Output template part (modules that overwrite templates must declare this into descriptor)
  6277. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  6278. foreach ($dirtpls as $reldir)
  6279. {
  6280. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) // No more type to show after
  6281. {
  6282. global $noMoreLinkedObjectBlockAfter;
  6283. $noMoreLinkedObjectBlockAfter = 1;
  6284. }
  6285. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  6286. if ($res)
  6287. {
  6288. $nboftypesoutput++;
  6289. break;
  6290. }
  6291. }
  6292. }
  6293. if (!$nboftypesoutput)
  6294. {
  6295. print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
  6296. }
  6297. print '</table>';
  6298. if (!empty($compatibleImportElementsList))
  6299. {
  6300. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  6301. }
  6302. print '</div>';
  6303. return $nbofdifferenttypes;
  6304. }
  6305. }
  6306. /**
  6307. * Show block with links to link to other objects.
  6308. *
  6309. * @param CommonObject $object Object we want to show links to
  6310. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  6311. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  6312. * @return string <0 if KO, >0 if OK
  6313. */
  6314. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  6315. {
  6316. global $conf, $langs, $hookmanager;
  6317. global $bc, $action;
  6318. $linktoelem = '';
  6319. $linktoelemlist = '';
  6320. $listofidcompanytoscan = '';
  6321. if (!is_object($object->thirdparty)) $object->fetch_thirdparty();
  6322. $possiblelinks = array();
  6323. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0)
  6324. {
  6325. $listofidcompanytoscan = $object->thirdparty->id;
  6326. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  6327. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
  6328. {
  6329. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6330. $tmpproject = new Project($this->db);
  6331. $tmpproject->fetch($object->fk_project);
  6332. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan .= ','.$tmpproject->socid;
  6333. unset($tmpproject);
  6334. }
  6335. $possiblelinks = array(
  6336. '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 (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),
  6337. '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 (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),
  6338. '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 as 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 (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
  6339. '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 as 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 (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
  6340. 'contrat'=>array('enabled'=>$conf->contrat->enabled, 'perms'=>1, 'label'=>'LinkToContract',
  6341. '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, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
  6342. 'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, '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 (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),
  6343. '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 (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
  6344. '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 (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
  6345. '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 (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')'),
  6346. '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 (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('ticket').')')
  6347. );
  6348. }
  6349. // Can complete the possiblelink array
  6350. $hookmanager->initHooks(array('commonobject'));
  6351. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan);
  6352. if (!empty($listofidcompanytoscan)) // If empty, we don't have criteria to scan the object we can link to
  6353. {
  6354. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  6355. }
  6356. if (empty($reshook))
  6357. {
  6358. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  6359. {
  6360. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  6361. }
  6362. } elseif ($reshook > 0)
  6363. {
  6364. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  6365. {
  6366. $possiblelinks = $hookmanager->resArray;
  6367. }
  6368. }
  6369. foreach ($possiblelinks as $key => $possiblelink)
  6370. {
  6371. $num = 0;
  6372. if (empty($possiblelink['enabled'])) continue;
  6373. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto)))
  6374. {
  6375. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  6376. $sql = $possiblelink['sql'];
  6377. $resqllist = $this->db->query($sql);
  6378. if ($resqllist)
  6379. {
  6380. $num = $this->db->num_rows($resqllist);
  6381. $i = 0;
  6382. print '<br>';
  6383. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  6384. print '<input type="hidden" name="action" value="addlink">';
  6385. print '<input type="hidden" name="token" value="'.newToken().'">';
  6386. print '<input type="hidden" name="id" value="'.$object->id.'">';
  6387. print '<input type="hidden" name="addlink" value="'.$key.'">';
  6388. print '<table class="noborder">';
  6389. print '<tr class="liste_titre">';
  6390. print '<td class="nowrap"></td>';
  6391. print '<td class="center">'.$langs->trans("Ref").'</td>';
  6392. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  6393. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  6394. print '<td class="left">'.$langs->trans("Company").'</td>';
  6395. print '</tr>';
  6396. while ($i < $num)
  6397. {
  6398. $objp = $this->db->fetch_object($resqllist);
  6399. print '<tr class="oddeven">';
  6400. print '<td class="left">';
  6401. print '<input type="radio" name="idtolinkto" value='.$objp->rowid.'>';
  6402. print '</td>';
  6403. print '<td class="center">'.$objp->ref.'</td>';
  6404. print '<td>'.$objp->ref_client.'</td>';
  6405. print '<td class="right">'.price($objp->total_ht).'</td>';
  6406. print '<td>'.$objp->name.'</td>';
  6407. print '</tr>';
  6408. $i++;
  6409. }
  6410. print '</table>';
  6411. print '<div class="center"><input type="submit" class="button valignmiddle" value="'.$langs->trans('ToLink').'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  6412. print '</form>';
  6413. $this->db->free($resqllist);
  6414. } else {
  6415. dol_print_error($this->db);
  6416. }
  6417. print '</div>';
  6418. if ($num > 0)
  6419. {
  6420. }
  6421. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  6422. if ($num > 0) $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  6423. //else $linktoelem.=$langs->trans($possiblelink['label']);
  6424. else $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  6425. }
  6426. }
  6427. if ($linktoelemlist)
  6428. {
  6429. $linktoelem = '
  6430. <dl class="dropdown" id="linktoobjectname">
  6431. ';
  6432. if (!empty($conf->use_javascript_ajax)) $linktoelem .= '<dt><a href="#linktoobjectname">'.$langs->trans("LinkTo").'...</a></dt>';
  6433. $linktoelem .= '<dd>
  6434. <div class="multiselectlinkto">
  6435. <ul class="ulselectedfields">'.$linktoelemlist.'
  6436. </ul>
  6437. </div>
  6438. </dd>
  6439. </dl>';
  6440. } else {
  6441. $linktoelem = '';
  6442. }
  6443. if (!empty($conf->use_javascript_ajax))
  6444. {
  6445. print '<!-- Add js to show linkto box -->
  6446. <script>
  6447. jQuery(document).ready(function() {
  6448. jQuery(".linkto").click(function() {
  6449. console.log("We choose to show/hide link for rel="+jQuery(this).attr(\'rel\'));
  6450. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  6451. });
  6452. });
  6453. </script>
  6454. ';
  6455. }
  6456. return $linktoelem;
  6457. }
  6458. /**
  6459. * Return an html string with a select combo box to choose yes or no
  6460. *
  6461. * @param string $htmlname Name of html select field
  6462. * @param string $value Pre-selected value
  6463. * @param int $option 0 return yes/no, 1 return 1/0
  6464. * @param bool $disabled true or false
  6465. * @param int $useempty 1=Add empty line
  6466. * @param int $addjscombo 1=Add js beautifier on combo box
  6467. * @return string See option
  6468. */
  6469. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0)
  6470. {
  6471. global $langs;
  6472. $yes = "yes"; $no = "no";
  6473. if ($option)
  6474. {
  6475. $yes = "1";
  6476. $no = "0";
  6477. }
  6478. $disabled = ($disabled ? ' disabled' : '');
  6479. $resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  6480. if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  6481. if (("$value" == 'yes') || ($value == 1))
  6482. {
  6483. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  6484. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  6485. } else {
  6486. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  6487. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  6488. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  6489. }
  6490. $resultyesno .= '</select>'."\n";
  6491. if ($addjscombo) {
  6492. $resultyesno .= ajax_combobox($htmlname);
  6493. }
  6494. return $resultyesno;
  6495. }
  6496. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6497. /**
  6498. * Return list of export templates
  6499. *
  6500. * @param string $selected Id modele pre-selectionne
  6501. * @param string $htmlname Name of HTML select
  6502. * @param string $type Type of searched templates
  6503. * @param int $useempty Affiche valeur vide dans liste
  6504. * @return void
  6505. */
  6506. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  6507. {
  6508. // phpcs:enable
  6509. $sql = "SELECT rowid, label";
  6510. $sql .= " FROM ".MAIN_DB_PREFIX."export_model";
  6511. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  6512. $sql .= " ORDER BY rowid";
  6513. $result = $this->db->query($sql);
  6514. if ($result)
  6515. {
  6516. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  6517. if ($useempty)
  6518. {
  6519. print '<option value="-1">&nbsp;</option>';
  6520. }
  6521. $num = $this->db->num_rows($result);
  6522. $i = 0;
  6523. while ($i < $num)
  6524. {
  6525. $obj = $this->db->fetch_object($result);
  6526. if ($selected == $obj->rowid)
  6527. {
  6528. print '<option value="'.$obj->rowid.'" selected>';
  6529. } else {
  6530. print '<option value="'.$obj->rowid.'">';
  6531. }
  6532. print $obj->label;
  6533. print '</option>';
  6534. $i++;
  6535. }
  6536. print "</select>";
  6537. } else {
  6538. dol_print_error($this->db);
  6539. }
  6540. }
  6541. /**
  6542. * Return a HTML area with the reference of object and a navigation bar for a business object
  6543. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  6544. *
  6545. * @param object $object Object to show.
  6546. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  6547. * @param string $morehtml More html content to output just before the nav bar.
  6548. * @param int $shownav Show Condition (navigation is shown if value is 1).
  6549. * @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.
  6550. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  6551. * @param string $morehtmlref More html to show after ref.
  6552. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  6553. * @param int $nodbprefix Do not include DB prefix to forge table name.
  6554. * @param string $morehtmlleft More html code to show before ref.
  6555. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  6556. * @param string $morehtmlright More html code to show after ref.
  6557. * @return string Portion HTML with ref + navigation buttons
  6558. */
  6559. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  6560. {
  6561. global $langs, $conf, $hookmanager, $extralanguages;
  6562. $ret = '';
  6563. if (empty($fieldid)) $fieldid = 'rowid';
  6564. if (empty($fieldref)) $fieldref = 'ref';
  6565. // Add where from hooks
  6566. if (is_object($hookmanager))
  6567. {
  6568. $parameters = array();
  6569. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  6570. $object->next_prev_filter .= $hookmanager->resPrint;
  6571. }
  6572. $previous_ref = $next_ref = '';
  6573. if ($shownav)
  6574. {
  6575. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  6576. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  6577. $navurl = $_SERVER["PHP_SELF"];
  6578. // Special case for project/task page
  6579. if ($paramid == 'project_ref')
  6580. {
  6581. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) // TODO Remove this when nav with project_ref on task pages are ok
  6582. {
  6583. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  6584. $paramid = 'ref';
  6585. }
  6586. }
  6587. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  6588. // accesskey is for Mac: CTRL + key for all browsers
  6589. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  6590. if ($conf->browser->name == 'chrome')
  6591. {
  6592. $stringforfirstkey .= ' ALT +';
  6593. } elseif ($conf->browser->name == 'firefox')
  6594. {
  6595. $stringforfirstkey .= ' ALT + SHIFT +';
  6596. } else {
  6597. $stringforfirstkey .= ' CTL +';
  6598. }
  6599. $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>';
  6600. $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>';
  6601. }
  6602. //print "xx".$previous_ref."x".$next_ref;
  6603. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  6604. // Right part of banner
  6605. if ($morehtmlright) $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  6606. if ($previous_ref || $next_ref || $morehtml)
  6607. {
  6608. $ret .= '<div class="pagination paginationref"><ul class="right">';
  6609. }
  6610. if ($morehtml)
  6611. {
  6612. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  6613. }
  6614. if ($shownav && ($previous_ref || $next_ref))
  6615. {
  6616. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  6617. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  6618. }
  6619. if ($previous_ref || $next_ref || $morehtml)
  6620. {
  6621. $ret .= '</ul></div>';
  6622. }
  6623. $parameters = array();
  6624. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  6625. if (empty($reshook)) $morehtmlstatus .= $hookmanager->resPrint;
  6626. else $morehtmlstatus = $hookmanager->resPrint;
  6627. if ($morehtmlstatus) $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  6628. $parameters = array();
  6629. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  6630. if (empty($reshook)) $morehtmlref .= $hookmanager->resPrint;
  6631. elseif ($reshook > 0) $morehtmlref = $hookmanager->resPrint;
  6632. // Left part of banner
  6633. if ($morehtmlleft)
  6634. {
  6635. if ($conf->browser->layout == 'phone') $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  6636. else $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  6637. }
  6638. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  6639. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  6640. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  6641. if ($object->element == 'societe')
  6642. {
  6643. $ret .= dol_htmlentities($object->name);
  6644. // List of extra languages
  6645. $arrayoflangcode = array();
  6646. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  6647. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  6648. if (!is_object($extralanguages)) {
  6649. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  6650. $extralanguages = new ExtraLanguages($this->db);
  6651. }
  6652. $extralanguages->fetch_name_extralanguages('societe');
  6653. if (!empty($extralanguages->attributes['societe']['name']))
  6654. {
  6655. $object->fetchValuesForExtraLanguages();
  6656. $htmltext = '';
  6657. // If there is extra languages
  6658. foreach ($arrayoflangcode as $extralangcode) {
  6659. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  6660. if ($object->array_languages['name'][$extralangcode]) {
  6661. $htmltext .= $object->array_languages['name'][$extralangcode];
  6662. } else {
  6663. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  6664. }
  6665. }
  6666. $ret .= '<!-- Show translations of name -->'."\n";
  6667. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  6668. }
  6669. }
  6670. } elseif ($object->element == 'member')
  6671. {
  6672. $ret .= $object->ref.'<br>';
  6673. $fullname = $object->getFullName($langs);
  6674. if ($object->morphy == 'mor' && $object->societe) {
  6675. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).')' : '');
  6676. } else {
  6677. $ret .= dol_htmlentities($fullname).((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  6678. }
  6679. } elseif (in_array($object->element, array('contact', 'user', 'usergroup')))
  6680. {
  6681. $ret .= dol_htmlentities($object->getFullName($langs));
  6682. } elseif (in_array($object->element, array('action', 'agenda')))
  6683. {
  6684. $ret .= $object->ref.'<br>'.$object->label;
  6685. } elseif (in_array($object->element, array('adherent_type')))
  6686. {
  6687. $ret .= $object->label;
  6688. } elseif ($object->element == 'ecm_directories')
  6689. {
  6690. $ret .= '';
  6691. } elseif ($fieldref != 'none')
  6692. {
  6693. $ret .= dol_htmlentities($object->$fieldref);
  6694. }
  6695. if ($morehtmlref)
  6696. {
  6697. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  6698. if (substr($morehtmlref, 0, 4) != '<div')
  6699. {
  6700. $ret .= ' ';
  6701. }
  6702. $ret .= $morehtmlref;
  6703. }
  6704. $ret .= '</div>';
  6705. $ret .= '</div><!-- End banner content -->';
  6706. return $ret;
  6707. }
  6708. /**
  6709. * Return HTML code to output a barcode
  6710. *
  6711. * @param Object $object Object containing data to retrieve file name
  6712. * @param int $width Width of photo
  6713. * @return string HTML code to output barcode
  6714. */
  6715. public function showbarcode(&$object, $width = 100)
  6716. {
  6717. global $conf;
  6718. //Check if barcode is filled in the card
  6719. if (empty($object->barcode)) return '';
  6720. // Complete object if not complete
  6721. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
  6722. {
  6723. $result = $object->fetch_barcode();
  6724. //Check if fetch_barcode() failed
  6725. if ($result < 1) return '<!-- ErrorFetchBarcode -->';
  6726. }
  6727. // Barcode image
  6728. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  6729. $out = '<!-- url barcode = '.$url.' -->';
  6730. $out .= '<img src="'.$url.'">';
  6731. return $out;
  6732. }
  6733. /**
  6734. * Return HTML code to output a photo
  6735. *
  6736. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  6737. * @param object $object Object containing data to retrieve file name
  6738. * @param int $width Width of photo
  6739. * @param int $height Height of photo (auto if 0)
  6740. * @param int $caneditfield Add edit fields
  6741. * @param string $cssclass CSS name to use on img for photo
  6742. * @param string $imagesize 'mini', 'small' or '' (original)
  6743. * @param int $addlinktofullsize Add link to fullsize image
  6744. * @param int $cache 1=Accept to use image in cache
  6745. * @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 ''.
  6746. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  6747. * @return string HTML code to output photo
  6748. */
  6749. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  6750. {
  6751. global $conf, $langs;
  6752. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  6753. $id = (!empty($object->id) ? $object->id : $object->rowid);
  6754. $ret = ''; $dir = ''; $file = ''; $originalfile = ''; $altfile = ''; $email = ''; $capture = '';
  6755. if ($modulepart == 'societe')
  6756. {
  6757. $dir = $conf->societe->multidir_output[$entity];
  6758. if (!empty($object->logo))
  6759. {
  6760. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  6761. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
  6762. else $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  6763. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  6764. }
  6765. $email = $object->email;
  6766. } elseif ($modulepart == 'contact')
  6767. {
  6768. $dir = $conf->societe->multidir_output[$entity].'/contact';
  6769. if (!empty($object->photo))
  6770. {
  6771. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
  6772. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
  6773. else $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  6774. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  6775. }
  6776. $email = $object->email;
  6777. $capture = 'user';
  6778. } elseif ($modulepart == 'userphoto')
  6779. {
  6780. $dir = $conf->user->dir_output;
  6781. if (!empty($object->photo))
  6782. {
  6783. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
  6784. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
  6785. else $file = get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
  6786. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
  6787. }
  6788. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
  6789. $email = $object->email;
  6790. $capture = 'user';
  6791. } elseif ($modulepart == 'memberphoto')
  6792. {
  6793. $dir = $conf->adherent->dir_output;
  6794. if (!empty($object->photo))
  6795. {
  6796. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  6797. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  6798. else $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  6799. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  6800. }
  6801. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
  6802. $email = $object->email;
  6803. $capture = 'user';
  6804. } else {
  6805. // Generic case to show photos
  6806. $dir = $conf->$modulepart->dir_output;
  6807. if (!empty($object->photo))
  6808. {
  6809. if ((string) $imagesize == 'mini') $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  6810. elseif ((string) $imagesize == 'small') $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  6811. else $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  6812. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  6813. }
  6814. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
  6815. $email = $object->email;
  6816. }
  6817. if ($forcecapture) $capture = $forcecapture;
  6818. if ($dir)
  6819. {
  6820. if ($file && file_exists($dir."/".$file))
  6821. {
  6822. if ($addlinktofullsize) {
  6823. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  6824. if ($urladvanced) $ret .= '<a href="'.$urladvanced.'">';
  6825. else $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  6826. }
  6827. $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.'">';
  6828. if ($addlinktofullsize) $ret .= '</a>';
  6829. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  6830. if ($addlinktofullsize) {
  6831. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  6832. if ($urladvanced) $ret .= '<a href="'.$urladvanced.'">';
  6833. else $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  6834. }
  6835. $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.'">';
  6836. if ($addlinktofullsize) $ret .= '</a>';
  6837. } else {
  6838. $nophoto = '/public/theme/common/nophoto.png';
  6839. if (in_array($modulepart, array('userphoto', 'contact', 'memberphoto'))) { // For module that are "physical" users
  6840. if ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor') !== false) {
  6841. $nophoto = '/public/theme/common/company.png';
  6842. } else {
  6843. $nophoto = '/public/theme/common/user_anonymous.png';
  6844. if ($object->gender == 'man') $nophoto = '/public/theme/common/user_man.png';
  6845. if ($object->gender == 'woman') $nophoto = '/public/theme/common/user_woman.png';
  6846. }
  6847. }
  6848. if (!empty($conf->gravatar->enabled) && $email && empty($noexternsourceoverwrite)) {
  6849. // see https://gravatar.com/site/implement/images/php/
  6850. global $dolibarr_main_url_root;
  6851. $ret .= '<!-- Put link to gravatar -->';
  6852. //$defaultimg=urlencode(dol_buildpath($nophoto,3));
  6853. $defaultimg = 'mm';
  6854. $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
  6855. } else {
  6856. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  6857. }
  6858. }
  6859. if ($caneditfield)
  6860. {
  6861. if ($object->photo) $ret .= "<br>\n";
  6862. $ret .= '<table class="nobordernopadding centpercent">';
  6863. if ($object->photo) $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
  6864. $ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
  6865. $ret .= '</table>';
  6866. }
  6867. } else dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  6868. return $ret;
  6869. }
  6870. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6871. /**
  6872. * Return select list of groups
  6873. *
  6874. * @param string $selected Id group preselected
  6875. * @param string $htmlname Field name in form
  6876. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  6877. * @param string $exclude Array list of groups id to exclude
  6878. * @param int $disabled If select list must be disabled
  6879. * @param string $include Array list of groups id to include
  6880. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  6881. * @param string $force_entity '0' or Ids of environment to force
  6882. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  6883. * @param string $morecss More css to add to html component
  6884. * @return string
  6885. * @see select_dolusers()
  6886. */
  6887. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  6888. {
  6889. // phpcs:enable
  6890. global $conf, $user, $langs;
  6891. // Permettre l'exclusion de groupes
  6892. if (is_array($exclude)) $excludeGroups = implode("','", $exclude);
  6893. // Permettre l'inclusion de groupes
  6894. if (is_array($include)) $includeGroups = implode("','", $include);
  6895. if (!is_array($selected)) $selected = array($selected);
  6896. $out = '';
  6897. // On recherche les groupes
  6898. $sql = "SELECT ug.rowid, ug.nom as name";
  6899. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  6900. {
  6901. $sql .= ", e.label";
  6902. }
  6903. $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  6904. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  6905. {
  6906. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
  6907. if ($force_entity) $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  6908. else $sql .= " WHERE ug.entity IS NOT NULL";
  6909. } else {
  6910. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  6911. }
  6912. if (is_array($exclude) && $excludeGroups) $sql .= " AND ug.rowid NOT IN ('".$excludeGroups."')";
  6913. if (is_array($include) && $includeGroups) $sql .= " AND ug.rowid IN ('".$includeGroups."')";
  6914. $sql .= " ORDER BY ug.nom ASC";
  6915. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  6916. $resql = $this->db->query($sql);
  6917. if ($resql)
  6918. {
  6919. // Enhance with select2
  6920. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6921. $out .= ajax_combobox($htmlname);
  6922. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  6923. $num = $this->db->num_rows($resql);
  6924. $i = 0;
  6925. if ($num)
  6926. {
  6927. if ($show_empty && !$multiple) $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  6928. while ($i < $num)
  6929. {
  6930. $obj = $this->db->fetch_object($resql);
  6931. $disableline = 0;
  6932. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) $disableline = 1;
  6933. $out .= '<option value="'.$obj->rowid.'"';
  6934. if ($disableline) $out .= ' disabled';
  6935. if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (!is_object($selected[0]) && in_array($obj->rowid, $selected)))
  6936. {
  6937. $out .= ' selected';
  6938. }
  6939. $out .= '>';
  6940. $out .= $obj->name;
  6941. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
  6942. {
  6943. $out .= " (".$obj->label.")";
  6944. }
  6945. $out .= '</option>';
  6946. $i++;
  6947. }
  6948. } else {
  6949. if ($show_empty) $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  6950. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  6951. }
  6952. $out .= '</select>';
  6953. } else {
  6954. dol_print_error($this->db);
  6955. }
  6956. return $out;
  6957. }
  6958. /**
  6959. * Return HTML to show the search and clear seach button
  6960. *
  6961. * @return string
  6962. */
  6963. public function showFilterButtons()
  6964. {
  6965. $out = '<div class="nowrap">';
  6966. $out .= '<button type="submit" class="liste_titre button_search" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  6967. $out .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  6968. $out .= '</div>';
  6969. return $out;
  6970. }
  6971. /**
  6972. * Return HTML to show the search and clear search button
  6973. *
  6974. * @param string $cssclass CSS class
  6975. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  6976. * @param string $massactionname Mass action button name that will launch an action on the selected items
  6977. * @return string
  6978. */
  6979. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  6980. {
  6981. global $conf, $langs;
  6982. $out = '';
  6983. if (!empty($conf->use_javascript_ajax)) $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  6984. $out .= '<script>
  6985. $(document).ready(function() {
  6986. $("#' . $cssclass.'s").click(function() {
  6987. if($(this).is(\':checked\')){
  6988. console.log("We check all '.$cssclass.' and trigger the change method");
  6989. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  6990. }
  6991. else
  6992. {
  6993. console.log("We uncheck all");
  6994. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  6995. }'."\n";
  6996. if ($calljsfunction) $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  6997. $out .= ' });
  6998. $(".' . $cssclass.'").change(function() {
  6999. $(this).closest("tr").toggleClass("highlight", this.checked);
  7000. });
  7001. });
  7002. </script>';
  7003. return $out;
  7004. }
  7005. /**
  7006. * Return HTML to show the search and clear seach button
  7007. *
  7008. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  7009. * @param string $cssclass CSS class
  7010. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  7011. * @param string $massactionname Mass action name
  7012. * @return string
  7013. */
  7014. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  7015. {
  7016. $out = $this->showFilterButtons();
  7017. if ($addcheckuncheckall)
  7018. {
  7019. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  7020. }
  7021. return $out;
  7022. }
  7023. /**
  7024. * Return HTML to show the select of expense categories
  7025. *
  7026. * @param string $selected preselected category
  7027. * @param string $htmlname name of HTML select list
  7028. * @param integer $useempty 1=Add empty line
  7029. * @param array $excludeid id to exclude
  7030. * @param string $target htmlname of target select to bind event
  7031. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  7032. * @param array $params param to give
  7033. * @param int $info_admin Show the tooltip help picto to setup list
  7034. * @return string
  7035. */
  7036. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  7037. {
  7038. global $db, $langs, $user;
  7039. $out = '';
  7040. $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
  7041. $sql .= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
  7042. if (!empty($excludeid)) $sql .= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
  7043. $sql .= ' ORDER BY label';
  7044. $resql = $db->query($sql);
  7045. if ($resql)
  7046. {
  7047. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  7048. if ($useempty) $out .= '<option value="0">&nbsp;</option>';
  7049. while ($obj = $db->fetch_object($resql))
  7050. {
  7051. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  7052. }
  7053. $out .= '</select>';
  7054. $out .= ajax_combobox('select_'.$htmlname);
  7055. if (!empty($htmlname) && $user->admin && $info_admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  7056. if (!empty($target))
  7057. {
  7058. $sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  7059. $resql = $db->query($sql);
  7060. if ($resql)
  7061. {
  7062. if ($db->num_rows($resql) > 0)
  7063. {
  7064. $obj = $db->fetch_object($resql);
  7065. $out .= '<script>
  7066. $(function() {
  7067. $("select[name='.$target.']").on("change", function() {
  7068. var current_val = $(this).val();
  7069. if (current_val == '.$obj->id.') {';
  7070. if (!empty($default_selected) || !empty($selected)) $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  7071. $out .= '
  7072. $("select[name='.$htmlname.']").change();
  7073. }
  7074. });
  7075. $("select[name='.$htmlname.']").change(function() {
  7076. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  7077. // get price of kilometer to fill the unit price
  7078. var data = '.json_encode($params).';
  7079. data.fk_c_exp_tax_cat = $(this).val();
  7080. $.ajax({
  7081. method: "POST",
  7082. dataType: "json",
  7083. data: data,
  7084. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php').'",
  7085. }).done(function( data, textStatus, jqXHR ) {
  7086. console.log(data);
  7087. if (typeof data.up != "undefined") {
  7088. $("input[name=value_unit]").val(data.up);
  7089. $("select[name='.$htmlname.']").attr("title", data.title);
  7090. } else {
  7091. $("input[name=value_unit]").val("");
  7092. $("select[name='.$htmlname.']").attr("title", "");
  7093. }
  7094. });
  7095. }
  7096. });
  7097. });
  7098. </script>';
  7099. }
  7100. }
  7101. }
  7102. } else {
  7103. dol_print_error($db);
  7104. }
  7105. return $out;
  7106. }
  7107. /**
  7108. * Return HTML to show the select ranges of expense range
  7109. *
  7110. * @param string $selected preselected category
  7111. * @param string $htmlname name of HTML select list
  7112. * @param integer $useempty 1=Add empty line
  7113. * @return string
  7114. */
  7115. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  7116. {
  7117. global $db, $conf, $langs;
  7118. $out = '';
  7119. $sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
  7120. $sql .= ' WHERE entity = '.$conf->entity.' AND active = 1';
  7121. $resql = $db->query($sql);
  7122. if ($resql)
  7123. {
  7124. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  7125. if ($useempty) $out .= '<option value="0"></option>';
  7126. while ($obj = $db->fetch_object($resql))
  7127. {
  7128. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  7129. }
  7130. $out .= '</select>';
  7131. } else {
  7132. dol_print_error($db);
  7133. }
  7134. return $out;
  7135. }
  7136. /**
  7137. * Return HTML to show a select of expense
  7138. *
  7139. * @param string $selected preselected category
  7140. * @param string $htmlname name of HTML select list
  7141. * @param integer $useempty 1=Add empty choice
  7142. * @param integer $allchoice 1=Add all choice
  7143. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  7144. * @return string
  7145. */
  7146. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  7147. {
  7148. global $db, $langs;
  7149. $out = '';
  7150. $sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
  7151. $sql .= ' WHERE active = 1';
  7152. $resql = $db->query($sql);
  7153. if ($resql)
  7154. {
  7155. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  7156. if ($useempty) $out .= '<option value="0"></option>';
  7157. if ($allchoice) $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  7158. $field = 'code';
  7159. if ($useid) $field = 'id';
  7160. while ($obj = $db->fetch_object($resql))
  7161. {
  7162. $key = $langs->trans($obj->code);
  7163. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  7164. }
  7165. $out .= '</select>';
  7166. } else {
  7167. dol_print_error($db);
  7168. }
  7169. return $out;
  7170. }
  7171. /**
  7172. * Output a combo list with invoices qualified for a third party
  7173. *
  7174. * @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)
  7175. * @param int $selected Id invoice preselected
  7176. * @param string $htmlname Name of HTML select
  7177. * @param int $maxlength Maximum length of label
  7178. * @param int $option_only Return only html options lines without the select tag
  7179. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  7180. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  7181. * @param int $forcefocus Force focus on field (works with javascript only)
  7182. * @param int $disabled Disabled
  7183. * @param string $morecss More css added to the select component
  7184. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  7185. * @param string $showproject 'all' = Show project info, ''=Hide project info
  7186. * @param User $usertofilter User object to use for filtering
  7187. * @return int Nbr of project if OK, <0 if KO
  7188. */
  7189. 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)
  7190. {
  7191. global $user, $conf, $langs;
  7192. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7193. if (is_null($usertofilter))
  7194. {
  7195. $usertofilter = $user;
  7196. }
  7197. $out = '';
  7198. $hideunselectables = false;
  7199. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
  7200. if (empty($projectsListId))
  7201. {
  7202. if (empty($usertofilter->rights->projet->all->lire))
  7203. {
  7204. $projectstatic = new Project($this->db);
  7205. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  7206. }
  7207. }
  7208. // Search all projects
  7209. $sql = 'SELECT f.rowid, f.ref as fref, "nolabel" as flabel, p.rowid as pid, f.ref,
  7210. p.title, p.fk_soc, p.fk_statut, p.public,';
  7211. $sql .= ' s.nom as name';
  7212. $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as p';
  7213. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,';
  7214. $sql .= ' '.MAIN_DB_PREFIX.'facture as f';
  7215. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  7216. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  7217. //if ($projectsListId) $sql.= " AND p.rowid IN (".$projectsListId.")";
  7218. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  7219. //if ($socid > 0) $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
  7220. $sql .= " GROUP BY f.ref ORDER BY p.ref, f.ref ASC";
  7221. $resql = $this->db->query($sql);
  7222. if ($resql)
  7223. {
  7224. // Use select2 selector
  7225. if (!empty($conf->use_javascript_ajax))
  7226. {
  7227. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7228. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  7229. $out .= $comboenhancement;
  7230. $morecss = 'minwidth200imp maxwidth500';
  7231. }
  7232. if (empty($option_only)) {
  7233. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  7234. }
  7235. if (!empty($show_empty)) {
  7236. $out .= '<option value="0" class="optiongrey">';
  7237. if (!is_numeric($show_empty)) $out .= $show_empty;
  7238. else $out .= '&nbsp;';
  7239. $out .= '</option>';
  7240. }
  7241. $num = $this->db->num_rows($resql);
  7242. $i = 0;
  7243. if ($num)
  7244. {
  7245. while ($i < $num)
  7246. {
  7247. $obj = $this->db->fetch_object($resql);
  7248. // 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.
  7249. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire))
  7250. {
  7251. // Do nothing
  7252. } else {
  7253. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED)
  7254. {
  7255. $i++;
  7256. continue;
  7257. }
  7258. $labeltoshow = '';
  7259. if ($showproject == 'all')
  7260. {
  7261. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  7262. if ($obj->name) $labeltoshow .= ' - '.$obj->name; // Soc name
  7263. $disabled = 0;
  7264. if ($obj->fk_statut == Project::STATUS_DRAFT)
  7265. {
  7266. $disabled = 1;
  7267. $labeltoshow .= ' - '.$langs->trans("Draft");
  7268. } elseif ($obj->fk_statut == Project::STATUS_CLOSED)
  7269. {
  7270. if ($discard_closed == 2) $disabled = 1;
  7271. $labeltoshow .= ' - '.$langs->trans("Closed");
  7272. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid))
  7273. {
  7274. $disabled = 1;
  7275. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  7276. }
  7277. }
  7278. if (!empty($selected) && $selected == $obj->rowid)
  7279. {
  7280. $out .= '<option value="'.$obj->rowid.'" selected';
  7281. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  7282. $out .= '>'.$labeltoshow.'</option>';
  7283. } else {
  7284. if ($hideunselectables && $disabled && ($selected != $obj->rowid))
  7285. {
  7286. $resultat = '';
  7287. } else {
  7288. $resultat = '<option value="'.$obj->rowid.'"';
  7289. if ($disabled) $resultat .= ' disabled';
  7290. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  7291. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  7292. $resultat .= '>';
  7293. $resultat .= $labeltoshow;
  7294. $resultat .= '</option>';
  7295. }
  7296. $out .= $resultat;
  7297. }
  7298. }
  7299. $i++;
  7300. }
  7301. }
  7302. if (empty($option_only)) {
  7303. $out .= '</select>';
  7304. }
  7305. print $out;
  7306. $this->db->free($resql);
  7307. return $num;
  7308. } else {
  7309. dol_print_error($this->db);
  7310. return -1;
  7311. }
  7312. }
  7313. /**
  7314. * Output the component to make advanced search criteries
  7315. *
  7316. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  7317. * @param array $search_component_params Array of selected search criterias
  7318. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  7319. * @return string HTML component for advanced search
  7320. */
  7321. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array())
  7322. {
  7323. global $langs;
  7324. $ret = '';
  7325. $ret .= '<div class="nowrap centpercent">';
  7326. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  7327. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor paddingright">';
  7328. $ret .= '<span class="fas fa-filter linkobject boxfilter" title="Filter" id="idsubimgproductdistribution"></span>';
  7329. $ret .= $langs->trans("Filters");
  7330. $ret .= '</a>';
  7331. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  7332. $ret .= '<div name="search_component_params" class="search_component_params inline-block minwidth500 maxwidth300onsmartphone valignmiddle">';
  7333. $texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  7334. $ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  7335. $ret .= '</div>';
  7336. $ret .= '<input type="hidden" name="search_component_params_hidden" class="search_component_params_hidden" value="'.GETPOST("search_component_params_hidden").'">';
  7337. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  7338. foreach ($arrayofcriterias as $criterias) {
  7339. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  7340. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) continue;
  7341. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) continue;
  7342. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  7343. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  7344. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  7345. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  7346. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  7347. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  7348. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  7349. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  7350. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  7351. } else {
  7352. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  7353. }
  7354. }
  7355. }
  7356. $ret .= '</div>';
  7357. return $ret;
  7358. }
  7359. /**
  7360. * selectModelMail
  7361. *
  7362. * @param string $prefix Prefix
  7363. * @param string $modelType Model type
  7364. * @param int $default 1=Show also Default mail template
  7365. * @return string HTML select string
  7366. */
  7367. public function selectModelMail($prefix, $modelType = '', $default = 0)
  7368. {
  7369. global $langs, $db, $user;
  7370. $retstring = '';
  7371. $TModels = array();
  7372. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  7373. $formmail = new FormMail($db);
  7374. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  7375. if ($default) $TModels[0] = $langs->trans('DefaultMailModel');
  7376. if ($result > 0) {
  7377. foreach ($formmail->lines_model as $model) {
  7378. $TModels[$model->id] = $model->label;
  7379. }
  7380. }
  7381. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  7382. foreach ($TModels as $id_model=>$label_model) {
  7383. $retstring .= '<option value="'.$id_model.'"';
  7384. $retstring .= ">".$label_model."</option>";
  7385. }
  7386. $retstring .= "</select>";
  7387. return $retstring;
  7388. }
  7389. }