html.form.class.php 422 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149
  1. <?php
  2. /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  7. * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>
  10. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
  11. * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
  12. * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
  13. * Copyright (C) 2010-2021 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  15. * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
  16. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  17. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  18. * Copyright (C) 2014-2020 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018-2022 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  21. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  22. * Copyright (C) 2018 Christophe Battarel <christophe@altairis.fr>
  23. * Copyright (C) 2018 Josep Lluis Amador <joseplluis@lliuretic.cat>
  24. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. */
  38. /**
  39. * \file htdocs/core/class/html.form.class.php
  40. * \ingroup core
  41. * \brief File of class with all html predefined components
  42. */
  43. /**
  44. * Class to manage generation of HTML components
  45. * Only common components must be here.
  46. *
  47. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  48. */
  49. class Form
  50. {
  51. /**
  52. * @var DoliDB Database handler.
  53. */
  54. public $db;
  55. /**
  56. * @var string Error code (or message)
  57. */
  58. public $error = '';
  59. /**
  60. * @var string[] Array of error strings
  61. */
  62. public $errors = array();
  63. public $num;
  64. // Cache arrays
  65. public $cache_types_paiements = array();
  66. public $cache_conditions_paiements = array();
  67. public $cache_transport_mode = array();
  68. public $cache_availability = array();
  69. public $cache_demand_reason = array();
  70. public $cache_types_fees = array();
  71. public $cache_vatrates = array();
  72. /**
  73. * Constructor
  74. *
  75. * @param DoliDB $db Database handler
  76. */
  77. public function __construct($db)
  78. {
  79. $this->db = $db;
  80. }
  81. /**
  82. * Output key field for an editable field
  83. *
  84. * @param string $text Text of label or key to translate
  85. * @param string $htmlname Name of select field ('edit' prefix will be added)
  86. * @param string $preselected Value to show/edit (not used in this function)
  87. * @param object $object Object
  88. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  89. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'checkbox:ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  90. * @param string $moreparam More param to add on a href URL.
  91. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  92. * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
  93. * @param string $paramid Key of parameter for id ('id', 'socid')
  94. * @param string $help Tooltip help
  95. * @return string HTML edit field
  96. */
  97. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  98. {
  99. global $conf, $langs;
  100. $ret = '';
  101. // TODO change for compatibility
  102. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
  103. if (!empty($perm)) {
  104. $tmp = explode(':', $typeofdata);
  105. $ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  106. if ($fieldrequired) {
  107. $ret .= '<span class="fieldrequired">';
  108. }
  109. if ($help) {
  110. $ret .= $this->textwithpicto($langs->trans($text), $help);
  111. } else {
  112. $ret .= $langs->trans($text);
  113. }
  114. if ($fieldrequired) {
  115. $ret .= '</span>';
  116. }
  117. $ret .= '</div>'."\n";
  118. } else {
  119. if ($fieldrequired) {
  120. $ret .= '<span class="fieldrequired">';
  121. }
  122. if ($help) {
  123. $ret .= $this->textwithpicto($langs->trans($text), $help);
  124. } else {
  125. $ret .= $langs->trans($text);
  126. }
  127. if ($fieldrequired) {
  128. $ret .= '</span>';
  129. }
  130. }
  131. } else {
  132. if (empty($notabletag) && $perm) {
  133. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  134. }
  135. if ($fieldrequired) {
  136. $ret .= '<span class="fieldrequired">';
  137. }
  138. if ($help) {
  139. $ret .= $this->textwithpicto($langs->trans($text), $help);
  140. } else {
  141. $ret .= $langs->trans($text);
  142. }
  143. if ($fieldrequired) {
  144. $ret .= '</span>';
  145. }
  146. if (!empty($notabletag)) {
  147. $ret .= ' ';
  148. }
  149. if (empty($notabletag) && $perm) {
  150. $ret .= '</td>';
  151. }
  152. if (empty($notabletag) && $perm) {
  153. $ret .= '<td class="right">';
  154. }
  155. if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  156. $ret .= '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&token='.newToken().'&'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  157. }
  158. if (!empty($notabletag) && $notabletag == 1) {
  159. $ret .= ' : ';
  160. }
  161. if (!empty($notabletag) && $notabletag == 3) {
  162. $ret .= ' ';
  163. }
  164. if (empty($notabletag) && $perm) {
  165. $ret .= '</td>';
  166. }
  167. if (empty($notabletag) && $perm) {
  168. $ret .= '</tr></table>';
  169. }
  170. }
  171. return $ret;
  172. }
  173. /**
  174. * Output value of a field for an editable field
  175. *
  176. * @param string $text Text of label (not used in this function)
  177. * @param string $htmlname Name of select field
  178. * @param string $value Value to show/edit
  179. * @param object $object Object
  180. * @param boolean $perm Permission to allow button to edit parameter
  181. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select;xkey:xval,ykey:yval,...')
  182. * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of numeric value). Use '' to use same than $value
  183. * @param object $extObject External object
  184. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  185. * @param string $moreparam More param to add on the form action href URL
  186. * @param int $notabletag Do no output table tags
  187. * @param string $formatfunc Call a specific function to output field in view mode (For example: 'dol_print_email')
  188. * @param string $paramid Key of parameter for id ('id', 'socid')
  189. * @param string $gm 'auto' or 'tzuser' or 'tzserver' (when $typeofdata is a date)
  190. * @return string HTML edit field
  191. */
  192. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id', $gm = 'auto')
  193. {
  194. global $conf, $langs;
  195. $ret = '';
  196. // Check parameters
  197. if (empty($typeofdata)) {
  198. return 'ErrorBadParameter';
  199. }
  200. // When option to edit inline is activated
  201. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  202. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  203. } else {
  204. $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
  205. if ($editmode) {
  206. $ret .= "\n";
  207. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  208. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  209. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  210. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  211. if (empty($notabletag)) {
  212. $ret .= '<table class="nobordernopadding centpercent">';
  213. }
  214. if (empty($notabletag)) {
  215. $ret .= '<tr><td>';
  216. }
  217. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) {
  218. $tmp = explode(':', $typeofdata);
  219. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  220. } elseif (preg_match('/^(integer)/', $typeofdata)) {
  221. $tmp = explode(':', $typeofdata);
  222. $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
  223. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.$valuetoshow.'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  224. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  225. $tmp = explode(':', $typeofdata);
  226. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  227. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ? price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  228. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  229. $tmp = explode(':', $typeofdata);
  230. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  231. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  232. $tmp = explode(':', $typeofdata);
  233. $cols = $tmp[2];
  234. $morealt = '';
  235. if (preg_match('/%/', $cols)) {
  236. $morealt = ' style="width: '.$cols.'"';
  237. $cols = '';
  238. }
  239. $valuetoshow = ($editvalue ? $editvalue : $value);
  240. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  241. // textarea convert automatically entities chars into simple chars.
  242. // 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.
  243. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  244. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  245. $ret .= '</textarea>';
  246. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  247. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  248. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  249. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  250. } elseif (preg_match('/^select;/', $typeofdata)) {
  251. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  252. $arraylist = array();
  253. foreach ($arraydata as $val) {
  254. $tmp = explode(':', $val);
  255. $tmpkey = str_replace('|', ':', $tmp[0]);
  256. $arraylist[$tmpkey] = $tmp[1];
  257. }
  258. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  259. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  260. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  261. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  262. $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'));
  263. $ret .= $doleditor->Create(1);
  264. }
  265. if (empty($notabletag)) {
  266. $ret .= '</td>';
  267. }
  268. // Button save-cancel
  269. if (empty($notabletag)) {
  270. $ret .= '<td class="left">';
  271. }
  272. //else $ret.='<div class="clearboth"></div>';
  273. $ret .= '<input type="submit" class="smallpaddingimp button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  274. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  275. $ret .= '<br>'."\n";
  276. }
  277. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  278. if (empty($notabletag)) {
  279. $ret .= '</td>';
  280. }
  281. if (empty($notabletag)) {
  282. $ret .= '</tr></table>'."\n";
  283. }
  284. $ret .= '</form>'."\n";
  285. } else {
  286. if (preg_match('/^(email)/', $typeofdata)) {
  287. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  288. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  289. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  290. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  291. $tmp = explode(':', $typeofdata);
  292. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  293. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  294. $ret .= dol_htmlentitiesbr($value);
  295. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  296. $ret .= dol_string_onlythesehtmltags($value);
  297. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  298. $ret .= dol_string_onlythesehtmltags($value);
  299. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  300. $ret .= '<span class="valuedate">'.dol_print_date($value, 'day', $gm).'</span>';
  301. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  302. $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour', $gm).'</span>';
  303. } elseif (preg_match('/^select;/', $typeofdata)) {
  304. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  305. $arraylist = array();
  306. foreach ($arraydata as $val) {
  307. $tmp = explode(':', $val);
  308. $arraylist[$tmp[0]] = $tmp[1];
  309. }
  310. $ret .= $arraylist[$value];
  311. if ($htmlname == 'fk_product_type') {
  312. if ($value == 0) {
  313. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  314. } else {
  315. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  316. }
  317. }
  318. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  319. $tmpcontent = dol_htmlentitiesbr($value);
  320. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  321. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  322. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  323. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  324. }
  325. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  326. // clean data from some dangerous html
  327. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  328. } else {
  329. $ret .= dol_escape_htmltag($value);
  330. }
  331. if ($formatfunc && method_exists($object, $formatfunc)) {
  332. $ret = $object->$formatfunc($ret);
  333. }
  334. }
  335. }
  336. return $ret;
  337. }
  338. /**
  339. * Output edit in place form
  340. *
  341. * @param string $fieldname Name of the field
  342. * @param object $object Object
  343. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  344. * @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]'...)
  345. * @param string $check Same coe than $check parameter of GETPOST()
  346. * @param string $morecss More CSS
  347. * @return string HTML code for the edit of alternative language
  348. */
  349. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  350. {
  351. global $conf, $langs, $extralanguages;
  352. $result = '';
  353. // List of extra languages
  354. $arrayoflangcode = array();
  355. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  356. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  357. }
  358. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  359. if (!is_object($extralanguages)) {
  360. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  361. $extralanguages = new ExtraLanguages($this->db);
  362. }
  363. $extralanguages->fetch_name_extralanguages('societe');
  364. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  365. return ''; // No extralang field to show
  366. }
  367. $result .= '<!-- Widget for translation -->'."\n";
  368. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  369. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  370. $result .= $s;
  371. $result .= '</div>';
  372. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  373. $resultforextrlang = '';
  374. foreach ($arrayoflangcode as $langcode) {
  375. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  376. if (empty($valuetoshow)) {
  377. $object->fetchValuesForExtraLanguages();
  378. //var_dump($object->array_languages);
  379. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  380. }
  381. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  382. $resultforextrlang .= $s;
  383. // TODO Use the showInputField() method of ExtraLanguages object
  384. if ($typeofdata == 'textarea') {
  385. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  386. $resultforextrlang .= $valuetoshow;
  387. $resultforextrlang .= '</textarea>';
  388. } else {
  389. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  390. }
  391. }
  392. $result .= $resultforextrlang;
  393. $result .= '</div>';
  394. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  395. }
  396. return $result;
  397. }
  398. /**
  399. * Output edit in place form
  400. *
  401. * @param object $object Object
  402. * @param string $value Value to show/edit
  403. * @param string $htmlname DIV ID (field name)
  404. * @param int $condition Condition to edit
  405. * @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')
  406. * @param string $editvalue When in edit mode, use this value as $value instead of value
  407. * @param object $extObject External object
  408. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  409. * @return string HTML edit in place
  410. */
  411. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  412. {
  413. global $conf;
  414. $out = '';
  415. // Check parameters
  416. if (preg_match('/^text/', $inputType)) {
  417. $value = dol_nl2br($value);
  418. } elseif (preg_match('/^numeric/', $inputType)) {
  419. $value = price($value);
  420. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  421. $value = dol_print_date($value, 'day');
  422. }
  423. if ($condition) {
  424. $element = false;
  425. $table_element = false;
  426. $fk_element = false;
  427. $loadmethod = false;
  428. $savemethod = false;
  429. $ext_element = false;
  430. $button_only = false;
  431. $inputOption = '';
  432. if (is_object($object)) {
  433. $element = $object->element;
  434. $table_element = $object->table_element;
  435. $fk_element = $object->id;
  436. }
  437. if (is_object($extObject)) {
  438. $ext_element = $extObject->element;
  439. }
  440. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  441. $tmp = explode(':', $inputType);
  442. $inputType = $tmp[0];
  443. if (!empty($tmp[1])) {
  444. $inputOption = $tmp[1];
  445. }
  446. if (!empty($tmp[2])) {
  447. $savemethod = $tmp[2];
  448. }
  449. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  450. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  451. $tmp = explode(':', $inputType);
  452. $inputType = $tmp[0];
  453. if (!empty($tmp[1])) {
  454. $inputOption = $tmp[1];
  455. }
  456. if (!empty($tmp[2])) {
  457. $savemethod = $tmp[2];
  458. }
  459. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  460. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  461. $tmp = explode(':', $inputType);
  462. $inputType = $tmp[0];
  463. $loadmethod = $tmp[1];
  464. if (!empty($tmp[2])) {
  465. $savemethod = $tmp[2];
  466. }
  467. if (!empty($tmp[3])) {
  468. $button_only = true;
  469. }
  470. } elseif (preg_match('/^textarea/', $inputType)) {
  471. $tmp = explode(':', $inputType);
  472. $inputType = $tmp[0];
  473. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  474. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  475. } elseif (preg_match('/^ckeditor/', $inputType)) {
  476. $tmp = explode(':', $inputType);
  477. $inputType = $tmp[0];
  478. $toolbar = $tmp[1];
  479. if (!empty($tmp[2])) {
  480. $width = $tmp[2];
  481. }
  482. if (!empty($tmp[3])) {
  483. $heigth = $tmp[3];
  484. }
  485. if (!empty($tmp[4])) {
  486. $savemethod = $tmp[4];
  487. }
  488. if (!empty($conf->fckeditor->enabled)) {
  489. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  490. } else {
  491. $inputType = 'textarea';
  492. }
  493. }
  494. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  495. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  496. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  497. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  498. if (!empty($savemethod)) {
  499. $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  500. }
  501. if (!empty($ext_element)) {
  502. $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  503. }
  504. if (!empty($custommsg)) {
  505. if (is_array($custommsg)) {
  506. if (!empty($custommsg['success'])) {
  507. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  508. }
  509. if (!empty($custommsg['error'])) {
  510. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  511. }
  512. } else {
  513. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  514. }
  515. }
  516. if ($inputType == 'textarea') {
  517. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  518. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  519. }
  520. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  521. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  522. } else {
  523. $out = $value;
  524. }
  525. return $out;
  526. }
  527. /**
  528. * Show a text and picto with tooltip on text or picto.
  529. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  530. *
  531. * @param string $text Text to show
  532. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  533. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  534. * @param int $direction -1=image is before, 0=no image, 1=image is after
  535. * @param string $img Html code for image (use img_xxx() function to get it)
  536. * @param string $extracss Add a CSS style to td tags
  537. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  538. * @param string $incbefore Include code before the text
  539. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  540. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  541. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  542. * @return string Code html du tooltip (texte+picto)
  543. * @see textwithpicto() Use thisfunction if you can.
  544. */
  545. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  546. {
  547. if ($incbefore) {
  548. $text = $incbefore.$text;
  549. }
  550. if (!$htmltext) {
  551. return $text;
  552. }
  553. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  554. $tag = 'td';
  555. if ($notabs == 2) {
  556. $tag = 'div';
  557. }
  558. if ($notabs == 3) {
  559. $tag = 'span';
  560. }
  561. // Sanitize tooltip
  562. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  563. $extrastyle = '';
  564. if ($direction < 0) {
  565. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  566. $extrastyle = 'padding: 0px; padding-left: 3px !important;';
  567. }
  568. if ($direction > 0) {
  569. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  570. $extrastyle = 'padding: 0px; padding-right: 3px !important;';
  571. }
  572. $classfortooltip = 'classfortooltip';
  573. $s = '';
  574. $textfordialog = '';
  575. if ($tooltiptrigger == '') {
  576. $htmltext = str_replace('"', '&quot;', $htmltext);
  577. } else {
  578. $classfortooltip = 'classfortooltiponclick';
  579. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  580. }
  581. if ($tooltipon == 2 || $tooltipon == 3) {
  582. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  583. if ($tooltiptrigger == '') {
  584. $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  585. } else {
  586. $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  587. }
  588. } else {
  589. $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  590. }
  591. if ($tooltipon == 1 || $tooltipon == 3) {
  592. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  593. if ($tooltiptrigger == '') {
  594. $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  595. } else {
  596. $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  597. }
  598. } else {
  599. $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  600. }
  601. if (empty($notabs)) {
  602. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  603. } elseif ($notabs == 2) {
  604. $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  605. }
  606. // Define value if value is before
  607. if ($direction < 0) {
  608. $s .= '<'.$tag.$paramfortooltipimg;
  609. if ($tag == 'td') {
  610. $s .= ' class=valigntop" width="14"';
  611. }
  612. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  613. }
  614. // Use another method to help avoid having a space in value in order to use this value with jquery
  615. // Define label
  616. if ((string) $text != '') {
  617. $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  618. }
  619. // Define value if value is after
  620. if ($direction > 0) {
  621. $s .= '<'.$tag.$paramfortooltipimg;
  622. if ($tag == 'td') {
  623. $s .= ' class="valignmiddle" width="14"';
  624. }
  625. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  626. }
  627. if (empty($notabs)) {
  628. $s .= '</tr></table>';
  629. } elseif ($notabs == 2) {
  630. $s .= '</div>';
  631. }
  632. return $s;
  633. }
  634. /**
  635. * Show a text with a picto and a tooltip on picto
  636. *
  637. * @param string $text Text to show
  638. * @param string $htmltext Content of tooltip
  639. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  640. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  641. * @param string $extracss Add a CSS style to td, div or span tag
  642. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  643. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  644. * @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')
  645. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  646. * @return string HTML code of text, picto, tooltip
  647. */
  648. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  649. {
  650. global $conf, $langs;
  651. $alt = '';
  652. if ($tooltiptrigger) {
  653. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  654. }
  655. //For backwards compatibility
  656. if ($type == '0') {
  657. $type = 'info';
  658. } elseif ($type == '1') {
  659. $type = 'help';
  660. }
  661. // If info or help with no javascript, show only text
  662. if (empty($conf->use_javascript_ajax)) {
  663. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  664. return $text;
  665. } else {
  666. $alt = $htmltext;
  667. $htmltext = '';
  668. }
  669. }
  670. // If info or help with smartphone, show only text (tooltip hover can't works)
  671. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  672. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  673. return $text;
  674. }
  675. }
  676. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  677. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  678. //{
  679. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  680. //}
  681. $img = '';
  682. if ($type == 'info') {
  683. $img = img_help(0, $alt);
  684. } elseif ($type == 'help') {
  685. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  686. } elseif ($type == 'helpclickable') {
  687. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  688. } elseif ($type == 'superadmin') {
  689. $img = img_picto($alt, 'redstar');
  690. } elseif ($type == 'admin') {
  691. $img = img_picto($alt, 'star');
  692. } elseif ($type == 'warning') {
  693. $img = img_warning($alt);
  694. } elseif ($type != 'none') {
  695. $img = img_picto($alt, $type); // $type can be an image path
  696. }
  697. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  698. }
  699. /**
  700. * Generate select HTML to choose massaction
  701. *
  702. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  703. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  704. * @param int $alwaysvisible 1=select button always visible
  705. * @param string $name Name for massaction
  706. * @param string $cssclass CSS class used to check for select
  707. * @return string|void Select list
  708. */
  709. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  710. {
  711. global $conf, $langs, $hookmanager;
  712. $disabled = 0;
  713. $ret = '<div class="centpercent center">';
  714. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  715. // 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.
  716. $parameters = array();
  717. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  718. // check if there is a mass action
  719. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  720. return;
  721. }
  722. if (empty($reshook)) {
  723. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  724. foreach ($arrayofaction as $code => $label) {
  725. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  726. }
  727. }
  728. $ret .= $hookmanager->resPrint;
  729. $ret .= '</select>';
  730. if (empty($conf->dol_optimize_smallscreen)) {
  731. $ret .= ajax_combobox('.'.$name.'select');
  732. }
  733. // 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
  734. $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.
  735. $ret .= '<input type="submit" disabled name="confirmmassaction"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display: none"').' class="button smallpaddingimp'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'confirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  736. $ret .= '</div>';
  737. if (!empty($conf->use_javascript_ajax)) {
  738. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  739. <script>
  740. 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 */
  741. {
  742. atleastoneselected=0;
  743. jQuery("."+cssclass).each(function( index ) {
  744. /* console.log( index + ": " + $( this ).text() ); */
  745. if ($(this).is(\':checked\')) atleastoneselected++;
  746. });
  747. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  748. if (atleastoneselected || '.$alwaysvisible.')
  749. {
  750. jQuery("."+name).show();
  751. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  752. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  753. }
  754. else
  755. {
  756. jQuery("."+name).hide();
  757. jQuery("."+name+"other").hide();
  758. }
  759. }
  760. jQuery(document).ready(function () {
  761. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  762. jQuery(".' . $cssclass.'").click(function() {
  763. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  764. });
  765. jQuery(".' . $name.'select").change(function() {
  766. var massaction = $( this ).val();
  767. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  768. if (massaction == "builddoc")
  769. {
  770. urlform = urlform + "#show_files";
  771. }
  772. $( this ).closest("form").attr("action", urlform);
  773. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  774. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  775. if ($(this).val() != \'0\')
  776. {
  777. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  778. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  779. jQuery(".' . $name.'"+massaction).show();
  780. }
  781. else
  782. {
  783. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  784. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  785. }
  786. });
  787. });
  788. </script>
  789. ';
  790. }
  791. return $ret;
  792. }
  793. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  794. /**
  795. * Return combo list of activated countries, into language of user
  796. *
  797. * @param string $selected Id or Code or Label of preselected country
  798. * @param string $htmlname Name of html select object
  799. * @param string $htmloption More html options on select object
  800. * @param integer $maxlength Max length for labels (0=no limit)
  801. * @param string $morecss More css class
  802. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  803. * @param int $showempty Show empty choice
  804. * @param int $disablefavorites 1=Disable favorites,
  805. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  806. * @param array $exclude_country_code Array of country code (iso2) to exclude
  807. * @param int $hideflags Hide flags
  808. * @return string HTML string with select
  809. */
  810. public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array(), $hideflags = 0)
  811. {
  812. // phpcs:enable
  813. global $conf, $langs, $mysoc;
  814. $langs->load("dict");
  815. $out = '';
  816. $countryArray = array();
  817. $favorite = array();
  818. $label = array();
  819. $atleastonefavorite = 0;
  820. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  821. $sql .= " FROM ".$this->db->prefix()."c_country";
  822. $sql .= " WHERE active > 0";
  823. //$sql.= " ORDER BY code ASC";
  824. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  825. $resql = $this->db->query($sql);
  826. if ($resql) {
  827. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  828. $num = $this->db->num_rows($resql);
  829. $i = 0;
  830. if ($num) {
  831. while ($i < $num) {
  832. $obj = $this->db->fetch_object($resql);
  833. $countryArray[$i]['rowid'] = $obj->rowid;
  834. $countryArray[$i]['code_iso'] = $obj->code_iso;
  835. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  836. $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 : ''));
  837. $countryArray[$i]['favorite'] = $obj->favorite;
  838. $countryArray[$i]['eec'] = $obj->eec;
  839. $favorite[$i] = $obj->favorite;
  840. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  841. $i++;
  842. }
  843. if (empty($disablefavorites)) {
  844. array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  845. } else {
  846. $countryArray = dol_sort_array($countryArray, 'label');
  847. }
  848. if ($showempty) {
  849. $out .= '<option value="">&nbsp;</option>'."\n";
  850. }
  851. if ($addspecialentries) { // Add dedicated entries for groups of countries
  852. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  853. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  854. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  855. if ($mysoc->isInEEC()) {
  856. $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  857. }
  858. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  859. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  860. }
  861. foreach ($countryArray as $row) {
  862. //if (empty($showempty) && empty($row['rowid'])) continue;
  863. if (empty($row['rowid'])) {
  864. continue;
  865. }
  866. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  867. continue; // exclude some countries
  868. }
  869. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  870. $atleastonefavorite++;
  871. }
  872. if (empty($row['favorite']) && $atleastonefavorite) {
  873. $atleastonefavorite = 0;
  874. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  875. }
  876. $labeltoshow = '';
  877. if ($row['label']) {
  878. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  879. } else {
  880. $labeltoshow .= '&nbsp;';
  881. }
  882. if ($row['code_iso']) {
  883. $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
  884. if (empty($hideflags)) {
  885. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  886. $labeltoshow = $tmpflag.' '.$labeltoshow;
  887. }
  888. }
  889. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  890. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" selected data-html="'.dol_escape_htmltag($labeltoshow).'" data-eec="'.((int) $row['eec']).'">';
  891. } else {
  892. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" data-html="'.dol_escape_htmltag($labeltoshow).'" data-eec="'.((int) $row['eec']).'">';
  893. }
  894. $out .= $labeltoshow;
  895. $out .= '</option>'."\n";
  896. }
  897. }
  898. $out .= '</select>';
  899. } else {
  900. dol_print_error($this->db);
  901. }
  902. // Make select dynamic
  903. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  904. $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
  905. return $out;
  906. }
  907. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  908. /**
  909. * Return select list of incoterms
  910. *
  911. * @param string $selected Id or Code of preselected incoterm
  912. * @param string $location_incoterms Value of input location
  913. * @param string $page Defined the form action
  914. * @param string $htmlname Name of html select object
  915. * @param string $htmloption Options html on select object
  916. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  917. * @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')))
  918. * @return string HTML string with select and input
  919. */
  920. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
  921. {
  922. // phpcs:enable
  923. global $conf, $langs;
  924. $langs->load("dict");
  925. $out = '';
  926. $moreattrib = '';
  927. $incotermArray = array();
  928. $sql = "SELECT rowid, code";
  929. $sql .= " FROM ".$this->db->prefix()."c_incoterms";
  930. $sql .= " WHERE active > 0";
  931. $sql .= " ORDER BY code ASC";
  932. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  933. $resql = $this->db->query($sql);
  934. if ($resql) {
  935. if ($conf->use_javascript_ajax && !$forcecombo) {
  936. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  937. $out .= ajax_combobox($htmlname, $events);
  938. }
  939. if (!empty($page)) {
  940. $out .= '<form method="post" action="'.$page.'">';
  941. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  942. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  943. }
  944. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm width75" name="'.$htmlname.'" '.$htmloption.'>';
  945. $out .= '<option value="0">&nbsp;</option>';
  946. $num = $this->db->num_rows($resql);
  947. $i = 0;
  948. if ($num) {
  949. $foundselected = false;
  950. while ($i < $num) {
  951. $obj = $this->db->fetch_object($resql);
  952. $incotermArray[$i]['rowid'] = $obj->rowid;
  953. $incotermArray[$i]['code'] = $obj->code;
  954. $i++;
  955. }
  956. foreach ($incotermArray as $row) {
  957. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  958. $out .= '<option value="'.$row['rowid'].'" selected>';
  959. } else {
  960. $out .= '<option value="'.$row['rowid'].'">';
  961. }
  962. if ($row['code']) {
  963. $out .= $row['code'];
  964. }
  965. $out .= '</option>';
  966. }
  967. }
  968. $out .= '</select>';
  969. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  970. $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT.'/core/ajax/locationincoterms.php')."\n";
  971. $moreattrib .= ' autocomplete="off"';
  972. }
  973. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="'.$location_incoterms.'">'."\n";
  974. if (!empty($page)) {
  975. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="'.$langs->trans("Modify").'"></form>';
  976. }
  977. } else {
  978. dol_print_error($this->db);
  979. }
  980. return $out;
  981. }
  982. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  983. /**
  984. * Return list of types of lines (product or service)
  985. * Example: 0=product, 1=service, 9=other (for external module)
  986. *
  987. * @param string $selected Preselected type
  988. * @param string $htmlname Name of field in html form
  989. * @param int $showempty Add an empty field
  990. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  991. * @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')
  992. * @return void
  993. */
  994. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  995. {
  996. // phpcs:enable
  997. global $langs, $conf;
  998. // If product & services are enabled or both disabled.
  999. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  1000. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled))) {
  1001. if (empty($hidetext)) {
  1002. print $langs->trans("Type").': ';
  1003. }
  1004. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  1005. if ($showempty) {
  1006. print '<option value="-1"';
  1007. if ($selected == -1) {
  1008. print ' selected';
  1009. }
  1010. print '>&nbsp;</option>';
  1011. }
  1012. print '<option value="0"';
  1013. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1014. print ' selected';
  1015. }
  1016. print '>'.$langs->trans("Product");
  1017. print '<option value="1"';
  1018. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1019. print ' selected';
  1020. }
  1021. print '>'.$langs->trans("Service");
  1022. print '</select>';
  1023. print ajax_combobox('select_'.$htmlname);
  1024. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1025. }
  1026. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3) {
  1027. print $langs->trans("Service");
  1028. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  1029. }
  1030. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2) {
  1031. print $langs->trans("Product");
  1032. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  1033. }
  1034. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1035. 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
  1036. }
  1037. }
  1038. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1039. /**
  1040. * Load into cache cache_types_fees, array of types of fees
  1041. *
  1042. * @return int Nb of lines loaded, <0 if KO
  1043. */
  1044. public function load_cache_types_fees()
  1045. {
  1046. // phpcs:enable
  1047. global $langs;
  1048. $num = count($this->cache_types_fees);
  1049. if ($num > 0) {
  1050. return 0; // Cache already loaded
  1051. }
  1052. dol_syslog(__METHOD__, LOG_DEBUG);
  1053. $langs->load("trips");
  1054. $sql = "SELECT c.code, c.label";
  1055. $sql .= " FROM ".$this->db->prefix()."c_type_fees as c";
  1056. $sql .= " WHERE active > 0";
  1057. $resql = $this->db->query($sql);
  1058. if ($resql) {
  1059. $num = $this->db->num_rows($resql);
  1060. $i = 0;
  1061. while ($i < $num) {
  1062. $obj = $this->db->fetch_object($resql);
  1063. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1064. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1065. $this->cache_types_fees[$obj->code] = $label;
  1066. $i++;
  1067. }
  1068. asort($this->cache_types_fees);
  1069. return $num;
  1070. } else {
  1071. dol_print_error($this->db);
  1072. return -1;
  1073. }
  1074. }
  1075. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1076. /**
  1077. * Return list of types of notes
  1078. *
  1079. * @param string $selected Preselected type
  1080. * @param string $htmlname Name of field in form
  1081. * @param int $showempty Add an empty field
  1082. * @return void
  1083. */
  1084. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1085. {
  1086. // phpcs:enable
  1087. global $user, $langs;
  1088. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  1089. $this->load_cache_types_fees();
  1090. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  1091. if ($showempty) {
  1092. print '<option value="-1"';
  1093. if ($selected == -1) {
  1094. print ' selected';
  1095. }
  1096. print '>&nbsp;</option>';
  1097. }
  1098. foreach ($this->cache_types_fees as $key => $value) {
  1099. print '<option value="'.$key.'"';
  1100. if ($key == $selected) {
  1101. print ' selected';
  1102. }
  1103. print '>';
  1104. print $value;
  1105. print '</option>';
  1106. }
  1107. print '</select>';
  1108. if ($user->admin) {
  1109. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1110. }
  1111. }
  1112. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1113. /**
  1114. * Output html form to select a third party
  1115. *
  1116. * @param string $selected Preselected type
  1117. * @param string $htmlname Name of field in form
  1118. * @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)')
  1119. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1120. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1121. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1122. * @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')))
  1123. * @param int $limit Maximum number of elements
  1124. * @param string $morecss Add more css styles to the SELECT component
  1125. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1126. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1127. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1128. * @param array $ajaxoptions Options for ajax_autocompleter
  1129. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1130. * @param array $excludeids Exclude IDs from the select combo
  1131. * @return string HTML string with select box for thirdparty.
  1132. */
  1133. public function select_company($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $limit = 0, $morecss = 'minwidth100', $moreparam = '', $selected_input_value = '', $hidelabel = 1, $ajaxoptions = array(), $multiple = false, $excludeids = array())
  1134. {
  1135. // phpcs:enable
  1136. global $conf, $user, $langs;
  1137. $out = '';
  1138. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1139. if (is_null($ajaxoptions)) {
  1140. $ajaxoptions = array();
  1141. }
  1142. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1143. // No immediate load of all database
  1144. $placeholder = '';
  1145. if ($selected && empty($selected_input_value)) {
  1146. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1147. $societetmp = new Societe($this->db);
  1148. $societetmp->fetch($selected);
  1149. $selected_input_value = $societetmp->name;
  1150. unset($societetmp);
  1151. }
  1152. // mode 1
  1153. $urloption = 'htmlname='.urlencode(str_replace('.', '_', $htmlname)).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '');
  1154. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1155. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1156. if (empty($hidelabel)) {
  1157. print $langs->trans("RefOrLabel").' : ';
  1158. } elseif ($hidelabel > 1) {
  1159. $placeholder = $langs->trans("RefOrLabel");
  1160. if ($hidelabel == 2) {
  1161. $out .= img_picto($langs->trans("Search"), 'search');
  1162. }
  1163. }
  1164. $out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '').' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1165. if ($hidelabel == 3) {
  1166. $out .= img_picto($langs->trans("Search"), 'search');
  1167. }
  1168. } else {
  1169. // Immediate load of all database
  1170. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids);
  1171. }
  1172. return $out;
  1173. }
  1174. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1175. /**
  1176. * Output html form to select a third party.
  1177. * 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.
  1178. *
  1179. * @param string $selected Preselected type
  1180. * @param string $htmlname Name of field in form
  1181. * @param string $filter Optional filters criteras (example: 's.rowid NOT IN (x)', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  1182. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1183. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1184. * @param int $forcecombo Force to use standard HTML select component without beautification
  1185. * @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')))
  1186. * @param string $filterkey Filter on key value
  1187. * @param int $outputmode 0=HTML select string, 1=Array
  1188. * @param int $limit Limit number of answers
  1189. * @param string $morecss Add more css styles to the SELECT component
  1190. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1191. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1192. * @param array $excludeids Exclude IDs from the select combo
  1193. * @return string HTML string with
  1194. */
  1195. public function select_thirdparty_list($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $filterkey = '', $outputmode = 0, $limit = 0, $morecss = 'minwidth100', $moreparam = '', $multiple = false, $excludeids = array())
  1196. {
  1197. // phpcs:enable
  1198. global $conf, $user, $langs;
  1199. global $hookmanager;
  1200. $out = '';
  1201. $num = 0;
  1202. $outarray = array();
  1203. if ($selected === '') {
  1204. $selected = array();
  1205. } elseif (!is_array($selected)) {
  1206. $selected = array($selected);
  1207. }
  1208. // Clean $filter that may contains sql conditions so sql code
  1209. if (function_exists('testSqlAndScriptInject')) {
  1210. if (testSqlAndScriptInject($filter, 3) > 0) {
  1211. $filter = '';
  1212. }
  1213. }
  1214. // We search companies
  1215. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1216. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1217. $sql .= ", s.address, s.zip, s.town";
  1218. $sql .= ", dictp.code as country_code";
  1219. }
  1220. $sql .= " FROM ".$this->db->prefix()."societe as s";
  1221. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1222. $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as dictp ON dictp.rowid = s.fk_pays";
  1223. }
  1224. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1225. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  1226. }
  1227. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1228. if (!empty($user->socid)) {
  1229. $sql .= " AND s.rowid = ".((int) $user->socid);
  1230. }
  1231. if ($filter) {
  1232. $sql .= " AND (".$filter.")";
  1233. }
  1234. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1235. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1236. }
  1237. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1238. $sql .= " AND s.status <> 0";
  1239. }
  1240. if (!empty($excludeids)) {
  1241. $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
  1242. }
  1243. // Add where from hooks
  1244. $parameters = array();
  1245. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1246. $sql .= $hookmanager->resPrint;
  1247. // Add criteria
  1248. if ($filterkey && $filterkey != '') {
  1249. $sql .= " AND (";
  1250. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1251. // For natural search
  1252. $scrit = explode(' ', $filterkey);
  1253. $i = 0;
  1254. if (count($scrit) > 1) {
  1255. $sql .= "(";
  1256. }
  1257. foreach ($scrit as $crit) {
  1258. if ($i > 0) {
  1259. $sql .= " AND ";
  1260. }
  1261. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1262. $i++;
  1263. }
  1264. if (count($scrit) > 1) {
  1265. $sql .= ")";
  1266. }
  1267. if (!empty($conf->barcode->enabled)) {
  1268. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1269. }
  1270. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1271. $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1272. $sql .= ")";
  1273. }
  1274. $sql .= $this->db->order("nom", "ASC");
  1275. $sql .= $this->db->plimit($limit, 0);
  1276. // Build output string
  1277. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1278. $resql = $this->db->query($sql);
  1279. if ($resql) {
  1280. if (!$forcecombo) {
  1281. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1282. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1283. }
  1284. // Construct $out and $outarray
  1285. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1286. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1287. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1288. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1289. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1290. if ($showempty && !is_numeric($showempty)) {
  1291. $textifempty = $langs->trans($showempty);
  1292. } else {
  1293. $textifempty .= $langs->trans("All");
  1294. }
  1295. }
  1296. if ($showempty) {
  1297. $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
  1298. }
  1299. $num = $this->db->num_rows($resql);
  1300. $i = 0;
  1301. if ($num) {
  1302. while ($i < $num) {
  1303. $obj = $this->db->fetch_object($resql);
  1304. $label = '';
  1305. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1306. if (($obj->client) && (!empty($obj->code_client))) {
  1307. $label = $obj->code_client.' - ';
  1308. }
  1309. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1310. $label .= $obj->code_fournisseur.' - ';
  1311. }
  1312. $label .= ' '.$obj->name;
  1313. } else {
  1314. $label = $obj->name;
  1315. }
  1316. if (!empty($obj->name_alias)) {
  1317. $label .= ' ('.$obj->name_alias.')';
  1318. }
  1319. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1320. $label .= ' - '.$obj->tva_intra.'';
  1321. }
  1322. if ($showtype) {
  1323. if ($obj->client || $obj->fournisseur) {
  1324. $label .= ' (';
  1325. }
  1326. if ($obj->client == 1 || $obj->client == 3) {
  1327. $label .= $langs->trans("Customer");
  1328. }
  1329. if ($obj->client == 2 || $obj->client == 3) {
  1330. $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1331. }
  1332. if ($obj->fournisseur) {
  1333. $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1334. }
  1335. if ($obj->client || $obj->fournisseur) {
  1336. $label .= ')';
  1337. }
  1338. }
  1339. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1340. $label .= ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1341. if (!empty($obj->country_code)) {
  1342. $label .= ', '.$langs->trans('Country'.$obj->country_code);
  1343. }
  1344. }
  1345. if (empty($outputmode)) {
  1346. if (in_array($obj->rowid, $selected)) {
  1347. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1348. } else {
  1349. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1350. }
  1351. } else {
  1352. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1353. }
  1354. $i++;
  1355. if (($i % 10) == 0) {
  1356. $out .= "\n";
  1357. }
  1358. }
  1359. }
  1360. $out .= '</select>'."\n";
  1361. } else {
  1362. dol_print_error($this->db);
  1363. }
  1364. $this->result = array('nbofthirdparties'=>$num);
  1365. if ($outputmode) {
  1366. return $outarray;
  1367. }
  1368. return $out;
  1369. }
  1370. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1371. /**
  1372. * Return HTML combo list of absolute discounts
  1373. *
  1374. * @param string $selected Id remise fixe pre-selectionnee
  1375. * @param string $htmlname Nom champ formulaire
  1376. * @param string $filter Criteres optionnels de filtre
  1377. * @param int $socid Id of thirdparty
  1378. * @param int $maxvalue Max value for lines that can be selected
  1379. * @return int Return number of qualifed lines in list
  1380. */
  1381. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1382. {
  1383. // phpcs:enable
  1384. global $langs, $conf;
  1385. // On recherche les remises
  1386. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1387. $sql .= " re.description, re.fk_facture_source";
  1388. $sql .= " FROM ".$this->db->prefix()."societe_remise_except as re";
  1389. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1390. $sql .= " AND re.entity = ".$conf->entity;
  1391. if ($filter) {
  1392. $sql .= " AND ".$filter;
  1393. }
  1394. $sql .= " ORDER BY re.description ASC";
  1395. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1396. $resql = $this->db->query($sql);
  1397. if ($resql) {
  1398. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1399. $num = $this->db->num_rows($resql);
  1400. $qualifiedlines = $num;
  1401. $i = 0;
  1402. if ($num) {
  1403. print '<option value="0">&nbsp;</option>';
  1404. while ($i < $num) {
  1405. $obj = $this->db->fetch_object($resql);
  1406. $desc = dol_trunc($obj->description, 40);
  1407. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1408. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1409. }
  1410. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1411. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1412. }
  1413. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1414. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1415. }
  1416. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1417. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1418. }
  1419. $selectstring = '';
  1420. if ($selected > 0 && $selected == $obj->rowid) {
  1421. $selectstring = ' selected';
  1422. }
  1423. $disabled = '';
  1424. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1425. $qualifiedlines--;
  1426. $disabled = ' disabled';
  1427. }
  1428. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1429. $tmpfac = new Facture($this->db);
  1430. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1431. $desc = $desc.' - '.$tmpfac->ref;
  1432. }
  1433. }
  1434. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1435. $i++;
  1436. }
  1437. }
  1438. print '</select>';
  1439. print ajax_combobox('select_'.$htmlname);
  1440. return $qualifiedlines;
  1441. } else {
  1442. dol_print_error($this->db);
  1443. return -1;
  1444. }
  1445. }
  1446. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1447. /**
  1448. * Return list of all contacts (for a third party or all)
  1449. *
  1450. * @param int $socid Id ot third party or 0 for all
  1451. * @param string $selected Id contact pre-selectionne
  1452. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1453. * @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
  1454. * @param string $exclude List of contacts id to exclude
  1455. * @param string $limitto Disable answers that are not id in this array list
  1456. * @param integer $showfunction Add function into label
  1457. * @param string $morecss Add more class to class style
  1458. * @param integer $showsoc Add company into label
  1459. * @param int $forcecombo Force to use combo box
  1460. * @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')))
  1461. * @param bool $options_only Return options only (for ajax treatment)
  1462. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1463. * @param string $htmlid Html id to use instead of htmlname
  1464. * @return int <0 if KO, Nb of contact in list if OK
  1465. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1466. */
  1467. public function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
  1468. {
  1469. // phpcs:enable
  1470. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1471. return $this->num;
  1472. }
  1473. /**
  1474. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1475. * This also set the number of contacts found into $this->num
  1476. *
  1477. * @since 9.0 Add afterSelectContactOptions hook
  1478. *
  1479. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1480. * @param array|int $selected Array of ID of pre-selected contact id
  1481. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1482. * @param int|string $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
  1483. * @param string $exclude List of contacts id to exclude
  1484. * @param string $limitto Disable answers that are not id in this array list
  1485. * @param integer $showfunction Add function into label
  1486. * @param string $morecss Add more class to class style
  1487. * @param bool $options_only Return options only (for ajax treatment)
  1488. * @param integer $showsoc Add company into label
  1489. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1490. * @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')))
  1491. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1492. * @param string $htmlid Html id to use instead of htmlname
  1493. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1494. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1495. * @return int|string <0 if KO, HTML with select string if OK.
  1496. */
  1497. public function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0)
  1498. {
  1499. global $conf, $langs, $hookmanager, $action;
  1500. $langs->load('companies');
  1501. if (empty($htmlid)) {
  1502. $htmlid = $htmlname;
  1503. }
  1504. $num = 0;
  1505. if ($selected === '') {
  1506. $selected = array();
  1507. } elseif (!is_array($selected)) {
  1508. $selected = array($selected);
  1509. }
  1510. $out = '';
  1511. if (!is_object($hookmanager)) {
  1512. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1513. $hookmanager = new HookManager($this->db);
  1514. }
  1515. // We search third parties
  1516. $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";
  1517. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1518. $sql .= ", s.nom as company, s.town AS company_town";
  1519. }
  1520. $sql .= " FROM ".$this->db->prefix()."socpeople as sp";
  1521. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1522. $sql .= " LEFT OUTER JOIN ".$this->db->prefix()."societe as s ON s.rowid=sp.fk_soc";
  1523. }
  1524. $sql .= " WHERE sp.entity IN (".getEntity('contact').")";
  1525. if ($socid > 0 || $socid == -1) {
  1526. $sql .= " AND sp.fk_soc = ".((int) $socid);
  1527. }
  1528. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1529. $sql .= " AND sp.statut <> 0";
  1530. }
  1531. // Add where from hooks
  1532. $parameters = array();
  1533. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1534. $sql .= $hookmanager->resPrint;
  1535. $sql .= " ORDER BY sp.lastname ASC";
  1536. dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
  1537. $resql = $this->db->query($sql);
  1538. if ($resql) {
  1539. $num = $this->db->num_rows($resql);
  1540. if ($htmlname != 'none' && !$options_only) {
  1541. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1542. }
  1543. if ($showempty && ! is_numeric($showempty)) {
  1544. $textforempty = $showempty;
  1545. $out .= '<option class="optiongrey" value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>'.$textforempty.'</option>';
  1546. } else {
  1547. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && ! $multiple) {
  1548. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1549. }
  1550. if ($showempty == 2) {
  1551. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1552. }
  1553. }
  1554. $i = 0;
  1555. if ($num) {
  1556. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1557. $contactstatic = new Contact($this->db);
  1558. while ($i < $num) {
  1559. $obj = $this->db->fetch_object($resql);
  1560. // Set email (or phones) and town extended infos
  1561. $extendedInfos = '';
  1562. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1563. $extendedInfos = array();
  1564. $email = trim($obj->email);
  1565. if (!empty($email)) {
  1566. $extendedInfos[] = $email;
  1567. } else {
  1568. $phone = trim($obj->phone);
  1569. $phone_perso = trim($obj->phone_perso);
  1570. $phone_mobile = trim($obj->phone_mobile);
  1571. if (!empty($phone)) {
  1572. $extendedInfos[] = $phone;
  1573. }
  1574. if (!empty($phone_perso)) {
  1575. $extendedInfos[] = $phone_perso;
  1576. }
  1577. if (!empty($phone_mobile)) {
  1578. $extendedInfos[] = $phone_mobile;
  1579. }
  1580. }
  1581. $contact_town = trim($obj->contact_town);
  1582. $company_town = trim($obj->company_town);
  1583. if (!empty($contact_town)) {
  1584. $extendedInfos[] = $contact_town;
  1585. } elseif (!empty($company_town)) {
  1586. $extendedInfos[] = $company_town;
  1587. }
  1588. $extendedInfos = implode(' - ', $extendedInfos);
  1589. if (!empty($extendedInfos)) {
  1590. $extendedInfos = ' - '.$extendedInfos;
  1591. }
  1592. }
  1593. $contactstatic->id = $obj->rowid;
  1594. $contactstatic->lastname = $obj->lastname;
  1595. $contactstatic->firstname = $obj->firstname;
  1596. if ($obj->statut == 1) {
  1597. if ($htmlname != 'none') {
  1598. $disabled = 0;
  1599. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1600. $disabled = 1;
  1601. }
  1602. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1603. $disabled = 1;
  1604. }
  1605. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1606. $out .= '<option value="'.$obj->rowid.'"';
  1607. if ($disabled) {
  1608. $out .= ' disabled';
  1609. }
  1610. $out .= ' selected>';
  1611. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1612. if ($showfunction && $obj->poste) {
  1613. $out .= ' ('.$obj->poste.')';
  1614. }
  1615. if (($showsoc > 0) && $obj->company) {
  1616. $out .= ' - ('.$obj->company.')';
  1617. }
  1618. $out .= '</option>';
  1619. } else {
  1620. $out .= '<option value="'.$obj->rowid.'"';
  1621. if ($disabled) {
  1622. $out .= ' disabled';
  1623. }
  1624. $out .= '>';
  1625. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1626. if ($showfunction && $obj->poste) {
  1627. $out .= ' ('.$obj->poste.')';
  1628. }
  1629. if (($showsoc > 0) && $obj->company) {
  1630. $out .= ' - ('.$obj->company.')';
  1631. }
  1632. $out .= '</option>';
  1633. }
  1634. } else {
  1635. if (in_array($obj->rowid, $selected)) {
  1636. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1637. if ($showfunction && $obj->poste) {
  1638. $out .= ' ('.$obj->poste.')';
  1639. }
  1640. if (($showsoc > 0) && $obj->company) {
  1641. $out .= ' - ('.$obj->company.')';
  1642. }
  1643. }
  1644. }
  1645. }
  1646. $i++;
  1647. }
  1648. } else {
  1649. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1650. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1651. $out .= $labeltoshow;
  1652. $out .= '</option>';
  1653. }
  1654. $parameters = array(
  1655. 'socid'=>$socid,
  1656. 'htmlname'=>$htmlname,
  1657. 'resql'=>$resql,
  1658. 'out'=>&$out,
  1659. 'showfunction'=>$showfunction,
  1660. 'showsoc'=>$showsoc,
  1661. );
  1662. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1663. if ($htmlname != 'none' && !$options_only) {
  1664. $out .= '</select>';
  1665. }
  1666. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1667. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1668. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1669. }
  1670. $this->num = $num;
  1671. return $out;
  1672. } else {
  1673. dol_print_error($this->db);
  1674. return -1;
  1675. }
  1676. }
  1677. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1678. /**
  1679. * Return the HTML select list of users
  1680. *
  1681. * @param string $selected Id user preselected
  1682. * @param string $htmlname Field name in form
  1683. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1684. * @param array $exclude Array list of users id to exclude
  1685. * @param int $disabled If select list must be disabled
  1686. * @param array|string $include Array list of users id to include. User '' for all users or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1687. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1688. * @param string $force_entity '0' or Ids of environment to force
  1689. * @return void
  1690. * @deprecated Use select_dolusers instead
  1691. * @see select_dolusers()
  1692. */
  1693. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1694. {
  1695. // phpcs:enable
  1696. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1697. }
  1698. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1699. /**
  1700. * Return select list of users
  1701. *
  1702. * @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)
  1703. * @param string $htmlname Field name in form
  1704. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1705. * @param array $exclude Array list of users id to exclude
  1706. * @param int $disabled If select list must be disabled
  1707. * @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
  1708. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1709. * @param string $force_entity '0' or Ids of environment to force
  1710. * @param int $maxlength Maximum length of string into list (0=no limit)
  1711. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1712. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1713. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1714. * @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.
  1715. * @param string $morecss More css
  1716. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1717. * @param int $outputmode 0=HTML select string, 1=Array
  1718. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1719. * @return string HTML select string
  1720. * @see select_dolgroups()
  1721. */
  1722. 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)
  1723. {
  1724. // phpcs:enable
  1725. global $conf, $user, $langs, $hookmanager;
  1726. // If no preselected user defined, we take current user
  1727. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1728. $selected = $user->id;
  1729. }
  1730. if ($selected === '') {
  1731. $selected = array();
  1732. } elseif (!is_array($selected)) {
  1733. $selected = array($selected);
  1734. }
  1735. $excludeUsers = null;
  1736. $includeUsers = null;
  1737. // Permettre l'exclusion d'utilisateurs
  1738. if (is_array($exclude)) {
  1739. $excludeUsers = implode(",", $exclude);
  1740. }
  1741. // Permettre l'inclusion d'utilisateurs
  1742. if (is_array($include)) {
  1743. $includeUsers = implode(",", $include);
  1744. } elseif ($include == 'hierarchy') {
  1745. // Build list includeUsers to have only hierarchy
  1746. $includeUsers = implode(",", $user->getAllChildIds(0));
  1747. } elseif ($include == 'hierarchyme') {
  1748. // Build list includeUsers to have only hierarchy and current user
  1749. $includeUsers = implode(",", $user->getAllChildIds(1));
  1750. }
  1751. $out = '';
  1752. $outarray = array();
  1753. // Forge request to select users
  1754. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1755. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1756. $sql .= ", e.label";
  1757. }
  1758. $sql .= " FROM ".$this->db->prefix()."user as u";
  1759. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1760. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid = u.entity";
  1761. if ($force_entity) {
  1762. $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
  1763. } else {
  1764. $sql .= " WHERE u.entity IS NOT NULL";
  1765. }
  1766. } else {
  1767. if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1768. $sql .= " LEFT JOIN ".$this->db->prefix()."usergroup_user as ug";
  1769. $sql .= " ON ug.fk_user = u.rowid";
  1770. $sql .= " WHERE ug.entity = ".$conf->entity;
  1771. } else {
  1772. $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
  1773. }
  1774. }
  1775. if (!empty($user->socid)) {
  1776. $sql .= " AND u.fk_soc = ".((int) $user->socid);
  1777. }
  1778. if (is_array($exclude) && $excludeUsers) {
  1779. $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
  1780. }
  1781. if ($includeUsers) {
  1782. $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
  1783. }
  1784. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) {
  1785. $sql .= " AND u.statut <> 0";
  1786. }
  1787. if (!empty($morefilter)) {
  1788. $sql .= " ".$morefilter;
  1789. }
  1790. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1791. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1792. if (!empty($reshook)) {
  1793. $sql .= $hookmanager->resPrint;
  1794. }
  1795. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1796. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1797. } else {
  1798. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1799. }
  1800. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1801. $resql = $this->db->query($sql);
  1802. if ($resql) {
  1803. $num = $this->db->num_rows($resql);
  1804. $i = 0;
  1805. if ($num) {
  1806. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1807. $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1808. if ($show_empty && !$multiple) {
  1809. $textforempty = ' ';
  1810. if (!empty($conf->use_javascript_ajax)) {
  1811. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1812. }
  1813. if (!is_numeric($show_empty)) {
  1814. $textforempty = $show_empty;
  1815. }
  1816. $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  1817. }
  1818. if ($show_every) {
  1819. $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1820. }
  1821. $userstatic = new User($this->db);
  1822. while ($i < $num) {
  1823. $obj = $this->db->fetch_object($resql);
  1824. $userstatic->id = $obj->rowid;
  1825. $userstatic->lastname = $obj->lastname;
  1826. $userstatic->firstname = $obj->firstname;
  1827. $userstatic->photo = $obj->photo;
  1828. $userstatic->statut = $obj->status;
  1829. $userstatic->entity = $obj->entity;
  1830. $userstatic->admin = $obj->admin;
  1831. $disableline = '';
  1832. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1833. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1834. }
  1835. $labeltoshow = '';
  1836. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1837. $fullNameMode = 0;
  1838. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1839. $fullNameMode = 1; //Firstname+lastname
  1840. }
  1841. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1842. if (empty($obj->firstname) && empty($obj->lastname)) {
  1843. $labeltoshow .= $obj->login;
  1844. }
  1845. // Complete name with more info
  1846. $moreinfo = '';
  1847. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1848. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1849. }
  1850. if ($showstatus >= 0) {
  1851. if ($obj->status == 1 && $showstatus == 1) {
  1852. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1853. }
  1854. if ($obj->status == 0 && $showstatus == 1) {
  1855. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1856. }
  1857. }
  1858. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1859. if (!$obj->entity) {
  1860. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1861. } else {
  1862. if ($obj->entity != $conf->entity) {
  1863. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1864. }
  1865. }
  1866. }
  1867. $moreinfo .= ($moreinfo ? ')' : '');
  1868. if ($disableline && $disableline != '1') {
  1869. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1870. }
  1871. $labeltoshow .= $moreinfo;
  1872. $out .= '<option value="'.$obj->rowid.'"';
  1873. if ($disableline) {
  1874. $out .= ' disabled';
  1875. }
  1876. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1877. $out .= ' selected';
  1878. }
  1879. $out .= ' data-html="';
  1880. $outhtml = '';
  1881. // if (!empty($obj->photo)) {
  1882. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1883. // }
  1884. if ($showstatus >= 0 && $obj->status == 0) {
  1885. $outhtml .= '<strike class="opacitymediumxxx">';
  1886. }
  1887. $outhtml .= $labeltoshow;
  1888. if ($showstatus >= 0 && $obj->status == 0) {
  1889. $outhtml .= '</strike>';
  1890. }
  1891. $out .= dol_escape_htmltag($outhtml);
  1892. $out .= '">';
  1893. $out .= $labeltoshow;
  1894. $out .= '</option>';
  1895. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1896. $i++;
  1897. }
  1898. } else {
  1899. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1900. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1901. }
  1902. $out .= '</select>';
  1903. if ($num) {
  1904. // Enhance with select2
  1905. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1906. $out .= ajax_combobox($htmlname);
  1907. }
  1908. } else {
  1909. dol_print_error($this->db);
  1910. }
  1911. if ($outputmode) {
  1912. return $outarray;
  1913. }
  1914. return $out;
  1915. }
  1916. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1917. /**
  1918. * Return select list of users. Selected users are stored into session.
  1919. * List of users are provided into $_SESSION['assignedtouser'].
  1920. *
  1921. * @param string $action Value for $action
  1922. * @param string $htmlname Field name in form
  1923. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1924. * @param array $exclude Array list of users id to exclude
  1925. * @param int $disabled If select list must be disabled
  1926. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1927. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1928. * @param int $force_entity '0' or Ids of environment to force
  1929. * @param int $maxlength Maximum length of string into list (0=no limit)
  1930. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1931. * @param string $morefilter Add more filters into sql request
  1932. * @param int $showproperties Show properties of each attendees
  1933. * @param array $listofuserid Array with properties of each user
  1934. * @param array $listofcontactid Array with properties of each contact
  1935. * @param array $listofotherid Array with properties of each other contact
  1936. * @return string HTML select string
  1937. * @see select_dolgroups()
  1938. */
  1939. 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())
  1940. {
  1941. // phpcs:enable
  1942. global $conf, $user, $langs;
  1943. $userstatic = new User($this->db);
  1944. $out = '';
  1945. $assignedtouser = array();
  1946. if (!empty($_SESSION['assignedtouser'])) {
  1947. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1948. }
  1949. $nbassignetouser = count($assignedtouser);
  1950. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1951. if ($nbassignetouser) {
  1952. $out .= '<ul class="attendees">';
  1953. }
  1954. $i = 0;
  1955. $ownerid = 0;
  1956. foreach ($assignedtouser as $key => $value) {
  1957. if ($value['id'] == $ownerid) {
  1958. continue;
  1959. }
  1960. $out .= '<li>';
  1961. $userstatic->fetch($value['id']);
  1962. $out .= $userstatic->getNomUrl(-1);
  1963. if ($i == 0) {
  1964. $ownerid = $value['id'];
  1965. $out .= ' ('.$langs->trans("Owner").')';
  1966. }
  1967. if ($nbassignetouser > 1 && $action != 'view') {
  1968. $out .= ' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned reposition" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
  1969. }
  1970. // Show my availability
  1971. if ($showproperties) {
  1972. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  1973. $out .= '<div class="myavailability inline-block">';
  1974. $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>';
  1975. $out .= '</div>';
  1976. }
  1977. }
  1978. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1979. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1980. $out .= '</li>';
  1981. $i++;
  1982. }
  1983. if ($nbassignetouser) {
  1984. $out .= '</ul>';
  1985. }
  1986. // Method with no ajax
  1987. if ($action != 'view') {
  1988. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1989. $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
  1990. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  1991. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  1992. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  1993. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  1994. $out .= '});';
  1995. $out .= '})</script>';
  1996. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1997. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1998. $out .= '<br>';
  1999. }
  2000. return $out;
  2001. }
  2002. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2003. /**
  2004. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2005. *
  2006. * @param int $selected Preselected products
  2007. * @param string $htmlname Name of HTML select field (must be unique in page).
  2008. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2009. * @param int $limit Limit on number of returned lines
  2010. * @param int $price_level Level of price to show
  2011. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2012. * @param int $finished 2=all, 1=finished, 0=raw material
  2013. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2014. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2015. * @param array $ajaxoptions Options for ajax_autocompleter
  2016. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2017. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2018. * @param int $forcecombo Force to use combo box
  2019. * @param string $morecss Add more css on select
  2020. * @param int $hidepriceinlabel 1=Hide prices in label
  2021. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2022. * 'warehouseopen' = count products from open warehouses,
  2023. * 'warehouseclosed' = count products from closed warehouses,
  2024. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2025. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2026. * @param string $nooutput No print, return the output into a string
  2027. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2028. * @return void|string
  2029. */
  2030. public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 0, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = null, $nooutput = 0, $status_purchase = -1)
  2031. {
  2032. // phpcs:enable
  2033. global $langs, $conf;
  2034. $out = '';
  2035. // check parameters
  2036. $price_level = (!empty($price_level) ? $price_level : 0);
  2037. if (is_null($ajaxoptions)) {
  2038. $ajaxoptions = array();
  2039. }
  2040. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  2041. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  2042. $filtertype = '0';
  2043. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  2044. $filtertype = '1';
  2045. }
  2046. }
  2047. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2048. $placeholder = '';
  2049. if ($selected && empty($selected_input_value)) {
  2050. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2051. $producttmpselect = new Product($this->db);
  2052. $producttmpselect->fetch($selected);
  2053. $selected_input_value = $producttmpselect->ref;
  2054. unset($producttmpselect);
  2055. }
  2056. // handle case where product or service module is disabled + no filter specified
  2057. if ($filtertype == '') {
  2058. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2059. $filtertype = 1;
  2060. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2061. $filtertype = 0;
  2062. }
  2063. }
  2064. // mode=1 means customers products
  2065. $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&status_purchase='.$status_purchase.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  2066. //Price by customer
  2067. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2068. $urloption .= '&socid='.$socid;
  2069. }
  2070. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2071. if (!empty($conf->variants->enabled) && is_array($selected_combinations)) {
  2072. // Code to automatically insert with javascript the select of attributes under the select of product
  2073. // when a parent of variant has been selected.
  2074. $out .= '
  2075. <!-- script to auto show attributes select tags if a variant was selected -->
  2076. <script>
  2077. // auto show attributes fields
  2078. selected = '.json_encode($selected_combinations).';
  2079. combvalues = {};
  2080. jQuery(document).ready(function () {
  2081. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2082. if (jQuery(this).val() == \'free\') {
  2083. jQuery(\'div#attributes_box\').empty();
  2084. }
  2085. });
  2086. jQuery("input#'.$htmlname.'").change(function () {
  2087. if (!jQuery(this).val()) {
  2088. jQuery(\'div#attributes_box\').empty();
  2089. return;
  2090. }
  2091. console.log("A change has started. We get variants fields to inject html select");
  2092. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  2093. id: jQuery(this).val()
  2094. }, function (data) {
  2095. jQuery(\'div#attributes_box\').empty();
  2096. jQuery.each(data, function (key, val) {
  2097. combvalues[val.id] = val.values;
  2098. var span = jQuery(document.createElement(\'div\')).css({
  2099. \'display\': \'table-row\'
  2100. });
  2101. span.append(
  2102. jQuery(document.createElement(\'div\')).text(val.label).css({
  2103. \'font-weight\': \'bold\',
  2104. \'display\': \'table-cell\'
  2105. })
  2106. );
  2107. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2108. \'margin-left\': \'15px\',
  2109. \'white-space\': \'pre\'
  2110. }).append(
  2111. jQuery(document.createElement(\'option\')).val(\'\')
  2112. );
  2113. jQuery.each(combvalues[val.id], function (key, val) {
  2114. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2115. if (selected[val.fk_product_attribute] == val.id) {
  2116. tag.attr(\'selected\', \'selected\');
  2117. }
  2118. html.append(tag);
  2119. });
  2120. span.append(html);
  2121. jQuery(\'div#attributes_box\').append(span);
  2122. });
  2123. })
  2124. });
  2125. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  2126. });
  2127. </script>
  2128. ';
  2129. }
  2130. if (empty($hidelabel)) {
  2131. $out .= $langs->trans("RefOrLabel").' : ';
  2132. } elseif ($hidelabel > 1) {
  2133. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  2134. if ($hidelabel == 2) {
  2135. $out .= img_picto($langs->trans("Search"), 'search');
  2136. }
  2137. }
  2138. $out .= '<input type="text" class="minwidth100'.($morecss ? ' '.$morecss : '').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  2139. if ($hidelabel == 3) {
  2140. $out .= img_picto($langs->trans("Search"), 'search');
  2141. }
  2142. } else {
  2143. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2144. }
  2145. if (empty($nooutput)) {
  2146. print $out;
  2147. } else {
  2148. return $out;
  2149. }
  2150. }
  2151. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2152. /**
  2153. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2154. *
  2155. * @param int $selected Preselected BOM id
  2156. * @param string $htmlname Name of HTML select field (must be unique in page).
  2157. * @param int $limit Limit on number of returned lines
  2158. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2159. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2160. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2161. * @param string $morecss Add more css on select
  2162. * @param string $nooutput No print, return the output into a string
  2163. * @param int $forcecombo Force to use combo box
  2164. * @return void|string
  2165. */
  2166. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 1, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0)
  2167. {
  2168. // phpcs:enable
  2169. global $conf, $user, $langs, $db;
  2170. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2171. $error = 0;
  2172. $out = '';
  2173. if (!$forcecombo) {
  2174. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2175. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2176. }
  2177. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2178. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2179. $sql.= ' FROM '.MAIN_DB_PREFIX.'bom_bom as b';
  2180. $sql.= ' WHERE b.entity IN ('.getEntity('bom').')';
  2181. if (!empty($status)) $sql.= ' AND status = '. (int) $status;
  2182. if (!empty($type)) $sql.= ' AND status = '. (int) $type;
  2183. if (!empty($limit)) $sql.= 'LIMIT '. (int) $limit;
  2184. $resql = $db->query($sql);
  2185. if ($resql) {
  2186. if ($showempty) {
  2187. $out .= '<option value="-1"';
  2188. if (empty($selected)) $out .= ' selected';
  2189. $out .= '>&nbsp;</option>';
  2190. }
  2191. while ($obj = $db->fetch_object($resql)) {
  2192. $product = new Product($db);
  2193. $res = $product->fetch($obj->fk_product);
  2194. if ($obj->rowid == $selected) $out .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.' - '. $product->label .' - '.$obj->label.'</option>';
  2195. $out .= '<option value="'.$obj->rowid.'">'.$obj->ref.' - '.$product->label .' - '. $obj->label.'</option>';
  2196. }
  2197. } else {
  2198. $error++;
  2199. dol_print_error($db);
  2200. }
  2201. if (empty($nooutput)) {
  2202. print $out;
  2203. } else {
  2204. return $out;
  2205. }
  2206. }
  2207. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2208. /**
  2209. * Return list of products for a customer.
  2210. * Called by select_produits.
  2211. *
  2212. * @param int $selected Preselected product
  2213. * @param string $htmlname Name of select html
  2214. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2215. * @param int $limit Limit on number of returned lines
  2216. * @param int $price_level Level of price to show
  2217. * @param string $filterkey Filter on product
  2218. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2219. * @param int $finished Filter on finished field: 2=No filter
  2220. * @param int $outputmode 0=HTML select string, 1=Array
  2221. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2222. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2223. * @param int $forcecombo Force to use combo box
  2224. * @param string $morecss Add more css on select
  2225. * @param int $hidepriceinlabel 1=Hide prices in label
  2226. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2227. * 'warehouseopen' = count products from open warehouses,
  2228. * 'warehouseclosed' = count products from closed warehouses,
  2229. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2230. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2231. * @return array Array of keys for json
  2232. */
  2233. public function select_produits_list($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $status_purchase = -1)
  2234. {
  2235. // phpcs:enable
  2236. global $langs, $conf;
  2237. global $hookmanager;
  2238. $out = '';
  2239. $outarray = array();
  2240. // Units
  2241. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2242. $langs->load('other');
  2243. }
  2244. $warehouseStatusArray = array();
  2245. if (!empty($warehouseStatus)) {
  2246. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2247. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2248. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2249. }
  2250. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2251. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2252. }
  2253. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2254. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2255. }
  2256. }
  2257. $selectFields = " p.rowid, p.ref, p.label, p.description, p.barcode, p.fk_country, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.default_vat_code, p.duration, p.fk_price_expression";
  2258. if (count($warehouseStatusArray)) {
  2259. $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
  2260. } else {
  2261. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  2262. }
  2263. $sql = "SELECT ";
  2264. $sql .= $selectFields.$selectFieldsGrouped;
  2265. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2266. //Product category
  2267. $sql .= ", (SELECT ".$this->db->prefix()."categorie_product.fk_categorie
  2268. FROM ".$this->db->prefix()."categorie_product
  2269. WHERE ".$this->db->prefix()."categorie_product.fk_product=p.rowid
  2270. LIMIT 1
  2271. ) AS categorie_product_id ";
  2272. }
  2273. //Price by customer
  2274. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2275. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2276. $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx, pcp.default_vat_code as custdefault_vat_code, pcp.ref_customer as custref';
  2277. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2278. }
  2279. // Units
  2280. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2281. $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";
  2282. $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';
  2283. }
  2284. // Multilang : we add translation
  2285. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2286. $sql .= ", pl.label as label_translated";
  2287. $sql .= ", pl.description as description_translated";
  2288. $selectFields .= ", label_translated";
  2289. $selectFields .= ", description_translated";
  2290. }
  2291. // Price by quantity
  2292. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2293. $sql .= ", (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid";
  2294. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2295. $sql .= " AND price_level = ".((int) $price_level);
  2296. }
  2297. $sql .= " ORDER BY date_price";
  2298. $sql .= " DESC LIMIT 1) as price_rowid";
  2299. $sql .= ", (SELECT pp.price_by_qty FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid"; // price_by_qty is 1 if some prices by qty exists in subtable
  2300. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2301. $sql .= " AND price_level = ".((int) $price_level);
  2302. }
  2303. $sql .= " ORDER BY date_price";
  2304. $sql .= " DESC LIMIT 1) as price_by_qty";
  2305. $selectFields .= ", price_rowid, price_by_qty";
  2306. }
  2307. $sql .= " FROM ".$this->db->prefix()."product as p";
  2308. if (count($warehouseStatusArray)) {
  2309. $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock as ps on ps.fk_product = p.rowid";
  2310. $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  2311. $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.
  2312. }
  2313. // include search in supplier ref
  2314. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2315. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2316. }
  2317. //Price by customer
  2318. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2319. $sql .= " LEFT JOIN ".$this->db->prefix()."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
  2320. }
  2321. // Units
  2322. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2323. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2324. }
  2325. // Multilang : we add translation
  2326. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2327. $sql .= " LEFT JOIN ".$this->db->prefix()."product_lang as pl ON pl.fk_product = p.rowid ";
  2328. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2329. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  2330. $soc = new Societe($this->db);
  2331. $result = $soc->fetch($socid);
  2332. if ($result > 0 && !empty($soc->default_lang)) {
  2333. $sql .= " AND pl.lang = '".$this->db->escape($soc->default_lang)."'";
  2334. } else {
  2335. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2336. }
  2337. } else {
  2338. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2339. }
  2340. }
  2341. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2342. $sql .= " LEFT JOIN ".$this->db->prefix()."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2343. }
  2344. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  2345. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2346. $sql .= " AND pac.rowid IS NULL";
  2347. }
  2348. if ($finished == 0) {
  2349. $sql .= " AND p.finished = ".((int) $finished);
  2350. } elseif ($finished == 1) {
  2351. $sql .= " AND p.finished = ".((int) $finished);
  2352. if ($status >= 0) {
  2353. $sql .= " AND p.tosell = ".((int) $status);
  2354. }
  2355. } elseif ($status >= 0) {
  2356. $sql .= " AND p.tosell = ".((int) $status);
  2357. }
  2358. if ($status_purchase >= 0) {
  2359. $sql .= " AND p.tobuy = ".((int) $status_purchase);
  2360. }
  2361. // Filter by product type
  2362. if (strval($filtertype) != '') {
  2363. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2364. } elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2365. $sql .= " AND p.fk_product_type = 1";
  2366. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2367. $sql .= " AND p.fk_product_type = 0";
  2368. }
  2369. // Add where from hooks
  2370. $parameters = array();
  2371. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2372. $sql .= $hookmanager->resPrint;
  2373. // Add criteria on ref/label
  2374. if ($filterkey != '') {
  2375. $sql .= ' AND (';
  2376. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2377. // For natural search
  2378. $scrit = explode(' ', $filterkey);
  2379. $i = 0;
  2380. if (count($scrit) > 1) {
  2381. $sql .= "(";
  2382. }
  2383. foreach ($scrit as $crit) {
  2384. if ($i > 0) {
  2385. $sql .= " AND ";
  2386. }
  2387. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2388. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2389. $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2390. }
  2391. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && ! empty($socid)) {
  2392. $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
  2393. }
  2394. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2395. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2396. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2397. $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2398. }
  2399. }
  2400. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2401. $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2402. }
  2403. $sql .= ")";
  2404. $i++;
  2405. }
  2406. if (count($scrit) > 1) {
  2407. $sql .= ")";
  2408. }
  2409. if (!empty($conf->barcode->enabled)) {
  2410. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2411. }
  2412. $sql .= ')';
  2413. }
  2414. if (count($warehouseStatusArray)) {
  2415. $sql .= " GROUP BY ".$selectFields;
  2416. }
  2417. //Sort by category
  2418. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2419. $sql .= " ORDER BY categorie_product_id ";
  2420. //ASC OR DESC order
  2421. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2422. } else {
  2423. $sql .= $this->db->order("p.ref");
  2424. }
  2425. $sql .= $this->db->plimit($limit, 0);
  2426. // Build output string
  2427. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2428. $result = $this->db->query($sql);
  2429. if ($result) {
  2430. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2431. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2432. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2433. $num = $this->db->num_rows($result);
  2434. $events = null;
  2435. if (!$forcecombo) {
  2436. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2437. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2438. }
  2439. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2440. $textifempty = '';
  2441. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2442. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2443. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2444. if ($showempty && !is_numeric($showempty)) {
  2445. $textifempty = $langs->trans($showempty);
  2446. } else {
  2447. $textifempty .= $langs->trans("All");
  2448. }
  2449. } else {
  2450. if ($showempty && !is_numeric($showempty)) {
  2451. $textifempty = $langs->trans($showempty);
  2452. }
  2453. }
  2454. if ($showempty) {
  2455. $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
  2456. }
  2457. $i = 0;
  2458. while ($num && $i < $num) {
  2459. $opt = '';
  2460. $optJson = array();
  2461. $objp = $this->db->fetch_object($result);
  2462. if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1) { // Price by quantity will return many prices for the same product
  2463. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2464. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2465. $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
  2466. $sql .= " ORDER BY quantity ASC";
  2467. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2468. $result2 = $this->db->query($sql);
  2469. if ($result2) {
  2470. $nb_prices = $this->db->num_rows($result2);
  2471. $j = 0;
  2472. while ($nb_prices && $j < $nb_prices) {
  2473. $objp2 = $this->db->fetch_object($result2);
  2474. $objp->price_by_qty_rowid = $objp2->rowid;
  2475. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2476. $objp->price_by_qty_quantity = $objp2->quantity;
  2477. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2478. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2479. // For backward compatibility
  2480. $objp->quantity = $objp2->quantity;
  2481. $objp->price = $objp2->price;
  2482. $objp->unitprice = $objp2->unitprice;
  2483. $objp->remise_percent = $objp2->remise_percent;
  2484. $objp->remise = $objp2->remise;
  2485. //$objp->tva_tx is not overwritten by $objp2 value
  2486. //$objp->default_vat_code is not overwritten by $objp2 value
  2487. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2488. $j++;
  2489. // Add new entry
  2490. // "key" value of json key array is used by jQuery automatically as selected value
  2491. // "label" value of json key array is used by jQuery automatically as text for combo box
  2492. $out .= $opt;
  2493. array_push($outarray, $optJson);
  2494. }
  2495. }
  2496. } else {
  2497. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2498. $price_product = new Product($this->db);
  2499. $price_product->fetch($objp->rowid, '', '', 1);
  2500. $priceparser = new PriceParser($this->db);
  2501. $price_result = $priceparser->parseProduct($price_product);
  2502. if ($price_result >= 0) {
  2503. $objp->price = $price_result;
  2504. $objp->unitprice = $price_result;
  2505. //Calculate the VAT
  2506. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2507. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2508. }
  2509. }
  2510. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2511. // Add new entry
  2512. // "key" value of json key array is used by jQuery automatically as selected value
  2513. // "label" value of json key array is used by jQuery automatically as text for combo box
  2514. $out .= $opt;
  2515. array_push($outarray, $optJson);
  2516. }
  2517. $i++;
  2518. }
  2519. $out .= '</select>';
  2520. $this->db->free($result);
  2521. if (empty($outputmode)) {
  2522. return $out;
  2523. }
  2524. return $outarray;
  2525. } else {
  2526. dol_print_error($this->db);
  2527. }
  2528. }
  2529. /**
  2530. * Function to forge the string with OPTIONs of SELECT.
  2531. * This define value for &$opt and &$optJson.
  2532. * This function is called by select_produits_list().
  2533. *
  2534. * @param resource $objp Resultset of fetch
  2535. * @param string $opt Option (var used for returned value in string option format)
  2536. * @param string $optJson Option (var used for returned value in json format)
  2537. * @param int $price_level Price level
  2538. * @param string $selected Preselected value
  2539. * @param int $hidepriceinlabel Hide price in label
  2540. * @param string $filterkey Filter key to highlight
  2541. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2542. * @return void
  2543. */
  2544. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2545. {
  2546. global $langs, $conf, $user;
  2547. $outkey = '';
  2548. $outval = '';
  2549. $outref = '';
  2550. $outlabel = '';
  2551. $outlabel_translated = '';
  2552. $outdesc = '';
  2553. $outdesc_translated = '';
  2554. $outbarcode = '';
  2555. $outorigin = '';
  2556. $outtype = '';
  2557. $outprice_ht = '';
  2558. $outprice_ttc = '';
  2559. $outpricebasetype = '';
  2560. $outtva_tx = '';
  2561. $outdefault_vat_code = '';
  2562. $outqty = 1;
  2563. $outdiscount = 0;
  2564. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2565. $label = $objp->label;
  2566. if (!empty($objp->label_translated)) {
  2567. $label = $objp->label_translated;
  2568. }
  2569. if (!empty($filterkey) && $filterkey != '') {
  2570. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2571. }
  2572. $outkey = $objp->rowid;
  2573. $outref = $objp->ref;
  2574. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2575. $outlabel = $objp->label;
  2576. $outdesc = $objp->description;
  2577. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2578. $outlabel_translated = $objp->label_translated;
  2579. $outdesc_translated = $objp->description_translated;
  2580. }
  2581. $outbarcode = $objp->barcode;
  2582. $outorigin = $objp->fk_country;
  2583. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2584. $outtype = $objp->fk_product_type;
  2585. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2586. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2587. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2588. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2589. }
  2590. // Units
  2591. $outvalUnits = '';
  2592. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2593. if (!empty($objp->unit_short)) {
  2594. $outvalUnits .= ' - '.$objp->unit_short;
  2595. }
  2596. }
  2597. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2598. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2599. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2600. $outvalUnits .= ' - '.$unitToShow;
  2601. }
  2602. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2603. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2604. $outvalUnits .= ' - '.$unitToShow;
  2605. }
  2606. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2607. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2608. $outvalUnits .= ' - '.$unitToShow;
  2609. }
  2610. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2611. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2612. $outvalUnits .= ' - '.$unitToShow;
  2613. }
  2614. }
  2615. if ($outdurationvalue && $outdurationunit) {
  2616. $da = array(
  2617. 'h' => $langs->trans('Hour'),
  2618. 'd' => $langs->trans('Day'),
  2619. 'w' => $langs->trans('Week'),
  2620. 'm' => $langs->trans('Month'),
  2621. 'y' => $langs->trans('Year')
  2622. );
  2623. if (isset($da[$outdurationunit])) {
  2624. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2625. }
  2626. }
  2627. $opt = '<option value="'.$objp->rowid.'"';
  2628. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2629. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2630. $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.'"';
  2631. }
  2632. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2633. if (!empty($user->rights->stock->lire)) {
  2634. if ($objp->stock > 0) {
  2635. $opt .= ' class="product_line_stock_ok"';
  2636. } elseif ($objp->stock <= 0) {
  2637. $opt .= ' class="product_line_stock_too_low"';
  2638. }
  2639. }
  2640. }
  2641. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2642. $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
  2643. $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
  2644. }
  2645. $opt .= '>';
  2646. $opt .= $objp->ref;
  2647. if (! empty($objp->custref)) {
  2648. $opt.= ' (' . $objp->custref . ')';
  2649. }
  2650. if ($outbarcode) {
  2651. $opt .= ' ('.$outbarcode.')';
  2652. }
  2653. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2654. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2655. $opt .= ' ('.getCountry($outorigin, 1).')';
  2656. }
  2657. $objRef = $objp->ref;
  2658. if (! empty($objp->custref)) {
  2659. $objRef .= ' (' . $objp->custref . ')';
  2660. }
  2661. if (!empty($filterkey) && $filterkey != '') {
  2662. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2663. }
  2664. $outval .= $objRef;
  2665. if ($outbarcode) {
  2666. $outval .= ' ('.$outbarcode.')';
  2667. }
  2668. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2669. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2670. $outval .= ' ('.getCountry($outorigin, 1).')';
  2671. }
  2672. // Units
  2673. $opt .= $outvalUnits;
  2674. $outval .= $outvalUnits;
  2675. $found = 0;
  2676. // Multiprice
  2677. // If we need a particular price level (from 1 to n)
  2678. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2679. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2680. $sql .= " FROM ".$this->db->prefix()."product_price";
  2681. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2682. $sql .= " AND entity IN (".getEntity('productprice').")";
  2683. $sql .= " AND price_level = ".((int) $price_level);
  2684. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2685. $sql .= " LIMIT 1";
  2686. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2687. $result2 = $this->db->query($sql);
  2688. if ($result2) {
  2689. $objp2 = $this->db->fetch_object($result2);
  2690. if ($objp2) {
  2691. $found = 1;
  2692. if ($objp2->price_base_type == 'HT') {
  2693. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2694. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2695. } else {
  2696. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2697. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2698. }
  2699. $outprice_ht = price($objp2->price);
  2700. $outprice_ttc = price($objp2->price_ttc);
  2701. $outpricebasetype = $objp2->price_base_type;
  2702. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2703. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2704. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2705. } else {
  2706. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2707. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2708. }
  2709. }
  2710. } else {
  2711. dol_print_error($this->db);
  2712. }
  2713. }
  2714. // Price by quantity
  2715. 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))) {
  2716. $found = 1;
  2717. $outqty = $objp->quantity;
  2718. $outdiscount = $objp->remise_percent;
  2719. if ($objp->quantity == 1) {
  2720. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2721. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2722. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2723. $outval .= $langs->transnoentities("Unit");
  2724. } else {
  2725. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2726. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2727. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2728. $outval .= $langs->transnoentities("Units");
  2729. }
  2730. $outprice_ht = price($objp->unitprice);
  2731. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2732. $outpricebasetype = $objp->price_base_type;
  2733. $outtva_tx = $objp->tva_tx; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
  2734. $outdefault_vat_code = $objp->default_vat_code; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
  2735. }
  2736. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2737. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2738. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2739. }
  2740. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2741. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2742. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2743. }
  2744. // Price by customer
  2745. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2746. if (!empty($objp->idprodcustprice)) {
  2747. $found = 1;
  2748. if ($objp->custprice_base_type == 'HT') {
  2749. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2750. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2751. } else {
  2752. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2753. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2754. }
  2755. $outprice_ht = price($objp->custprice);
  2756. $outprice_ttc = price($objp->custprice_ttc);
  2757. $outpricebasetype = $objp->custprice_base_type;
  2758. $outtva_tx = $objp->custtva_tx;
  2759. $outdefault_vat_code = $objp->custdefault_vat_code;
  2760. }
  2761. }
  2762. // If level no defined or multiprice not found, we used the default price
  2763. if (empty($hidepriceinlabel) && !$found) {
  2764. if ($objp->price_base_type == 'HT') {
  2765. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2766. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2767. } else {
  2768. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2769. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2770. }
  2771. $outprice_ht = price($objp->price);
  2772. $outprice_ttc = price($objp->price_ttc);
  2773. $outpricebasetype = $objp->price_base_type;
  2774. $outtva_tx = $objp->tva_tx;
  2775. $outdefault_vat_code = $objp->default_vat_code;
  2776. }
  2777. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2778. if (!empty($user->rights->stock->lire)) {
  2779. $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  2780. if ($objp->stock > 0) {
  2781. $outval .= ' - <span class="product_line_stock_ok">';
  2782. } elseif ($objp->stock <= 0) {
  2783. $outval .= ' - <span class="product_line_stock_too_low">';
  2784. }
  2785. $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
  2786. $outval .= '</span>';
  2787. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2788. $langs->load("stocks");
  2789. $tmpproduct = new Product($this->db);
  2790. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2791. $tmpproduct->load_virtual_stock();
  2792. $virtualstock = $tmpproduct->stock_theorique;
  2793. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2794. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2795. if ($virtualstock > 0) {
  2796. $outval .= '<span class="product_line_stock_ok">';
  2797. } elseif ($virtualstock <= 0) {
  2798. $outval .= '<span class="product_line_stock_too_low">';
  2799. }
  2800. $outval .= $virtualstock;
  2801. $outval .= '</span>';
  2802. unset($tmpproduct);
  2803. }
  2804. }
  2805. }
  2806. $opt .= "</option>\n";
  2807. $optJson = array(
  2808. 'key'=>$outkey,
  2809. 'value'=>$outref,
  2810. 'label'=>$outval,
  2811. 'label2'=>$outlabel,
  2812. 'desc'=>$outdesc,
  2813. 'type'=>$outtype,
  2814. 'price_ht'=>price2num($outprice_ht),
  2815. 'price_ttc'=>price2num($outprice_ttc),
  2816. 'pricebasetype'=>$outpricebasetype,
  2817. 'tva_tx'=>$outtva_tx,
  2818. 'default_vat_code'=>$outdefault_vat_code,
  2819. 'qty'=>$outqty,
  2820. 'discount'=>$outdiscount,
  2821. 'duration_value'=>$outdurationvalue,
  2822. 'duration_unit'=>$outdurationunit,
  2823. 'pbq'=>$outpbq,
  2824. 'labeltrans'=>$outlabel_translated,
  2825. 'desctrans'=>$outdesc_translated,
  2826. 'ref_customer'=>$outrefcust
  2827. );
  2828. }
  2829. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2830. /**
  2831. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2832. *
  2833. * @param int $socid Id third party
  2834. * @param string $selected Preselected product
  2835. * @param string $htmlname Name of HTML Select
  2836. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2837. * @param string $filtre For a SQL filter
  2838. * @param array $ajaxoptions Options for ajax_autocompleter
  2839. * @param int $hidelabel Hide label (0=no, 1=yes)
  2840. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2841. * @param string $morecss More CSS
  2842. * @param string $placeholder Placeholder
  2843. * @return void
  2844. */
  2845. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2846. {
  2847. // phpcs:enable
  2848. global $langs, $conf;
  2849. global $price_level, $status, $finished;
  2850. if (!isset($status)) {
  2851. $status = 1;
  2852. }
  2853. $selected_input_value = '';
  2854. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2855. if ($selected > 0) {
  2856. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2857. $producttmpselect = new Product($this->db);
  2858. $producttmpselect->fetch($selected);
  2859. $selected_input_value = $producttmpselect->ref;
  2860. unset($producttmpselect);
  2861. }
  2862. // mode=2 means suppliers products
  2863. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2864. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2865. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
  2866. } else {
  2867. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2868. }
  2869. }
  2870. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2871. /**
  2872. * Return list of suppliers products
  2873. *
  2874. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2875. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2876. * @param string $htmlname Name of HTML select
  2877. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2878. * @param string $filtre Generic filter. Data must not come from user input.
  2879. * @param string $filterkey Filter of produdts
  2880. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2881. * @param int $outputmode 0=HTML select string, 1=Array
  2882. * @param int $limit Limit of line number
  2883. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2884. * @param string $morecss Add more CSS
  2885. * @param int $showstockinlist Show stock information (slower).
  2886. * @param string $placeholder Placeholder
  2887. * @return array Array of keys for json
  2888. */
  2889. public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '', $showstockinlist = 0, $placeholder = '')
  2890. {
  2891. // phpcs:enable
  2892. global $langs, $conf, $user;
  2893. global $hookmanager;
  2894. $out = '';
  2895. $outarray = array();
  2896. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2897. $langs->load('stocks');
  2898. // Units
  2899. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2900. $langs->load('other');
  2901. }
  2902. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock,";
  2903. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2904. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  2905. $sql .= " pfp.supplier_reputation";
  2906. // if we use supplier description of the products
  2907. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2908. $sql .= " ,pfp.desc_fourn as description";
  2909. } else {
  2910. $sql .= " ,p.description";
  2911. }
  2912. // Units
  2913. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2914. $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";
  2915. }
  2916. if (!empty($conf->barcode->enabled)) {
  2917. $sql .= ", pfp.barcode";
  2918. }
  2919. $sql .= " FROM ".$this->db->prefix()."product as p";
  2920. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2921. if ($socid > 0) {
  2922. $sql .= " AND pfp.fk_soc = ".((int) $socid);
  2923. }
  2924. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  2925. // Units
  2926. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2927. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2928. }
  2929. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2930. if ($statut != -1) {
  2931. $sql .= " AND p.tobuy = ".((int) $statut);
  2932. }
  2933. if (strval($filtertype) != '') {
  2934. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2935. }
  2936. if (!empty($filtre)) {
  2937. $sql .= " ".$filtre;
  2938. }
  2939. // Add where from hooks
  2940. $parameters = array();
  2941. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2942. $sql .= $hookmanager->resPrint;
  2943. // Add criteria on ref/label
  2944. if ($filterkey != '') {
  2945. $sql .= ' AND (';
  2946. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2947. // For natural search
  2948. $scrit = explode(' ', $filterkey);
  2949. $i = 0;
  2950. if (count($scrit) > 1) {
  2951. $sql .= "(";
  2952. }
  2953. foreach ($scrit as $crit) {
  2954. if ($i > 0) {
  2955. $sql .= " AND ";
  2956. }
  2957. $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)."%'";
  2958. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2959. $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2960. }
  2961. $sql .= ")";
  2962. $i++;
  2963. }
  2964. if (count($scrit) > 1) {
  2965. $sql .= ")";
  2966. }
  2967. if (!empty($conf->barcode->enabled)) {
  2968. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2969. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2970. }
  2971. $sql .= ')';
  2972. }
  2973. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2974. $sql .= $this->db->plimit($limit, 0);
  2975. // Build output string
  2976. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2977. $result = $this->db->query($sql);
  2978. if ($result) {
  2979. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2980. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2981. $num = $this->db->num_rows($result);
  2982. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2983. $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2984. if (!$selected) {
  2985. $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2986. } else {
  2987. $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2988. }
  2989. $i = 0;
  2990. while ($i < $num) {
  2991. $objp = $this->db->fetch_object($result);
  2992. $outkey = $objp->idprodfournprice; // id in table of price
  2993. if (!$outkey && $alsoproductwithnosupplierprice) {
  2994. $outkey = 'idprod_'.$objp->rowid; // id of product
  2995. }
  2996. $outref = $objp->ref;
  2997. $outval = '';
  2998. $outbarcode = $objp->barcode;
  2999. $outqty = 1;
  3000. $outdiscount = 0;
  3001. $outtype = $objp->fk_product_type;
  3002. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3003. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  3004. // Units
  3005. $outvalUnits = '';
  3006. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  3007. if (!empty($objp->unit_short)) {
  3008. $outvalUnits .= ' - '.$objp->unit_short;
  3009. }
  3010. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3011. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3012. $outvalUnits .= ' - '.$unitToShow;
  3013. }
  3014. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3015. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  3016. $outvalUnits .= ' - '.$unitToShow;
  3017. }
  3018. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3019. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3020. $outvalUnits .= ' - '.$unitToShow;
  3021. }
  3022. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3023. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3024. $outvalUnits .= ' - '.$unitToShow;
  3025. }
  3026. if ($outdurationvalue && $outdurationunit) {
  3027. $da = array(
  3028. 'h' => $langs->trans('Hour'),
  3029. 'd' => $langs->trans('Day'),
  3030. 'w' => $langs->trans('Week'),
  3031. 'm' => $langs->trans('Month'),
  3032. 'y' => $langs->trans('Year')
  3033. );
  3034. if (isset($da[$outdurationunit])) {
  3035. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  3036. }
  3037. }
  3038. }
  3039. $objRef = $objp->ref;
  3040. if ($filterkey && $filterkey != '') {
  3041. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  3042. }
  3043. $objRefFourn = $objp->ref_fourn;
  3044. if ($filterkey && $filterkey != '') {
  3045. $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3046. }
  3047. $label = $objp->label;
  3048. if ($filterkey && $filterkey != '') {
  3049. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  3050. }
  3051. $optlabel = $objp->ref;
  3052. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3053. $optlabel .= ' <span class="opacitymedium">('.$objp->ref_fourn.')</span>';
  3054. }
  3055. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3056. $optlabel .= ' ('.$outbarcode.')';
  3057. }
  3058. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3059. $outvallabel = $objRef;
  3060. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3061. $outvallabel .= ' ('.$objRefFourn.')';
  3062. }
  3063. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3064. $outvallabel .= ' ('.$outbarcode.')';
  3065. }
  3066. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3067. // Units
  3068. $optlabel .= $outvalUnits;
  3069. $outvallabel .= $outvalUnits;
  3070. if (!empty($objp->idprodfournprice)) {
  3071. $outqty = $objp->quantity;
  3072. $outdiscount = $objp->remise_percent;
  3073. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3074. $prod_supplier = new ProductFournisseur($this->db);
  3075. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3076. $prod_supplier->id = $objp->fk_product;
  3077. $prod_supplier->fourn_qty = $objp->quantity;
  3078. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3079. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3080. $priceparser = new PriceParser($this->db);
  3081. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3082. if ($price_result >= 0) {
  3083. $objp->fprice = $price_result;
  3084. if ($objp->quantity >= 1) {
  3085. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3086. }
  3087. }
  3088. }
  3089. if ($objp->quantity == 1) {
  3090. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3091. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  3092. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3093. $outvallabel .= $langs->transnoentities("Unit");
  3094. } else {
  3095. $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;
  3096. $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;
  3097. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3098. $outvallabel .= ' '.$langs->transnoentities("Units");
  3099. }
  3100. if ($objp->quantity > 1) {
  3101. $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
  3102. $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
  3103. }
  3104. if ($objp->remise_percent >= 1) {
  3105. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  3106. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  3107. }
  3108. if ($objp->duration) {
  3109. $optlabel .= " - ".$objp->duration;
  3110. $outvallabel .= " - ".$objp->duration;
  3111. }
  3112. if (!$socid) {
  3113. $optlabel .= " - ".dol_trunc($objp->name, 8);
  3114. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  3115. }
  3116. if ($objp->supplier_reputation) {
  3117. //TODO dictionary
  3118. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  3119. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  3120. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  3121. }
  3122. } else {
  3123. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3124. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3125. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3126. } else // No supplier price defined for product, even on other suppliers
  3127. {
  3128. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3129. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3130. }
  3131. }
  3132. if (!empty($conf->stock->enabled) && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3133. $novirtualstock = ($showstockinlist == 2);
  3134. if (!empty($user->rights->stock->lire)) {
  3135. $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  3136. if ($objp->stock > 0) {
  3137. $optlabel .= ' - <span class="product_line_stock_ok">';
  3138. } elseif ($objp->stock <= 0) {
  3139. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3140. }
  3141. $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
  3142. $optlabel .= '</span>';
  3143. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3144. $langs->load("stocks");
  3145. $tmpproduct = new Product($this->db);
  3146. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3147. $tmpproduct->load_virtual_stock();
  3148. $virtualstock = $tmpproduct->stock_theorique;
  3149. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  3150. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  3151. if ($virtualstock > 0) {
  3152. $optlabel .= '<span class="product_line_stock_ok">';
  3153. } elseif ($virtualstock <= 0) {
  3154. $optlabel .= '<span class="product_line_stock_too_low">';
  3155. }
  3156. $optlabel .= $virtualstock;
  3157. $optlabel .= '</span>';
  3158. unset($tmpproduct);
  3159. }
  3160. }
  3161. }
  3162. $opt = '<option value="'.$outkey.'"';
  3163. if ($selected && $selected == $objp->idprodfournprice) {
  3164. $opt .= ' selected';
  3165. }
  3166. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3167. $opt .= ' disabled';
  3168. }
  3169. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3170. $opt .= ' data-product-id="'.$objp->rowid.'" data-price-id="'.$objp->idprodfournprice.'" data-qty="'.$objp->quantity.'" data-up="'.$objp->unitprice.'" data-discount="'.$outdiscount.'"';
  3171. }
  3172. $opt .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
  3173. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  3174. $opt .= '>';
  3175. $opt .= $optlabel;
  3176. $outval .= $outvallabel;
  3177. $opt .= "</option>\n";
  3178. // Add new entry
  3179. // "key" value of json key array is used by jQuery automatically as selected value. Example: 'type' = product or service, 'price_ht' = unit price without tax
  3180. // "label" value of json key array is used by jQuery automatically as text for combo box
  3181. $out .= $opt;
  3182. array_push(
  3183. $outarray,
  3184. array('key'=>$outkey,
  3185. 'value'=>$outref,
  3186. 'label'=>$outval,
  3187. 'qty'=>$outqty,
  3188. 'price_qty_ht'=>price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3189. 'price_unit_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3190. 'price_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3191. 'tva_tx'=>$objp->tva_tx,
  3192. 'default_vat_code'=>$objp->default_vat_code,
  3193. 'discount'=>$outdiscount,
  3194. 'type'=>$outtype,
  3195. 'duration_value'=>$outdurationvalue,
  3196. 'duration_unit'=>$outdurationunit,
  3197. 'disabled'=>(empty($objp->idprodfournprice) ? true : false),
  3198. 'description'=>$objp->description
  3199. )
  3200. );
  3201. // Exemple of var_dump $outarray
  3202. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3203. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3204. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3205. //}
  3206. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3207. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3208. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3209. $i++;
  3210. }
  3211. $out .= '</select>';
  3212. $this->db->free($result);
  3213. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  3214. $out .= ajax_combobox($htmlname);
  3215. if (empty($outputmode)) {
  3216. return $out;
  3217. }
  3218. return $outarray;
  3219. } else {
  3220. dol_print_error($this->db);
  3221. }
  3222. }
  3223. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3224. /**
  3225. * Return list of suppliers prices for a product
  3226. *
  3227. * @param int $productid Id of product
  3228. * @param string $htmlname Name of HTML field
  3229. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3230. * @return string
  3231. */
  3232. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3233. {
  3234. // phpcs:enable
  3235. global $langs, $conf;
  3236. $langs->load('stocks');
  3237. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3238. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3239. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3240. $sql .= " FROM ".$this->db->prefix()."product as p";
  3241. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3242. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  3243. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  3244. $sql .= " AND p.tobuy = 1";
  3245. $sql .= " AND s.fournisseur = 1";
  3246. $sql .= " AND p.rowid = ".((int) $productid);
  3247. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3248. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  3249. $result = $this->db->query($sql);
  3250. if ($result) {
  3251. $num = $this->db->num_rows($result);
  3252. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3253. if (!$num) {
  3254. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  3255. } else {
  3256. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3257. $form .= '<option value="0">&nbsp;</option>';
  3258. $i = 0;
  3259. while ($i < $num) {
  3260. $objp = $this->db->fetch_object($result);
  3261. $opt = '<option value="'.$objp->idprodfournprice.'"';
  3262. //if there is only one supplier, preselect it
  3263. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  3264. $opt .= ' selected';
  3265. }
  3266. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  3267. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3268. $prod_supplier = new ProductFournisseur($this->db);
  3269. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3270. $prod_supplier->id = $productid;
  3271. $prod_supplier->fourn_qty = $objp->quantity;
  3272. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3273. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3274. $priceparser = new PriceParser($this->db);
  3275. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3276. if ($price_result >= 0) {
  3277. $objp->fprice = $price_result;
  3278. if ($objp->quantity >= 1) {
  3279. $objp->unitprice = $objp->fprice / $objp->quantity;
  3280. }
  3281. }
  3282. }
  3283. if ($objp->quantity == 1) {
  3284. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3285. }
  3286. $opt .= $objp->quantity.' ';
  3287. if ($objp->quantity == 1) {
  3288. $opt .= $langs->trans("Unit");
  3289. } else {
  3290. $opt .= $langs->trans("Units");
  3291. }
  3292. if ($objp->quantity > 1) {
  3293. $opt .= " - ";
  3294. $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");
  3295. }
  3296. if ($objp->duration) {
  3297. $opt .= " - ".$objp->duration;
  3298. }
  3299. $opt .= "</option>\n";
  3300. $form .= $opt;
  3301. $i++;
  3302. }
  3303. }
  3304. $form .= '</select>';
  3305. $this->db->free($result);
  3306. return $form;
  3307. } else {
  3308. dol_print_error($this->db);
  3309. }
  3310. }
  3311. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3312. /**
  3313. * Return list of delivery address
  3314. *
  3315. * @param string $selected Id contact pre-selectionn
  3316. * @param int $socid Id of company
  3317. * @param string $htmlname Name of HTML field
  3318. * @param int $showempty Add an empty field
  3319. * @return integer|null
  3320. */
  3321. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3322. {
  3323. // phpcs:enable
  3324. // looking for users
  3325. $sql = "SELECT a.rowid, a.label";
  3326. $sql .= " FROM ".$this->db->prefix()."societe_address as a";
  3327. $sql .= " WHERE a.fk_soc = ".((int) $socid);
  3328. $sql .= " ORDER BY a.label ASC";
  3329. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  3330. $resql = $this->db->query($sql);
  3331. if ($resql) {
  3332. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3333. if ($showempty) {
  3334. print '<option value="0">&nbsp;</option>';
  3335. }
  3336. $num = $this->db->num_rows($resql);
  3337. $i = 0;
  3338. if ($num) {
  3339. while ($i < $num) {
  3340. $obj = $this->db->fetch_object($resql);
  3341. if ($selected && $selected == $obj->rowid) {
  3342. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  3343. } else {
  3344. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  3345. }
  3346. $i++;
  3347. }
  3348. }
  3349. print '</select>';
  3350. return $num;
  3351. } else {
  3352. dol_print_error($this->db);
  3353. }
  3354. }
  3355. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3356. /**
  3357. * Load into cache list of payment terms
  3358. *
  3359. * @return int Nb of lines loaded, <0 if KO
  3360. */
  3361. public function load_cache_conditions_paiements()
  3362. {
  3363. // phpcs:enable
  3364. global $langs;
  3365. $num = count($this->cache_conditions_paiements);
  3366. if ($num > 0) {
  3367. return 0; // Cache already loaded
  3368. }
  3369. dol_syslog(__METHOD__, LOG_DEBUG);
  3370. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3371. $sql .= " FROM ".$this->db->prefix().'c_payment_term';
  3372. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  3373. $sql .= " AND active > 0";
  3374. $sql .= " ORDER BY sortorder";
  3375. $resql = $this->db->query($sql);
  3376. if ($resql) {
  3377. $num = $this->db->num_rows($resql);
  3378. $i = 0;
  3379. while ($i < $num) {
  3380. $obj = $this->db->fetch_object($resql);
  3381. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3382. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3383. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3384. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3385. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3386. $i++;
  3387. }
  3388. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3389. return $num;
  3390. } else {
  3391. dol_print_error($this->db);
  3392. return -1;
  3393. }
  3394. }
  3395. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3396. /**
  3397. * Load int a cache property th elist of possible delivery delays.
  3398. *
  3399. * @return int Nb of lines loaded, <0 if KO
  3400. */
  3401. public function load_cache_availability()
  3402. {
  3403. // phpcs:enable
  3404. global $langs;
  3405. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3406. if ($num > 0) {
  3407. return 0; // Cache already loaded
  3408. }
  3409. dol_syslog(__METHOD__, LOG_DEBUG);
  3410. $langs->load('propal');
  3411. $sql = "SELECT rowid, code, label, position";
  3412. $sql .= " FROM ".$this->db->prefix().'c_availability';
  3413. $sql .= " WHERE active > 0";
  3414. $resql = $this->db->query($sql);
  3415. if ($resql) {
  3416. $num = $this->db->num_rows($resql);
  3417. $i = 0;
  3418. while ($i < $num) {
  3419. $obj = $this->db->fetch_object($resql);
  3420. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3421. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3422. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3423. $this->cache_availability[$obj->rowid]['label'] = $label;
  3424. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3425. $i++;
  3426. }
  3427. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3428. return $num;
  3429. } else {
  3430. dol_print_error($this->db);
  3431. return -1;
  3432. }
  3433. }
  3434. /**
  3435. * Retourne la liste des types de delais de livraison possibles
  3436. *
  3437. * @param int $selected Id du type de delais pre-selectionne
  3438. * @param string $htmlname Nom de la zone select
  3439. * @param string $filtertype To add a filter
  3440. * @param int $addempty Add empty entry
  3441. * @param string $morecss More CSS
  3442. * @return void
  3443. */
  3444. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3445. {
  3446. global $langs, $user;
  3447. $this->load_cache_availability();
  3448. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3449. print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3450. if ($addempty) {
  3451. print '<option value="0">&nbsp;</option>';
  3452. }
  3453. foreach ($this->cache_availability as $id => $arrayavailability) {
  3454. if ($selected == $id) {
  3455. print '<option value="'.$id.'" selected>';
  3456. } else {
  3457. print '<option value="'.$id.'">';
  3458. }
  3459. print dol_escape_htmltag($arrayavailability['label']);
  3460. print '</option>';
  3461. }
  3462. print '</select>';
  3463. if ($user->admin) {
  3464. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3465. }
  3466. print ajax_combobox($htmlname);
  3467. }
  3468. /**
  3469. * Load into cache cache_demand_reason, array of input reasons
  3470. *
  3471. * @return int Nb of lines loaded, <0 if KO
  3472. */
  3473. public function loadCacheInputReason()
  3474. {
  3475. global $langs;
  3476. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3477. if ($num > 0) {
  3478. return 0; // Cache already loaded
  3479. }
  3480. $sql = "SELECT rowid, code, label";
  3481. $sql .= " FROM ".$this->db->prefix().'c_input_reason';
  3482. $sql .= " WHERE active > 0";
  3483. $resql = $this->db->query($sql);
  3484. if ($resql) {
  3485. $num = $this->db->num_rows($resql);
  3486. $i = 0;
  3487. $tmparray = array();
  3488. while ($i < $num) {
  3489. $obj = $this->db->fetch_object($resql);
  3490. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3491. $label = ($obj->label != '-' ? $obj->label : '');
  3492. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
  3493. $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3494. }
  3495. if ($langs->trans($obj->code) != $obj->code) {
  3496. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3497. }
  3498. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3499. $tmparray[$obj->rowid]['code'] = $obj->code;
  3500. $tmparray[$obj->rowid]['label'] = $label;
  3501. $i++;
  3502. }
  3503. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3504. unset($tmparray);
  3505. return $num;
  3506. } else {
  3507. dol_print_error($this->db);
  3508. return -1;
  3509. }
  3510. }
  3511. /**
  3512. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3513. * List found into table c_input_reason loaded by loadCacheInputReason
  3514. *
  3515. * @param int $selected Id or code of type origin to select by default
  3516. * @param string $htmlname Nom de la zone select
  3517. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3518. * @param int $addempty Add an empty entry
  3519. * @param string $morecss Add more css to the HTML select component
  3520. * @param int $notooltip Do not show the tooltip for admin
  3521. * @return void
  3522. */
  3523. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3524. {
  3525. global $langs, $user;
  3526. $this->loadCacheInputReason();
  3527. print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3528. if ($addempty) {
  3529. print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3530. }
  3531. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3532. if ($arraydemandreason['code'] == $exclude) {
  3533. continue;
  3534. }
  3535. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3536. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3537. } else {
  3538. print '<option value="'.$arraydemandreason['id'].'">';
  3539. }
  3540. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3541. print $langs->trans($label);
  3542. print '</option>';
  3543. }
  3544. print '</select>';
  3545. if ($user->admin && empty($notooltip)) {
  3546. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3547. }
  3548. print ajax_combobox('select_'.$htmlname);
  3549. }
  3550. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3551. /**
  3552. * Charge dans cache la liste des types de paiements possibles
  3553. *
  3554. * @return int Nb of lines loaded, <0 if KO
  3555. */
  3556. public function load_cache_types_paiements()
  3557. {
  3558. // phpcs:enable
  3559. global $langs;
  3560. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3561. if ($num > 0) {
  3562. return $num; // Cache already loaded
  3563. }
  3564. dol_syslog(__METHOD__, LOG_DEBUG);
  3565. $this->cache_types_paiements = array();
  3566. $sql = "SELECT id, code, libelle as label, type, active";
  3567. $sql .= " FROM ".$this->db->prefix()."c_paiement";
  3568. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3569. $resql = $this->db->query($sql);
  3570. if ($resql) {
  3571. $num = $this->db->num_rows($resql);
  3572. $i = 0;
  3573. while ($i < $num) {
  3574. $obj = $this->db->fetch_object($resql);
  3575. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3576. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3577. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3578. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3579. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3580. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3581. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3582. $i++;
  3583. }
  3584. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3585. return $num;
  3586. } else {
  3587. dol_print_error($this->db);
  3588. return -1;
  3589. }
  3590. }
  3591. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3592. /**
  3593. * print list of payment modes.
  3594. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3595. * See instead to force the default value by the caller.
  3596. *
  3597. * @param int $selected Id of payment term to preselect by default
  3598. * @param string $htmlname Nom de la zone select
  3599. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3600. * @param int $addempty Add an empty entry
  3601. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3602. * @param string $morecss Add more CSS on select tag
  3603. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3604. * 0 : use default deposit percentage from entry
  3605. * > 0 : force deposit percentage (for example, from company object)
  3606. * @return void
  3607. */
  3608. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3609. {
  3610. // phpcs:enable
  3611. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent = -1);
  3612. }
  3613. /**
  3614. * Return list of payment modes.
  3615. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3616. * See instead to force the default value by the caller.
  3617. *
  3618. * @param int $selected Id of payment term to preselect by default
  3619. * @param string $htmlname Nom de la zone select
  3620. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3621. * @param int $addempty Add an empty entry
  3622. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3623. * @param string $morecss Add more CSS on select tag
  3624. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3625. * 0 : use default deposit percentage from entry
  3626. * > 0 : force deposit percentage (for example, from company object)
  3627. * @return string
  3628. */
  3629. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3630. {
  3631. global $langs, $user, $conf;
  3632. $out = '';
  3633. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3634. $this->load_cache_conditions_paiements();
  3635. // Set default value if not already set by caller
  3636. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3637. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3638. }
  3639. $out.= '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3640. if ($addempty) {
  3641. $out.= '<option value="0">&nbsp;</option>';
  3642. }
  3643. $selectedDepositPercent = null;
  3644. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3645. if ($filtertype <= 0 && ! empty($arrayconditions['deposit_percent'])) {
  3646. continue;
  3647. }
  3648. if ($selected == $id) {
  3649. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3650. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3651. } else {
  3652. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3653. }
  3654. $label = $arrayconditions['label'];
  3655. if (! empty($arrayconditions['deposit_percent'])) {
  3656. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3657. }
  3658. $out.= $label;
  3659. $out.= '</option>';
  3660. }
  3661. $out.= '</select>';
  3662. if ($user->admin && empty($noinfoadmin)) {
  3663. $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3664. }
  3665. $out.= ajax_combobox($htmlname);
  3666. if ($deposit_percent >= 0) {
  3667. $out .= ' <span id="'.$htmlname.'_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3668. $out .= $langs->trans('DepositPercent') . ' : ';
  3669. $out .= '<input id="'.$htmlname.'_deposit_percent" name="'.$htmlname.'_deposit_percent" class="maxwidth50" value="' . strval($deposit_percent) . '" />';
  3670. $out .= '</span>';
  3671. $out .= '
  3672. <script>
  3673. $(document).ready(function () {
  3674. $("#' . $htmlname . '").change(function () {
  3675. let $selected = $(this).find("option:selected");
  3676. let depositPercent = $selected.attr("data-deposit_percent");
  3677. if (depositPercent.length > 0) {
  3678. $("#'.$htmlname.'_deposit_percent_container").show().find("#'.$htmlname.'_deposit_percent").val(depositPercent);
  3679. } else {
  3680. $("#'.$htmlname.'_deposit_percent_container").hide();
  3681. }
  3682. return true;
  3683. });
  3684. });
  3685. </script>';
  3686. }
  3687. return $out;
  3688. }
  3689. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3690. /**
  3691. * Return list of payment methods
  3692. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3693. *
  3694. * @param string $selected Id or code or preselected payment mode
  3695. * @param string $htmlname Name of select field
  3696. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3697. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3698. * @param int $empty 1=can be empty, 0 otherwise
  3699. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3700. * @param int $maxlength Max length of label
  3701. * @param int $active Active or not, -1 = all
  3702. * @param string $morecss Add more CSS on select tag
  3703. * @param int $nooutput 1=Return string, do not send to output
  3704. * @return void
  3705. */
  3706. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3707. {
  3708. // phpcs:enable
  3709. global $langs, $user, $conf;
  3710. $out = '';
  3711. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3712. $filterarray = array();
  3713. if ($filtertype == 'CRDT') {
  3714. $filterarray = array(0, 2, 3);
  3715. } elseif ($filtertype == 'DBIT') {
  3716. $filterarray = array(1, 2, 3);
  3717. } elseif ($filtertype != '' && $filtertype != '-1') {
  3718. $filterarray = explode(',', $filtertype);
  3719. }
  3720. $this->load_cache_types_paiements();
  3721. // Set default value if not already set by caller
  3722. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3723. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3724. }
  3725. $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3726. if ($empty) {
  3727. $out .= '<option value="">&nbsp;</option>';
  3728. }
  3729. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3730. // If not good status
  3731. if ($active >= 0 && $arraytypes['active'] != $active) {
  3732. continue;
  3733. }
  3734. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3735. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3736. continue;
  3737. }
  3738. // We discard empty line if showempty is on because an empty line has already been output.
  3739. if ($empty && empty($arraytypes['code'])) {
  3740. continue;
  3741. }
  3742. if ($format == 0) {
  3743. $out .= '<option value="'.$id.'"';
  3744. } elseif ($format == 1) {
  3745. $out .= '<option value="'.$arraytypes['code'].'"';
  3746. } elseif ($format == 2) {
  3747. $out .= '<option value="'.$arraytypes['code'].'"';
  3748. } elseif ($format == 3) {
  3749. $out .= '<option value="'.$id.'"';
  3750. }
  3751. // Print attribute selected or not
  3752. if ($format == 1 || $format == 2) {
  3753. if ($selected == $arraytypes['code']) {
  3754. $out .= ' selected';
  3755. }
  3756. } else {
  3757. if ($selected == $id) {
  3758. $out .= ' selected';
  3759. }
  3760. }
  3761. $out .= '>';
  3762. if ($format == 0) {
  3763. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3764. } elseif ($format == 1) {
  3765. $value = $arraytypes['code'];
  3766. } elseif ($format == 2) {
  3767. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3768. } elseif ($format == 3) {
  3769. $value = $arraytypes['code'];
  3770. }
  3771. $out .= $value ? $value : '&nbsp;';
  3772. $out .= '</option>';
  3773. }
  3774. $out .= '</select>';
  3775. if ($user->admin && !$noadmininfo) {
  3776. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3777. }
  3778. $out .= ajax_combobox('select'.$htmlname);
  3779. if (empty($nooutput)) {
  3780. print $out;
  3781. } else {
  3782. return $out;
  3783. }
  3784. }
  3785. /**
  3786. * Selection HT or TTC
  3787. *
  3788. * @param string $selected Id pre-selectionne
  3789. * @param string $htmlname Nom de la zone select
  3790. * @param string $addjscombo Add js combo
  3791. * @return string Code of HTML select to chose tax or not
  3792. */
  3793. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3794. {
  3795. global $langs;
  3796. $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3797. $options = array(
  3798. 'HT'=>$langs->trans("HT"),
  3799. 'TTC'=>$langs->trans("TTC")
  3800. );
  3801. foreach ($options as $id => $value) {
  3802. if ($selected == $id) {
  3803. $return .= '<option value="'.$id.'" selected>'.$value;
  3804. } else {
  3805. $return .= '<option value="'.$id.'">'.$value;
  3806. }
  3807. $return .= '</option>';
  3808. }
  3809. $return .= '</select>';
  3810. if ($addjscombo) {
  3811. $return .= ajax_combobox('select_'.$htmlname);
  3812. }
  3813. return $return;
  3814. }
  3815. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3816. /**
  3817. * Load in cache list of transport mode
  3818. *
  3819. * @return int Nb of lines loaded, <0 if KO
  3820. */
  3821. public function load_cache_transport_mode()
  3822. {
  3823. // phpcs:enable
  3824. global $langs;
  3825. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  3826. if ($num > 0) {
  3827. return $num; // Cache already loaded
  3828. }
  3829. dol_syslog(__METHOD__, LOG_DEBUG);
  3830. $this->cache_transport_mode = array();
  3831. $sql = "SELECT rowid, code, label, active";
  3832. $sql .= " FROM ".$this->db->prefix()."c_transport_mode";
  3833. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3834. $resql = $this->db->query($sql);
  3835. if ($resql) {
  3836. $num = $this->db->num_rows($resql);
  3837. $i = 0;
  3838. while ($i < $num) {
  3839. $obj = $this->db->fetch_object($resql);
  3840. // If traduction exist, we use it else we take the default label
  3841. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3842. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3843. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3844. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3845. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3846. $i++;
  3847. }
  3848. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3849. return $num;
  3850. } else {
  3851. dol_print_error($this->db);
  3852. return -1;
  3853. }
  3854. }
  3855. /**
  3856. * Return list of transport mode for intracomm report
  3857. *
  3858. * @param string $selected Id of the transport mode pre-selected
  3859. * @param string $htmlname Name of the select field
  3860. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3861. * @param int $empty 1=can be empty, 0 else
  3862. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3863. * @param int $maxlength Max length of label
  3864. * @param int $active Active or not, -1 = all
  3865. * @param string $morecss Add more CSS on select tag
  3866. * @return void
  3867. */
  3868. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3869. {
  3870. global $langs, $user;
  3871. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3872. $this->load_cache_transport_mode();
  3873. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3874. if ($empty) {
  3875. print '<option value="">&nbsp;</option>';
  3876. }
  3877. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3878. // If not good status
  3879. if ($active >= 0 && $arraytypes['active'] != $active) {
  3880. continue;
  3881. }
  3882. // We discard empty line if showempty is on because an empty line has already been output.
  3883. if ($empty && empty($arraytypes['code'])) {
  3884. continue;
  3885. }
  3886. if ($format == 0) {
  3887. print '<option value="'.$id.'"';
  3888. } elseif ($format == 1) {
  3889. print '<option value="'.$arraytypes['code'].'"';
  3890. } elseif ($format == 2) {
  3891. print '<option value="'.$arraytypes['code'].'"';
  3892. } elseif ($format == 3) {
  3893. print '<option value="'.$id.'"';
  3894. }
  3895. // If text is selected, we compare with code, else with id
  3896. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  3897. print ' selected';
  3898. } elseif ($selected == $id) {
  3899. print ' selected';
  3900. }
  3901. print '>';
  3902. if ($format == 0) {
  3903. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3904. } elseif ($format == 1) {
  3905. $value = $arraytypes['code'];
  3906. } elseif ($format == 2) {
  3907. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3908. } elseif ($format == 3) {
  3909. $value = $arraytypes['code'];
  3910. }
  3911. print $value ? $value : '&nbsp;';
  3912. print '</option>';
  3913. }
  3914. print '</select>';
  3915. if ($user->admin && !$noadmininfo) {
  3916. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3917. }
  3918. }
  3919. /**
  3920. * Return a HTML select list of shipping mode
  3921. *
  3922. * @param string $selected Id shipping mode pre-selected
  3923. * @param string $htmlname Name of select zone
  3924. * @param string $filtre To filter list. This parameter must not come from input of users
  3925. * @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.
  3926. * @param string $moreattrib To add more attribute on select
  3927. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3928. * @param string $morecss More CSS
  3929. * @return void
  3930. */
  3931. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  3932. {
  3933. global $langs, $conf, $user;
  3934. $langs->load("admin");
  3935. $langs->load("deliveries");
  3936. $sql = "SELECT rowid, code, libelle as label";
  3937. $sql .= " FROM ".$this->db->prefix()."c_shipment_mode";
  3938. $sql .= " WHERE active > 0";
  3939. if ($filtre) {
  3940. $sql .= " AND ".$filtre;
  3941. }
  3942. $sql .= " ORDER BY libelle ASC";
  3943. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3944. $result = $this->db->query($sql);
  3945. if ($result) {
  3946. $num = $this->db->num_rows($result);
  3947. $i = 0;
  3948. if ($num) {
  3949. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3950. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3951. print '<option value="-1">&nbsp;</option>';
  3952. }
  3953. while ($i < $num) {
  3954. $obj = $this->db->fetch_object($result);
  3955. if ($selected == $obj->rowid) {
  3956. print '<option value="'.$obj->rowid.'" selected>';
  3957. } else {
  3958. print '<option value="'.$obj->rowid.'">';
  3959. }
  3960. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3961. print '</option>';
  3962. $i++;
  3963. }
  3964. print "</select>";
  3965. if ($user->admin && empty($noinfoadmin)) {
  3966. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3967. }
  3968. print ajax_combobox('select'.$htmlname);
  3969. } else {
  3970. print $langs->trans("NoShippingMethodDefined");
  3971. }
  3972. } else {
  3973. dol_print_error($this->db);
  3974. }
  3975. }
  3976. /**
  3977. * Display form to select shipping mode
  3978. *
  3979. * @param string $page Page
  3980. * @param int $selected Id of shipping mode
  3981. * @param string $htmlname Name of select html field
  3982. * @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.
  3983. * @return void
  3984. */
  3985. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  3986. {
  3987. global $langs;
  3988. $langs->load("deliveries");
  3989. if ($htmlname != "none") {
  3990. print '<form method="POST" action="'.$page.'">';
  3991. print '<input type="hidden" name="action" value="setshippingmethod">';
  3992. print '<input type="hidden" name="token" value="'.newToken().'">';
  3993. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3994. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3995. print '</form>';
  3996. } else {
  3997. if ($selected) {
  3998. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  3999. print $langs->trans("SendingMethod".strtoupper($code));
  4000. } else {
  4001. print "&nbsp;";
  4002. }
  4003. }
  4004. }
  4005. /**
  4006. * Creates HTML last in cycle situation invoices selector
  4007. *
  4008. * @param string $selected Preselected ID
  4009. * @param int $socid Company ID
  4010. *
  4011. * @return string HTML select
  4012. */
  4013. public function selectSituationInvoices($selected = '', $socid = 0)
  4014. {
  4015. global $langs;
  4016. $langs->load('bills');
  4017. $opt = '<option value="" selected></option>';
  4018. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4019. $sql .= ' FROM '.$this->db->prefix().'facture';
  4020. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  4021. $sql .= ' AND situation_counter >= 1';
  4022. $sql .= ' AND fk_soc = '.(int) $socid;
  4023. $sql .= ' AND type <> 2';
  4024. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4025. $resql = $this->db->query($sql);
  4026. if ($resql && $this->db->num_rows($resql) > 0) {
  4027. // Last seen cycle
  4028. $ref = 0;
  4029. while ($obj = $this->db->fetch_object($resql)) {
  4030. //Same cycle ?
  4031. if ($obj->situation_cycle_ref != $ref) {
  4032. // Just seen this cycle
  4033. $ref = $obj->situation_cycle_ref;
  4034. //not final ?
  4035. if ($obj->situation_final != 1) {
  4036. //Not prov?
  4037. if (substr($obj->ref, 1, 4) != 'PROV') {
  4038. if ($selected == $obj->rowid) {
  4039. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  4040. } else {
  4041. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  4042. }
  4043. }
  4044. }
  4045. }
  4046. }
  4047. } else {
  4048. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4049. }
  4050. if ($opt == '<option value ="" selected></option>') {
  4051. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  4052. }
  4053. return $opt;
  4054. }
  4055. /**
  4056. * Creates HTML units selector (code => label)
  4057. *
  4058. * @param string $selected Preselected Unit ID
  4059. * @param string $htmlname Select name
  4060. * @param int $showempty Add a nempty line
  4061. * @param string $unit_type Restrict to one given unit type
  4062. * @return string HTML select
  4063. */
  4064. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4065. {
  4066. global $langs;
  4067. $langs->load('products');
  4068. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  4069. $sql = "SELECT rowid, label, code FROM ".$this->db->prefix()."c_units";
  4070. $sql .= ' WHERE active > 0';
  4071. if (!empty($unit_type)) {
  4072. $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
  4073. }
  4074. $sql .= " ORDER BY sortorder";
  4075. $resql = $this->db->query($sql);
  4076. if ($resql && $this->db->num_rows($resql) > 0) {
  4077. if ($showempty) {
  4078. $return .= '<option value="none"></option>';
  4079. }
  4080. while ($res = $this->db->fetch_object($resql)) {
  4081. $unitLabel = $res->label;
  4082. if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
  4083. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  4084. }
  4085. if ($selected == $res->rowid) {
  4086. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  4087. } else {
  4088. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  4089. }
  4090. }
  4091. $return .= '</select>';
  4092. }
  4093. return $return;
  4094. }
  4095. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4096. /**
  4097. * Return a HTML select list of bank accounts
  4098. *
  4099. * @param string $selected Id account pre-selected
  4100. * @param string $htmlname Name of select zone
  4101. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4102. * @param string $filtre To filter list. This parameter must not come from input of users
  4103. * @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.
  4104. * @param string $moreattrib To add more attribute on select
  4105. * @param int $showcurrency Show currency in label
  4106. * @param string $morecss More CSS
  4107. * @param int $nooutput 1=Return string, do not send to output
  4108. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4109. */
  4110. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4111. {
  4112. // phpcs:enable
  4113. global $langs, $conf;
  4114. $out = '';
  4115. $langs->load("admin");
  4116. $num = 0;
  4117. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4118. $sql .= " FROM ".$this->db->prefix()."bank_account";
  4119. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  4120. if ($status != 2) {
  4121. $sql .= " AND clos = ".(int) $status;
  4122. }
  4123. if ($filtre) {
  4124. $sql .= " AND ".$filtre;
  4125. }
  4126. $sql .= " ORDER BY label";
  4127. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  4128. $result = $this->db->query($sql);
  4129. if ($result) {
  4130. $num = $this->db->num_rows($result);
  4131. $i = 0;
  4132. if ($num) {
  4133. $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4134. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4135. $out .= '<option value="-1">&nbsp;</option>';
  4136. }
  4137. while ($i < $num) {
  4138. $obj = $this->db->fetch_object($result);
  4139. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4140. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
  4141. } else {
  4142. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
  4143. }
  4144. $out .= trim($obj->label);
  4145. if ($showcurrency) {
  4146. $out .= ' ('.$obj->currency_code.')';
  4147. }
  4148. if ($status == 2 && $obj->status == 1) {
  4149. $out .= ' ('.$langs->trans("Closed").')';
  4150. }
  4151. $out .= '</option>';
  4152. $i++;
  4153. }
  4154. $out .= "</select>";
  4155. $out .= ajax_combobox('select'.$htmlname);
  4156. } else {
  4157. if ($status == 0) {
  4158. $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  4159. } else {
  4160. $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  4161. }
  4162. }
  4163. } else {
  4164. dol_print_error($this->db);
  4165. }
  4166. // Output or return
  4167. if (empty($nooutput)) {
  4168. print $out;
  4169. } else {
  4170. return $out;
  4171. }
  4172. return $num;
  4173. }
  4174. /**
  4175. * Return a HTML select list of establishment
  4176. *
  4177. * @param string $selected Id establishment pre-selected
  4178. * @param string $htmlname Name of select zone
  4179. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4180. * @param string $filtre To filter list. This parameter must not come from input of users
  4181. * @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.
  4182. * @param string $moreattrib To add more attribute on select
  4183. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4184. */
  4185. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4186. {
  4187. global $langs, $conf;
  4188. $langs->load("admin");
  4189. $num = 0;
  4190. $sql = "SELECT rowid, name, fk_country, status, entity";
  4191. $sql .= " FROM ".$this->db->prefix()."establishment";
  4192. $sql .= " WHERE 1=1";
  4193. if ($status != 2) {
  4194. $sql .= " AND status = ".(int) $status;
  4195. }
  4196. if ($filtre) {
  4197. $sql .= " AND ".$filtre;
  4198. }
  4199. $sql .= " ORDER BY name";
  4200. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  4201. $result = $this->db->query($sql);
  4202. if ($result) {
  4203. $num = $this->db->num_rows($result);
  4204. $i = 0;
  4205. if ($num) {
  4206. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4207. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4208. print '<option value="-1">&nbsp;</option>';
  4209. }
  4210. while ($i < $num) {
  4211. $obj = $this->db->fetch_object($result);
  4212. if ($selected == $obj->rowid) {
  4213. print '<option value="'.$obj->rowid.'" selected>';
  4214. } else {
  4215. print '<option value="'.$obj->rowid.'">';
  4216. }
  4217. print trim($obj->name);
  4218. if ($status == 2 && $obj->status == 1) {
  4219. print ' ('.$langs->trans("Closed").')';
  4220. }
  4221. print '</option>';
  4222. $i++;
  4223. }
  4224. print "</select>";
  4225. } else {
  4226. if ($status == 0) {
  4227. print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  4228. } else {
  4229. print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  4230. }
  4231. }
  4232. } else {
  4233. dol_print_error($this->db);
  4234. }
  4235. }
  4236. /**
  4237. * Display form to select bank account
  4238. *
  4239. * @param string $page Page
  4240. * @param int $selected Id of bank account
  4241. * @param string $htmlname Name of select html field
  4242. * @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.
  4243. * @return void
  4244. */
  4245. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4246. {
  4247. global $langs;
  4248. if ($htmlname != "none") {
  4249. print '<form method="POST" action="'.$page.'">';
  4250. print '<input type="hidden" name="action" value="setbankaccount">';
  4251. print '<input type="hidden" name="token" value="'.newToken().'">';
  4252. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4253. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4254. if ($nbaccountfound > 0) {
  4255. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4256. }
  4257. print '</form>';
  4258. } else {
  4259. $langs->load('banks');
  4260. if ($selected) {
  4261. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  4262. $bankstatic = new Account($this->db);
  4263. $result = $bankstatic->fetch($selected);
  4264. if ($result) {
  4265. print $bankstatic->getNomUrl(1);
  4266. }
  4267. } else {
  4268. print "&nbsp;";
  4269. }
  4270. }
  4271. }
  4272. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4273. /**
  4274. * Return list of categories having choosed type
  4275. *
  4276. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4277. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4278. * @param string $htmlname HTML field name
  4279. * @param int $maxlength Maximum length for labels
  4280. * @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.
  4281. * $markafterid can be an :
  4282. * - int (id of category)
  4283. * - string (categories ids seprated by comma)
  4284. * - array (list of categories ids)
  4285. * @param int $outputmode 0=HTML select string, 1=Array
  4286. * @param int $include [=0] Removed or 1=Keep only
  4287. * @param string $morecss More CSS
  4288. * @return string
  4289. * @see select_categories()
  4290. */
  4291. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4292. {
  4293. // phpcs:enable
  4294. global $conf, $langs;
  4295. $langs->load("categories");
  4296. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4297. // For backward compatibility
  4298. if (is_numeric($type)) {
  4299. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4300. }
  4301. if ($type === Categorie::TYPE_BANK_LINE) {
  4302. // TODO Move this into common category feature
  4303. $cate_arbo = array();
  4304. $sql = "SELECT c.label, c.rowid";
  4305. $sql .= " FROM ".$this->db->prefix()."bank_categ as c";
  4306. $sql .= " WHERE entity = ".$conf->entity;
  4307. $sql .= " ORDER BY c.label";
  4308. $result = $this->db->query($sql);
  4309. if ($result) {
  4310. $num = $this->db->num_rows($result);
  4311. $i = 0;
  4312. while ($i < $num) {
  4313. $objp = $this->db->fetch_object($result);
  4314. if ($objp) {
  4315. $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  4316. }
  4317. $i++;
  4318. }
  4319. $this->db->free($result);
  4320. } else {
  4321. dol_print_error($this->db);
  4322. }
  4323. } else {
  4324. $cat = new Categorie($this->db);
  4325. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4326. }
  4327. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  4328. $outarray = array();
  4329. if (is_array($cate_arbo)) {
  4330. if (!count($cate_arbo)) {
  4331. $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  4332. } else {
  4333. $output .= '<option value="-1">&nbsp;</option>';
  4334. foreach ($cate_arbo as $key => $value) {
  4335. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4336. $add = 'selected ';
  4337. } else {
  4338. $add = '';
  4339. }
  4340. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  4341. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4342. }
  4343. }
  4344. }
  4345. $output .= '</select>';
  4346. $output .= "\n";
  4347. if ($outputmode) {
  4348. return $outarray;
  4349. }
  4350. return $output;
  4351. }
  4352. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4353. /**
  4354. * Show a confirmation HTML form or AJAX popup
  4355. *
  4356. * @param string $page Url of page to call if confirmation is OK
  4357. * @param string $title Title
  4358. * @param string $question Question
  4359. * @param string $action Action
  4360. * @param array $formquestion An array with forms complementary inputs
  4361. * @param string $selectedchoice "" or "no" or "yes"
  4362. * @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
  4363. * @param int $height Force height of box
  4364. * @param int $width Force width of box
  4365. * @return void
  4366. * @deprecated
  4367. * @see formconfirm()
  4368. */
  4369. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4370. {
  4371. // phpcs:enable
  4372. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4373. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4374. }
  4375. /**
  4376. * Show a confirmation HTML form or AJAX popup.
  4377. * Easiest way to use this is with useajax=1.
  4378. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4379. * just after calling this method. For example:
  4380. * print '<script type="text/javascript">'."\n";
  4381. * print 'jQuery(document).ready(function() {'."\n";
  4382. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4383. * print '});'."\n";
  4384. * print '</script>'."\n";
  4385. *
  4386. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4387. * @param string $title Title
  4388. * @param string $question Question
  4389. * @param string $action Action
  4390. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>))
  4391. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', 'other' or 'onecolumn'...
  4392. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  4393. * @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
  4394. * @param int|string $height Force height of box (0 = auto)
  4395. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4396. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4397. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4398. */
  4399. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0)
  4400. {
  4401. global $langs, $conf;
  4402. $more = '<!-- formconfirm before calling page='.dol_escape_htmltag($page).' -->';
  4403. $formconfirm = '';
  4404. $inputok = array();
  4405. $inputko = array();
  4406. // Clean parameters
  4407. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4408. if ($conf->browser->layout == 'phone') {
  4409. $width = '95%';
  4410. }
  4411. // Set height automatically if not defined
  4412. if (empty($height)) {
  4413. $height = 220;
  4414. if (is_array($formquestion) && count($formquestion) > 2) {
  4415. $height += ((count($formquestion) - 2) * 24);
  4416. }
  4417. }
  4418. if (is_array($formquestion) && !empty($formquestion)) {
  4419. // First add hidden fields and value
  4420. foreach ($formquestion as $key => $input) {
  4421. if (is_array($input) && !empty($input)) {
  4422. if ($input['type'] == 'hidden') {
  4423. $more .= '<input type="hidden" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  4424. }
  4425. }
  4426. }
  4427. // Now add questions
  4428. $moreonecolumn = '';
  4429. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  4430. foreach ($formquestion as $key => $input) {
  4431. if (is_array($input) && !empty($input)) {
  4432. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
  4433. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4434. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4435. if ($input['type'] == 'text') {
  4436. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="text" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4437. } elseif ($input['type'] == 'password') {
  4438. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="password" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4439. } elseif ($input['type'] == 'textarea') {
  4440. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4441. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4442. $more .= $input['value'];
  4443. $more .= '</textarea>';
  4444. $more .= '</div></div>'."\n";*/
  4445. $moreonecolumn .= '<div class="margintoponly">';
  4446. $moreonecolumn .= $input['label'].'<br>';
  4447. $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
  4448. $moreonecolumn .= $input['value'];
  4449. $moreonecolumn .= '</textarea>';
  4450. $moreonecolumn .= '</div>';
  4451. } elseif ($input['type'] == 'select') {
  4452. if (empty($morecss)) {
  4453. $morecss = 'minwidth100';
  4454. }
  4455. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4456. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4457. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4458. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4459. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4460. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4461. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4462. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4463. if (!empty($input['label'])) {
  4464. $more .= $input['label'].'</div><div class="tagtd left">';
  4465. }
  4466. $more .= $this->selectarray($input['name'], $input['values'], $input['default'], $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4467. $more .= '</div></div>'."\n";
  4468. } elseif ($input['type'] == 'checkbox') {
  4469. $more .= '<div class="tagtr">';
  4470. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  4471. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
  4472. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4473. $more .= ' checked';
  4474. }
  4475. if (is_bool($input['value']) && $input['value']) {
  4476. $more .= ' checked';
  4477. }
  4478. if (isset($input['disabled'])) {
  4479. $more .= ' disabled';
  4480. }
  4481. $more .= ' /></div>';
  4482. $more .= '</div>'."\n";
  4483. } elseif ($input['type'] == 'radio') {
  4484. $i = 0;
  4485. foreach ($input['values'] as $selkey => $selval) {
  4486. $more .= '<div class="tagtr">';
  4487. if ($i == 0) {
  4488. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4489. } else {
  4490. $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  4491. }
  4492. $more .= '<div class="tagtd'.($i == 0 ? ' tdtop' : '').'"><input type="radio" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name'].$selkey).'" name="'.dol_escape_htmltag($input['name']).'" value="'.$selkey.'"'.$moreattr;
  4493. if ($input['disabled']) {
  4494. $more .= ' disabled';
  4495. }
  4496. if (isset($input['default']) && $input['default'] === $selkey) {
  4497. $more .= ' checked="checked"';
  4498. }
  4499. $more .= ' /> ';
  4500. $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'">'.$selval.'</label>';
  4501. $more .= '</div></div>'."\n";
  4502. $i++;
  4503. }
  4504. } elseif ($input['type'] == 'date') {
  4505. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4506. $more .= '<div class="tagtd">';
  4507. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4508. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, $addnowlink);
  4509. $more .= '</div></div>'."\n";
  4510. $formquestion[] = array('name'=>$input['name'].'day');
  4511. $formquestion[] = array('name'=>$input['name'].'month');
  4512. $formquestion[] = array('name'=>$input['name'].'year');
  4513. $formquestion[] = array('name'=>$input['name'].'hour');
  4514. $formquestion[] = array('name'=>$input['name'].'min');
  4515. } elseif ($input['type'] == 'other') {
  4516. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4517. if (!empty($input['label'])) {
  4518. $more .= $input['label'].'</div><div class="tagtd">';
  4519. }
  4520. $more .= $input['value'];
  4521. $more .= '</div></div>'."\n";
  4522. } elseif ($input['type'] == 'onecolumn') {
  4523. $moreonecolumn .= '<div class="margintoponly">';
  4524. $moreonecolumn .= $input['value'];
  4525. $moreonecolumn .= '</div>'."\n";
  4526. } elseif ($input['type'] == 'hidden') {
  4527. // Do nothing more, already added by a previous loop
  4528. } elseif ($input['type'] == 'separator') {
  4529. $more .= '<br>';
  4530. } else {
  4531. $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
  4532. }
  4533. }
  4534. }
  4535. $more .= '</div>'."\n";
  4536. $more .= $moreonecolumn;
  4537. }
  4538. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4539. // 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
  4540. // See page product/card.php for example
  4541. if (!empty($conf->dol_use_jmobile)) {
  4542. $useajax = 0;
  4543. }
  4544. if (empty($conf->use_javascript_ajax)) {
  4545. $useajax = 0;
  4546. }
  4547. if ($useajax) {
  4548. $autoOpen = true;
  4549. $dialogconfirm = 'dialog-confirm';
  4550. $button = '';
  4551. if (!is_numeric($useajax)) {
  4552. $button = $useajax;
  4553. $useajax = 1;
  4554. $autoOpen = false;
  4555. $dialogconfirm .= '-'.$button;
  4556. }
  4557. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=yes';
  4558. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=no' : '');
  4559. // Add input fields into list of fields to read during submit (inputok and inputko)
  4560. if (is_array($formquestion)) {
  4561. foreach ($formquestion as $key => $input) {
  4562. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4563. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4564. if (is_array($input) && isset($input['name'])) {
  4565. if (strpos($input['name'], ',') > 0) {
  4566. $inputok = array_merge($inputok, explode(',', $input['name']));
  4567. } else {
  4568. array_push($inputok, $input['name']);
  4569. }
  4570. }
  4571. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4572. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4573. array_push($inputko, $input['name']);
  4574. }
  4575. }
  4576. }
  4577. // Show JQuery confirm box.
  4578. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  4579. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4580. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  4581. }
  4582. if (!empty($more)) {
  4583. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  4584. }
  4585. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  4586. $formconfirm .= '</div>'."\n";
  4587. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=".$page." -->\n";
  4588. $formconfirm .= '<script type="text/javascript">'."\n";
  4589. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4590. $formconfirm .= 'jQuery(document).ready(function() {
  4591. $(function() {
  4592. $( "#'.$dialogconfirm.'" ).dialog(
  4593. {
  4594. autoOpen: '.($autoOpen ? "true" : "false").',';
  4595. if ($newselectedchoice == 'no') {
  4596. $formconfirm .= '
  4597. open: function() {
  4598. $(this).parent().find("button.ui-button:eq(2)").focus();
  4599. },';
  4600. }
  4601. $formconfirm .= '
  4602. resizable: false,
  4603. height: "'.$height.'",
  4604. width: "'.$width.'",
  4605. modal: true,
  4606. closeOnEscape: false,
  4607. buttons: {
  4608. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  4609. var options = "&token='.urlencode(newToken()).'";
  4610. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  4611. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  4612. if (inputok.length>0) {
  4613. $.each(inputok, function(i, inputname) {
  4614. var more = "";
  4615. var inputvalue;
  4616. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4617. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4618. } else {
  4619. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4620. inputvalue = $("#" + inputname + more).val();
  4621. }
  4622. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4623. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4624. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4625. });
  4626. }
  4627. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  4628. if (pageyes.length > 0) { location.href = urljump; }
  4629. $(this).dialog("close");
  4630. },
  4631. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  4632. var options = "&token='.urlencode(newToken()).'";
  4633. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  4634. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  4635. if (inputko.length>0) {
  4636. $.each(inputko, function(i, inputname) {
  4637. var more = "";
  4638. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4639. var inputvalue = $("#" + inputname + more).val();
  4640. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4641. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4642. });
  4643. }
  4644. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  4645. //alert(urljump);
  4646. if (pageno.length > 0) { location.href = urljump; }
  4647. $(this).dialog("close");
  4648. }
  4649. }
  4650. }
  4651. );
  4652. var button = "'.$button.'";
  4653. if (button.length > 0) {
  4654. $( "#" + button ).click(function() {
  4655. $("#'.$dialogconfirm.'").dialog("open");
  4656. });
  4657. }
  4658. });
  4659. });
  4660. </script>';
  4661. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4662. } else {
  4663. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  4664. if (empty($disableformtag)) {
  4665. $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  4666. }
  4667. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  4668. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  4669. $formconfirm .= '<table class="valid centpercent">'."\n";
  4670. // Line title
  4671. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4672. $formconfirm .= img_picto('', 'recent').' '.$title;
  4673. $formconfirm .= '</td></tr>'."\n";
  4674. // Line text
  4675. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4676. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  4677. }
  4678. // Line form fields
  4679. if ($more) {
  4680. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
  4681. $formconfirm .= $more;
  4682. $formconfirm .= '</td></tr>'."\n";
  4683. }
  4684. // Line with question
  4685. $formconfirm .= '<tr class="valid">';
  4686. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4687. $formconfirm .= '<td class="valid center">';
  4688. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly');
  4689. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="'.$langs->trans("Validate").'">';
  4690. $formconfirm .= '</td>';
  4691. $formconfirm .= '</tr>'."\n";
  4692. $formconfirm .= '</table>'."\n";
  4693. if (empty($disableformtag)) {
  4694. $formconfirm .= "</form>\n";
  4695. }
  4696. $formconfirm .= '<br>';
  4697. if (!empty($conf->use_javascript_ajax)) {
  4698. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4699. $formconfirm .= '<script type="text/javascript">'."\n";
  4700. $formconfirm .= '
  4701. $(document).ready(function () {
  4702. $(".confirmvalidatebutton").on("click", function() {
  4703. console.log("We click on button");
  4704. $(this).attr("disabled", "disabled");
  4705. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4706. //console.log($(this).closest("form"));
  4707. $(this).closest("form").submit();
  4708. });
  4709. });
  4710. ';
  4711. $formconfirm .= '</script>'."\n";
  4712. }
  4713. $formconfirm .= "<!-- end formconfirm -->\n";
  4714. }
  4715. return $formconfirm;
  4716. }
  4717. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4718. /**
  4719. * Show a form to select a project
  4720. *
  4721. * @param int $page Page
  4722. * @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)
  4723. * @param int $selected Id pre-selected project
  4724. * @param string $htmlname Name of select field
  4725. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4726. * @param int $maxlength Max length
  4727. * @param int $forcefocus Force focus on field (works with javascript only)
  4728. * @param int $nooutput No print is done. String is returned.
  4729. * @return string Return html content
  4730. */
  4731. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  4732. {
  4733. // phpcs:enable
  4734. global $langs;
  4735. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4736. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4737. $out = '';
  4738. $formproject = new FormProjets($this->db);
  4739. $langs->load("project");
  4740. if ($htmlname != "none") {
  4741. $out .= "\n";
  4742. $out .= '<form method="post" action="'.$page.'">';
  4743. $out .= '<input type="hidden" name="action" value="classin">';
  4744. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4745. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  4746. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4747. $out .= '</form>';
  4748. } else {
  4749. $out .= '<span class="project_head_block">';
  4750. if ($selected) {
  4751. $projet = new Project($this->db);
  4752. $projet->fetch($selected);
  4753. $out .= $projet->getNomUrl(1, '', 1);
  4754. } else {
  4755. $out .= "&nbsp;";
  4756. }
  4757. $out .= '</span>';
  4758. }
  4759. if (empty($nooutput)) {
  4760. print $out;
  4761. return '';
  4762. }
  4763. return $out;
  4764. }
  4765. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4766. /**
  4767. * Show a form to select payment conditions
  4768. *
  4769. * @param int $page Page
  4770. * @param string $selected Id condition pre-selectionne
  4771. * @param string $htmlname Name of select html field
  4772. * @param int $addempty Add empty entry
  4773. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4774. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  4775. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  4776. * 0 : use default deposit percentage from entry
  4777. * > 0 : force deposit percentage (for example, from company object)
  4778. * @return void
  4779. */
  4780. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1)
  4781. {
  4782. // phpcs:enable
  4783. global $langs;
  4784. if ($htmlname != "none") {
  4785. print '<form method="POST" action="'.$page.'">';
  4786. print '<input type="hidden" name="action" value="setconditions">';
  4787. print '<input type="hidden" name="token" value="'.newToken().'">';
  4788. if ($type) {
  4789. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4790. }
  4791. $this->select_conditions_paiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  4792. print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4793. print '</form>';
  4794. } else {
  4795. if ($selected) {
  4796. $this->load_cache_conditions_paiements();
  4797. if (isset($this->cache_conditions_paiements[$selected])) {
  4798. $label = $this->cache_conditions_paiements[$selected]['label'];
  4799. if (! empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  4800. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  4801. }
  4802. print $label;
  4803. } else {
  4804. $langs->load('errors');
  4805. print $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4806. }
  4807. } else {
  4808. print "&nbsp;";
  4809. }
  4810. }
  4811. }
  4812. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4813. /**
  4814. * Show a form to select a delivery delay
  4815. *
  4816. * @param int $page Page
  4817. * @param string $selected Id condition pre-selectionne
  4818. * @param string $htmlname Name of select html field
  4819. * @param int $addempty Ajoute entree vide
  4820. * @return void
  4821. */
  4822. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4823. {
  4824. // phpcs:enable
  4825. global $langs;
  4826. if ($htmlname != "none") {
  4827. print '<form method="post" action="'.$page.'">';
  4828. print '<input type="hidden" name="action" value="setavailability">';
  4829. print '<input type="hidden" name="token" value="'.newToken().'">';
  4830. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4831. print '<input type="submit" name="modify" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4832. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="'.$langs->trans("Cancel").'">';
  4833. print '</form>';
  4834. } else {
  4835. if ($selected) {
  4836. $this->load_cache_availability();
  4837. print $this->cache_availability[$selected]['label'];
  4838. } else {
  4839. print "&nbsp;";
  4840. }
  4841. }
  4842. }
  4843. /**
  4844. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  4845. * List found into table c_input_reason loaded by loadCacheInputReason
  4846. *
  4847. * @param string $page Page
  4848. * @param string $selected Id condition pre-selectionne
  4849. * @param string $htmlname Name of select html field
  4850. * @param int $addempty Add empty entry
  4851. * @return void
  4852. */
  4853. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  4854. {
  4855. global $langs;
  4856. if ($htmlname != "none") {
  4857. print '<form method="post" action="'.$page.'">';
  4858. print '<input type="hidden" name="action" value="setdemandreason">';
  4859. print '<input type="hidden" name="token" value="'.newToken().'">';
  4860. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  4861. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4862. print '</form>';
  4863. } else {
  4864. if ($selected) {
  4865. $this->loadCacheInputReason();
  4866. foreach ($this->cache_demand_reason as $key => $val) {
  4867. if ($val['id'] == $selected) {
  4868. print $val['label'];
  4869. break;
  4870. }
  4871. }
  4872. } else {
  4873. print "&nbsp;";
  4874. }
  4875. }
  4876. }
  4877. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4878. /**
  4879. * Show a form + html select a date
  4880. *
  4881. * @param string $page Page
  4882. * @param string $selected Date preselected
  4883. * @param string $htmlname Html name of date input fields or 'none'
  4884. * @param int $displayhour Display hour selector
  4885. * @param int $displaymin Display minutes selector
  4886. * @param int $nooutput 1=No print output, return string
  4887. * @param string $type 'direct-debit' or 'bank-transfer'
  4888. * @return string
  4889. * @see selectDate()
  4890. */
  4891. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  4892. {
  4893. // phpcs:enable
  4894. global $langs;
  4895. $ret = '';
  4896. if ($htmlname != "none") {
  4897. $ret .= '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4898. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4899. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4900. if ($type) {
  4901. $ret .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4902. }
  4903. $ret .= '<table class="nobordernopadding">';
  4904. $ret .= '<tr><td>';
  4905. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4906. $ret .= '</td>';
  4907. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  4908. $ret .= '</tr></table></form>';
  4909. } else {
  4910. if ($displayhour) {
  4911. $ret .= dol_print_date($selected, 'dayhour');
  4912. } else {
  4913. $ret .= dol_print_date($selected, 'day');
  4914. }
  4915. }
  4916. if (empty($nooutput)) {
  4917. print $ret;
  4918. }
  4919. return $ret;
  4920. }
  4921. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4922. /**
  4923. * Show a select form to choose a user
  4924. *
  4925. * @param string $page Page
  4926. * @param string $selected Id of user preselected
  4927. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4928. * @param array $exclude List of users id to exclude
  4929. * @param array $include List of users id to include
  4930. * @return void
  4931. */
  4932. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4933. {
  4934. // phpcs:enable
  4935. global $langs;
  4936. if ($htmlname != "none") {
  4937. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4938. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4939. print '<input type="hidden" name="token" value="'.newToken().'">';
  4940. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  4941. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4942. print '</form>';
  4943. } else {
  4944. if ($selected) {
  4945. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  4946. $theuser = new User($this->db);
  4947. $theuser->fetch($selected);
  4948. print $theuser->getNomUrl(1);
  4949. } else {
  4950. print "&nbsp;";
  4951. }
  4952. }
  4953. }
  4954. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4955. /**
  4956. * Show form with payment mode
  4957. *
  4958. * @param string $page Page
  4959. * @param int $selected Id mode pre-selectionne
  4960. * @param string $htmlname Name of select html field
  4961. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  4962. * @param int $active Active or not, -1 = all
  4963. * @param int $addempty 1=Add empty entry
  4964. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4965. * @return void
  4966. */
  4967. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '')
  4968. {
  4969. // phpcs:enable
  4970. global $langs;
  4971. if ($htmlname != "none") {
  4972. print '<form method="POST" action="'.$page.'">';
  4973. print '<input type="hidden" name="action" value="setmode">';
  4974. print '<input type="hidden" name="token" value="'.newToken().'">';
  4975. if ($type) {
  4976. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4977. }
  4978. print $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  4979. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4980. print '</form>';
  4981. } else {
  4982. if ($selected) {
  4983. $this->load_cache_types_paiements();
  4984. print $this->cache_types_paiements[$selected]['label'];
  4985. } else {
  4986. print "&nbsp;";
  4987. }
  4988. }
  4989. }
  4990. /**
  4991. * Show form with transport mode
  4992. *
  4993. * @param string $page Page
  4994. * @param int $selected Id mode pre-select
  4995. * @param string $htmlname Name of select html field
  4996. * @param int $active Active or not, -1 = all
  4997. * @param int $addempty 1=Add empty entry
  4998. * @return void
  4999. */
  5000. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5001. {
  5002. global $langs;
  5003. if ($htmlname != "none") {
  5004. print '<form method="POST" action="'.$page.'">';
  5005. print '<input type="hidden" name="action" value="settransportmode">';
  5006. print '<input type="hidden" name="token" value="'.newToken().'">';
  5007. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5008. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5009. print '</form>';
  5010. } else {
  5011. if ($selected) {
  5012. $this->load_cache_transport_mode();
  5013. print $this->cache_transport_mode[$selected]['label'];
  5014. } else {
  5015. print "&nbsp;";
  5016. }
  5017. }
  5018. }
  5019. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5020. /**
  5021. * Show form with multicurrency code
  5022. *
  5023. * @param string $page Page
  5024. * @param string $selected code pre-selectionne
  5025. * @param string $htmlname Name of select html field
  5026. * @return void
  5027. */
  5028. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5029. {
  5030. // phpcs:enable
  5031. global $langs;
  5032. if ($htmlname != "none") {
  5033. print '<form method="POST" action="'.$page.'">';
  5034. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5035. print '<input type="hidden" name="token" value="'.newToken().'">';
  5036. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5037. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5038. print '</form>';
  5039. } else {
  5040. dol_include_once('/core/lib/company.lib.php');
  5041. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5042. }
  5043. }
  5044. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5045. /**
  5046. * Show form with multicurrency rate
  5047. *
  5048. * @param string $page Page
  5049. * @param double $rate Current rate
  5050. * @param string $htmlname Name of select html field
  5051. * @param string $currency Currency code to explain the rate
  5052. * @return void
  5053. */
  5054. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5055. {
  5056. // phpcs:enable
  5057. global $langs, $mysoc, $conf;
  5058. if ($htmlname != "none") {
  5059. print '<form method="POST" action="'.$page.'">';
  5060. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5061. print '<input type="hidden" name="token" value="'.newToken().'">';
  5062. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
  5063. print '<select name="calculation_mode">';
  5064. print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
  5065. print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
  5066. print '</select> ';
  5067. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5068. print '</form>';
  5069. } else {
  5070. if (!empty($rate)) {
  5071. print price($rate, 1, $langs, 1, 0);
  5072. if ($currency && $rate != 1) {
  5073. print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  5074. }
  5075. } else {
  5076. print 1;
  5077. }
  5078. }
  5079. }
  5080. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5081. /**
  5082. * Show a select box with available absolute discounts
  5083. *
  5084. * @param string $page Page URL where form is shown
  5085. * @param int $selected Value pre-selected
  5086. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5087. * @param int $socid Third party id
  5088. * @param float $amount Total amount available
  5089. * @param string $filter SQL filter on discounts
  5090. * @param int $maxvalue Max value for lines that can be selected
  5091. * @param string $more More string to add
  5092. * @param int $hidelist 1=Hide list
  5093. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5094. * @return void
  5095. */
  5096. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5097. {
  5098. // phpcs:enable
  5099. global $conf, $langs;
  5100. if ($htmlname != "none") {
  5101. print '<form method="post" action="'.$page.'">';
  5102. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5103. print '<input type="hidden" name="token" value="'.newToken().'">';
  5104. print '<div class="inline-block">';
  5105. if (!empty($discount_type)) {
  5106. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5107. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5108. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5109. } else {
  5110. $translationKey = 'HasCreditNoteFromSupplier';
  5111. }
  5112. } else {
  5113. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5114. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5115. } else {
  5116. $translationKey = 'HasCreditNoteFromSupplier';
  5117. }
  5118. }
  5119. } else {
  5120. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5121. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5122. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5123. } else {
  5124. $translationKey = 'CompanyHasCreditNote';
  5125. }
  5126. } else {
  5127. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5128. $translationKey = 'CompanyHasAbsoluteDiscount';
  5129. } else {
  5130. $translationKey = 'CompanyHasCreditNote';
  5131. }
  5132. }
  5133. }
  5134. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5135. if (empty($hidelist)) {
  5136. print ' ';
  5137. }
  5138. print '</div>';
  5139. if (empty($hidelist)) {
  5140. print '<div class="inline-block" style="padding-right: 10px">';
  5141. $newfilter = 'discount_type='.intval($discount_type);
  5142. if (!empty($discount_type)) {
  5143. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5144. } else {
  5145. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5146. }
  5147. if ($filter) {
  5148. $newfilter .= ' AND ('.$filter.')';
  5149. }
  5150. // output the combo of discounts
  5151. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5152. if ($nbqualifiedlines > 0) {
  5153. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  5154. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5155. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5156. }
  5157. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5158. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5159. }
  5160. print '>';
  5161. }
  5162. print '</div>';
  5163. }
  5164. if ($more) {
  5165. print '<div class="inline-block">';
  5166. print $more;
  5167. print '</div>';
  5168. }
  5169. print '</form>';
  5170. } else {
  5171. if ($selected) {
  5172. print $selected;
  5173. } else {
  5174. print "0";
  5175. }
  5176. }
  5177. }
  5178. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5179. /**
  5180. * Show forms to select a contact
  5181. *
  5182. * @param string $page Page
  5183. * @param Societe $societe Filter on third party
  5184. * @param int $selected Id contact pre-selectionne
  5185. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5186. * @return void
  5187. */
  5188. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5189. {
  5190. // phpcs:enable
  5191. global $langs, $conf;
  5192. if ($htmlname != "none") {
  5193. print '<form method="post" action="'.$page.'">';
  5194. print '<input type="hidden" name="action" value="set_contact">';
  5195. print '<input type="hidden" name="token" value="'.newToken().'">';
  5196. print '<table class="nobordernopadding">';
  5197. print '<tr><td>';
  5198. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5199. $num = $this->num;
  5200. if ($num == 0) {
  5201. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5202. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  5203. }
  5204. print '</td>';
  5205. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5206. print '</tr></table></form>';
  5207. } else {
  5208. if ($selected) {
  5209. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  5210. $contact = new Contact($this->db);
  5211. $contact->fetch($selected);
  5212. print $contact->getFullName($langs);
  5213. } else {
  5214. print "&nbsp;";
  5215. }
  5216. }
  5217. }
  5218. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5219. /**
  5220. * Output html select to select thirdparty
  5221. *
  5222. * @param string $page Page
  5223. * @param string $selected Id preselected
  5224. * @param string $htmlname Name of HTML select
  5225. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5226. * @param int $showempty Add an empty field
  5227. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5228. * @param int $forcecombo Force to use combo box
  5229. * @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')))
  5230. * @param int $nooutput No print output. Return it only.
  5231. * @param array $excludeids Exclude IDs from the select combo
  5232. * @return void|string
  5233. */
  5234. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array())
  5235. {
  5236. // phpcs:enable
  5237. global $langs;
  5238. $out = '';
  5239. if ($htmlname != "none") {
  5240. $out .= '<form method="post" action="'.$page.'">';
  5241. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5242. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5243. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5244. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5245. $out .= '</form>';
  5246. } else {
  5247. if ($selected) {
  5248. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  5249. $soc = new Societe($this->db);
  5250. $soc->fetch($selected);
  5251. $out .= $soc->getNomUrl($langs);
  5252. } else {
  5253. $out .= "&nbsp;";
  5254. }
  5255. }
  5256. if ($nooutput) {
  5257. return $out;
  5258. } else {
  5259. print $out;
  5260. }
  5261. }
  5262. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5263. /**
  5264. * Retourne la liste des devises, dans la langue de l'utilisateur
  5265. *
  5266. * @param string $selected preselected currency code
  5267. * @param string $htmlname name of HTML select list
  5268. * @deprecated
  5269. * @return void
  5270. */
  5271. public function select_currency($selected = '', $htmlname = 'currency_id')
  5272. {
  5273. // phpcs:enable
  5274. print $this->selectCurrency($selected, $htmlname);
  5275. }
  5276. /**
  5277. * Retourne la liste des devises, dans la langue de l'utilisateur
  5278. *
  5279. * @param string $selected preselected currency code
  5280. * @param string $htmlname name of HTML select list
  5281. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5282. * @return string
  5283. */
  5284. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0)
  5285. {
  5286. global $conf, $langs, $user;
  5287. $langs->loadCacheCurrencies('');
  5288. $out = '';
  5289. if ($selected == 'euro' || $selected == 'euros') {
  5290. $selected = 'EUR'; // Pour compatibilite
  5291. }
  5292. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  5293. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5294. $labeltoshow = $currency['label'];
  5295. if ($mode == 1) {
  5296. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  5297. } else {
  5298. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  5299. }
  5300. if ($selected && $selected == $code_iso) {
  5301. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5302. } else {
  5303. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5304. }
  5305. $out .= $labeltoshow;
  5306. $out .= '</option>';
  5307. }
  5308. $out .= '</select>';
  5309. if ($user->admin) {
  5310. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5311. }
  5312. // Make select dynamic
  5313. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5314. $out .= ajax_combobox($htmlname);
  5315. return $out;
  5316. }
  5317. /**
  5318. * Return array of currencies in user language
  5319. *
  5320. * @param string $selected preselected currency code
  5321. * @param string $htmlname name of HTML select list
  5322. * @param integer $useempty 1=Add empty line
  5323. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5324. * @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
  5325. * @return string
  5326. */
  5327. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false)
  5328. {
  5329. global $conf, $langs;
  5330. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5331. $TCurrency = array();
  5332. $sql = "SELECT code FROM ".$this->db->prefix()."multicurrency";
  5333. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  5334. if ($filter) {
  5335. $sql .= " AND ".$filter;
  5336. }
  5337. $resql = $this->db->query($sql);
  5338. if ($resql) {
  5339. while ($obj = $this->db->fetch_object($resql)) {
  5340. $TCurrency[$obj->code] = $obj->code;
  5341. }
  5342. }
  5343. $out = '';
  5344. $out .= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  5345. if ($useempty) {
  5346. $out .= '<option value="">&nbsp;</option>';
  5347. }
  5348. // If company current currency not in table, we add it into list. Should always be available.
  5349. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5350. $TCurrency[$conf->currency] = $conf->currency;
  5351. }
  5352. if (count($TCurrency) > 0) {
  5353. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5354. if (isset($TCurrency[$code_iso])) {
  5355. if (!empty($selected) && $selected == $code_iso) {
  5356. $out .= '<option value="'.$code_iso.'" selected="selected">';
  5357. } else {
  5358. $out .= '<option value="'.$code_iso.'">';
  5359. }
  5360. $out .= $currency['label'];
  5361. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  5362. $out .= '</option>';
  5363. }
  5364. }
  5365. }
  5366. $out .= '</select>';
  5367. // Make select dynamic
  5368. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5369. $out .= ajax_combobox($htmlname);
  5370. return $out;
  5371. }
  5372. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5373. /**
  5374. * Load into the cache vat rates of a country
  5375. *
  5376. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5377. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5378. */
  5379. public function load_cache_vatrates($country_code)
  5380. {
  5381. // phpcs:enable
  5382. global $langs;
  5383. $num = count($this->cache_vatrates);
  5384. if ($num > 0) {
  5385. return $num; // Cache already loaded
  5386. }
  5387. dol_syslog(__METHOD__, LOG_DEBUG);
  5388. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5389. $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
  5390. $sql .= " WHERE t.fk_pays = c.rowid";
  5391. $sql .= " AND t.active > 0";
  5392. $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
  5393. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5394. $resql = $this->db->query($sql);
  5395. if ($resql) {
  5396. $num = $this->db->num_rows($resql);
  5397. if ($num) {
  5398. for ($i = 0; $i < $num; $i++) {
  5399. $obj = $this->db->fetch_object($resql);
  5400. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5401. $this->cache_vatrates[$i]['code'] = $obj->code;
  5402. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5403. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5404. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5405. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5406. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5407. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5408. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  5409. $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
  5410. $positiverates = '';
  5411. if ($obj->taux) {
  5412. $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  5413. }
  5414. if ($obj->localtax1) {
  5415. $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  5416. }
  5417. if ($obj->localtax2) {
  5418. $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  5419. }
  5420. if (empty($positiverates)) {
  5421. $positiverates = '0';
  5422. }
  5423. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5424. }
  5425. return $num;
  5426. } else {
  5427. $this->error = '<span class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</span>';
  5428. return -1;
  5429. }
  5430. } else {
  5431. $this->error = '<span class="error">'.$this->db->error().'</span>';
  5432. return -2;
  5433. }
  5434. }
  5435. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5436. /**
  5437. * Output an HTML select vat rate.
  5438. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5439. *
  5440. * @param string $htmlname Name of HTML select field
  5441. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5442. * @param Societe $societe_vendeuse Thirdparty seller
  5443. * @param Societe $societe_acheteuse Thirdparty buyer
  5444. * @param int $idprod Id product. O if unknown of NA.
  5445. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5446. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5447. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5448. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5449. * 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.
  5450. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5451. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5452. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5453. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5454. * @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
  5455. * @return string
  5456. */
  5457. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5458. {
  5459. // phpcs:enable
  5460. global $langs, $conf, $mysoc;
  5461. $langs->load('errors');
  5462. $return = '';
  5463. // Define defaultnpr, defaultttx and defaultcode
  5464. $defaultnpr = ($info_bits & 0x01);
  5465. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5466. $defaulttx = str_replace('*', '', $selectedrate);
  5467. $defaultcode = '';
  5468. $reg = array();
  5469. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5470. $defaultcode = $reg[1];
  5471. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5472. }
  5473. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5474. // Check parameters
  5475. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5476. if ($societe_vendeuse->id == $mysoc->id) {
  5477. $return .= '<span class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</span>';
  5478. } else {
  5479. $return .= '<span class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</span>';
  5480. }
  5481. return $return;
  5482. }
  5483. //var_dump($societe_acheteuse);
  5484. //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";
  5485. //exit;
  5486. // Define list of countries to use to search VAT rates to show
  5487. // First we defined code_country to use to find list
  5488. if (is_object($societe_vendeuse)) {
  5489. $code_country = "'".$societe_vendeuse->country_code."'";
  5490. } else {
  5491. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  5492. }
  5493. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5494. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5495. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5496. // We also add the buyer
  5497. if (is_numeric($type)) {
  5498. if ($type == 1) { // We know product is a service
  5499. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5500. }
  5501. } elseif (!$idprod) { // We don't know type of product
  5502. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5503. } else {
  5504. $prodstatic = new Product($this->db);
  5505. $prodstatic->fetch($idprod);
  5506. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5507. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5508. }
  5509. }
  5510. }
  5511. }
  5512. // Now we get list
  5513. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5514. if ($num > 0) {
  5515. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5516. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5517. $tmpthirdparty = new Societe($this->db);
  5518. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5519. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5520. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5521. $defaultcode = $reg[1];
  5522. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5523. }
  5524. if (empty($defaulttx)) {
  5525. $defaultnpr = 0;
  5526. }
  5527. }
  5528. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  5529. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  5530. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5531. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5532. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5533. } else {
  5534. $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  5535. }
  5536. }
  5537. // Disabled if seller is not subject to VAT
  5538. $disabled = false;
  5539. $title = '';
  5540. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5541. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5542. // of using supplier invoices (this is a very bad idea !)
  5543. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5544. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  5545. $disabled = true;
  5546. }
  5547. }
  5548. if (!$options_only) {
  5549. $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  5550. }
  5551. $selectedfound = false;
  5552. foreach ($this->cache_vatrates as $rate) {
  5553. // Keep only 0 if seller is not subject to VAT
  5554. if ($disabled && $rate['txtva'] != 0) {
  5555. continue;
  5556. }
  5557. // Define key to use into select list
  5558. $key = $rate['txtva'];
  5559. $key .= $rate['nprtva'] ? '*' : '';
  5560. if ($mode > 0 && $rate['code']) {
  5561. $key .= ' ('.$rate['code'].')';
  5562. }
  5563. if ($mode < 0) {
  5564. $key = $rate['rowid'];
  5565. }
  5566. $return .= '<option value="'.$key.'"';
  5567. if (!$selectedfound) {
  5568. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5569. if ($defaultcode == $rate['code']) {
  5570. $return .= ' selected';
  5571. $selectedfound = true;
  5572. }
  5573. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5574. $return .= ' selected';
  5575. $selectedfound = true;
  5576. }
  5577. }
  5578. $return .= '>';
  5579. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  5580. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5581. $return .= $rate['labelpositiverates'];
  5582. } else {
  5583. $return .= vatrate($rate['label']);
  5584. }
  5585. //$return.=($rate['code']?' '.$rate['code']:'');
  5586. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5587. $return .= '</option>';
  5588. }
  5589. if (!$options_only) {
  5590. $return .= '</select>';
  5591. }
  5592. } else {
  5593. $return .= $this->error;
  5594. }
  5595. $this->num = $num;
  5596. return $return;
  5597. }
  5598. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5599. /**
  5600. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5601. * Fields are preselected with :
  5602. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5603. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5604. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5605. *
  5606. * @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).
  5607. * @param string $prefix Prefix for fields name
  5608. * @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
  5609. * @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
  5610. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5611. * @param string $form_name Not used
  5612. * @param int $d 1=Show days, month, years
  5613. * @param int $addnowlink Add a link "Now"
  5614. * @param int $nooutput Do not output html string but return it
  5615. * @param int $disabled Disable input fields
  5616. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5617. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5618. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5619. * @return string|void Nothing or string if nooutput is 1
  5620. * @deprecated
  5621. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5622. */
  5623. 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 = '')
  5624. {
  5625. // phpcs:enable
  5626. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5627. if (!empty($nooutput)) {
  5628. return $retstring;
  5629. }
  5630. print $retstring;
  5631. return;
  5632. }
  5633. /**
  5634. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5635. * Fields are preselected with :
  5636. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5637. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5638. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5639. *
  5640. * @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).
  5641. * @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).
  5642. * @param string $prefix Prefix for fields name
  5643. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5644. * @param string $forcenewline Force new line between the 2 dates.
  5645. * @return string Html for selectDate
  5646. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5647. */
  5648. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5649. {
  5650. global $langs;
  5651. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5652. if ($forcenewline) {
  5653. $ret .= '<br>';
  5654. }
  5655. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5656. return $ret;
  5657. }
  5658. /**
  5659. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5660. * Fields are preselected with :
  5661. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5662. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5663. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5664. *
  5665. * @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).
  5666. * @param string $prefix Prefix for fields name
  5667. * @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
  5668. * @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
  5669. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5670. * @param string $form_name Not used
  5671. * @param int $d 1=Show days, month, years
  5672. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5673. * @param int $disabled Disable input fields
  5674. * @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')
  5675. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5676. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5677. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5678. * @param int $stepminutes Specify step for minutes between 1 and 30
  5679. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5680. * @param string $placeholder Placeholder
  5681. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5682. * @return string Html for selectDate
  5683. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5684. */
  5685. public function selectDate($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '', $openinghours = '', $stepminutes = 1, $labeladddateof = '', $placeholder = '', $gm = 'auto')
  5686. {
  5687. global $conf, $langs;
  5688. if ($gm === 'auto') {
  5689. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5690. }
  5691. $retstring = '';
  5692. if ($prefix == '') {
  5693. $prefix = 're';
  5694. }
  5695. if ($h == '') {
  5696. $h = 0;
  5697. }
  5698. if ($m == '') {
  5699. $m = 0;
  5700. }
  5701. $emptydate = 0;
  5702. $emptyhours = 0;
  5703. if ($stepminutes <= 0 || $stepminutes > 30) {
  5704. $stepminutes = 1;
  5705. }
  5706. if ($empty == 1) {
  5707. $emptydate = 1;
  5708. $emptyhours = 1;
  5709. }
  5710. if ($empty == 2) {
  5711. $emptydate = 0;
  5712. $emptyhours = 1;
  5713. }
  5714. $orig_set_time = $set_time;
  5715. if ($set_time === '' && $emptydate == 0) {
  5716. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5717. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5718. $set_time = dol_now($gm);
  5719. } else {
  5720. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5721. }
  5722. }
  5723. // Analysis of the pre-selection date
  5724. $reg = array();
  5725. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5726. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5727. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5728. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5729. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5730. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5731. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5732. } elseif (strval($set_time) != '' && $set_time != -1) {
  5733. // set_time est un timestamps (0 possible)
  5734. $syear = dol_print_date($set_time, "%Y", $gm);
  5735. $smonth = dol_print_date($set_time, "%m", $gm);
  5736. $sday = dol_print_date($set_time, "%d", $gm);
  5737. if ($orig_set_time != '') {
  5738. $shour = dol_print_date($set_time, "%H", $gm);
  5739. $smin = dol_print_date($set_time, "%M", $gm);
  5740. $ssec = dol_print_date($set_time, "%S", $gm);
  5741. } else {
  5742. $shour = '';
  5743. $smin = '';
  5744. $ssec = '';
  5745. }
  5746. } else {
  5747. // Date est '' ou vaut -1
  5748. $syear = '';
  5749. $smonth = '';
  5750. $sday = '';
  5751. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5752. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5753. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5754. }
  5755. if ($h == 3) {
  5756. $shour = '';
  5757. }
  5758. if ($m == 3) {
  5759. $smin = '';
  5760. }
  5761. $nowgmt = dol_now('gmt');
  5762. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5763. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5764. $usecalendar = 'combo';
  5765. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5766. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5767. }
  5768. if ($d) {
  5769. // Show date with popup
  5770. if ($usecalendar != 'combo') {
  5771. $formated_date = '';
  5772. //print "e".$set_time." t ".$conf->format_date_short;
  5773. if (strval($set_time) != '' && $set_time != -1) {
  5774. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5775. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5776. }
  5777. // Calendrier popup version eldy
  5778. if ($usecalendar == "eldy") {
  5779. // Input area to enter date manually
  5780. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5781. $retstring .= ($disabled ? ' disabled' : '');
  5782. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5783. $retstring .= '>';
  5784. // Icon calendar
  5785. $retstringbuttom = '';
  5786. if (!$disabled) {
  5787. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5788. $base = DOL_URL_ROOT.'/core/';
  5789. $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5790. $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5791. } else {
  5792. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5793. }
  5794. $retstring = $retstringbuttom.$retstring;
  5795. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5796. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5797. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5798. } elseif ($usecalendar == 'jquery') {
  5799. if (!$disabled) {
  5800. // Output javascript for datepicker
  5801. $retstring .= "<script type='text/javascript'>";
  5802. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5803. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5804. autoclose: true,
  5805. todayHighlight: true,";
  5806. if (!empty($conf->dol_use_jmobile)) {
  5807. $retstring .= "
  5808. beforeShow: function (input, datePicker) {
  5809. input.disabled = true;
  5810. },
  5811. onClose: function (dateText, datePicker) {
  5812. this.disabled = false;
  5813. },
  5814. ";
  5815. }
  5816. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  5817. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  5818. $retstring .= "
  5819. showOn: 'button', /* both has problem with autocompletion */
  5820. buttonImage: '".DOL_URL_ROOT."/theme/".dol_escape_js($conf->theme)."/img/object_calendarday.png',
  5821. buttonImageOnly: true";
  5822. }
  5823. $retstring .= "
  5824. }) });";
  5825. $retstring .= "</script>";
  5826. }
  5827. // Zone de saisie manuelle de la date
  5828. $retstring .= '<div class="nowrap inline-block divfordateinput">';
  5829. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5830. $retstring .= ($disabled ? ' disabled' : '');
  5831. $retstring .= ($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '');
  5832. $retstring .= ' onChange="dpChangeDay(\''.dol_escape_js($prefix).'\',\''.dol_escape_js($langs->trans("FormatDateShortJavaInput")).'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5833. $retstring .= '>';
  5834. // Icone calendrier
  5835. if (!$disabled) {
  5836. /* Not required. Managed by option buttonImage of jquery
  5837. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  5838. $retstring.="<script type='text/javascript'>";
  5839. $retstring.="jQuery(document).ready(function() {";
  5840. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  5841. $retstring.=" jQuery('#".$prefix."').focus();";
  5842. $retstring.=' });';
  5843. $retstring.='});';
  5844. $retstring.="</script>";*/
  5845. } else {
  5846. $retstringbutton = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5847. $retsring = $retstringbutton.$retstring;
  5848. }
  5849. $retstring .= '</div>';
  5850. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5851. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5852. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5853. } else {
  5854. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  5855. }
  5856. } else {
  5857. // Show date with combo selects
  5858. // Day
  5859. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  5860. if ($emptydate || $set_time == -1) {
  5861. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5862. }
  5863. for ($day = 1; $day <= 31; $day++) {
  5864. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  5865. }
  5866. $retstring .= "</select>";
  5867. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  5868. if ($emptydate || $set_time == -1) {
  5869. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5870. }
  5871. // Month
  5872. for ($month = 1; $month <= 12; $month++) {
  5873. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  5874. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  5875. $retstring .= "</option>";
  5876. }
  5877. $retstring .= "</select>";
  5878. // Year
  5879. if ($emptydate || $set_time == -1) {
  5880. $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.'">';
  5881. } else {
  5882. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  5883. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  5884. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  5885. }
  5886. $retstring .= "</select>\n";
  5887. }
  5888. }
  5889. }
  5890. if ($d && $h) {
  5891. $retstring .= ($h == 2 ? '<br>' : ' ');
  5892. $retstring .= '<span class="nowraponall">';
  5893. }
  5894. if ($h) {
  5895. $hourstart = 0;
  5896. $hourend = 24;
  5897. if ($openinghours != '') {
  5898. $openinghours = explode(',', $openinghours);
  5899. $hourstart = $openinghours[0];
  5900. $hourend = $openinghours[1];
  5901. if ($hourend < $hourstart) {
  5902. $hourend = $hourstart;
  5903. }
  5904. }
  5905. // Show hour
  5906. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  5907. if ($emptyhours) {
  5908. $retstring .= '<option value="-1">&nbsp;</option>';
  5909. }
  5910. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  5911. if (strlen($hour) < 2) {
  5912. $hour = "0".$hour;
  5913. }
  5914. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  5915. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  5916. $retstring .= '</option>';
  5917. }
  5918. $retstring .= '</select>';
  5919. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  5920. if ($m) {
  5921. $retstring .= ":";
  5922. }
  5923. }
  5924. if ($m) {
  5925. // Show minutes
  5926. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  5927. if ($emptyhours) {
  5928. $retstring .= '<option value="-1">&nbsp;</option>';
  5929. }
  5930. for ($min = 0; $min < 60; $min += $stepminutes) {
  5931. if (strlen($min) < 2) {
  5932. $min = "0".$min;
  5933. }
  5934. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  5935. }
  5936. $retstring .= '</select>';
  5937. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  5938. }
  5939. if ($d && $h) {
  5940. $retstring .= '</span>';
  5941. }
  5942. // Add a "Now" link
  5943. if ($conf->use_javascript_ajax && $addnowlink) {
  5944. // Script which will be inserted in the onClick of the "Now" link
  5945. $reset_scripts = "";
  5946. if ($addnowlink == 2) { // local computer time
  5947. // pad add leading 0 on numbers
  5948. $reset_scripts .= "Number.prototype.pad = function(size) {
  5949. var s = String(this);
  5950. while (s.length < (size || 2)) {s = '0' + s;}
  5951. return s;
  5952. };
  5953. var d = new Date();";
  5954. }
  5955. // Generate the date part, depending on the use or not of the javascript calendar
  5956. if ($addnowlink == 1) { // server time expressed in user time setup
  5957. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5958. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5959. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5960. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5961. } elseif ($addnowlink == 2) {
  5962. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  5963. * This break application for foreign languages.
  5964. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  5965. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  5966. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  5967. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  5968. */
  5969. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5970. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5971. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5972. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5973. }
  5974. /*if ($usecalendar == "eldy")
  5975. {
  5976. $base=DOL_URL_ROOT.'/core/';
  5977. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  5978. }
  5979. else
  5980. {
  5981. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  5982. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  5983. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  5984. }*/
  5985. // Update the hour part
  5986. if ($h) {
  5987. if ($fullday) {
  5988. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5989. }
  5990. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  5991. if ($addnowlink == 1) {
  5992. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  5993. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5994. } elseif ($addnowlink == 2) {
  5995. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  5996. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5997. }
  5998. if ($fullday) {
  5999. $reset_scripts .= ' } ';
  6000. }
  6001. }
  6002. // Update the minute part
  6003. if ($m) {
  6004. if ($fullday) {
  6005. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6006. }
  6007. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6008. if ($addnowlink == 1) {
  6009. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6010. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6011. } elseif ($addnowlink == 2) {
  6012. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  6013. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6014. }
  6015. if ($fullday) {
  6016. $reset_scripts .= ' } ';
  6017. }
  6018. }
  6019. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6020. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6021. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  6022. $retstring .= $langs->trans("Now");
  6023. $retstring .= '</button> ';
  6024. }
  6025. }
  6026. // Add a "Plus one hour" link
  6027. if ($conf->use_javascript_ajax && $addplusone) {
  6028. // Script which will be inserted in the onClick of the "Add plusone" link
  6029. $reset_scripts = "";
  6030. // Generate the date part, depending on the use or not of the javascript calendar
  6031. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');';
  6032. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6033. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6034. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6035. // Update the hour part
  6036. if ($h) {
  6037. if ($fullday) {
  6038. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6039. }
  6040. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  6041. if ($fullday) {
  6042. $reset_scripts .= ' } ';
  6043. }
  6044. }
  6045. // Update the minute part
  6046. if ($m) {
  6047. if ($fullday) {
  6048. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6049. }
  6050. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6051. if ($fullday) {
  6052. $reset_scripts .= ' } ';
  6053. }
  6054. }
  6055. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6056. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6057. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  6058. $retstring .= $langs->trans("DateStartPlusOne");
  6059. $retstring .= '</button> ';
  6060. }
  6061. }
  6062. // Add a link to set data
  6063. if ($conf->use_javascript_ajax && $adddateof) {
  6064. $tmparray = dol_getdate($adddateof);
  6065. if (empty($labeladddateof)) {
  6066. $labeladddateof = $langs->trans("DateInvoice");
  6067. }
  6068. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="console.log(\'Click on now link\'); jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'dayinputnoreduce').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$labeladddateof.'</a>';
  6069. }
  6070. return $retstring;
  6071. }
  6072. /**
  6073. * selectTypeDuration
  6074. *
  6075. * @param string $prefix Prefix
  6076. * @param string $selected Selected duration type
  6077. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6078. * @return string HTML select string
  6079. */
  6080. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6081. {
  6082. global $langs;
  6083. $TDurationTypes = array(
  6084. 'y'=>$langs->trans('Years'),
  6085. 'm'=>$langs->trans('Month'),
  6086. 'w'=>$langs->trans('Weeks'),
  6087. 'd'=>$langs->trans('Days'),
  6088. 'h'=>$langs->trans('Hours'),
  6089. 'i'=>$langs->trans('Minutes')
  6090. );
  6091. // Removed undesired duration types
  6092. foreach ($excludetypes as $value) {
  6093. unset($TDurationTypes[$value]);
  6094. }
  6095. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  6096. foreach ($TDurationTypes as $key => $typeduration) {
  6097. $retstring .= '<option value="'.$key.'"';
  6098. if ($key == $selected) {
  6099. $retstring .= " selected";
  6100. }
  6101. $retstring .= ">".$typeduration."</option>";
  6102. }
  6103. $retstring .= "</select>";
  6104. $retstring .= ajax_combobox('select_'.$prefix.'type_duration');
  6105. return $retstring;
  6106. }
  6107. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6108. /**
  6109. * Function to show a form to select a duration on a page
  6110. *
  6111. * @param string $prefix Prefix for input fields
  6112. * @param int $iSecond Default preselected duration (number of seconds or '')
  6113. * @param int $disabled Disable the combo box
  6114. * @param string $typehour If 'select' then input hour and input min is a combo,
  6115. * If 'text' input hour is in text and input min is a text,
  6116. * If 'textselect' input hour is in text and input min is a combo
  6117. * @param integer $minunderhours If 1, show minutes selection under the hours
  6118. * @param int $nooutput Do not output html string but return it
  6119. * @return string|void
  6120. */
  6121. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6122. {
  6123. // phpcs:enable
  6124. global $langs;
  6125. $retstring = '<span class="nowraponall">';
  6126. $hourSelected = 0;
  6127. $minSelected = 0;
  6128. // Hours
  6129. if ($iSecond != '') {
  6130. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6131. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6132. $minSelected = convertSecondToTime($iSecond, 'min');
  6133. }
  6134. if ($typehour == 'select') {
  6135. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  6136. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6137. $retstring .= '<option value="'.$hour.'"';
  6138. if ($hourSelected == $hour) {
  6139. $retstring .= " selected";
  6140. }
  6141. $retstring .= ">".$hour."</option>";
  6142. }
  6143. $retstring .= "</select>";
  6144. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6145. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  6146. } else {
  6147. return 'BadValueForParameterTypeHour';
  6148. }
  6149. if ($typehour != 'text') {
  6150. $retstring .= ' '.$langs->trans('HourShort');
  6151. } else {
  6152. $retstring .= '<span class="">:</span>';
  6153. }
  6154. // Minutes
  6155. if ($minunderhours) {
  6156. $retstring .= '<br>';
  6157. } else {
  6158. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6159. }
  6160. if ($typehour == 'select' || $typehour == 'textselect') {
  6161. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  6162. for ($min = 0; $min <= 55; $min = $min + 5) {
  6163. $retstring .= '<option value="'.$min.'"';
  6164. if ($minSelected == $min) {
  6165. $retstring .= ' selected';
  6166. }
  6167. $retstring .= '>'.$min.'</option>';
  6168. }
  6169. $retstring .= "</select>";
  6170. } elseif ($typehour == 'text') {
  6171. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  6172. }
  6173. if ($typehour != 'text') {
  6174. $retstring .= ' '.$langs->trans('MinuteShort');
  6175. }
  6176. $retstring.="</span>";
  6177. if (!empty($nooutput)) {
  6178. return $retstring;
  6179. }
  6180. print $retstring;
  6181. return;
  6182. }
  6183. /**
  6184. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6185. *
  6186. * @param int $selected Preselected tickets
  6187. * @param string $htmlname Name of HTML select field (must be unique in page).
  6188. * @param string $filtertype To add a filter
  6189. * @param int $limit Limit on number of returned lines
  6190. * @param int $status Ticket status
  6191. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6192. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6193. * @param array $ajaxoptions Options for ajax_autocompleter
  6194. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6195. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6196. * @param int $forcecombo Force to use combo box
  6197. * @param string $morecss Add more css on select
  6198. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6199. * @param string $nooutput No print, return the output into a string
  6200. * @return void|string
  6201. */
  6202. public function selectTickets($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6203. {
  6204. global $langs, $conf;
  6205. $out = '';
  6206. // check parameters
  6207. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6208. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6209. $placeholder = '';
  6210. if ($selected && empty($selected_input_value)) {
  6211. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6212. $tickettmpselect = new Ticket($this->db);
  6213. $tickettmpselect->fetch($selected);
  6214. $selected_input_value = $tickettmpselect->ref;
  6215. unset($tickettmpselect);
  6216. }
  6217. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6218. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6219. elseif ($hidelabel > 1) {
  6220. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6221. if ($hidelabel == 2) {
  6222. $out .= img_picto($langs->trans("Search"), 'search');
  6223. }
  6224. }
  6225. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6226. if ($hidelabel == 3) {
  6227. $out .= img_picto($langs->trans("Search"), 'search');
  6228. }
  6229. } else {
  6230. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6231. }
  6232. if (empty($nooutput)) print $out;
  6233. else return $out;
  6234. }
  6235. /**
  6236. * Return list of tickets.
  6237. * Called by selectTickets.
  6238. *
  6239. * @param int $selected Preselected ticket
  6240. * @param string $htmlname Name of select html
  6241. * @param string $filtertype Filter on ticket type
  6242. * @param int $limit Limit on number of returned lines
  6243. * @param string $filterkey Filter on ticket ref or subject
  6244. * @param int $status Ticket status
  6245. * @param int $outputmode 0=HTML select string, 1=Array
  6246. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6247. * @param int $forcecombo Force to use combo box
  6248. * @param string $morecss Add more css on select
  6249. * @return array Array of keys for json
  6250. */
  6251. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6252. {
  6253. global $langs, $conf;
  6254. $out = '';
  6255. $outarray = array();
  6256. $selectFields = " p.rowid, p.ref, p.message";
  6257. $sql = "SELECT ";
  6258. $sql .= $selectFields;
  6259. $sql .= " FROM ".$this->db->prefix()."ticket as p";
  6260. $sql .= ' WHERE p.entity IN ('.getEntity('ticket').')';
  6261. // Add criteria on ref/label
  6262. if ($filterkey != '') {
  6263. $sql .= ' AND (';
  6264. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6265. // For natural search
  6266. $scrit = explode(' ', $filterkey);
  6267. $i = 0;
  6268. if (count($scrit) > 1) $sql .= "(";
  6269. foreach ($scrit as $crit) {
  6270. if ($i > 0) $sql .= " AND ";
  6271. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.subject LIKE '".$this->db->escape($prefix.$crit)."%'";
  6272. $sql .= ")";
  6273. $i++;
  6274. }
  6275. if (count($scrit) > 1) $sql .= ")";
  6276. $sql .= ')';
  6277. }
  6278. $sql .= $this->db->plimit($limit, 0);
  6279. // Build output string
  6280. dol_syslog(get_class($this)."::selectTicketsList search tickets", LOG_DEBUG);
  6281. $result = $this->db->query($sql);
  6282. if ($result) {
  6283. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6284. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  6285. $num = $this->db->num_rows($result);
  6286. $events = null;
  6287. if (!$forcecombo) {
  6288. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6289. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6290. }
  6291. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6292. $textifempty = '';
  6293. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6294. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6295. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6296. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6297. else $textifempty .= $langs->trans("All");
  6298. } else {
  6299. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6300. }
  6301. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6302. $i = 0;
  6303. while ($num && $i < $num) {
  6304. $opt = '';
  6305. $optJson = array();
  6306. $objp = $this->db->fetch_object($result);
  6307. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6308. // Add new entry
  6309. // "key" value of json key array is used by jQuery automatically as selected value
  6310. // "label" value of json key array is used by jQuery automatically as text for combo box
  6311. $out .= $opt;
  6312. array_push($outarray, $optJson);
  6313. $i++;
  6314. }
  6315. $out .= '</select>';
  6316. $this->db->free($result);
  6317. if (empty($outputmode)) return $out;
  6318. return $outarray;
  6319. } else {
  6320. dol_print_error($this->db);
  6321. }
  6322. }
  6323. /**
  6324. * constructTicketListOption.
  6325. * This define value for &$opt and &$optJson.
  6326. *
  6327. * @param resource $objp Result set of fetch
  6328. * @param string $opt Option (var used for returned value in string option format)
  6329. * @param string $optJson Option (var used for returned value in json format)
  6330. * @param string $selected Preselected value
  6331. * @param string $filterkey Filter key to highlight
  6332. * @return void
  6333. */
  6334. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6335. {
  6336. $outkey = '';
  6337. $outval = '';
  6338. $outref = '';
  6339. $outlabel = '';
  6340. $outtype = '';
  6341. $label = $objp->label;
  6342. $outkey = $objp->rowid;
  6343. $outref = $objp->ref;
  6344. $outlabel = $objp->label;
  6345. $outtype = $objp->fk_product_type;
  6346. $opt = '<option value="'.$objp->rowid.'"';
  6347. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6348. $opt .= '>';
  6349. $opt .= $objp->ref;
  6350. $objRef = $objp->ref;
  6351. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6352. $outval .= $objRef;
  6353. $opt .= "</option>\n";
  6354. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtypem);
  6355. }
  6356. /**
  6357. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6358. *
  6359. * @param int $selected Preselected tickets
  6360. * @param string $htmlname Name of HTML select field (must be unique in page).
  6361. * @param string $filtertype To add a filter
  6362. * @param int $limit Limit on number of returned lines
  6363. * @param int $status Ticket status
  6364. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6365. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6366. * @param array $ajaxoptions Options for ajax_autocompleter
  6367. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6368. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6369. * @param int $forcecombo Force to use combo box
  6370. * @param string $morecss Add more css on select
  6371. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6372. * @param string $nooutput No print, return the output into a string
  6373. * @return void|string
  6374. */
  6375. public function selectProjects($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6376. {
  6377. global $langs, $conf;
  6378. $out = '';
  6379. // check parameters
  6380. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6381. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6382. $placeholder = '';
  6383. if ($selected && empty($selected_input_value)) {
  6384. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6385. $projecttmpselect = new Project($this->db);
  6386. $projecttmpselect->fetch($selected);
  6387. $selected_input_value = $projecttmpselect->ref;
  6388. unset($projecttmpselect);
  6389. }
  6390. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6391. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6392. elseif ($hidelabel > 1) {
  6393. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6394. if ($hidelabel == 2) {
  6395. $out .= img_picto($langs->trans("Search"), 'search');
  6396. }
  6397. }
  6398. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6399. if ($hidelabel == 3) {
  6400. $out .= img_picto($langs->trans("Search"), 'search');
  6401. }
  6402. } else {
  6403. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6404. }
  6405. if (empty($nooutput)) print $out;
  6406. else return $out;
  6407. }
  6408. /**
  6409. * Return list of projects.
  6410. * Called by selectProjects.
  6411. *
  6412. * @param int $selected Preselected project
  6413. * @param string $htmlname Name of select html
  6414. * @param string $filtertype Filter on project type
  6415. * @param int $limit Limit on number of returned lines
  6416. * @param string $filterkey Filter on project ref or subject
  6417. * @param int $status Ticket status
  6418. * @param int $outputmode 0=HTML select string, 1=Array
  6419. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6420. * @param int $forcecombo Force to use combo box
  6421. * @param string $morecss Add more css on select
  6422. * @return array Array of keys for json
  6423. */
  6424. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6425. {
  6426. global $langs, $conf;
  6427. $out = '';
  6428. $outarray = array();
  6429. $selectFields = " p.rowid, p.ref";
  6430. $sql = "SELECT ";
  6431. $sql .= $selectFields;
  6432. $sql .= " FROM ".$this->db->prefix()."projet as p";
  6433. $sql .= ' WHERE p.entity IN ('.getEntity('project').')';
  6434. // Add criteria on ref/label
  6435. if ($filterkey != '') {
  6436. $sql .= ' AND (';
  6437. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6438. // For natural search
  6439. $scrit = explode(' ', $filterkey);
  6440. $i = 0;
  6441. if (count($scrit) > 1) $sql .= "(";
  6442. foreach ($scrit as $crit) {
  6443. if ($i > 0) $sql .= " AND ";
  6444. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6445. $sql .= "";
  6446. $i++;
  6447. }
  6448. if (count($scrit) > 1) $sql .= ")";
  6449. $sql .= ')';
  6450. }
  6451. $sql .= $this->db->plimit($limit, 0);
  6452. // Build output string
  6453. dol_syslog(get_class($this)."::selectProjectsList search projects", LOG_DEBUG);
  6454. $result = $this->db->query($sql);
  6455. if ($result) {
  6456. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6457. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  6458. $num = $this->db->num_rows($result);
  6459. $events = null;
  6460. if (!$forcecombo) {
  6461. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6462. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6463. }
  6464. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6465. $textifempty = '';
  6466. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6467. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6468. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6469. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6470. else $textifempty .= $langs->trans("All");
  6471. } else {
  6472. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6473. }
  6474. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6475. $i = 0;
  6476. while ($num && $i < $num) {
  6477. $opt = '';
  6478. $optJson = array();
  6479. $objp = $this->db->fetch_object($result);
  6480. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6481. // Add new entry
  6482. // "key" value of json key array is used by jQuery automatically as selected value
  6483. // "label" value of json key array is used by jQuery automatically as text for combo box
  6484. $out .= $opt;
  6485. array_push($outarray, $optJson);
  6486. $i++;
  6487. }
  6488. $out .= '</select>';
  6489. $this->db->free($result);
  6490. if (empty($outputmode)) return $out;
  6491. return $outarray;
  6492. } else {
  6493. dol_print_error($this->db);
  6494. }
  6495. }
  6496. /**
  6497. * constructProjectListOption.
  6498. * This define value for &$opt and &$optJson.
  6499. *
  6500. * @param resource $objp Result set of fetch
  6501. * @param string $opt Option (var used for returned value in string option format)
  6502. * @param string $optJson Option (var used for returned value in json format)
  6503. * @param string $selected Preselected value
  6504. * @param string $filterkey Filter key to highlight
  6505. * @return void
  6506. */
  6507. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6508. {
  6509. $outkey = '';
  6510. $outval = '';
  6511. $outref = '';
  6512. $outlabel = '';
  6513. $outtype = '';
  6514. $label = $objp->label;
  6515. $outkey = $objp->rowid;
  6516. $outref = $objp->ref;
  6517. $outlabel = $objp->label;
  6518. $outtype = $objp->fk_product_type;
  6519. $opt = '<option value="'.$objp->rowid.'"';
  6520. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6521. $opt .= '>';
  6522. $opt .= $objp->ref;
  6523. $objRef = $objp->ref;
  6524. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6525. $outval .= $objRef;
  6526. $opt .= "</option>\n";
  6527. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6528. }
  6529. /**
  6530. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6531. *
  6532. * @param int $selected Preselected tickets
  6533. * @param string $htmlname Name of HTML select field (must be unique in page).
  6534. * @param string $filtertype To add a filter
  6535. * @param int $limit Limit on number of returned lines
  6536. * @param int $status Ticket status
  6537. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6538. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6539. * @param array $ajaxoptions Options for ajax_autocompleter
  6540. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6541. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6542. * @param int $forcecombo Force to use combo box
  6543. * @param string $morecss Add more css on select
  6544. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6545. * @param string $nooutput No print, return the output into a string
  6546. * @return void|string
  6547. */
  6548. public function selectMembers($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6549. {
  6550. global $langs, $conf;
  6551. $out = '';
  6552. // check parameters
  6553. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6554. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6555. $placeholder = '';
  6556. $urloption = '';
  6557. if ($selected && empty($selected_input_value)) {
  6558. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6559. $adherenttmpselect = new Adherent($this->db);
  6560. $adherenttmpselect->fetch($selected);
  6561. $selected_input_value = $adherenttmpselect->ref;
  6562. unset($adherenttmpselect);
  6563. }
  6564. $urloption = '';
  6565. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6566. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6567. elseif ($hidelabel > 1) {
  6568. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6569. if ($hidelabel == 2) {
  6570. $out .= img_picto($langs->trans("Search"), 'search');
  6571. }
  6572. }
  6573. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6574. if ($hidelabel == 3) {
  6575. $out .= img_picto($langs->trans("Search"), 'search');
  6576. }
  6577. } else {
  6578. $filterkey = '';
  6579. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  6580. }
  6581. if (empty($nooutput)) print $out;
  6582. else return $out;
  6583. }
  6584. /**
  6585. * Return list of adherents.
  6586. * Called by selectMembers.
  6587. *
  6588. * @param int $selected Preselected adherent
  6589. * @param string $htmlname Name of select html
  6590. * @param string $filtertype Filter on adherent type
  6591. * @param int $limit Limit on number of returned lines
  6592. * @param string $filterkey Filter on member status
  6593. * @param int $status Member status
  6594. * @param int $outputmode 0=HTML select string, 1=Array
  6595. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6596. * @param int $forcecombo Force to use combo box
  6597. * @param string $morecss Add more css on select
  6598. * @return array Array of keys for json
  6599. */
  6600. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6601. {
  6602. global $langs, $conf;
  6603. $out = '';
  6604. $outarray = array();
  6605. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname";
  6606. $sql = "SELECT ";
  6607. $sql .= $selectFields;
  6608. $sql .= " FROM ".$this->db->prefix()."adherent as p";
  6609. $sql .= ' WHERE p.entity IN ('.getEntity('adherent').')';
  6610. // Add criteria on ref/label
  6611. if ($filterkey != '') {
  6612. $sql .= ' AND (';
  6613. $prefix = empty($conf->global->MEMBER_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6614. // For natural search
  6615. $scrit = explode(' ', $filterkey);
  6616. $i = 0;
  6617. if (count($scrit) > 1) $sql .= "(";
  6618. foreach ($scrit as $crit) {
  6619. if ($i > 0) $sql .= " AND ";
  6620. $sql .= "(p.firstname LIKE '".$this->db->escape($prefix.$crit)."%'";
  6621. $sql .= " OR p.lastname LIKE '".$this->db->escape($prefix.$crit)."%')";
  6622. $i++;
  6623. }
  6624. if (count($scrit) > 1) $sql .= ")";
  6625. $sql .= ')';
  6626. }
  6627. if ($status != -1) {
  6628. $sql .= ' AND statut = '.((int) $status);
  6629. }
  6630. $sql .= $this->db->plimit($limit, 0);
  6631. // Build output string
  6632. dol_syslog(get_class($this)."::selectMembersList search adherents", LOG_DEBUG);
  6633. $result = $this->db->query($sql);
  6634. if ($result) {
  6635. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6636. require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
  6637. $num = $this->db->num_rows($result);
  6638. $events = null;
  6639. if (!$forcecombo) {
  6640. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6641. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6642. }
  6643. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6644. $textifempty = '';
  6645. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6646. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6647. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6648. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6649. else $textifempty .= $langs->trans("All");
  6650. } else {
  6651. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6652. }
  6653. if ($showempty) {
  6654. $out .= '<option value="-1" selected>'.$textifempty.'</option>';
  6655. }
  6656. $i = 0;
  6657. while ($num && $i < $num) {
  6658. $opt = '';
  6659. $optJson = array();
  6660. $objp = $this->db->fetch_object($result);
  6661. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6662. // Add new entry
  6663. // "key" value of json key array is used by jQuery automatically as selected value
  6664. // "label" value of json key array is used by jQuery automatically as text for combo box
  6665. $out .= $opt;
  6666. array_push($outarray, $optJson);
  6667. $i++;
  6668. }
  6669. $out .= '</select>';
  6670. $this->db->free($result);
  6671. if (empty($outputmode)) return $out;
  6672. return $outarray;
  6673. } else {
  6674. dol_print_error($this->db);
  6675. }
  6676. }
  6677. /**
  6678. * constructMemberListOption.
  6679. * This define value for &$opt and &$optJson.
  6680. *
  6681. * @param resource $objp Result set of fetch
  6682. * @param string $opt Option (var used for returned value in string option format)
  6683. * @param string $optJson Option (var used for returned value in json format)
  6684. * @param string $selected Preselected value
  6685. * @param string $filterkey Filter key to highlight
  6686. * @return void
  6687. */
  6688. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6689. {
  6690. $outkey = '';
  6691. $outlabel = '';
  6692. $outtype = '';
  6693. $outkey = $objp->rowid;
  6694. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  6695. $outtype = $objp->fk_adherent_type;
  6696. $opt = '<option value="'.$objp->rowid.'"';
  6697. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6698. $opt .= '>';
  6699. if (!empty($filterkey) && $filterkey != '') {
  6700. $outlabel = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $outlabel, 1);
  6701. }
  6702. $opt .= $outlabel;
  6703. $opt .= "</option>\n";
  6704. $optJson = array('key'=>$outkey, 'value'=>$outlabel, 'type'=>$outtype);
  6705. }
  6706. /**
  6707. * Generic method to select a component from a combo list.
  6708. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6709. * This is the generic method that will replace all specific existing methods.
  6710. *
  6711. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6712. * @param string $htmlname Name of HTML select component
  6713. * @param int $preselectedvalue Preselected value (ID of element)
  6714. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6715. * @param string $searchkey Search criteria
  6716. * @param string $placeholder Place holder
  6717. * @param string $morecss More CSS
  6718. * @param string $moreparams More params provided to ajax call
  6719. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6720. * @param int $disabled 1=Html component is disabled
  6721. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6722. * @return string Return HTML string
  6723. * @see selectForFormsList() select_thirdparty_list()
  6724. */
  6725. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6726. {
  6727. global $conf, $user;
  6728. $objecttmp = null;
  6729. // Example of value for $objectdec:
  6730. // Bom:bom/class/bom.class.php:0:t.status=1
  6731. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  6732. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  6733. $InfoFieldList = explode(":", $objectdesc, 4);
  6734. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  6735. $reg = array();
  6736. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  6737. $InfoFieldList[4] = $reg[1]; // take the sort field
  6738. }
  6739. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  6740. $classname = $InfoFieldList[0];
  6741. $classpath = $InfoFieldList[1];
  6742. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6743. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6744. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6745. if (!empty($classpath)) {
  6746. dol_include_once($classpath);
  6747. if ($classname && class_exists($classname)) {
  6748. $objecttmp = new $classname($this->db);
  6749. // Make some replacement
  6750. $sharedentities = getEntity(strtolower($classname));
  6751. $objecttmp->filter = str_replace(
  6752. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6753. array($conf->entity, $sharedentities, $user->id),
  6754. $filter
  6755. );
  6756. }
  6757. }
  6758. if (!is_object($objecttmp)) {
  6759. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  6760. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  6761. }
  6762. //var_dump($objecttmp->filter);
  6763. $prefixforautocompletemode = $objecttmp->element;
  6764. if ($prefixforautocompletemode == 'societe') {
  6765. $prefixforautocompletemode = 'company';
  6766. }
  6767. if ($prefixforautocompletemode == 'product') {
  6768. $prefixforautocompletemode = 'produit';
  6769. }
  6770. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6771. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  6772. $out = '';
  6773. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6774. // No immediate load of all database
  6775. $placeholder = '';
  6776. if ($preselectedvalue && empty($selected_input_value)) {
  6777. $objecttmp->fetch($preselectedvalue);
  6778. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6779. //unset($objecttmp);
  6780. }
  6781. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  6782. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  6783. // No immediate load of all database
  6784. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&objectdesc='.urlencode($objectdesc).'&filter='.urlencode($objecttmp->filter).($sortfield ? '&sortfield='.urlencode($sortfield) : '');
  6785. // Activate the auto complete using ajax call.
  6786. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6787. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6788. $out .= '<input type="text" class="'.$morecss.'"'.($disabled ? ' disabled="disabled"' : '').' name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '') .' />';
  6789. } else {
  6790. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  6791. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield);
  6792. }
  6793. return $out;
  6794. }
  6795. /**
  6796. * Function to forge a SQL criteria
  6797. *
  6798. * @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"
  6799. * @return string Forged criteria. Example: "t.field like 'abc%'"
  6800. */
  6801. protected static function forgeCriteriaCallback($matches)
  6802. {
  6803. global $db;
  6804. //dol_syslog("Convert matches ".$matches[1]);
  6805. if (empty($matches[1])) {
  6806. return '';
  6807. }
  6808. $tmp = explode(':', $matches[1]);
  6809. if (count($tmp) < 3) {
  6810. return '';
  6811. }
  6812. $tmpescaped = $tmp[2];
  6813. $regbis = array();
  6814. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  6815. $tmpescaped = "'".$db->escape($regbis[1])."'";
  6816. } else {
  6817. $tmpescaped = $db->escape($tmpescaped);
  6818. }
  6819. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  6820. }
  6821. /**
  6822. * Output html form to select an object.
  6823. * Note, this function is called by selectForForms or by ajax selectobject.php
  6824. *
  6825. * @param Object $objecttmp Object to knwo the table to scan for combo.
  6826. * @param string $htmlname Name of HTML select component
  6827. * @param int $preselectedvalue Preselected value (ID of element)
  6828. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6829. * @param string $searchkey Search value
  6830. * @param string $placeholder Place holder
  6831. * @param string $morecss More CSS
  6832. * @param string $moreparams More params provided to ajax call
  6833. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6834. * @param int $outputmode 0=HTML select string, 1=Array
  6835. * @param int $disabled 1=Html component is disabled
  6836. * @param string $sortfield Sort field
  6837. * @return string|array Return HTML string
  6838. * @see selectForForms()
  6839. */
  6840. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '')
  6841. {
  6842. global $conf, $langs, $user, $hookmanager;
  6843. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  6844. $prefixforautocompletemode = $objecttmp->element;
  6845. if ($prefixforautocompletemode == 'societe') {
  6846. $prefixforautocompletemode = 'company';
  6847. }
  6848. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6849. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  6850. $tmpfieldstoshow = '';
  6851. foreach ($objecttmp->fields as $key => $val) {
  6852. if (!dol_eval($val['enabled'], 1, 1, 1, '1')) {
  6853. continue;
  6854. }
  6855. if (!empty($val['showoncombobox'])) {
  6856. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  6857. }
  6858. }
  6859. if ($tmpfieldstoshow) {
  6860. $fieldstoshow = $tmpfieldstoshow;
  6861. }
  6862. } else {
  6863. // For backward compatibility
  6864. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  6865. }
  6866. if (empty($fieldstoshow)) {
  6867. if (isset($objecttmp->fields['ref'])) {
  6868. $fieldstoshow = 't.ref';
  6869. } else {
  6870. $langs->load("errors");
  6871. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  6872. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  6873. }
  6874. }
  6875. $out = '';
  6876. $outarray = array();
  6877. $num = 0;
  6878. // Search data
  6879. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".$this->db->prefix().$objecttmp->table_element." as t";
  6880. if (isset($objecttmp->ismultientitymanaged)) {
  6881. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6882. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  6883. $sql .= " INNER JOIN ".$this->db->prefix().$tmparray[1]." as parenttable ON parenttable.rowid = t.".$tmparray[0];
  6884. }
  6885. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6886. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6887. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  6888. }
  6889. }
  6890. }
  6891. // Add where from hooks
  6892. $parameters = array();
  6893. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  6894. if (!empty($hookmanager->resPrint)) {
  6895. $sql .= $hookmanager->resPrint;
  6896. } else {
  6897. $sql .= " WHERE 1=1";
  6898. if (isset($objecttmp->ismultientitymanaged)) {
  6899. if ($objecttmp->ismultientitymanaged == 1) {
  6900. $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  6901. }
  6902. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6903. $sql .= " AND parenttable.entity = t.".$tmparray[0];
  6904. }
  6905. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  6906. if ($objecttmp->element == 'societe') {
  6907. $sql .= " AND t.rowid = ".((int) $user->socid);
  6908. } else {
  6909. $sql .= " AND t.fk_soc = ".((int) $user->socid);
  6910. }
  6911. }
  6912. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6913. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6914. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  6915. }
  6916. }
  6917. }
  6918. if ($searchkey != '') {
  6919. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  6920. }
  6921. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  6922. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  6923. {
  6924. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  6925. }*/
  6926. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  6927. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  6928. }
  6929. }
  6930. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  6931. //$sql.=$this->db->plimit($limit, 0);
  6932. //print $sql;
  6933. // Build output string
  6934. $resql = $this->db->query($sql);
  6935. if ($resql) {
  6936. // Construct $out and $outarray
  6937. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  6938. // 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
  6939. $textifempty = '&nbsp;';
  6940. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6941. if (!empty($conf->global->$confkeyforautocompletemode)) {
  6942. if ($showempty && !is_numeric($showempty)) {
  6943. $textifempty = $langs->trans($showempty);
  6944. } else {
  6945. $textifempty .= $langs->trans("All");
  6946. }
  6947. }
  6948. if ($showempty) {
  6949. $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  6950. }
  6951. $num = $this->db->num_rows($resql);
  6952. $i = 0;
  6953. if ($num) {
  6954. while ($i < $num) {
  6955. $obj = $this->db->fetch_object($resql);
  6956. $label = '';
  6957. $tmparray = explode(',', $fieldstoshow);
  6958. $oldvalueforshowoncombobox = 0;
  6959. foreach ($tmparray as $key => $val) {
  6960. $val = preg_replace('/t\./', '', $val);
  6961. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  6962. $label .= $obj->$val;
  6963. $oldvalueforshowoncombobox = !empty($objecttmp->fields[$val]['showoncombobox']) ? $objecttmp->fields[$val]['showoncombobox'] : 0;
  6964. }
  6965. if (empty($outputmode)) {
  6966. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  6967. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  6968. } else {
  6969. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  6970. }
  6971. } else {
  6972. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  6973. }
  6974. $i++;
  6975. if (($i % 10) == 0) {
  6976. $out .= "\n";
  6977. }
  6978. }
  6979. }
  6980. $out .= '</select>'."\n";
  6981. if (!$forcecombo) {
  6982. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6983. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  6984. }
  6985. } else {
  6986. dol_print_error($this->db);
  6987. }
  6988. $this->result = array('nbofelement'=>$num);
  6989. if ($outputmode) {
  6990. return $outarray;
  6991. }
  6992. return $out;
  6993. }
  6994. /**
  6995. * Return a HTML select string, built from an array of key+value.
  6996. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  6997. *
  6998. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  6999. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7000. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7001. * @param int|string $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (If 1: key is -1 and value is '' or '&nbsp;', If placeholder string: key is -1 and value is the string), <0 to add an empty value with key that is this value.
  7002. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7003. * @param int $value_as_key 1 to use value as key
  7004. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7005. * @param int $translate 1=Translate and encode value
  7006. * @param int $maxlen Length maximum for labels
  7007. * @param int $disabled Html select box is disabled
  7008. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7009. * @param string $morecss Add more class to css styles
  7010. * @param int $addjscombo Add js combo
  7011. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7012. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7013. * @param int $nohtmlescape No html escaping.
  7014. * @return string HTML select string.
  7015. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7016. */
  7017. public static function selectarray($htmlname, $array, $id = '', $show_empty = 0, $key_in_label = 0, $value_as_key = 0, $moreparam = '', $translate = 0, $maxlen = 0, $disabled = 0, $sort = '', $morecss = '', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  7018. {
  7019. global $conf, $langs;
  7020. // Do we want a multiselect ?
  7021. //$jsbeautify = 0;
  7022. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7023. $jsbeautify = 1;
  7024. if ($value_as_key) {
  7025. $array = array_combine($array, $array);
  7026. }
  7027. $out = '';
  7028. if ($addjscombo < 0) {
  7029. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7030. $addjscombo = 1;
  7031. } else {
  7032. $addjscombo = 0;
  7033. }
  7034. }
  7035. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  7036. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  7037. $out .= '>';
  7038. if ($show_empty) {
  7039. $textforempty = ' ';
  7040. if (!empty($conf->use_javascript_ajax)) {
  7041. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7042. }
  7043. if (!is_numeric($show_empty)) {
  7044. $textforempty = $show_empty;
  7045. }
  7046. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  7047. }
  7048. if (is_array($array)) {
  7049. // Translate
  7050. if ($translate) {
  7051. foreach ($array as $key => $value) {
  7052. if (!is_array($value)) {
  7053. $array[$key] = $langs->trans($value);
  7054. } else {
  7055. $array[$key]['label'] = $langs->trans($value['label']);
  7056. }
  7057. }
  7058. }
  7059. // Sort
  7060. if ($sort == 'ASC') {
  7061. asort($array);
  7062. } elseif ($sort == 'DESC') {
  7063. arsort($array);
  7064. }
  7065. foreach ($array as $key => $tmpvalue) {
  7066. if (is_array($tmpvalue)) {
  7067. $value = $tmpvalue['label'];
  7068. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7069. $style = empty($tmpvalue['css']) ? '' : ' class="'.$tmpvalue['css'].'"';
  7070. } else {
  7071. $value = $tmpvalue;
  7072. $disabled = '';
  7073. $style = '';
  7074. }
  7075. if (!empty($disablebademail)) {
  7076. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7077. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7078. $disabled = ' disabled';
  7079. $style = ' class="warning"';
  7080. }
  7081. }
  7082. if ($key_in_label) {
  7083. if (empty($nohtmlescape)) {
  7084. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  7085. } else {
  7086. $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  7087. }
  7088. } else {
  7089. if (empty($nohtmlescape)) {
  7090. $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  7091. } else {
  7092. $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  7093. }
  7094. if ($value == '' || $value == '-') {
  7095. $selectOptionValue = '&nbsp;';
  7096. }
  7097. }
  7098. $out .= '<option value="'.$key.'"';
  7099. $out .= $style.$disabled;
  7100. if (is_array($id)) {
  7101. if (in_array($key, $id) && !$disabled) {
  7102. $out .= ' selected'; // To preselect a value
  7103. }
  7104. } else {
  7105. $id = (string) $id; // if $id = 0, then $id = '0'
  7106. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7107. $out .= ' selected'; // To preselect a value
  7108. }
  7109. }
  7110. if ($nohtmlescape) {
  7111. $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  7112. }
  7113. if (is_array($tmpvalue)) {
  7114. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7115. if (preg_match('/^data-/', $keyforvalue)) {
  7116. $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  7117. }
  7118. }
  7119. }
  7120. $out .= '>';
  7121. //var_dump($selectOptionValue);
  7122. $out .= $selectOptionValue;
  7123. $out .= "</option>\n";
  7124. }
  7125. }
  7126. $out .= "</select>";
  7127. // Add code for jquery to use multiselect
  7128. if ($addjscombo && $jsbeautify) {
  7129. // Enhance with select2
  7130. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7131. $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', $show_empty < 0 ? (string) $show_empty : '-1');
  7132. }
  7133. return $out;
  7134. }
  7135. /**
  7136. * 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.
  7137. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7138. *
  7139. * @param string $htmlname Name of html select area
  7140. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7141. * @param string $id Preselected key
  7142. * @param string $moreparam Add more parameters onto the select tag
  7143. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7144. * @param int $disabled Html select box is disabled
  7145. * @param int $minimumInputLength Minimum Input Length
  7146. * @param string $morecss Add more class to css styles
  7147. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7148. * @param string $placeholder String to use as placeholder
  7149. * @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)
  7150. * @return string HTML select string
  7151. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7152. */
  7153. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7154. {
  7155. global $conf, $langs;
  7156. global $delayedhtmlcontent; // Will be used later outside of this function
  7157. // TODO Use an internal dolibarr component instead of select2
  7158. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7159. return '';
  7160. }
  7161. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  7162. $outdelayed = '';
  7163. if (!empty($conf->use_javascript_ajax)) {
  7164. $tmpplugin = 'select2';
  7165. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7166. <script>
  7167. $(document).ready(function () {
  7168. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  7169. $(".'.$htmlname.'").select2({
  7170. ajax: {
  7171. dir: "ltr",
  7172. url: "'.$url.'",
  7173. dataType: \'json\',
  7174. delay: 250,
  7175. data: function (params) {
  7176. return {
  7177. q: params.term, // search term
  7178. page: params.page
  7179. };
  7180. },
  7181. processResults: function (data) {
  7182. // parse the results into the format expected by Select2.
  7183. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7184. //console.log(data);
  7185. saveRemoteData = data;
  7186. /* format json result for select2 */
  7187. result = []
  7188. $.each( data, function( key, value ) {
  7189. result.push({id: key, text: value.text});
  7190. });
  7191. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7192. //console.log(result);
  7193. return {results: result, more: false}
  7194. },
  7195. cache: true
  7196. },
  7197. language: select2arrayoflanguage,
  7198. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7199. placeholder: "'.dol_escape_js($placeholder).'",
  7200. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7201. minimumInputLength: '.$minimumInputLength.',
  7202. formatResult: function(result, container, query, escapeMarkup) {
  7203. return escapeMarkup(result.text);
  7204. },
  7205. });
  7206. '.($callurlonselect ? '
  7207. /* Code to execute a GET when we select a value */
  7208. $(".'.$htmlname.'").change(function() {
  7209. var selected = $(".'.$htmlname.'").val();
  7210. console.log("We select in selectArrayAjax the entry "+selected)
  7211. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7212. $.each( saveRemoteData, function( key, value ) {
  7213. if (key == selected)
  7214. {
  7215. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7216. location.assign(value.url);
  7217. }
  7218. });
  7219. });' : '').'
  7220. });
  7221. </script>';
  7222. }
  7223. if ($acceptdelayedhtml) {
  7224. $delayedhtmlcontent .= $outdelayed;
  7225. } else {
  7226. $out .= $outdelayed;
  7227. }
  7228. return $out;
  7229. }
  7230. /**
  7231. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7232. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7233. *
  7234. * @param string $htmlname Name of html select area
  7235. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7236. * @param string $id Preselected key
  7237. * @param string $moreparam Add more parameters onto the select tag
  7238. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7239. * @param int $disabled Html select box is disabled
  7240. * @param int $minimumInputLength Minimum Input Length
  7241. * @param string $morecss Add more class to css styles
  7242. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7243. * @param string $placeholder String to use as placeholder
  7244. * @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)
  7245. * @return string HTML select string
  7246. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7247. */
  7248. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7249. {
  7250. global $conf, $langs;
  7251. global $delayedhtmlcontent; // Will be used later outside of this function
  7252. // TODO Use an internal dolibarr component instead of select2
  7253. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7254. return '';
  7255. }
  7256. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  7257. $formattedarrayresult = array();
  7258. foreach ($array as $key => $value) {
  7259. $o = new stdClass();
  7260. $o->id = $key;
  7261. $o->text = $value['text'];
  7262. $o->url = $value['url'];
  7263. $formattedarrayresult[] = $o;
  7264. }
  7265. $outdelayed = '';
  7266. if (!empty($conf->use_javascript_ajax)) {
  7267. $tmpplugin = 'select2';
  7268. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7269. <script>
  7270. $(document).ready(function () {
  7271. var data = '.json_encode($formattedarrayresult).';
  7272. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  7273. $(".'.$htmlname.'").select2({
  7274. data: data,
  7275. language: select2arrayoflanguage,
  7276. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7277. placeholder: "'.dol_escape_js($placeholder).'",
  7278. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7279. minimumInputLength: '.$minimumInputLength.',
  7280. formatResult: function(result, container, query, escapeMarkup) {
  7281. return escapeMarkup(result.text);
  7282. },
  7283. matcher: function (params, data) {
  7284. if(! data.id) return null;';
  7285. if ($callurlonselect) {
  7286. $outdelayed .= '
  7287. var urlBase = data.url;
  7288. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7289. /* console.log("params.term="+params.term); */
  7290. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7291. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7292. }
  7293. if (!$disableFiltering) {
  7294. $outdelayed .= '
  7295. if(data.text.match(new RegExp(params.term))) {
  7296. return data;
  7297. }
  7298. return null;';
  7299. } else {
  7300. $outdelayed .= '
  7301. return data;';
  7302. }
  7303. $outdelayed .= '
  7304. }
  7305. });
  7306. '.($callurlonselect ? '
  7307. /* Code to execute a GET when we select a value */
  7308. $(".'.$htmlname.'").change(function() {
  7309. var selected = $(".'.$htmlname.'").val();
  7310. console.log("We select "+selected)
  7311. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7312. $.each( saveRemoteData, function( key, value ) {
  7313. if (key == selected)
  7314. {
  7315. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7316. location.assign(value.url);
  7317. }
  7318. });
  7319. });' : '').'
  7320. });
  7321. </script>';
  7322. }
  7323. if ($acceptdelayedhtml) {
  7324. $delayedhtmlcontent .= $outdelayed;
  7325. } else {
  7326. $out .= $outdelayed;
  7327. }
  7328. return $out;
  7329. }
  7330. /**
  7331. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7332. *
  7333. * @param string $htmlname Name of select
  7334. * @param array $array Array with key+value
  7335. * @param array $selected Array with key+value preselected
  7336. * @param int $key_in_label 1 to show key like in "[key] value"
  7337. * @param int $value_as_key 1 to use value as key
  7338. * @param string $morecss Add more css style
  7339. * @param int $translate Translate and encode value
  7340. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7341. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7342. * @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.
  7343. * @param string $placeholder String to use as placeholder
  7344. * @param int $addjscombo Add js combo
  7345. * @return string HTML multiselect string
  7346. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7347. */
  7348. 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)
  7349. {
  7350. global $conf, $langs;
  7351. $out = '';
  7352. if ($addjscombo < 0) {
  7353. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7354. $addjscombo = 1;
  7355. } else {
  7356. $addjscombo = 0;
  7357. }
  7358. }
  7359. // Try also magic suggest
  7360. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  7361. if (is_array($array) && !empty($array)) {
  7362. if ($value_as_key) {
  7363. $array = array_combine($array, $array);
  7364. }
  7365. if (!empty($array)) {
  7366. foreach ($array as $key => $value) {
  7367. $newval = ($translate ? $langs->trans($value) : $value);
  7368. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  7369. $out .= '<option value="'.$key.'"';
  7370. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != '')) {
  7371. $out .= ' selected';
  7372. }
  7373. $out .= ' data-html="'.dol_escape_htmltag($newval).'"';
  7374. $out .= '>';
  7375. $out .= dol_htmlentitiesbr($newval);
  7376. $out .= '</option>'."\n";
  7377. }
  7378. }
  7379. }
  7380. $out .= '</select>'."\n";
  7381. // Add code for jquery to use multiselect
  7382. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7383. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.', addjscombo='.$addjscombo.' -->';
  7384. $out .= "\n".'<script>'."\n";
  7385. if ($addjscombo == 1) {
  7386. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7387. $out .= 'function formatResult(record, container) {'."\n";
  7388. $out .= ' if ($(record.element).attr("data-html") != undefined) return htmlEntityDecodeJs($(record.element).attr("data-html")); // If property html set, we decode html entities and use this'."\n";
  7389. $out .= ' return record.text;';
  7390. $out .= '};'."\n";
  7391. $out .= 'function formatSelection(record) {'."\n";
  7392. if ($elemtype == 'category') {
  7393. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7394. } else {
  7395. $out .= 'return record.text;';
  7396. }
  7397. $out .= '};'."\n";
  7398. $out .= '$(document).ready(function () {
  7399. $(\'#'.$htmlname.'\').'.$tmpplugin.'({';
  7400. if ($placeholder) {
  7401. $out .= '
  7402. placeholder: {
  7403. id: \'-1\',
  7404. text: \''.dol_escape_js($placeholder).'\'
  7405. },';
  7406. }
  7407. $out .= ' dir: \'ltr\',
  7408. // Specify format function for dropdown item
  7409. formatResult: formatResult,
  7410. templateResult: formatResult, /* For 4.0 */
  7411. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7412. // Specify format function for selected item
  7413. formatSelection: formatSelection,
  7414. templateSelection: formatSelection /* For 4.0 */
  7415. });
  7416. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7417. the size only if component is not hidden by default on load */
  7418. $(\'#'.$htmlname.' + .select2\').addClass(\''.$morecss.'\');
  7419. });'."\n";
  7420. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7421. // Add other js lib
  7422. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7423. // ...
  7424. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  7425. $out .= '$(document).ready(function () {
  7426. $(\'#'.$htmlname.'\').multiSelect({
  7427. containerHTML: \'<div class="multi-select-container">\',
  7428. menuHTML: \'<div class="multi-select-menu">\',
  7429. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  7430. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7431. activeClass: \'multi-select-container--open\',
  7432. noneText: \''.$placeholder.'\'
  7433. });
  7434. })';
  7435. }
  7436. $out .= '</script>';
  7437. }
  7438. return $out;
  7439. }
  7440. /**
  7441. * Show a multiselect dropbox from an array. If a saved selection of fields exists for user (into $user->conf->MAIN_SELECTEDFIELDS_contextofpage), we use this one instead of default.
  7442. *
  7443. * @param string $htmlname Name of HTML field
  7444. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7445. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7446. * @param string $pos position colon on liste value left or right
  7447. * @return string HTML multiselect string
  7448. * @see selectarray()
  7449. */
  7450. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7451. {
  7452. global $conf, $langs, $user, $extrafields;
  7453. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7454. return '';
  7455. }
  7456. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved selected fields to show
  7457. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7458. $tmparray = explode(',', $user->conf->$tmpvar);
  7459. foreach ($array as $key => $val) {
  7460. //var_dump($key);
  7461. //var_dump($tmparray);
  7462. if (in_array($key, $tmparray)) {
  7463. $array[$key]['checked'] = 1;
  7464. } else {
  7465. $array[$key]['checked'] = 0;
  7466. }
  7467. }
  7468. } else { // There is no list of fields already customized for user
  7469. foreach ($array as $key => $val) {
  7470. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7471. $array[$key]['checked'] = 0;
  7472. }
  7473. }
  7474. }
  7475. $listoffieldsforselection = '';
  7476. $listcheckedstring = '';
  7477. foreach ($array as $key => $val) {
  7478. // var_dump($val);
  7479. // var_dump(array_key_exists('enabled', $val));
  7480. // var_dump(!$val['enabled']);
  7481. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7482. unset($array[$key]); // We don't want this field
  7483. continue;
  7484. }
  7485. if (!empty($val['type']) && $val['type'] == 'separate') {
  7486. // Field remains in array but we don't add it into $listoffieldsforselection
  7487. //$listoffieldsforselection .= '<li>-----</li>';
  7488. continue;
  7489. }
  7490. if ($val['label']) {
  7491. if (!empty($val['langfile']) && is_object($langs)) {
  7492. $langs->load($val['langfile']);
  7493. }
  7494. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7495. $listoffieldsforselection .= '<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.((empty($val['checked']) || $val['checked'] == '-1') ? '' : ' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
  7496. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  7497. }
  7498. }
  7499. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  7500. <dl class="dropdown">
  7501. <dt>
  7502. <a href="#'.$htmlname.'">
  7503. '.img_picto('', 'list').'
  7504. </a>
  7505. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  7506. </dt>
  7507. <dd class="dropdowndd">
  7508. <div class="multiselectcheckbox'.$htmlname.'">
  7509. <ul class="ul'.$htmlname.' '.$htmlname.$pos.'">
  7510. '.$listoffieldsforselection.'
  7511. </ul>
  7512. </div>
  7513. </dd>
  7514. </dl>
  7515. <script type="text/javascript">
  7516. jQuery(document).ready(function () {
  7517. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  7518. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7519. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7520. var title = $(this).val() + ",";
  7521. if ($(this).is(\':checked\')) {
  7522. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  7523. }
  7524. else {
  7525. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  7526. }
  7527. // Now, we submit page
  7528. //$(this).parents(\'form:first\').submit();
  7529. });
  7530. });
  7531. </script>
  7532. ';
  7533. return $out;
  7534. }
  7535. /**
  7536. * Render list of categories linked to object with id $id and type $type
  7537. *
  7538. * @param int $id Id of object
  7539. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7540. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7541. * @param int $nolink 1=Do not add html links
  7542. * @return string String with categories
  7543. */
  7544. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7545. {
  7546. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7547. $cat = new Categorie($this->db);
  7548. $categories = $cat->containing($id, $type);
  7549. if ($rendermode == 1) {
  7550. $toprint = array();
  7551. foreach ($categories as $c) {
  7552. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7553. foreach ($ways as $way) {
  7554. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  7555. }
  7556. }
  7557. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  7558. }
  7559. if ($rendermode == 0) {
  7560. $arrayselected = array();
  7561. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7562. foreach ($categories as $c) {
  7563. $arrayselected[] = $c->id;
  7564. }
  7565. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7566. }
  7567. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7568. }
  7569. /**
  7570. * Show linked object block.
  7571. *
  7572. * @param CommonObject $object Object we want to show links to
  7573. * @param string $morehtmlright More html to show on right of title
  7574. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7575. * @return int <0 if KO, >=0 if OK
  7576. */
  7577. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
  7578. {
  7579. global $conf, $langs, $hookmanager;
  7580. global $bc, $action;
  7581. $object->fetchObjectLinked();
  7582. // Bypass the default method
  7583. $hookmanager->initHooks(array('commonobject'));
  7584. $parameters = array(
  7585. 'morehtmlright' => $morehtmlright,
  7586. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7587. );
  7588. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7589. if (empty($reshook)) {
  7590. $nbofdifferenttypes = count($object->linkedObjects);
  7591. print '<!-- showLinkedObjectBlock -->';
  7592. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7593. print '<div class="div-table-responsive-no-min">';
  7594. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  7595. print '<tr class="liste_titre">';
  7596. print '<td>'.$langs->trans("Type").'</td>';
  7597. print '<td>'.$langs->trans("Ref").'</td>';
  7598. print '<td class="center"></td>';
  7599. print '<td class="center">'.$langs->trans("Date").'</td>';
  7600. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7601. print '<td class="right">'.$langs->trans("Status").'</td>';
  7602. print '<td></td>';
  7603. print '</tr>';
  7604. $nboftypesoutput = 0;
  7605. foreach ($object->linkedObjects as $objecttype => $objects) {
  7606. $tplpath = $element = $subelement = $objecttype;
  7607. // to display inport button on tpl
  7608. $showImportButton = false;
  7609. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7610. $showImportButton = true;
  7611. }
  7612. $regs = array();
  7613. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7614. $element = $regs[1];
  7615. $subelement = $regs[2];
  7616. $tplpath = $element.'/'.$subelement;
  7617. }
  7618. $tplname = 'linkedobjectblock';
  7619. // To work with non standard path
  7620. if ($objecttype == 'facture') {
  7621. $tplpath = 'compta/'.$element;
  7622. if (empty($conf->facture->enabled)) {
  7623. continue; // Do not show if module disabled
  7624. }
  7625. } elseif ($objecttype == 'facturerec') {
  7626. $tplpath = 'compta/facture';
  7627. $tplname = 'linkedobjectblockForRec';
  7628. if (empty($conf->facture->enabled)) {
  7629. continue; // Do not show if module disabled
  7630. }
  7631. } elseif ($objecttype == 'propal') {
  7632. $tplpath = 'comm/'.$element;
  7633. if (empty($conf->propal->enabled)) {
  7634. continue; // Do not show if module disabled
  7635. }
  7636. } elseif ($objecttype == 'supplier_proposal') {
  7637. if (empty($conf->supplier_proposal->enabled)) {
  7638. continue; // Do not show if module disabled
  7639. }
  7640. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  7641. $tplpath = 'expedition';
  7642. if (empty($conf->expedition->enabled)) {
  7643. continue; // Do not show if module disabled
  7644. }
  7645. } elseif ($objecttype == 'reception') {
  7646. $tplpath = 'reception';
  7647. if (empty($conf->reception->enabled)) {
  7648. continue; // Do not show if module disabled
  7649. }
  7650. } elseif ($objecttype == 'delivery') {
  7651. $tplpath = 'delivery';
  7652. if (empty($conf->expedition->enabled)) {
  7653. continue; // Do not show if module disabled
  7654. }
  7655. } elseif ($objecttype == 'mo') {
  7656. $tplpath = 'mrp/mo';
  7657. if (empty($conf->mrp->enabled)) {
  7658. continue; // Do not show if module disabled
  7659. }
  7660. } elseif ($objecttype == 'ficheinter') {
  7661. $tplpath = 'fichinter';
  7662. if (empty($conf->ficheinter->enabled)) {
  7663. continue; // Do not show if module disabled
  7664. }
  7665. } elseif ($objecttype == 'invoice_supplier') {
  7666. $tplpath = 'fourn/facture';
  7667. } elseif ($objecttype == 'order_supplier') {
  7668. $tplpath = 'fourn/commande';
  7669. } elseif ($objecttype == 'expensereport') {
  7670. $tplpath = 'expensereport';
  7671. } elseif ($objecttype == 'subscription') {
  7672. $tplpath = 'adherents';
  7673. } elseif ($objecttype == 'conferenceorbooth') {
  7674. $tplpath = 'eventorganization';
  7675. } elseif ($objecttype == 'conferenceorboothattendee') {
  7676. $tplpath = 'eventorganization';
  7677. } elseif ($objecttype == 'mo') {
  7678. $tplpath = 'mrp';
  7679. if (empty($conf->mrp->enabled)) {
  7680. continue; // Do not show if module disabled
  7681. }
  7682. }
  7683. global $linkedObjectBlock;
  7684. $linkedObjectBlock = $objects;
  7685. // Output template part (modules that overwrite templates must declare this into descriptor)
  7686. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  7687. foreach ($dirtpls as $reldir) {
  7688. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7689. global $noMoreLinkedObjectBlockAfter;
  7690. $noMoreLinkedObjectBlockAfter = 1;
  7691. }
  7692. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  7693. if ($res) {
  7694. $nboftypesoutput++;
  7695. break;
  7696. }
  7697. }
  7698. }
  7699. if (!$nboftypesoutput) {
  7700. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  7701. }
  7702. print '</table>';
  7703. if (!empty($compatibleImportElementsList)) {
  7704. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  7705. }
  7706. print '</div>';
  7707. return $nbofdifferenttypes;
  7708. }
  7709. }
  7710. /**
  7711. * Show block with links to link to other objects.
  7712. *
  7713. * @param CommonObject $object Object we want to show links to
  7714. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7715. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7716. * @return string <0 if KO, >0 if OK
  7717. */
  7718. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7719. {
  7720. global $conf, $langs, $hookmanager;
  7721. global $action;
  7722. $linktoelem = '';
  7723. $linktoelemlist = '';
  7724. $listofidcompanytoscan = '';
  7725. if (!is_object($object->thirdparty)) {
  7726. $object->fetch_thirdparty();
  7727. }
  7728. $possiblelinks = array();
  7729. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7730. $listofidcompanytoscan = $object->thirdparty->id;
  7731. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7732. $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  7733. }
  7734. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7735. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7736. $tmpproject = new Project($this->db);
  7737. $tmpproject->fetch($object->fk_project);
  7738. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7739. $listofidcompanytoscan .= ','.$tmpproject->socid;
  7740. }
  7741. unset($tmpproject);
  7742. }
  7743. $possiblelinks = array(
  7744. 'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('propal').')'),
  7745. 'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('commande').')'),
  7746. 'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('invoice').')'),
  7747. 'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('invoice').')'),
  7748. 'contrat'=>array(
  7749. 'enabled'=>$conf->contrat->enabled,
  7750. 'perms'=>1,
  7751. 'label'=>'LinkToContract',
  7752. 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_customer as ref_client, t.ref_supplier, SUM(td.total_ht) as total_ht
  7753. FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."contrat as t, ".$this->db->prefix()."contratdet as td WHERE t.fk_soc = s.rowid AND td.fk_contrat = t.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('contract').') GROUP BY s.rowid, s.nom, s.client, t.rowid, t.ref, t.ref_customer, t.ref_supplier'
  7754. ),
  7755. 'fichinter'=>array('enabled'=>!empty($conf->ficheinter->enabled) ? $conf->ficheinter->enabled : 0, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('intervention').')'),
  7756. 'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled, 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('supplier_proposal').')'),
  7757. 'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled, 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
  7758. 'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled, 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('facture_fourn').')'),
  7759. 'ticket'=>array('enabled'=>$conf->ticket->enabled, 'perms'=>1, 'label'=>'LinkToTicket', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('ticket').')'),
  7760. 'mo'=>array('enabled'=>$conf->mrp->enabled, 'perms'=>1, 'label'=>'LinkToMo', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM ".$this->db->prefix()."societe as s INNER JOIN ".$this->db->prefix()."mrp_mo as t ON t.fk_soc = s.rowid WHERE t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('mo').')')
  7761. );
  7762. }
  7763. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  7764. // Can complete the possiblelink array
  7765. $hookmanager->initHooks(array('commonobject'));
  7766. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  7767. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7768. }
  7769. if (empty($reshook)) {
  7770. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7771. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  7772. }
  7773. } elseif ($reshook > 0) {
  7774. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7775. $possiblelinks = $hookmanager->resArray;
  7776. }
  7777. }
  7778. foreach ($possiblelinks as $key => $possiblelink) {
  7779. $num = 0;
  7780. if (empty($possiblelink['enabled'])) {
  7781. continue;
  7782. }
  7783. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  7784. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  7785. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7786. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  7787. print '<input type="hidden" name="id" value="' . $object->id . '">';
  7788. print '<input type="hidden" name="action" value="addlinkbyref">';
  7789. print '<input type="hidden" name="token" value="'.newToken().'">';
  7790. print '<input type="hidden" name="addlink" value="' . $key . '">';
  7791. print '<table class="noborder">';
  7792. print '<tr>';
  7793. print '<td>' . $langs->trans("Ref") . '</td>';
  7794. print '<td><input type="text" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;<input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  7795. print '</tr>';
  7796. print '</table>';
  7797. print '</form>';
  7798. }
  7799. $sql = $possiblelink['sql'];
  7800. $resqllist = $this->db->query($sql);
  7801. if ($resqllist) {
  7802. $num = $this->db->num_rows($resqllist);
  7803. $i = 0;
  7804. print '<br>';
  7805. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  7806. print '<input type="hidden" name="action" value="addlink">';
  7807. print '<input type="hidden" name="token" value="'.newToken().'">';
  7808. print '<input type="hidden" name="id" value="'.$object->id.'">';
  7809. print '<input type="hidden" name="addlink" value="'.$key.'">';
  7810. print '<table class="noborder">';
  7811. print '<tr class="liste_titre">';
  7812. print '<td class="nowrap"></td>';
  7813. print '<td class="center">'.$langs->trans("Ref").'</td>';
  7814. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  7815. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7816. print '<td class="left">'.$langs->trans("Company").'</td>';
  7817. print '</tr>';
  7818. while ($i < $num) {
  7819. $objp = $this->db->fetch_object($resqllist);
  7820. print '<tr class="oddeven">';
  7821. print '<td class="left">';
  7822. print '<input type="radio" name="idtolinkto" id="'.$key.'_'.$objp->rowid.'" value="'.$objp->rowid.'">';
  7823. print '</td>';
  7824. print '<td class="center"><label for="'.$key.'_'.$objp->rowid.'">'.$objp->ref.'</label></td>';
  7825. print '<td>'.(!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')).'</td>';
  7826. print '<td class="right">';
  7827. if ($possiblelink['label'] == 'LinkToContract') {
  7828. $form = new Form($this->db);
  7829. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' ';
  7830. }
  7831. print '<span class="amount">'.price($objp->total_ht).'</span>';
  7832. print '</td>';
  7833. print '<td>'.$objp->name.'</td>';
  7834. print '</tr>';
  7835. $i++;
  7836. }
  7837. print '</table>';
  7838. print '<div class="center">';
  7839. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="'.$langs->trans('ToLink').'">';
  7840. if (empty($conf->use_javascript_ajax)) {
  7841. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7842. } else {
  7843. print '<input type="submit"; onclick="javascript:jQuery(\'#'.$key.'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7844. }
  7845. print '</form>';
  7846. $this->db->free($resqllist);
  7847. } else {
  7848. dol_print_error($this->db);
  7849. }
  7850. print '</div>';
  7851. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  7852. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7853. $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  7854. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  7855. } else {
  7856. $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  7857. }
  7858. }
  7859. }
  7860. if ($linktoelemlist) {
  7861. $linktoelem = '
  7862. <dl class="dropdown" id="linktoobjectname">
  7863. ';
  7864. if (!empty($conf->use_javascript_ajax)) {
  7865. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>'.$langs->trans("LinkTo").'...</a></dt>';
  7866. }
  7867. $linktoelem .= '<dd>
  7868. <div class="multiselectlinkto">
  7869. <ul class="ulselectedfields">'.$linktoelemlist.'
  7870. </ul>
  7871. </div>
  7872. </dd>
  7873. </dl>';
  7874. } else {
  7875. $linktoelem = '';
  7876. }
  7877. if (!empty($conf->use_javascript_ajax)) {
  7878. print '<!-- Add js to show linkto box -->
  7879. <script>
  7880. jQuery(document).ready(function() {
  7881. jQuery(".linkto").click(function() {
  7882. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  7883. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  7884. });
  7885. });
  7886. </script>
  7887. ';
  7888. }
  7889. return $linktoelem;
  7890. }
  7891. /**
  7892. * Return an html string with a select combo box to choose yes or no
  7893. *
  7894. * @param string $htmlname Name of html select field
  7895. * @param string $value Pre-selected value
  7896. * @param int $option 0 return yes/no, 1 return 1/0
  7897. * @param bool $disabled true or false
  7898. * @param int $useempty 1=Add empty line
  7899. * @param int $addjscombo 1=Add js beautifier on combo box
  7900. * @param string $morecss More CSS
  7901. * @return string See option
  7902. */
  7903. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '')
  7904. {
  7905. global $langs;
  7906. $yes = "yes";
  7907. $no = "no";
  7908. if ($option) {
  7909. $yes = "1";
  7910. $no = "0";
  7911. }
  7912. $disabled = ($disabled ? ' disabled' : '');
  7913. $resultyesno = '<select class="flat width75'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  7914. if ($useempty) {
  7915. $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  7916. }
  7917. if (("$value" == 'yes') || ($value == 1)) {
  7918. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  7919. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  7920. } else {
  7921. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  7922. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  7923. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  7924. }
  7925. $resultyesno .= '</select>'."\n";
  7926. if ($addjscombo) {
  7927. $resultyesno .= ajax_combobox($htmlname);
  7928. }
  7929. return $resultyesno;
  7930. }
  7931. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7932. /**
  7933. * Return list of export templates
  7934. *
  7935. * @param string $selected Id modele pre-selectionne
  7936. * @param string $htmlname Name of HTML select
  7937. * @param string $type Type of searched templates
  7938. * @param int $useempty Affiche valeur vide dans liste
  7939. * @return void
  7940. */
  7941. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  7942. {
  7943. // phpcs:enable
  7944. $sql = "SELECT rowid, label";
  7945. $sql .= " FROM ".$this->db->prefix()."export_model";
  7946. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  7947. $sql .= " ORDER BY rowid";
  7948. $result = $this->db->query($sql);
  7949. if ($result) {
  7950. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  7951. if ($useempty) {
  7952. print '<option value="-1">&nbsp;</option>';
  7953. }
  7954. $num = $this->db->num_rows($result);
  7955. $i = 0;
  7956. while ($i < $num) {
  7957. $obj = $this->db->fetch_object($result);
  7958. if ($selected == $obj->rowid) {
  7959. print '<option value="'.$obj->rowid.'" selected>';
  7960. } else {
  7961. print '<option value="'.$obj->rowid.'">';
  7962. }
  7963. print $obj->label;
  7964. print '</option>';
  7965. $i++;
  7966. }
  7967. print "</select>";
  7968. } else {
  7969. dol_print_error($this->db);
  7970. }
  7971. }
  7972. /**
  7973. * Return a HTML area with the reference of object and a navigation bar for a business object
  7974. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  7975. *
  7976. * @param object $object Object to show.
  7977. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  7978. * @param string $morehtml More html content to output just before the nav bar.
  7979. * @param int $shownav Show Condition (navigation is shown if value is 1).
  7980. * @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.
  7981. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  7982. * @param string $morehtmlref More html to show after ref.
  7983. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  7984. * @param int $nodbprefix Do not include DB prefix to forge table name.
  7985. * @param string $morehtmlleft More html code to show before ref.
  7986. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  7987. * @param string $morehtmlright More html code to show after ref.
  7988. * @return string Portion HTML with ref + navigation buttons
  7989. */
  7990. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  7991. {
  7992. global $conf, $langs, $hookmanager, $extralanguages;
  7993. $ret = '';
  7994. if (empty($fieldid)) {
  7995. $fieldid = 'rowid';
  7996. }
  7997. if (empty($fieldref)) {
  7998. $fieldref = 'ref';
  7999. }
  8000. // Preparing gender's display if there is one
  8001. $addgendertxt = '';
  8002. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8003. $addgendertxt = ' ';
  8004. switch ($object->gender) {
  8005. case 'man':
  8006. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8007. break;
  8008. case 'woman':
  8009. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8010. break;
  8011. case 'other':
  8012. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8013. break;
  8014. }
  8015. }
  8016. /*
  8017. $addadmin = '';
  8018. if (property_exists($object, 'admin')) {
  8019. if (!empty($conf->multicompany->enabled) && !empty($object->admin) && empty($object->entity)) {
  8020. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  8021. } elseif (!empty($object->admin)) {
  8022. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  8023. }
  8024. }*/
  8025. // Add where from hooks
  8026. if (is_object($hookmanager)) {
  8027. $parameters = array('showrefnav' => true);
  8028. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8029. $object->next_prev_filter .= $hookmanager->resPrint;
  8030. }
  8031. $previous_ref = $next_ref = '';
  8032. if ($shownav) {
  8033. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8034. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8035. $navurl = $_SERVER["PHP_SELF"];
  8036. // Special case for project/task page
  8037. if ($paramid == 'project_ref') {
  8038. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8039. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8040. $paramid = 'ref';
  8041. }
  8042. }
  8043. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8044. // accesskey is for Mac: CTRL + key for all browsers
  8045. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8046. if ($conf->browser->name == 'chrome') {
  8047. $stringforfirstkey .= ' ALT +';
  8048. } elseif ($conf->browser->name == 'firefox') {
  8049. $stringforfirstkey .= ' ALT + SHIFT +';
  8050. } else {
  8051. $stringforfirstkey .= ' CTL +';
  8052. }
  8053. $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>';
  8054. $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>';
  8055. }
  8056. //print "xx".$previous_ref."x".$next_ref;
  8057. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8058. // Right part of banner
  8059. if ($morehtmlright) {
  8060. $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  8061. }
  8062. if ($previous_ref || $next_ref || $morehtml) {
  8063. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8064. }
  8065. if ($morehtml) {
  8066. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  8067. }
  8068. if ($shownav && ($previous_ref || $next_ref)) {
  8069. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  8070. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  8071. }
  8072. if ($previous_ref || $next_ref || $morehtml) {
  8073. $ret .= '</ul></div>';
  8074. }
  8075. $parameters = array();
  8076. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8077. if (empty($reshook)) {
  8078. $morehtmlstatus .= $hookmanager->resPrint;
  8079. } else {
  8080. $morehtmlstatus = $hookmanager->resPrint;
  8081. }
  8082. if ($morehtmlstatus) {
  8083. $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  8084. }
  8085. $parameters = array();
  8086. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8087. if (empty($reshook)) {
  8088. $morehtmlref .= $hookmanager->resPrint;
  8089. } elseif ($reshook > 0) {
  8090. $morehtmlref = $hookmanager->resPrint;
  8091. }
  8092. // Left part of banner
  8093. if ($morehtmlleft) {
  8094. if ($conf->browser->layout == 'phone') {
  8095. $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  8096. } else {
  8097. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  8098. }
  8099. }
  8100. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8101. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  8102. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8103. if ($object->element == 'societe') {
  8104. $ret .= dol_htmlentities($object->name);
  8105. // List of extra languages
  8106. $arrayoflangcode = array();
  8107. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8108. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8109. }
  8110. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8111. if (!is_object($extralanguages)) {
  8112. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  8113. $extralanguages = new ExtraLanguages($this->db);
  8114. }
  8115. $extralanguages->fetch_name_extralanguages('societe');
  8116. if (!empty($extralanguages->attributes['societe']['name'])) {
  8117. $object->fetchValuesForExtraLanguages();
  8118. $htmltext = '';
  8119. // If there is extra languages
  8120. foreach ($arrayoflangcode as $extralangcode) {
  8121. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8122. if ($object->array_languages['name'][$extralangcode]) {
  8123. $htmltext .= $object->array_languages['name'][$extralangcode];
  8124. } else {
  8125. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  8126. }
  8127. }
  8128. $ret .= '<!-- Show translations of name -->'."\n";
  8129. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8130. }
  8131. }
  8132. } elseif ($object->element == 'member') {
  8133. $ret .= $object->ref.'<br>';
  8134. $fullname = $object->getFullName($langs);
  8135. if ($object->morphy == 'mor' && $object->societe) {
  8136. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).$addgendertxt.')' : '');
  8137. } else {
  8138. $ret .= dol_htmlentities($fullname).$addgendertxt.((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  8139. }
  8140. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8141. $ret .= dol_htmlentities($object->getFullName($langs)).$addgendertxt;
  8142. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8143. $ret .= $object->ref.'<br>'.$object->label;
  8144. } elseif (in_array($object->element, array('adherent_type'))) {
  8145. $ret .= $object->label;
  8146. } elseif ($object->element == 'ecm_directories') {
  8147. $ret .= '';
  8148. } elseif ($fieldref != 'none') {
  8149. $ret .= dol_htmlentities($object->$fieldref);
  8150. }
  8151. if ($morehtmlref) {
  8152. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8153. if (substr($morehtmlref, 0, 4) != '<div') {
  8154. $ret .= ' ';
  8155. }
  8156. $ret .= $morehtmlref;
  8157. }
  8158. $ret .= '</div>';
  8159. $ret .= '</div><!-- End banner content -->';
  8160. return $ret;
  8161. }
  8162. /**
  8163. * Return HTML code to output a barcode
  8164. *
  8165. * @param Object $object Object containing data to retrieve file name
  8166. * @param int $width Width of photo
  8167. * @param string $morecss More CSS on img of barcode
  8168. * @return string HTML code to output barcode
  8169. */
  8170. public function showbarcode(&$object, $width = 100, $morecss = '')
  8171. {
  8172. global $conf;
  8173. //Check if barcode is filled in the card
  8174. if (empty($object->barcode)) {
  8175. return '';
  8176. }
  8177. // Complete object if not complete
  8178. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8179. $result = $object->fetch_barcode();
  8180. //Check if fetch_barcode() failed
  8181. if ($result < 1) {
  8182. return '<!-- ErrorFetchBarcode -->';
  8183. }
  8184. }
  8185. // Barcode image
  8186. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  8187. $out = '<!-- url barcode = '.$url.' -->';
  8188. $out .= '<img src="'.$url.'"'.($morecss ? ' class="'.$morecss.'"' : '').'>';
  8189. return $out;
  8190. }
  8191. /**
  8192. * Return HTML code to output a photo
  8193. *
  8194. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8195. * @param object $object Object containing data to retrieve file name
  8196. * @param int $width Width of photo
  8197. * @param int $height Height of photo (auto if 0)
  8198. * @param int $caneditfield Add edit fields
  8199. * @param string $cssclass CSS name to use on img for photo
  8200. * @param string $imagesize 'mini', 'small' or '' (original)
  8201. * @param int $addlinktofullsize Add link to fullsize image
  8202. * @param int $cache 1=Accept to use image in cache
  8203. * @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 ''.
  8204. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8205. * @return string HTML code to output photo
  8206. */
  8207. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8208. {
  8209. global $conf, $langs;
  8210. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8211. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8212. $ret = '';
  8213. $dir = '';
  8214. $file = '';
  8215. $originalfile = '';
  8216. $altfile = '';
  8217. $email = '';
  8218. $capture = '';
  8219. if ($modulepart == 'societe') {
  8220. $dir = $conf->societe->multidir_output[$entity];
  8221. if (!empty($object->logo)) {
  8222. if (dolIsAllowedForPreview($object->logo)) {
  8223. if ((string) $imagesize == 'mini') {
  8224. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8225. } elseif ((string) $imagesize == 'small') {
  8226. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_small');
  8227. } else {
  8228. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8229. }
  8230. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8231. }
  8232. }
  8233. $email = $object->email;
  8234. } elseif ($modulepart == 'contact') {
  8235. $dir = $conf->societe->multidir_output[$entity].'/contact';
  8236. if (!empty($object->photo)) {
  8237. if (dolIsAllowedForPreview($object->photo)) {
  8238. if ((string) $imagesize == 'mini') {
  8239. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8240. } elseif ((string) $imagesize == 'small') {
  8241. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8242. } else {
  8243. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8244. }
  8245. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8246. }
  8247. }
  8248. $email = $object->email;
  8249. $capture = 'user';
  8250. } elseif ($modulepart == 'userphoto') {
  8251. $dir = $conf->user->dir_output;
  8252. if (!empty($object->photo)) {
  8253. if (dolIsAllowedForPreview($object->photo)) {
  8254. if ((string) $imagesize == 'mini') {
  8255. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8256. } elseif ((string) $imagesize == 'small') {
  8257. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8258. } else {
  8259. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8260. }
  8261. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8262. }
  8263. }
  8264. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8265. $altfile = $object->id.".jpg"; // For backward compatibility
  8266. }
  8267. $email = $object->email;
  8268. $capture = 'user';
  8269. } elseif ($modulepart == 'memberphoto') {
  8270. $dir = $conf->adherent->dir_output;
  8271. if (!empty($object->photo)) {
  8272. if (dolIsAllowedForPreview($object->photo)) {
  8273. if ((string) $imagesize == 'mini') {
  8274. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8275. } elseif ((string) $imagesize == 'small') {
  8276. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8277. } else {
  8278. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8279. }
  8280. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8281. }
  8282. }
  8283. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8284. $altfile = $object->id.".jpg"; // For backward compatibility
  8285. }
  8286. $email = $object->email;
  8287. $capture = 'user';
  8288. } else {
  8289. // Generic case to show photos
  8290. $dir = $conf->$modulepart->dir_output;
  8291. if (!empty($object->photo)) {
  8292. if (dolIsAllowedForPreview($object->photo)) {
  8293. if ((string) $imagesize == 'mini') {
  8294. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8295. } elseif ((string) $imagesize == 'small') {
  8296. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  8297. } else {
  8298. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8299. }
  8300. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8301. }
  8302. }
  8303. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8304. $altfile = $object->id.".jpg"; // For backward compatibility
  8305. }
  8306. $email = $object->email;
  8307. }
  8308. if ($forcecapture) {
  8309. $capture = $forcecapture;
  8310. }
  8311. if ($dir) {
  8312. if ($file && file_exists($dir."/".$file)) {
  8313. if ($addlinktofullsize) {
  8314. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8315. if ($urladvanced) {
  8316. $ret .= '<a href="'.$urladvanced.'">';
  8317. } else {
  8318. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8319. }
  8320. }
  8321. $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.'">';
  8322. if ($addlinktofullsize) {
  8323. $ret .= '</a>';
  8324. }
  8325. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  8326. if ($addlinktofullsize) {
  8327. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8328. if ($urladvanced) {
  8329. $ret .= '<a href="'.$urladvanced.'">';
  8330. } else {
  8331. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8332. }
  8333. }
  8334. $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.'">';
  8335. if ($addlinktofullsize) {
  8336. $ret .= '</a>';
  8337. }
  8338. } else {
  8339. $nophoto = '/public/theme/common/nophoto.png';
  8340. $defaultimg = 'identicon'; // For gravatar
  8341. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8342. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8343. $nophoto = 'company';
  8344. } else {
  8345. $nophoto = '/public/theme/common/user_anonymous.png';
  8346. if (!empty($object->gender) && $object->gender == 'man') {
  8347. $nophoto = '/public/theme/common/user_man.png';
  8348. }
  8349. if (!empty($object->gender) && $object->gender == 'woman') {
  8350. $nophoto = '/public/theme/common/user_woman.png';
  8351. }
  8352. }
  8353. }
  8354. if (!empty($conf->gravatar->enabled) && $email && empty($noexternsourceoverwrite)) {
  8355. // see https://gravatar.com/site/implement/images/php/
  8356. $ret .= '<!-- Put link to gravatar -->';
  8357. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" title="'.$email.' Gravatar avatar" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="https://www.gravatar.com/avatar/'.md5(strtolower(trim($email))).'?s='.$width.'&d='.$defaultimg.'">'; // gravatar need md5 hash
  8358. } else {
  8359. if ($nophoto == 'company') {
  8360. $ret .= '<div class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'">'.img_picto('', 'company').'</div>';
  8361. } else {
  8362. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  8363. }
  8364. }
  8365. }
  8366. if ($caneditfield) {
  8367. if ($object->photo) {
  8368. $ret .= "<br>\n";
  8369. }
  8370. $ret .= '<table class="nobordernopadding centpercent">';
  8371. if ($object->photo) {
  8372. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">'.$langs->trans("Delete").'</label><br><br></td></tr>';
  8373. }
  8374. $ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
  8375. $ret .= '</table>';
  8376. }
  8377. } else {
  8378. dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  8379. }
  8380. return $ret;
  8381. }
  8382. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8383. /**
  8384. * Return select list of groups
  8385. *
  8386. * @param string $selected Id group preselected
  8387. * @param string $htmlname Field name in form
  8388. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8389. * @param string $exclude Array list of groups id to exclude
  8390. * @param int $disabled If select list must be disabled
  8391. * @param string $include Array list of groups id to include
  8392. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8393. * @param string $force_entity '0' or Ids of environment to force
  8394. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8395. * @param string $morecss More css to add to html component
  8396. * @return string
  8397. * @see select_dolusers()
  8398. */
  8399. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8400. {
  8401. // phpcs:enable
  8402. global $conf, $user, $langs;
  8403. // Permettre l'exclusion de groupes
  8404. if (is_array($exclude)) {
  8405. $excludeGroups = implode(",", $exclude);
  8406. }
  8407. // Permettre l'inclusion de groupes
  8408. if (is_array($include)) {
  8409. $includeGroups = implode(",", $include);
  8410. }
  8411. if (!is_array($selected)) {
  8412. $selected = array($selected);
  8413. }
  8414. $out = '';
  8415. // On recherche les groupes
  8416. $sql = "SELECT ug.rowid, ug.nom as name";
  8417. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8418. $sql .= ", e.label";
  8419. }
  8420. $sql .= " FROM ".$this->db->prefix()."usergroup as ug ";
  8421. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8422. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid=ug.entity";
  8423. if ($force_entity) {
  8424. $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  8425. } else {
  8426. $sql .= " WHERE ug.entity IS NOT NULL";
  8427. }
  8428. } else {
  8429. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  8430. }
  8431. if (is_array($exclude) && $excludeGroups) {
  8432. $sql .= " AND ug.rowid NOT IN (".$this->db->sanitize($excludeGroups).")";
  8433. }
  8434. if (is_array($include) && $includeGroups) {
  8435. $sql .= " AND ug.rowid IN (".$this->db->sanitize($includeGroups).")";
  8436. }
  8437. $sql .= " ORDER BY ug.nom ASC";
  8438. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  8439. $resql = $this->db->query($sql);
  8440. if ($resql) {
  8441. // Enhance with select2
  8442. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8443. $out .= ajax_combobox($htmlname);
  8444. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  8445. $num = $this->db->num_rows($resql);
  8446. $i = 0;
  8447. if ($num) {
  8448. if ($show_empty && !$multiple) {
  8449. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8450. }
  8451. while ($i < $num) {
  8452. $obj = $this->db->fetch_object($resql);
  8453. $disableline = 0;
  8454. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8455. $disableline = 1;
  8456. }
  8457. $out .= '<option value="'.$obj->rowid.'"';
  8458. if ($disableline) {
  8459. $out .= ' disabled';
  8460. }
  8461. if ((isset($selected[0]) && is_object($selected[0]) && $selected[0]->id == $obj->rowid) || ((!isset($selected[0]) || !is_object($selected[0])) && !empty($selected) && in_array($obj->rowid, $selected))) {
  8462. $out .= ' selected';
  8463. }
  8464. $out .= '>';
  8465. $out .= $obj->name;
  8466. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8467. $out .= " (".$obj->label.")";
  8468. }
  8469. $out .= '</option>';
  8470. $i++;
  8471. }
  8472. } else {
  8473. if ($show_empty) {
  8474. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  8475. }
  8476. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  8477. }
  8478. $out .= '</select>';
  8479. } else {
  8480. dol_print_error($this->db);
  8481. }
  8482. return $out;
  8483. }
  8484. /**
  8485. * Return HTML to show the search and clear seach button
  8486. *
  8487. * @param string $pos position colon on liste value left or right
  8488. * @return string
  8489. */
  8490. public function showFilterButtons($pos = '')
  8491. {
  8492. $out = '<div class="nowraponall">';
  8493. if ($pos == 'left') {
  8494. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8495. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8496. } else {
  8497. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8498. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8499. }
  8500. $out .= '</div>';
  8501. return $out;
  8502. }
  8503. /**
  8504. * Return HTML to show the search and clear search button
  8505. *
  8506. * @param string $cssclass CSS class
  8507. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8508. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8509. * @return string
  8510. */
  8511. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8512. {
  8513. global $conf, $langs;
  8514. $out = '';
  8515. if (!empty($conf->use_javascript_ajax)) {
  8516. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  8517. }
  8518. $out .= '<script>
  8519. $(document).ready(function() {
  8520. $("#' . $cssclass.'s").click(function() {
  8521. if($(this).is(\':checked\')){
  8522. console.log("We check all '.$cssclass.' and trigger the change method");
  8523. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  8524. }
  8525. else
  8526. {
  8527. console.log("We uncheck all");
  8528. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  8529. }'."\n";
  8530. if ($calljsfunction) {
  8531. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8532. }
  8533. $out .= ' });
  8534. $(".' . $cssclass.'").change(function() {
  8535. $(this).closest("tr").toggleClass("highlight", this.checked);
  8536. });
  8537. });
  8538. </script>';
  8539. return $out;
  8540. }
  8541. /**
  8542. * Return HTML to show the search and clear seach button
  8543. *
  8544. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8545. * @param string $cssclass CSS class
  8546. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8547. * @param string $massactionname Mass action name
  8548. * @return string
  8549. */
  8550. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8551. {
  8552. $out = $this->showFilterButtons();
  8553. if ($addcheckuncheckall) {
  8554. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8555. }
  8556. return $out;
  8557. }
  8558. /**
  8559. * Return HTML to show the select of expense categories
  8560. *
  8561. * @param string $selected preselected category
  8562. * @param string $htmlname name of HTML select list
  8563. * @param integer $useempty 1=Add empty line
  8564. * @param array $excludeid id to exclude
  8565. * @param string $target htmlname of target select to bind event
  8566. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8567. * @param array $params param to give
  8568. * @param int $info_admin Show the tooltip help picto to setup list
  8569. * @return string
  8570. */
  8571. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8572. {
  8573. global $langs, $user;
  8574. $out = '';
  8575. $sql = "SELECT rowid, label FROM ".$this->db->prefix()."c_exp_tax_cat WHERE active = 1";
  8576. $sql .= " AND entity IN (0,".getEntity('exp_tax_cat').")";
  8577. if (!empty($excludeid)) {
  8578. $sql .= " AND rowid NOT IN (".$this->db->sanitize(implode(',', $excludeid)).")";
  8579. }
  8580. $sql .= " ORDER BY label";
  8581. $resql = $this->db->query($sql);
  8582. if ($resql) {
  8583. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  8584. if ($useempty) {
  8585. $out .= '<option value="0">&nbsp;</option>';
  8586. }
  8587. while ($obj = $this->db->fetch_object($resql)) {
  8588. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  8589. }
  8590. $out .= '</select>';
  8591. $out .= ajax_combobox('select_'.$htmlname);
  8592. if (!empty($htmlname) && $user->admin && $info_admin) {
  8593. $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8594. }
  8595. if (!empty($target)) {
  8596. $sql = "SELECT c.id FROM ".$this->db->prefix()."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8597. $resql = $this->db->query($sql);
  8598. if ($resql) {
  8599. if ($this->db->num_rows($resql) > 0) {
  8600. $obj = $this->db->fetch_object($resql);
  8601. $out .= '<script>
  8602. $(function() {
  8603. $("select[name='.$target.']").on("change", function() {
  8604. var current_val = $(this).val();
  8605. if (current_val == '.$obj->id.') {';
  8606. if (!empty($default_selected) || !empty($selected)) {
  8607. $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  8608. }
  8609. $out .= '
  8610. $("select[name='.$htmlname.']").change();
  8611. }
  8612. });
  8613. $("select[name='.$htmlname.']").change(function() {
  8614. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  8615. // get price of kilometer to fill the unit price
  8616. $.ajax({
  8617. method: "POST",
  8618. dataType: "json",
  8619. data: { fk_c_exp_tax_cat: $(this).val(), token: \''.currentToken().'\' },
  8620. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php?'.$params).'",
  8621. }).done(function( data, textStatus, jqXHR ) {
  8622. console.log(data);
  8623. if (typeof data.up != "undefined") {
  8624. $("input[name=value_unit]").val(data.up);
  8625. $("select[name='.$htmlname.']").attr("title", data.title);
  8626. } else {
  8627. $("input[name=value_unit]").val("");
  8628. $("select[name='.$htmlname.']").attr("title", "");
  8629. }
  8630. });
  8631. }
  8632. });
  8633. });
  8634. </script>';
  8635. }
  8636. }
  8637. }
  8638. } else {
  8639. dol_print_error($this->db);
  8640. }
  8641. return $out;
  8642. }
  8643. /**
  8644. * Return HTML to show the select ranges of expense range
  8645. *
  8646. * @param string $selected preselected category
  8647. * @param string $htmlname name of HTML select list
  8648. * @param integer $useempty 1=Add empty line
  8649. * @return string
  8650. */
  8651. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8652. {
  8653. global $conf, $langs;
  8654. $out = '';
  8655. $sql = "SELECT rowid, range_ik FROM ".$this->db->prefix()."c_exp_tax_range";
  8656. $sql .= " WHERE entity = ".$conf->entity." AND active = 1";
  8657. $resql = $this->db->query($sql);
  8658. if ($resql) {
  8659. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8660. if ($useempty) {
  8661. $out .= '<option value="0"></option>';
  8662. }
  8663. while ($obj = $this->db->fetch_object($resql)) {
  8664. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  8665. }
  8666. $out .= '</select>';
  8667. } else {
  8668. dol_print_error($this->db);
  8669. }
  8670. return $out;
  8671. }
  8672. /**
  8673. * Return HTML to show a select of expense
  8674. *
  8675. * @param string $selected preselected category
  8676. * @param string $htmlname name of HTML select list
  8677. * @param integer $useempty 1=Add empty choice
  8678. * @param integer $allchoice 1=Add all choice
  8679. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8680. * @return string
  8681. */
  8682. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8683. {
  8684. global $langs;
  8685. $out = '';
  8686. $sql = "SELECT id, code, label FROM ".$this->db->prefix()."c_type_fees";
  8687. $sql .= " WHERE active = 1";
  8688. $resql = $this->db->query($sql);
  8689. if ($resql) {
  8690. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8691. if ($useempty) {
  8692. $out .= '<option value="0"></option>';
  8693. }
  8694. if ($allchoice) {
  8695. $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  8696. }
  8697. $field = 'code';
  8698. if ($useid) {
  8699. $field = 'id';
  8700. }
  8701. while ($obj = $this->db->fetch_object($resql)) {
  8702. $key = $langs->trans($obj->code);
  8703. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  8704. }
  8705. $out .= '</select>';
  8706. } else {
  8707. dol_print_error($this->db);
  8708. }
  8709. return $out;
  8710. }
  8711. /**
  8712. * Output a combo list with invoices qualified for a third party
  8713. *
  8714. * @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)
  8715. * @param int $selected Id invoice preselected
  8716. * @param string $htmlname Name of HTML select
  8717. * @param int $maxlength Maximum length of label
  8718. * @param int $option_only Return only html options lines without the select tag
  8719. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8720. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8721. * @param int $forcefocus Force focus on field (works with javascript only)
  8722. * @param int $disabled Disabled
  8723. * @param string $morecss More css added to the select component
  8724. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  8725. * @param string $showproject 'all' = Show project info, ''=Hide project info
  8726. * @param User $usertofilter User object to use for filtering
  8727. * @return int Nbr of project if OK, <0 if KO
  8728. */
  8729. 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)
  8730. {
  8731. global $user, $conf, $langs;
  8732. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  8733. if (is_null($usertofilter)) {
  8734. $usertofilter = $user;
  8735. }
  8736. $out = '';
  8737. $hideunselectables = false;
  8738. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  8739. $hideunselectables = true;
  8740. }
  8741. if (empty($projectsListId)) {
  8742. if (empty($usertofilter->rights->projet->all->lire)) {
  8743. $projectstatic = new Project($this->db);
  8744. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  8745. }
  8746. }
  8747. // Search all projects
  8748. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  8749. p.title, p.fk_soc, p.fk_statut, p.public,";
  8750. $sql .= ' s.nom as name';
  8751. $sql .= ' FROM '.$this->db->prefix().'projet as p';
  8752. $sql .= ' LEFT JOIN '.$this->db->prefix().'societe as s ON s.rowid = p.fk_soc,';
  8753. $sql .= ' '.$this->db->prefix().'facture as f';
  8754. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  8755. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  8756. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  8757. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  8758. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  8759. $sql .= " ORDER BY p.ref, f.ref ASC";
  8760. $resql = $this->db->query($sql);
  8761. if ($resql) {
  8762. // Use select2 selector
  8763. if (!empty($conf->use_javascript_ajax)) {
  8764. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8765. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8766. $out .= $comboenhancement;
  8767. $morecss = 'minwidth200imp maxwidth500';
  8768. }
  8769. if (empty($option_only)) {
  8770. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  8771. }
  8772. if (!empty($show_empty)) {
  8773. $out .= '<option value="0" class="optiongrey">';
  8774. if (!is_numeric($show_empty)) {
  8775. $out .= $show_empty;
  8776. } else {
  8777. $out .= '&nbsp;';
  8778. }
  8779. $out .= '</option>';
  8780. }
  8781. $num = $this->db->num_rows($resql);
  8782. $i = 0;
  8783. if ($num) {
  8784. while ($i < $num) {
  8785. $obj = $this->db->fetch_object($resql);
  8786. // 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.
  8787. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  8788. // Do nothing
  8789. } else {
  8790. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  8791. $i++;
  8792. continue;
  8793. }
  8794. $labeltoshow = '';
  8795. if ($showproject == 'all') {
  8796. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  8797. if ($obj->name) {
  8798. $labeltoshow .= ' - '.$obj->name; // Soc name
  8799. }
  8800. $disabled = 0;
  8801. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  8802. $disabled = 1;
  8803. $labeltoshow .= ' - '.$langs->trans("Draft");
  8804. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  8805. if ($discard_closed == 2) {
  8806. $disabled = 1;
  8807. }
  8808. $labeltoshow .= ' - '.$langs->trans("Closed");
  8809. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  8810. $disabled = 1;
  8811. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  8812. }
  8813. }
  8814. if (!empty($selected) && $selected == $obj->rowid) {
  8815. $out .= '<option value="'.$obj->rowid.'" selected';
  8816. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8817. $out .= '>'.$labeltoshow.'</option>';
  8818. } else {
  8819. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  8820. $resultat = '';
  8821. } else {
  8822. $resultat = '<option value="'.$obj->rowid.'"';
  8823. if ($disabled) {
  8824. $resultat .= ' disabled';
  8825. }
  8826. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  8827. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  8828. $resultat .= '>';
  8829. $resultat .= $labeltoshow;
  8830. $resultat .= '</option>';
  8831. }
  8832. $out .= $resultat;
  8833. }
  8834. }
  8835. $i++;
  8836. }
  8837. }
  8838. if (empty($option_only)) {
  8839. $out .= '</select>';
  8840. }
  8841. print $out;
  8842. $this->db->free($resql);
  8843. return $num;
  8844. } else {
  8845. dol_print_error($this->db);
  8846. return -1;
  8847. }
  8848. }
  8849. /**
  8850. * Output a combo list with invoices qualified for a third party
  8851. *
  8852. * @param int $selected Id invoice preselected
  8853. * @param string $htmlname Name of HTML select
  8854. * @param int $maxlength Maximum length of label
  8855. * @param int $option_only Return only html options lines without the select tag
  8856. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8857. * @param int $forcefocus Force focus on field (works with javascript only)
  8858. * @param int $disabled Disabled
  8859. * @param string $morecss More css added to the select component
  8860. * @return int Nbr of project if OK, <0 if KO
  8861. */
  8862. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  8863. {
  8864. global $user, $conf, $langs;
  8865. $out = '';
  8866. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  8867. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  8868. //$sql.= ', el.fk_source';
  8869. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  8870. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  8871. $sql .= " ORDER BY f.titre ASC";
  8872. $resql = $this->db->query($sql);
  8873. if ($resql) {
  8874. // Use select2 selector
  8875. if (!empty($conf->use_javascript_ajax)) {
  8876. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  8877. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8878. $out .= $comboenhancement;
  8879. $morecss = 'minwidth200imp maxwidth500';
  8880. }
  8881. if (empty($option_only)) {
  8882. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  8883. }
  8884. if (!empty($show_empty)) {
  8885. $out .= '<option value="0" class="optiongrey">';
  8886. if (!is_numeric($show_empty)) {
  8887. $out .= $show_empty;
  8888. } else {
  8889. $out .= '&nbsp;';
  8890. }
  8891. $out .= '</option>';
  8892. }
  8893. $num = $this->db->num_rows($resql);
  8894. if ($num) {
  8895. while ($obj = $this->db->fetch_object($resql)) {
  8896. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  8897. $disabled = 0;
  8898. if (!empty($obj->suspended)) {
  8899. $disabled = 1;
  8900. $labeltoshow .= ' - ' . $langs->trans("Closed");
  8901. }
  8902. if (!empty($selected) && $selected == $obj->rowid) {
  8903. $out .= '<option value="' . $obj->rowid . '" selected';
  8904. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8905. $out .= '>' . $labeltoshow . '</option>';
  8906. } else {
  8907. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  8908. $resultat = '';
  8909. } else {
  8910. $resultat = '<option value="' . $obj->rowid . '"';
  8911. if ($disabled) {
  8912. $resultat .= ' disabled';
  8913. }
  8914. $resultat .= '>';
  8915. $resultat .= $labeltoshow;
  8916. $resultat .= '</option>';
  8917. }
  8918. $out .= $resultat;
  8919. }
  8920. }
  8921. }
  8922. if (empty($option_only)) {
  8923. $out .= '</select>';
  8924. }
  8925. print $out;
  8926. $this->db->free($resql);
  8927. return $num;
  8928. } else {
  8929. $this->errors[]=$this->db->lasterror;
  8930. return -1;
  8931. }
  8932. }
  8933. /**
  8934. * Output the component to make advanced search criteries
  8935. *
  8936. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  8937. * @param array $search_component_params Array of selected search criterias
  8938. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  8939. * @param string $search_component_params_hidden String with $search_component_params criterias
  8940. * @return string HTML component for advanced search
  8941. */
  8942. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  8943. {
  8944. global $langs;
  8945. $ret = '';
  8946. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  8947. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8948. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  8949. $ret .= '<span class="fas fa-filter linkobject boxfilter pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("Filters")).'" id="idsubimgproductdistribution"></span>';
  8950. //$ret .= $langs->trans("Filters");
  8951. $ret .= '</a>';
  8952. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  8953. // Show select fields as tags.
  8954. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  8955. if ($search_component_params_hidden) {
  8956. if (!preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  8957. $search_component_params_hidden .= '('.$search_component_params_hidden.')';
  8958. }
  8959. $errormessage = '';
  8960. if (!dolCheckFilters($search_component_params_hidden, $errormessage)) {
  8961. print 'ERROR in parsing search string';
  8962. }
  8963. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  8964. //var_dump($search_component_params_hidden);
  8965. $htmltags = preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $search_component_params_hidden);
  8966. //var_dump($htmltags);
  8967. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch"><span class="tagsearchdelete select2-selection__choice__remove">x</span> '.$htmltags.'</span>';
  8968. }
  8969. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8970. //$ret .= search_component_params
  8971. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  8972. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  8973. $show_search_component_params_hidden = 1;
  8974. if ($show_search_component_params_hidden) {
  8975. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  8976. }
  8977. $ret .= "<!-- We store the full search string into this field. For example: (t.ref:like:'SO-%') and ((t.ref:like:'CO-%') or (t.ref:like:'AA%')) -->";
  8978. $ret .= '<input type="hidden" name="search_component_params_hidden" value="'.dol_escape_htmltag($search_component_params_hidden).'">';
  8979. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  8980. foreach ($arrayofcriterias as $criterias) {
  8981. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  8982. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  8983. continue;
  8984. }
  8985. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  8986. continue;
  8987. }
  8988. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  8989. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  8990. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  8991. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  8992. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  8993. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  8994. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  8995. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  8996. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  8997. } else {
  8998. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  8999. }
  9000. }
  9001. }
  9002. $ret .= '</div>';
  9003. $ret .= "<!-- Syntax of Generic filter string: t.ref:like:'SO-%', t.date_creation:<:'20160101', t.date_creation:<:'2016-01-01 12:30:00', t.nature:is:NULL, t.field2:isnot:NULL -->\n";
  9004. $ret .= '<input type="text" placeholder="'.$langs->trans("Search").'" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9005. $ret .= '</div>';
  9006. $ret .= '</div>';
  9007. return $ret;
  9008. }
  9009. /**
  9010. * selectModelMail
  9011. *
  9012. * @param string $prefix Prefix
  9013. * @param string $modelType Model type
  9014. * @param int $default 1=Show also Default mail template
  9015. * @param int $addjscombo Add js combobox
  9016. * @return string HTML select string
  9017. */
  9018. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9019. {
  9020. global $langs, $user;
  9021. $retstring = '';
  9022. $TModels = array();
  9023. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  9024. $formmail = new FormMail($this->db);
  9025. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9026. if ($default) {
  9027. $TModels[0] = $langs->trans('DefaultMailModel');
  9028. }
  9029. if ($result > 0) {
  9030. foreach ($formmail->lines_model as $model) {
  9031. $TModels[$model->id] = $model->label;
  9032. }
  9033. }
  9034. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  9035. foreach ($TModels as $id_model => $label_model) {
  9036. $retstring .= '<option value="'.$id_model.'"';
  9037. $retstring .= ">".$label_model."</option>";
  9038. }
  9039. $retstring .= "</select>";
  9040. if ($addjscombo) {
  9041. $retstring .= ajax_combobox('select_'.$prefix.'model_mail');
  9042. }
  9043. return $retstring;
  9044. }
  9045. /**
  9046. * Output the buttons to submit a creation/edit form
  9047. *
  9048. * @param string $save_label Alternative label for save button
  9049. * @param string $cancel_label Alternative label for cancel button
  9050. * @param array $morebuttons Add additional buttons between save and cancel
  9051. * @param bool $withoutdiv Option to remove enclosing centered div
  9052. * @param string $morecss More CSS
  9053. * @param string $dol_openinpopup If the button are shown in a context of a page shown inside a popup, we put here the string name of popup.
  9054. * @return string Html code with the buttons
  9055. */
  9056. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9057. {
  9058. global $langs;
  9059. $buttons = array();
  9060. $save = array(
  9061. 'name' => 'save',
  9062. 'label_key' => $save_label,
  9063. );
  9064. if ($save_label == 'Create' || $save_label == 'Add' ) {
  9065. $save['name'] = 'add';
  9066. } elseif ($save_label == 'Modify') {
  9067. $save['name'] = 'edit';
  9068. }
  9069. $cancel = array(
  9070. 'name' => 'cancel',
  9071. 'label_key' => 'Cancel',
  9072. );
  9073. !empty($save_label) ? $buttons[] = $save : '';
  9074. if (!empty($morebuttons)) {
  9075. $buttons[] = $morebuttons;
  9076. }
  9077. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9078. $retstring = $withoutdiv ? '': '<div class="center">';
  9079. foreach ($buttons as $button) {
  9080. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9081. $retstring .= '<input type="submit" class="button button-'.$button['name'].($morecss ? ' '.$morecss : '').' '.$addclass.'" name="'.$button['name'].'" value="'.dol_escape_htmltag($langs->trans($button['label_key'])).'">';
  9082. }
  9083. $retstring .= $withoutdiv ? '': '</div>';
  9084. if ($dol_openinpopup) {
  9085. $retstring .= '<!-- buttons are shown into a $dol_openinpopup='.$dol_openinpopup.' context, so we enable the close of dialog on cancel -->'."\n";
  9086. $retstring .= '<script>';
  9087. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9088. e.preventDefault(); console.log(\'We click on cancel in iframe popup '.$dol_openinpopup.'\');
  9089. window.parent.jQuery(\'#idfordialog'.$dol_openinpopup.'\').dialog(\'close\');
  9090. });';
  9091. $retstring .= '</script>';
  9092. // TODO @LDR for the save button, in action "add", set parent var to return data and close the window
  9093. //$retstring .= '<a onclick="javascript:$(\'#varforreturndialogid'.$dol_openinpopup.'\', window.parent.document).text(\'setid\');">setid</a> ';
  9094. //$retstring .= '<a onclick="javascript:$(\'#varforreturndialoglabel'.$dol_openinpopup.'\', window.parent.document).text(\'setlabel\');">setlabel</a>';
  9095. }
  9096. return $retstring;
  9097. }
  9098. }