html.form.class.php 292 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338
  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-2014 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  15. * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
  16. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  17. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  18. * Copyright (C) 2014 Alexandre Spangaro <aspangaro.dolibarr@gmail.com>
  19. * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
  21. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  22. *
  23. * This program is free software; you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation; either version 3 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  35. */
  36. /**
  37. * \file htdocs/core/class/html.form.class.php
  38. * \ingroup core
  39. * \brief File of class with all html predefined components
  40. */
  41. /**
  42. * Class to manage generation of HTML components
  43. * Only common components must be here.
  44. *
  45. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  46. */
  47. class Form
  48. {
  49. /**
  50. * @var DoliDB Database handler.
  51. */
  52. public $db;
  53. /**
  54. * @var string Error code (or message)
  55. */
  56. public $error='';
  57. /**
  58. * @var string[] Array of error strings
  59. */
  60. public $errors = array();
  61. public $num;
  62. // Cache arrays
  63. public $cache_types_paiements=array();
  64. public $cache_conditions_paiements=array();
  65. public $cache_availability=array();
  66. public $cache_demand_reason=array();
  67. public $cache_types_fees=array();
  68. public $cache_vatrates=array();
  69. /**
  70. * Constructor
  71. *
  72. * @param DoliDB $db Database handler
  73. */
  74. public function __construct($db)
  75. {
  76. $this->db = $db;
  77. }
  78. /**
  79. * Output key field for an editable field
  80. *
  81. * @param string $text Text of label or key to translate
  82. * @param string $htmlname Name of select field ('edit' prefix will be added)
  83. * @param string $preselected Value to show/edit (not used in this function)
  84. * @param object $object Object
  85. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  86. * @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]'...)
  87. * @param string $moreparam More param to add on a href URL.
  88. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  89. * @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 ' '
  90. * @param string $paramid Key of parameter for id ('id', 'socid')
  91. * @return string HTML edit field
  92. */
  93. function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0, $paramid='id')
  94. {
  95. global $conf,$langs;
  96. $ret='';
  97. // TODO change for compatibility
  98. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))
  99. {
  100. if (! empty($perm))
  101. {
  102. $tmp=explode(':',$typeofdata);
  103. $ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  104. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  105. $ret.= $langs->trans($text);
  106. if ($fieldrequired) $ret.='</span>';
  107. $ret.= '</div>'."\n";
  108. }
  109. else
  110. {
  111. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  112. $ret.= $langs->trans($text);
  113. if ($fieldrequired) $ret.='</span>';
  114. }
  115. }
  116. else
  117. {
  118. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
  119. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  120. $ret.=$langs->trans($text);
  121. if ($fieldrequired) $ret.='</span>';
  122. if (! empty($notabletag)) $ret.=' ';
  123. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
  124. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align="right">';
  125. if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  126. if (! empty($notabletag) && $notabletag == 1) $ret.=' : ';
  127. if (! empty($notabletag) && $notabletag == 3) $ret.=' ';
  128. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
  129. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
  130. }
  131. return $ret;
  132. }
  133. /**
  134. * Output value of a field for an editable field
  135. *
  136. * @param string $text Text of label (not used in this function)
  137. * @param string $htmlname Name of select field
  138. * @param string $value Value to show/edit
  139. * @param object $object Object
  140. * @param boolean $perm Permission to allow button to edit parameter
  141. * @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:xxx'...)
  142. * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value
  143. * @param object $extObject External object
  144. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  145. * @param string $moreparam More param to add on the form action href URL
  146. * @param int $notabletag Do no output table tags
  147. * @param string $formatfunc Call a specific function to output field
  148. * @param string $paramid Key of parameter for id ('id', 'socid')
  149. * @return string HTML edit field
  150. */
  151. function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='', $paramid='id')
  152. {
  153. global $conf,$langs,$db;
  154. $ret='';
  155. // Check parameters
  156. if (empty($typeofdata)) return 'ErrorBadParameter';
  157. // When option to edit inline is activated
  158. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
  159. {
  160. $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  161. }
  162. else
  163. {
  164. if (GETPOST('action','aZ09') == 'edit'.$htmlname)
  165. {
  166. $ret.="\n";
  167. $ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam?'?'.$moreparam:'').'">';
  168. $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
  169. $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  170. $ret.='<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  171. if (empty($notabletag)) $ret.='<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
  172. if (empty($notabletag)) $ret.='<tr><td>';
  173. if (preg_match('/^(string|email)/',$typeofdata))
  174. {
  175. $tmp=explode(':',$typeofdata);
  176. $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
  177. }
  178. else if (preg_match('/^(numeric|amount)/',$typeofdata))
  179. {
  180. $tmp=explode(':',$typeofdata);
  181. $valuetoshow=price2num($editvalue?$editvalue:$value);
  182. $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
  183. }
  184. else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
  185. {
  186. $tmp=explode(':',$typeofdata);
  187. $cols=$tmp[2];
  188. $morealt='';
  189. if (preg_match('/%/',$cols))
  190. {
  191. $morealt=' style="width: '.$cols.'"';
  192. $cols='';
  193. }
  194. $valuetoshow = ($editvalue?$editvalue:$value);
  195. $ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'"'.($cols?' cols="'.$cols.'"':'class="quatrevingtpercent"').$morealt.'">';
  196. $ret.=dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  197. $ret.='</textarea>';
  198. }
  199. else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
  200. {
  201. $ret.=$this->selectDate($value,$htmlname,0,0,1,'form'.$htmlname,1,0);
  202. }
  203. else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
  204. {
  205. $ret.=$this->selectDate($value,$htmlname,1,1,1,'form'.$htmlname,1,0);
  206. }
  207. else if (preg_match('/^select;/',$typeofdata))
  208. {
  209. $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
  210. foreach($arraydata as $val)
  211. {
  212. $tmp=explode(':',$val);
  213. $arraylist[$tmp[0]]=$tmp[1];
  214. }
  215. $ret.=$this->selectarray($htmlname,$arraylist,$value);
  216. }
  217. else if (preg_match('/^ckeditor/',$typeofdata))
  218. {
  219. $tmp=explode(':',$typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols
  220. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  221. $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), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));
  222. $ret.=$doleditor->Create(1);
  223. }
  224. if (empty($notabletag)) $ret.='</td>';
  225. if (empty($notabletag)) $ret.='<td align="left">';
  226. //else $ret.='<div class="clearboth"></div>';
  227. $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  228. if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'."\n";
  229. $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  230. if (empty($notabletag)) $ret.='</td>';
  231. if (empty($notabletag)) $ret.='</tr></table>'."\n";
  232. $ret.='</form>'."\n";
  233. }
  234. else
  235. {
  236. if (preg_match('/^(email)/',$typeofdata)) $ret.=dol_print_email($value,0,0,0,0,1);
  237. elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
  238. elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value);
  239. elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
  240. elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
  241. else if (preg_match('/^select;/',$typeofdata))
  242. {
  243. $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
  244. foreach($arraydata as $val)
  245. {
  246. $tmp=explode(':',$val);
  247. $arraylist[$tmp[0]]=$tmp[1];
  248. }
  249. $ret.=$arraylist[$value];
  250. }
  251. else if (preg_match('/^ckeditor/',$typeofdata))
  252. {
  253. $tmpcontent=dol_htmlentitiesbr($value);
  254. if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
  255. {
  256. $firstline=preg_replace('/<br>.*/','',$tmpcontent);
  257. $firstline=preg_replace('/[\n\r].*/','',$firstline);
  258. $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
  259. }
  260. $ret.=$tmpcontent;
  261. }
  262. else $ret.=$value;
  263. if ($formatfunc && method_exists($object, $formatfunc))
  264. {
  265. $ret=$object->$formatfunc($ret);
  266. }
  267. }
  268. }
  269. return $ret;
  270. }
  271. /**
  272. * Output edit in place form
  273. *
  274. * @param object $object Object
  275. * @param string $value Value to show/edit
  276. * @param string $htmlname DIV ID (field name)
  277. * @param int $condition Condition to edit
  278. * @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:xxx')
  279. * @param string $editvalue When in edit mode, use this value as $value instead of value
  280. * @param object $extObject External object
  281. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  282. * @return string HTML edit in place
  283. */
  284. private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
  285. {
  286. global $conf;
  287. $out='';
  288. // Check parameters
  289. if (preg_match('/^text/',$inputType)) $value = dol_nl2br($value);
  290. else if (preg_match('/^numeric/',$inputType)) $value = price($value);
  291. else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
  292. if ($condition)
  293. {
  294. $element = false;
  295. $table_element = false;
  296. $fk_element = false;
  297. $loadmethod = false;
  298. $savemethod = false;
  299. $ext_element = false;
  300. $button_only = false;
  301. $inputOption = '';
  302. if (is_object($object))
  303. {
  304. $element = $object->element;
  305. $table_element = $object->table_element;
  306. $fk_element = $object->id;
  307. }
  308. if (is_object($extObject))
  309. {
  310. $ext_element = $extObject->element;
  311. }
  312. if (preg_match('/^(string|email|numeric)/',$inputType))
  313. {
  314. $tmp=explode(':',$inputType);
  315. $inputType=$tmp[0];
  316. if (! empty($tmp[1])) $inputOption=$tmp[1];
  317. if (! empty($tmp[2])) $savemethod=$tmp[2];
  318. $out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  319. }
  320. else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
  321. {
  322. $tmp=explode(':',$inputType);
  323. $inputType=$tmp[0];
  324. if (! empty($tmp[1])) $inputOption=$tmp[1];
  325. if (! empty($tmp[2])) $savemethod=$tmp[2];
  326. $out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  327. }
  328. else if (preg_match('/^(select|autocomplete)/',$inputType))
  329. {
  330. $tmp=explode(':',$inputType);
  331. $inputType=$tmp[0]; $loadmethod=$tmp[1];
  332. if (! empty($tmp[2])) $savemethod=$tmp[2];
  333. if (! empty($tmp[3])) $button_only=true;
  334. }
  335. else if (preg_match('/^textarea/',$inputType))
  336. {
  337. $tmp=explode(':',$inputType);
  338. $inputType=$tmp[0];
  339. $rows=(empty($tmp[1])?'8':$tmp[1]);
  340. $cols=(empty($tmp[2])?'80':$tmp[2]);
  341. }
  342. else if (preg_match('/^ckeditor/',$inputType))
  343. {
  344. $tmp=explode(':',$inputType);
  345. $inputType=$tmp[0]; $toolbar=$tmp[1];
  346. if (! empty($tmp[2])) $width=$tmp[2];
  347. if (! empty($tmp[3])) $heigth=$tmp[3];
  348. if (! empty($tmp[4])) $savemethod=$tmp[4];
  349. if (! empty($conf->fckeditor->enabled))
  350. {
  351. $out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  352. }
  353. else
  354. {
  355. $inputType = 'textarea';
  356. }
  357. }
  358. $out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  359. $out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  360. $out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  361. $out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  362. if (! empty($savemethod)) $out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  363. if (! empty($ext_element)) $out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  364. if (! empty($custommsg))
  365. {
  366. if (is_array($custommsg))
  367. {
  368. if (!empty($custommsg['success']))
  369. $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  370. if (!empty($custommsg['error']))
  371. $out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  372. }
  373. else
  374. $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  375. }
  376. if ($inputType == 'textarea') {
  377. $out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  378. $out.= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  379. }
  380. $out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  381. $out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  382. }
  383. else
  384. {
  385. $out = $value;
  386. }
  387. return $out;
  388. }
  389. /**
  390. * Show a text and picto with tooltip on text or picto.
  391. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  392. *
  393. * @param string $text Text to show
  394. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  395. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  396. * @param int $direction -1=image is before, 0=no image, 1=image is after
  397. * @param string $img Html code for image (use img_xxx() function to get it)
  398. * @param string $extracss Add a CSS style to td tags
  399. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  400. * @param string $incbefore Include code before the text
  401. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  402. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  403. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  404. * @return string Code html du tooltip (texte+picto)
  405. * @see Use function textwithpicto if you can.
  406. * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
  407. */
  408. function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='', $forcenowrap=0)
  409. {
  410. global $conf;
  411. if ($incbefore) $text = $incbefore.$text;
  412. if (! $htmltext) return $text;
  413. $tag='td';
  414. if ($notabs == 2) $tag='div';
  415. if ($notabs == 3) $tag='span';
  416. // Sanitize tooltip
  417. //$htmltext=str_replace("\\","\\\\",$htmltext);
  418. $htmltext=str_replace("\r","",$htmltext);
  419. $htmltext=str_replace("\n","",$htmltext);
  420. $extrastyle='';
  421. if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }
  422. if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }
  423. $classfortooltip='classfortooltip';
  424. $s='';$textfordialog='';
  425. if ($tooltiptrigger == '')
  426. {
  427. $htmltext=str_replace('"',"&quot;",$htmltext);
  428. }
  429. else
  430. {
  431. $classfortooltip='classfortooltiponclick';
  432. $textfordialog.='<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  433. }
  434. if ($tooltipon == 2 || $tooltipon == 3)
  435. {
  436. $paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"';
  437. if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
  438. else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
  439. }
  440. else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
  441. if ($tooltipon == 1 || $tooltipon == 3)
  442. {
  443. $paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" ';
  444. if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
  445. else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
  446. }
  447. else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
  448. if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
  449. elseif ($notabs == 2) $s.='<div class="inline-block'.($forcenowrap?' nowrap':'').'">';
  450. // Define value if value is before
  451. if ($direction < 0) {
  452. $s.='<'.$tag.$paramfortooltipimg;
  453. if ($tag == 'td') {
  454. $s .= ' valign="top" width="14"';
  455. }
  456. $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
  457. }
  458. // Use another method to help avoid having a space in value in order to use this value with jquery
  459. // Define label
  460. if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  461. // Define value if value is after
  462. if ($direction > 0) {
  463. $s.='<'.$tag.$paramfortooltipimg;
  464. if ($tag == 'td') $s .= ' valign="middle" width="14"';
  465. $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
  466. }
  467. if (empty($notabs)) $s.='</tr></table>';
  468. elseif ($notabs == 2) $s.='</div>';
  469. return $s;
  470. }
  471. /**
  472. * Show a text with a picto and a tooltip on picto
  473. *
  474. * @param string $text Text to show
  475. * @param string $htmltext Content of tooltip
  476. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  477. * @param string $type Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  478. * @param string $extracss Add a CSS style to td, div or span tag
  479. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  480. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  481. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  482. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  483. * @return string HTML code of text, picto, tooltip
  484. */
  485. function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='', $forcenowrap=0)
  486. {
  487. global $conf, $langs;
  488. $alt = '';
  489. if ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv("ClickToShowHelp");
  490. //For backwards compatibility
  491. if ($type == '0') $type = 'info';
  492. elseif ($type == '1') $type = 'help';
  493. // If info or help with no javascript, show only text
  494. if (empty($conf->use_javascript_ajax))
  495. {
  496. if ($type == 'info' || $type == 'help') return $text;
  497. else
  498. {
  499. $alt = $htmltext;
  500. $htmltext = '';
  501. }
  502. }
  503. // If info or help with smartphone, show only text (tooltip hover can't works)
  504. if (! empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
  505. {
  506. if ($type == 'info' || $type == 'help') return $text;
  507. }
  508. // If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)
  509. if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  510. {
  511. if ($type == 'info' || $type == 'help') return $text;
  512. }
  513. $img='';
  514. if ($type == 'info') $img = img_help(0, $alt);
  515. elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  516. elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
  517. elseif ($type == 'admin') $img = img_picto($alt, 'star');
  518. elseif ($type == 'warning') $img = img_warning($alt);
  519. elseif ($type != 'none') $img = img_picto($alt, $type); // $type can be an image path
  520. return $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && ! $img)?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  521. }
  522. /**
  523. * Generate select HTML to choose massaction
  524. *
  525. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  526. * @param int $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  527. * @param int $alwaysvisible 1=select button always visible
  528. * @return string Select list
  529. */
  530. function selectMassAction($selected, $arrayofaction, $alwaysvisible=0)
  531. {
  532. global $conf,$langs,$hookmanager;
  533. if (count($arrayofaction) == 0) return;
  534. $disabled=0;
  535. $ret='<div class="centpercent center">';
  536. $ret.='<select class="flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
  537. // 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.
  538. $parameters=array();
  539. $reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters); // Note that $action and $object may have been modified by hook
  540. if (empty($reshook))
  541. {
  542. $ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
  543. foreach($arrayofaction as $code => $label)
  544. {
  545. $ret.='<option value="'.$code.'"'.($disabled?' disabled="disabled"':'').'>'.$label.'</option>';
  546. }
  547. }
  548. $ret.=$hookmanager->resPrint;
  549. $ret.='</select>';
  550. // 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
  551. $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.
  552. $ret.='<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  553. $ret.='</div>';
  554. if (! empty($conf->use_javascript_ajax))
  555. {
  556. $ret.='<!-- JS CODE TO ENABLE mass action select -->
  557. <script type="text/javascript">
  558. function initCheckForSelect(mode) /* mode is 0 during init of page or click all, 1 when we click on 1 checkbox */
  559. {
  560. atleastoneselected=0;
  561. jQuery(".checkforselect").each(function( index ) {
  562. /* console.log( index + ": " + $( this ).text() ); */
  563. if ($(this).is(\':checked\')) atleastoneselected++;
  564. });
  565. console.log("initCheckForSelect mode="+mode+" atleastoneselected="+atleastoneselected);
  566. if (atleastoneselected || '.$alwaysvisible.')
  567. {
  568. jQuery(".massaction").show();
  569. '.($selected ? 'if (atleastoneselected) { jQuery(".massactionselect").val("'.$selected.'"); jQuery(".massactionconfirmed").prop(\'disabled\', false); }' : '').'
  570. '.($selected ? 'if (! atleastoneselected) { jQuery(".massactionselect").val("0"); jQuery(".massactionconfirmed").prop(\'disabled\', true); } ' : '').'
  571. }
  572. else
  573. {
  574. jQuery(".massaction").hide();
  575. }
  576. }
  577. jQuery(document).ready(function () {
  578. initCheckForSelect(0);
  579. jQuery(".checkforselect").click(function() {
  580. initCheckForSelect(1);
  581. });
  582. jQuery(".massactionselect").change(function() {
  583. var massaction = $( this ).val();
  584. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  585. if (massaction == "builddoc")
  586. {
  587. urlform = urlform + "#show_files";
  588. }
  589. $( this ).closest("form").attr("action", urlform);
  590. console.log("we select a mass action "+massaction+" - "+urlform);
  591. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  592. if ($(this).val() != \'0\')
  593. {
  594. jQuery(".massactionconfirmed").prop(\'disabled\', false);
  595. }
  596. else
  597. {
  598. jQuery(".massactionconfirmed").prop(\'disabled\', true);
  599. }
  600. });
  601. });
  602. </script>
  603. ';
  604. }
  605. return $ret;
  606. }
  607. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  608. /**
  609. * Return combo list of activated countries, into language of user
  610. *
  611. * @param string $selected Id or Code or Label of preselected country
  612. * @param string $htmlname Name of html select object
  613. * @param string $htmloption Options html on select object
  614. * @param integer $maxlength Max length for labels (0=no limit)
  615. * @param string $morecss More css class
  616. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  617. * @param int $showempty Show empty choice
  618. * @param int $disablefavorites 1=Disable favorites,
  619. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  620. * @return string HTML string with select
  621. */
  622. function select_country($selected='', $htmlname='country_id', $htmloption='', $maxlength=0, $morecss='minwidth300', $usecodeaskey='', $showempty=1, $disablefavorites=0, $addspecialentries=0)
  623. {
  624. // phpcs:enable
  625. global $conf,$langs,$mysoc;
  626. $langs->load("dict");
  627. $out='';
  628. $countryArray=array();
  629. $favorite=array();
  630. $label=array();
  631. $atleastonefavorite=0;
  632. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
  633. $sql.= " FROM ".MAIN_DB_PREFIX."c_country";
  634. $sql.= " WHERE active > 0";
  635. //$sql.= " ORDER BY code ASC";
  636. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  637. $resql=$this->db->query($sql);
  638. if ($resql)
  639. {
  640. $out.= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" '.$htmloption.'>';
  641. $num = $this->db->num_rows($resql);
  642. $i = 0;
  643. if ($num)
  644. {
  645. $foundselected=false;
  646. while ($i < $num)
  647. {
  648. $obj = $this->db->fetch_object($resql);
  649. $countryArray[$i]['rowid'] = $obj->rowid;
  650. $countryArray[$i]['code_iso'] = $obj->code_iso;
  651. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  652. $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:''));
  653. $countryArray[$i]['favorite'] = $obj->favorite;
  654. $favorite[$i] = $obj->favorite;
  655. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  656. $i++;
  657. }
  658. if (empty($disablefavorites)) array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  659. else $countryArray = dol_sort_array($countryArray, 'label');
  660. if ($showempty)
  661. {
  662. $out.='<option value="">&nbsp;</option>'."\n";
  663. }
  664. if ($addspecialentries) // Add dedicated entries for groups of countries
  665. {
  666. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  667. $out.= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  668. $out.= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  669. if ($mysoc->isInEEC()) $out.= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  670. $out.= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  671. $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  672. }
  673. foreach ($countryArray as $row)
  674. {
  675. //if (empty($showempty) && empty($row['rowid'])) continue;
  676. if (empty($row['rowid'])) continue;
  677. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
  678. if (empty($row['favorite']) && $atleastonefavorite)
  679. {
  680. $atleastonefavorite=0;
  681. $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  682. }
  683. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )
  684. {
  685. $foundselected=true;
  686. $out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'" selected>';
  687. }
  688. else
  689. {
  690. $out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'">';
  691. }
  692. if ($row['label']) $out.= dol_trunc($row['label'],$maxlength,'middle');
  693. else $out.= '&nbsp;';
  694. if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
  695. $out.= '</option>';
  696. }
  697. }
  698. $out.= '</select>';
  699. }
  700. else
  701. {
  702. dol_print_error($this->db);
  703. }
  704. // Make select dynamic
  705. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  706. $out .= ajax_combobox('select'.$htmlname);
  707. return $out;
  708. }
  709. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  710. /**
  711. * Return select list of incoterms
  712. *
  713. * @param string $selected Id or Code of preselected incoterm
  714. * @param string $location_incoterms Value of input location
  715. * @param string $page Defined the form action
  716. * @param string $htmlname Name of html select object
  717. * @param string $htmloption Options html on select object
  718. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  719. * @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')))
  720. * @return string HTML string with select and input
  721. */
  722. function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())
  723. {
  724. // phpcs:enable
  725. global $conf,$langs;
  726. $langs->load("dict");
  727. $out='';
  728. $incotermArray=array();
  729. $sql = "SELECT rowid, code";
  730. $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms";
  731. $sql.= " WHERE active > 0";
  732. $sql.= " ORDER BY code ASC";
  733. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  734. $resql=$this->db->query($sql);
  735. if ($resql)
  736. {
  737. if ($conf->use_javascript_ajax && ! $forcecombo)
  738. {
  739. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  740. $out .= ajax_combobox($htmlname, $events);
  741. }
  742. if (!empty($page))
  743. {
  744. $out .= '<form method="post" action="'.$page.'">';
  745. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  746. $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  747. }
  748. $out.= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
  749. $out.= '<option value="0">&nbsp;</option>';
  750. $num = $this->db->num_rows($resql);
  751. $i = 0;
  752. if ($num)
  753. {
  754. $foundselected=false;
  755. while ($i < $num)
  756. {
  757. $obj = $this->db->fetch_object($resql);
  758. $incotermArray[$i]['rowid'] = $obj->rowid;
  759. $incotermArray[$i]['code'] = $obj->code;
  760. $i++;
  761. }
  762. foreach ($incotermArray as $row)
  763. {
  764. if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
  765. {
  766. $out.= '<option value="'.$row['rowid'].'" selected>';
  767. }
  768. else
  769. {
  770. $out.= '<option value="'.$row['rowid'].'">';
  771. }
  772. if ($row['code']) $out.= $row['code'];
  773. $out.= '</option>';
  774. }
  775. }
  776. $out.= '</select>';
  777. $out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
  778. if (!empty($page))
  779. {
  780. $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
  781. }
  782. }
  783. else
  784. {
  785. dol_print_error($this->db);
  786. }
  787. return $out;
  788. }
  789. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  790. /**
  791. * Return list of types of lines (product or service)
  792. * Example: 0=product, 1=service, 9=other (for external module)
  793. *
  794. * @param string $selected Preselected type
  795. * @param string $htmlname Name of field in html form
  796. * @param int $showempty Add an empty field
  797. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  798. * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, -1=Force none (and set hidden field to 'service')
  799. * @return void
  800. */
  801. function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
  802. {
  803. // phpcs:enable
  804. global $db,$langs,$user,$conf;
  805. // If product & services are enabled or both disabled.
  806. if ($forceall > 0 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
  807. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
  808. {
  809. if (empty($hidetext)) print $langs->trans("Type").': ';
  810. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  811. if ($showempty)
  812. {
  813. print '<option value="-1"';
  814. if ($selected == -1) print ' selected';
  815. print '>&nbsp;</option>';
  816. }
  817. print '<option value="0"';
  818. if (0 == $selected) print ' selected';
  819. print '>'.$langs->trans("Product");
  820. print '<option value="1"';
  821. if (1 == $selected) print ' selected';
  822. print '>'.$langs->trans("Service");
  823. print '</select>';
  824. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  825. }
  826. if (empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled))
  827. {
  828. print $langs->trans("Service");
  829. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  830. }
  831. if (empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled))
  832. {
  833. print $langs->trans("Product");
  834. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  835. }
  836. if ($forceall < 0) // This should happened only for contracts when both predefined product and service are disabled.
  837. {
  838. 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
  839. }
  840. }
  841. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  842. /**
  843. * Load into cache cache_types_fees, array of types of fees
  844. *
  845. * @return int Nb of lines loaded, <0 if KO
  846. */
  847. function load_cache_types_fees()
  848. {
  849. // phpcs:enable
  850. global $langs;
  851. $num = count($this->cache_types_fees);
  852. if ($num > 0) return 0; // Cache already loaded
  853. dol_syslog(__METHOD__, LOG_DEBUG);
  854. $langs->load("trips");
  855. $sql = "SELECT c.code, c.label";
  856. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  857. $sql.= " WHERE active > 0";
  858. $resql=$this->db->query($sql);
  859. if ($resql)
  860. {
  861. $num = $this->db->num_rows($resql);
  862. $i = 0;
  863. while ($i < $num)
  864. {
  865. $obj = $this->db->fetch_object($resql);
  866. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  867. $label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  868. $this->cache_types_fees[$obj->code] = $label;
  869. $i++;
  870. }
  871. asort($this->cache_types_fees);
  872. return $num;
  873. }
  874. else
  875. {
  876. dol_print_error($this->db);
  877. return -1;
  878. }
  879. }
  880. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  881. /**
  882. * Return list of types of notes
  883. *
  884. * @param string $selected Preselected type
  885. * @param string $htmlname Name of field in form
  886. * @param int $showempty Add an empty field
  887. * @return void
  888. */
  889. function select_type_fees($selected='',$htmlname='type',$showempty=0)
  890. {
  891. // phpcs:enable
  892. global $user, $langs;
  893. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  894. $this->load_cache_types_fees();
  895. print '<select class="flat" name="'.$htmlname.'">';
  896. if ($showempty)
  897. {
  898. print '<option value="-1"';
  899. if ($selected == -1) print ' selected';
  900. print '>&nbsp;</option>';
  901. }
  902. foreach($this->cache_types_fees as $key => $value)
  903. {
  904. print '<option value="'.$key.'"';
  905. if ($key == $selected) print ' selected';
  906. print '>';
  907. print $value;
  908. print '</option>';
  909. }
  910. print '</select>';
  911. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  912. }
  913. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  914. /**
  915. * Return HTML code to select a company.
  916. *
  917. * @param int $selected Preselected products
  918. * @param string $htmlname Name of HTML select field (must be unique in page)
  919. * @param int $filter Filter on thirdparty
  920. * @param int $limit Limit on number of returned lines
  921. * @param array $ajaxoptions Options for ajax_autocompleter
  922. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  923. * @return string Return select box for thirdparty.
  924. * @deprecated 3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)
  925. */
  926. function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)
  927. {
  928. // phpcs:enable
  929. return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit);
  930. }
  931. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  932. /**
  933. * Output html form to select a third party
  934. *
  935. * @param string $selected Preselected type
  936. * @param string $htmlname Name of field in form
  937. * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')
  938. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  939. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  940. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  941. * @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')))
  942. * @param int $limit Maximum number of elements
  943. * @param string $morecss Add more css styles to the SELECT component
  944. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  945. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  946. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  947. * @param array $ajaxoptions Options for ajax_autocompleter
  948. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  949. * @return string HTML string with select box for thirdparty.
  950. */
  951. 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)
  952. {
  953. // phpcs:enable
  954. global $conf,$user,$langs;
  955. $out='';
  956. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)
  957. {
  958. // No immediate load of all database
  959. $placeholder='';
  960. if ($selected && empty($selected_input_value))
  961. {
  962. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  963. $societetmp = new Societe($this->db);
  964. $societetmp->fetch($selected);
  965. $selected_input_value=$societetmp->name;
  966. unset($societetmp);
  967. }
  968. // mode 1
  969. $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');
  970. $out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  971. $out.='<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
  972. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  973. else if ($hidelabel > 1) {
  974. $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
  975. if ($hidelabel == 2) {
  976. $out.= img_picto($langs->trans("Search"), 'search');
  977. }
  978. }
  979. $out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  980. if ($hidelabel == 3) {
  981. $out.= img_picto($langs->trans("Search"), 'search');
  982. }
  983. }
  984. else
  985. {
  986. // Immediate load of all database
  987. $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
  988. }
  989. return $out;
  990. }
  991. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  992. /**
  993. * Output html form to select a third party.
  994. * 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.
  995. *
  996. * @param string $selected Preselected type
  997. * @param string $htmlname Name of field in form
  998. * @param string $filter Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
  999. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1000. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1001. * @param int $forcecombo Force to use standard HTML select component without beautification
  1002. * @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')))
  1003. * @param string $filterkey Filter on key value
  1004. * @param int $outputmode 0=HTML select string, 1=Array
  1005. * @param int $limit Limit number of answers
  1006. * @param string $morecss Add more css styles to the SELECT component
  1007. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1008. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1009. * @return string HTML string with
  1010. */
  1011. 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)
  1012. {
  1013. // phpcs:enable
  1014. global $conf,$user,$langs;
  1015. $out='';
  1016. $num=0;
  1017. $outarray=array();
  1018. if ($selected === '') $selected = array();
  1019. else if (!is_array($selected)) $selected = array($selected);
  1020. // Clean $filter that may contains sql conditions so sql code
  1021. if (function_exists('testSqlAndScriptInject')) {
  1022. if (testSqlAndScriptInject($filter, 3)>0) {
  1023. $filter ='';
  1024. }
  1025. }
  1026. // On recherche les societes
  1027. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1028. if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
  1029. $sql .= ", s.address, s.zip, s.town";
  1030. $sql .= ", dictp.code as country_code";
  1031. }
  1032. $sql.= " FROM (".MAIN_DB_PREFIX ."societe as s";
  1033. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1034. $sql.= " )";
  1035. if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
  1036. $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
  1037. }
  1038. $sql.= " WHERE s.entity IN (".getEntity('societe').")";
  1039. if (! empty($user->socid)) $sql.= " AND s.rowid = ".$user->socid;
  1040. if ($filter) $sql.= " AND (".$filter.")";
  1041. if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
  1042. if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
  1043. // Add criteria
  1044. if ($filterkey && $filterkey != '')
  1045. {
  1046. $sql.=" AND (";
  1047. $prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1048. // For natural search
  1049. $scrit = explode(' ', $filterkey);
  1050. $i=0;
  1051. if (count($scrit) > 1) $sql.="(";
  1052. foreach ($scrit as $crit) {
  1053. if ($i > 0) $sql.=" AND ";
  1054. $sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1055. $i++;
  1056. }
  1057. if (count($scrit) > 1) $sql.=")";
  1058. if (! empty($conf->barcode->enabled))
  1059. {
  1060. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1061. }
  1062. $sql.= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1063. $sql.=")";
  1064. }
  1065. $sql.=$this->db->order("nom","ASC");
  1066. $sql.=$this->db->plimit($limit, 0);
  1067. // Build output string
  1068. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1069. $resql=$this->db->query($sql);
  1070. if ($resql)
  1071. {
  1072. if (! $forcecombo)
  1073. {
  1074. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1075. $out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
  1076. }
  1077. // Construct $out and $outarray
  1078. $out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparam?' '.$moreparam:'').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1079. $textifempty='';
  1080. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1081. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1082. if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
  1083. {
  1084. if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
  1085. else $textifempty.=$langs->trans("All");
  1086. }
  1087. if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
  1088. $num = $this->db->num_rows($resql);
  1089. $i = 0;
  1090. if ($num)
  1091. {
  1092. while ($i < $num)
  1093. {
  1094. $obj = $this->db->fetch_object($resql);
  1095. $label='';
  1096. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1097. if (($obj->client) && (!empty($obj->code_client))) {
  1098. $label = $obj->code_client. ' - ';
  1099. }
  1100. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1101. $label .= $obj->code_fournisseur. ' - ';
  1102. }
  1103. $label.=' '.$obj->name;
  1104. }
  1105. else
  1106. {
  1107. $label=$obj->name;
  1108. }
  1109. if(!empty($obj->name_alias)) {
  1110. $label.=' ('.$obj->name_alias.')';
  1111. }
  1112. if ($showtype)
  1113. {
  1114. if ($obj->client || $obj->fournisseur) $label.=' (';
  1115. if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
  1116. if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
  1117. if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
  1118. if ($obj->client || $obj->fournisseur) $label.=')';
  1119. }
  1120. if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
  1121. $label.='-'.$obj->address.'-'. $obj->zip.' '. $obj->town;
  1122. if (!empty($obj->country_code)) {
  1123. $label.= ' '. $langs->trans('Country'.$obj->country_code);
  1124. }
  1125. }
  1126. if (empty($outputmode))
  1127. {
  1128. if (in_array($obj->rowid,$selected))
  1129. {
  1130. $out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1131. }
  1132. else
  1133. {
  1134. $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1135. }
  1136. }
  1137. else
  1138. {
  1139. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1140. }
  1141. $i++;
  1142. if (($i % 10) == 0) $out.="\n";
  1143. }
  1144. }
  1145. $out.= '</select>'."\n";
  1146. }
  1147. else
  1148. {
  1149. dol_print_error($this->db);
  1150. }
  1151. $this->result=array('nbofthirdparties'=>$num);
  1152. if ($outputmode) return $outarray;
  1153. return $out;
  1154. }
  1155. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1156. /**
  1157. * Return HTML combo list of absolute discounts
  1158. *
  1159. * @param string $selected Id remise fixe pre-selectionnee
  1160. * @param string $htmlname Nom champ formulaire
  1161. * @param string $filter Criteres optionnels de filtre
  1162. * @param int $socid Id of thirdparty
  1163. * @param int $maxvalue Max value for lines that can be selected
  1164. * @return int Return number of qualifed lines in list
  1165. */
  1166. function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
  1167. {
  1168. // phpcs:enable
  1169. global $langs,$conf;
  1170. // On recherche les remises
  1171. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1172. $sql.= " re.description, re.fk_facture_source";
  1173. $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
  1174. $sql.= " WHERE re.fk_soc = ".(int) $socid;
  1175. $sql.= " AND re.entity = " . $conf->entity;
  1176. if ($filter) $sql.= " AND ".$filter;
  1177. $sql.= " ORDER BY re.description ASC";
  1178. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1179. $resql=$this->db->query($sql);
  1180. if ($resql)
  1181. {
  1182. print '<select class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1183. $num = $this->db->num_rows($resql);
  1184. $qualifiedlines=$num;
  1185. $i = 0;
  1186. if ($num)
  1187. {
  1188. print '<option value="0">&nbsp;</option>';
  1189. while ($i < $num)
  1190. {
  1191. $obj = $this->db->fetch_object($resql);
  1192. $desc=dol_trunc($obj->description,40);
  1193. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1194. if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1195. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1196. if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1197. $selectstring='';
  1198. if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
  1199. $disabled='';
  1200. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
  1201. {
  1202. $qualifiedlines--;
  1203. $disabled=' disabled';
  1204. }
  1205. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
  1206. {
  1207. $tmpfac = new Facture($this->db);
  1208. if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref;
  1209. }
  1210. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1211. $i++;
  1212. }
  1213. }
  1214. print '</select>';
  1215. return $qualifiedlines;
  1216. }
  1217. else
  1218. {
  1219. dol_print_error($this->db);
  1220. return -1;
  1221. }
  1222. }
  1223. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1224. /**
  1225. * Return list of all contacts (for a third party or all)
  1226. *
  1227. * @param int $socid Id ot third party or 0 for all
  1228. * @param string $selected Id contact pre-selectionne
  1229. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1230. * @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
  1231. * @param string $exclude List of contacts id to exclude
  1232. * @param string $limitto Disable answers that are not id in this array list
  1233. * @param integer $showfunction Add function into label
  1234. * @param string $moreclass Add more class to class style
  1235. * @param integer $showsoc Add company into label
  1236. * @param int $forcecombo Force to use combo box
  1237. * @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')))
  1238. * @param bool $options_only Return options only (for ajax treatment)
  1239. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1240. * @param string $htmlid Html id to use instead of htmlname
  1241. * @return int <0 if KO, Nb of contact in list if OK
  1242. * @deprected You can use selectcontacts directly (warning order of param was changed)
  1243. */
  1244. function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false, $moreparam='', $htmlid='')
  1245. {
  1246. // phpcs:enable
  1247. print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1248. return $this->num;
  1249. }
  1250. /**
  1251. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1252. * This also set the number of contacts found into $this->num
  1253. *
  1254. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1255. * @param array|int $selected Array of ID of pre-selected contact id
  1256. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1257. * @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
  1258. * @param string $exclude List of contacts id to exclude
  1259. * @param string $limitto Disable answers that are not id in this array list
  1260. * @param integer $showfunction Add function into label
  1261. * @param string $moreclass Add more class to class style
  1262. * @param bool $options_only Return options only (for ajax treatment)
  1263. * @param integer $showsoc Add company into label
  1264. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1265. * @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')))
  1266. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1267. * @param string $htmlid Html id to use instead of htmlname
  1268. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1269. * @return int <0 if KO, Nb of contact in list if OK
  1270. */
  1271. function selectcontacts($socid, $selected='', $htmlname='contactid', $showempty=0, $exclude='', $limitto='', $showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array(), $moreparam='', $htmlid='', $multiple=false)
  1272. {
  1273. global $conf,$langs;
  1274. $langs->load('companies');
  1275. if (empty($htmlid)) $htmlid = $htmlname;
  1276. if ($selected === '') $selected = array();
  1277. else if (!is_array($selected)) $selected = array($selected);
  1278. $out='';
  1279. // On recherche les societes
  1280. $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
  1281. if ($showsoc > 0) $sql.= " , s.nom as company";
  1282. $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
  1283. if ($showsoc > 0) $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
  1284. $sql.= " WHERE sp.entity IN (".getEntity('socpeople').")";
  1285. if ($socid > 0 || $socid == -1) $sql.= " AND sp.fk_soc=".$socid;
  1286. if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
  1287. $sql.= " ORDER BY sp.lastname ASC";
  1288. dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
  1289. $resql=$this->db->query($sql);
  1290. if ($resql)
  1291. {
  1292. $num=$this->db->num_rows($resql);
  1293. if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)
  1294. {
  1295. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1296. $out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
  1297. }
  1298. if ($htmlname != 'none' && ! $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1299. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>&nbsp;</option>';
  1300. if ($showempty == 2) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>'.$langs->trans("Internal").'</option>';
  1301. $num = $this->db->num_rows($resql);
  1302. $i = 0;
  1303. if ($num)
  1304. {
  1305. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1306. $contactstatic=new Contact($this->db);
  1307. while ($i < $num)
  1308. {
  1309. $obj = $this->db->fetch_object($resql);
  1310. $contactstatic->id=$obj->rowid;
  1311. $contactstatic->lastname=$obj->lastname;
  1312. $contactstatic->firstname=$obj->firstname;
  1313. if ($obj->statut == 1){
  1314. if ($htmlname != 'none')
  1315. {
  1316. $disabled=0;
  1317. if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
  1318. if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
  1319. if (!empty($selected) && in_array($obj->rowid, $selected))
  1320. {
  1321. $out.= '<option value="'.$obj->rowid.'"';
  1322. if ($disabled) $out.= ' disabled';
  1323. $out.= ' selected>';
  1324. $out.= $contactstatic->getFullName($langs);
  1325. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1326. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1327. $out.= '</option>';
  1328. }
  1329. else
  1330. {
  1331. $out.= '<option value="'.$obj->rowid.'"';
  1332. if ($disabled) $out.= ' disabled';
  1333. $out.= '>';
  1334. $out.= $contactstatic->getFullName($langs);
  1335. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1336. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1337. $out.= '</option>';
  1338. }
  1339. }
  1340. else
  1341. {
  1342. if (in_array($obj->rowid, $selected))
  1343. {
  1344. $out.= $contactstatic->getFullName($langs);
  1345. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1346. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1347. }
  1348. }
  1349. }
  1350. $i++;
  1351. }
  1352. }
  1353. else
  1354. {
  1355. $out.= '<option value="-1"'.(($showempty==2 || $multiple) ? '' : ' selected').' disabled>';
  1356. $out.= ($socid != -1) ? ($langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1357. $out.= '</option>';
  1358. }
  1359. if ($htmlname != 'none' && ! $options_only)
  1360. {
  1361. $out.= '</select>';
  1362. }
  1363. $this->num = $num;
  1364. return $out;
  1365. }
  1366. else
  1367. {
  1368. dol_print_error($this->db);
  1369. return -1;
  1370. }
  1371. }
  1372. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1373. /**
  1374. * Return select list of users
  1375. *
  1376. * @param string $selected Id user preselected
  1377. * @param string $htmlname Field name in form
  1378. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1379. * @param array $exclude Array list of users id to exclude
  1380. * @param int $disabled If select list must be disabled
  1381. * @param array $include Array list of users id to include
  1382. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1383. * @param string $force_entity '0' or Ids of environment to force
  1384. * @return void
  1385. * @deprecated Use select_dolusers instead
  1386. * @see select_dolusers()
  1387. */
  1388. function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity='0')
  1389. {
  1390. // phpcs:enable
  1391. print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
  1392. }
  1393. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1394. /**
  1395. * Return select list of users
  1396. *
  1397. * @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)
  1398. * @param string $htmlname Field name in form
  1399. * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list
  1400. * @param array $exclude Array list of users id to exclude
  1401. * @param int $disabled If select list must be disabled
  1402. * @param array|string $include Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1403. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1404. * @param string $force_entity '0' or Ids of environment to force
  1405. * @param int $maxlength Maximum length of string into list (0=no limit)
  1406. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1407. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1')
  1408. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1409. * @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.
  1410. * @param string $morecss More css
  1411. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1412. * @param int $outputmode 0=HTML select string, 1=Array
  1413. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1414. * @return string HTML select string
  1415. * @see select_dolgroups
  1416. */
  1417. 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)
  1418. {
  1419. // phpcs:enable
  1420. global $conf,$user,$langs;
  1421. // If no preselected user defined, we take current user
  1422. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
  1423. if ($selected === '') $selected = array();
  1424. else if (!is_array($selected)) $selected = array($selected);
  1425. $excludeUsers=null;
  1426. $includeUsers=null;
  1427. // Permettre l'exclusion d'utilisateurs
  1428. if (is_array($exclude)) $excludeUsers = implode(",",$exclude);
  1429. // Permettre l'inclusion d'utilisateurs
  1430. if (is_array($include)) $includeUsers = implode(",",$include);
  1431. else if ($include == 'hierarchy')
  1432. {
  1433. // Build list includeUsers to have only hierarchy
  1434. $includeUsers = implode(",",$user->getAllChildIds(0));
  1435. }
  1436. else if ($include == 'hierarchyme')
  1437. {
  1438. // Build list includeUsers to have only hierarchy and current user
  1439. $includeUsers = implode(",",$user->getAllChildIds(1));
  1440. }
  1441. $out='';
  1442. $outarray = array();
  1443. // Forge request to select users
  1444. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
  1445. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1446. {
  1447. $sql.= ", e.label";
  1448. }
  1449. $sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
  1450. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1451. {
  1452. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
  1453. if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
  1454. else $sql.= " WHERE u.entity IS NOT NULL";
  1455. }
  1456. else
  1457. {
  1458. if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
  1459. {
  1460. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
  1461. $sql.= " ON ug.fk_user = u.rowid";
  1462. $sql.= " WHERE ug.entity = ".$conf->entity;
  1463. }
  1464. else
  1465. {
  1466. $sql.= " WHERE u.entity IN (0,".$conf->entity.")";
  1467. }
  1468. }
  1469. if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
  1470. if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
  1471. if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")";
  1472. if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
  1473. if (! empty($morefilter)) $sql.=" ".$morefilter;
  1474. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1475. {
  1476. $sql.= " ORDER BY u.firstname ASC";
  1477. }
  1478. else
  1479. {
  1480. $sql.= " ORDER BY u.lastname ASC";
  1481. }
  1482. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1483. $resql=$this->db->query($sql);
  1484. if ($resql)
  1485. {
  1486. $num = $this->db->num_rows($resql);
  1487. $i = 0;
  1488. if ($num)
  1489. {
  1490. // Enhance with select2
  1491. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1492. $out .= ajax_combobox($htmlname);
  1493. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1494. $out.= '<select class="flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
  1495. if ($show_empty && !$multiple) $out.= '<option value="-1"'.((empty($selected) || in_array(-1,$selected))?' selected':'').'>&nbsp;</option>'."\n";
  1496. if ($show_every) $out.= '<option value="-2"'.((in_array(-2,$selected))?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1497. $userstatic=new User($this->db);
  1498. while ($i < $num)
  1499. {
  1500. $obj = $this->db->fetch_object($resql);
  1501. $userstatic->id=$obj->rowid;
  1502. $userstatic->lastname=$obj->lastname;
  1503. $userstatic->firstname=$obj->firstname;
  1504. $disableline='';
  1505. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
  1506. if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && in_array($obj->rowid,$selected) ))
  1507. {
  1508. $out.= '<option value="'.$obj->rowid.'"';
  1509. if ($disableline) $out.= ' disabled';
  1510. $out.= ' selected>';
  1511. }
  1512. else
  1513. {
  1514. $out.= '<option value="'.$obj->rowid.'"';
  1515. if ($disableline) $out.= ' disabled';
  1516. $out.= '>';
  1517. }
  1518. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1519. $fullNameMode = 0;
  1520. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))
  1521. {
  1522. $fullNameMode = 1; //Firstname+lastname
  1523. }
  1524. $out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1525. // Complete name with more info
  1526. $moreinfo=0;
  1527. if (! empty($conf->global->MAIN_SHOW_LOGIN))
  1528. {
  1529. $out.= ($moreinfo?' - ':' (').$obj->login;
  1530. $moreinfo++;
  1531. }
  1532. if ($showstatus >= 0)
  1533. {
  1534. if ($obj->statut == 1 && $showstatus == 1)
  1535. {
  1536. $out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
  1537. $moreinfo++;
  1538. }
  1539. if ($obj->statut == 0)
  1540. {
  1541. $out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
  1542. $moreinfo++;
  1543. }
  1544. }
  1545. if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1546. {
  1547. if (! $obj->entity)
  1548. {
  1549. $out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
  1550. $moreinfo++;
  1551. }
  1552. else
  1553. {
  1554. $out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
  1555. $moreinfo++;
  1556. }
  1557. }
  1558. $out.=($moreinfo?')':'');
  1559. if ($disableline && $disableline != '1')
  1560. {
  1561. $out.=' - '.$disableline; // This is text from $enableonlytext parameter
  1562. }
  1563. $out.= '</option>';
  1564. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1565. $i++;
  1566. }
  1567. }
  1568. else
  1569. {
  1570. $out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1571. $out.= '<option value="">'.$langs->trans("None").'</option>';
  1572. }
  1573. $out.= '</select>';
  1574. }
  1575. else
  1576. {
  1577. dol_print_error($this->db);
  1578. }
  1579. if ($outputmode) return $outarray;
  1580. return $out;
  1581. }
  1582. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1583. /**
  1584. * Return select list of users. Selected users are stored into session.
  1585. * List of users are provided into $_SESSION['assignedtouser'].
  1586. *
  1587. * @param string $action Value for $action
  1588. * @param string $htmlname Field name in form
  1589. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1590. * @param array $exclude Array list of users id to exclude
  1591. * @param int $disabled If select list must be disabled
  1592. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1593. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1594. * @param int $force_entity '0' or Ids of environment to force
  1595. * @param int $maxlength Maximum length of string into list (0=no limit)
  1596. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1597. * @param string $morefilter Add more filters into sql request
  1598. * @param int $showproperties Show properties of each attendees
  1599. * @param array $listofuserid Array with properties of each user
  1600. * @param array $listofcontactid Array with properties of each contact
  1601. * @param array $listofotherid Array with properties of each other contact
  1602. * @return string HTML select string
  1603. * @see select_dolgroups
  1604. */
  1605. 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())
  1606. {
  1607. // phpcs:enable
  1608. global $conf, $user, $langs;
  1609. $userstatic=new User($this->db);
  1610. $out='';
  1611. // Method with no ajax
  1612. //$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
  1613. if ($action == 'view')
  1614. {
  1615. $out.='';
  1616. }
  1617. else
  1618. {
  1619. $out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1620. $out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () { jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });})</script>';
  1621. $out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1622. $out.=' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1623. $out.='<br>';
  1624. }
  1625. $assignedtouser=array();
  1626. if (!empty($_SESSION['assignedtouser']))
  1627. {
  1628. $assignedtouser=json_decode($_SESSION['assignedtouser'], true);
  1629. }
  1630. $nbassignetouser=count($assignedtouser);
  1631. if ($nbassignetouser && $action != 'view') $out.='<br>';
  1632. if ($nbassignetouser) $out.='<ul class="attendees">';
  1633. $i=0; $ownerid=0;
  1634. foreach($assignedtouser as $key => $value)
  1635. {
  1636. if ($value['id'] == $ownerid) continue;
  1637. $out.='<li>';
  1638. $userstatic->fetch($value['id']);
  1639. $out.= $userstatic->getNomUrl(-1);
  1640. if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; }
  1641. if ($nbassignetouser > 1 && $action != 'view')
  1642. {
  1643. $out.=' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
  1644. }
  1645. // Show my availability
  1646. if ($showproperties)
  1647. {
  1648. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))
  1649. {
  1650. $out.='<div class="myavailability inline-block">';
  1651. $out.='&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span> <input id="transparency" class="marginleftonly marginrightonly" '.($action == 'view'?'disabled':'').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency']?' checked':'').'>'.$langs->trans("Busy");
  1652. $out.='</div>';
  1653. }
  1654. }
  1655. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1656. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1657. $out.='</li>';
  1658. $i++;
  1659. }
  1660. if ($nbassignetouser) $out.='</ul>';
  1661. //$out.='</form>';
  1662. return $out;
  1663. }
  1664. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1665. /**
  1666. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1667. *
  1668. * @param int $selected Preselected products
  1669. * @param string $htmlname Name of HTML select field (must be unique in page)
  1670. * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1671. * @param int $limit Limit on number of returned lines
  1672. * @param int $price_level Level of price to show
  1673. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1674. * @param int $finished 2=all, 1=finished, 0=raw material
  1675. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1676. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1677. * @param array $ajaxoptions Options for ajax_autocompleter
  1678. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1679. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1680. * @param int $forcecombo Force to use combo box
  1681. * @param string $morecss Add more css on select
  1682. * @param int $hidepriceinlabel 1=Hide prices in label
  1683. * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used
  1684. * 'warehouseopen' = select products from open warehouses,
  1685. * 'warehouseclosed' = select products from closed warehouses,
  1686. * 'warehouseinternal' = select products from warehouses for internal correct/transfer only
  1687. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  1688. * @return void
  1689. */
  1690. function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array())
  1691. {
  1692. // phpcs:enable
  1693. global $langs,$conf;
  1694. $price_level = (! empty($price_level) ? $price_level : 0);
  1695. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1696. {
  1697. $placeholder='';
  1698. if ($selected && empty($selected_input_value))
  1699. {
  1700. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1701. $producttmpselect = new Product($this->db);
  1702. $producttmpselect->fetch($selected);
  1703. $selected_input_value=$producttmpselect->ref;
  1704. unset($producttmpselect);
  1705. }
  1706. // mode=1 means customers products
  1707. $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  1708. //Price by customer
  1709. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1710. $urloption.='&socid='.$socid;
  1711. }
  1712. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1713. if (!empty($conf->variants->enabled)) {
  1714. ?>
  1715. <script>
  1716. selected = <?php echo json_encode($selected_combinations) ?>;
  1717. combvalues = {};
  1718. jQuery(document).ready(function () {
  1719. jQuery("input[name='prod_entry_mode']").change(function () {
  1720. if (jQuery(this).val() == 'free') {
  1721. jQuery('div#attributes_box').empty();
  1722. }
  1723. });
  1724. jQuery("input#<?php echo $htmlname ?>").change(function () {
  1725. if (!jQuery(this).val()) {
  1726. jQuery('div#attributes_box').empty();
  1727. return;
  1728. }
  1729. jQuery.getJSON("<?php echo dol_buildpath('/variants/ajax/getCombinations.php', 2) ?>", {
  1730. id: jQuery(this).val()
  1731. }, function (data) {
  1732. jQuery('div#attributes_box').empty();
  1733. jQuery.each(data, function (key, val) {
  1734. combvalues[val.id] = val.values;
  1735. var span = jQuery(document.createElement('div')).css({
  1736. 'display': 'table-row'
  1737. });
  1738. span.append(
  1739. jQuery(document.createElement('div')).text(val.label).css({
  1740. 'font-weight': 'bold',
  1741. 'display': 'table-cell',
  1742. 'text-align': 'right'
  1743. })
  1744. );
  1745. var html = jQuery(document.createElement('select')).attr('name', 'combinations[' + val.id + ']').css({
  1746. 'margin-left': '15px',
  1747. 'white-space': 'pre'
  1748. }).append(
  1749. jQuery(document.createElement('option')).val('')
  1750. );
  1751. jQuery.each(combvalues[val.id], function (key, val) {
  1752. var tag = jQuery(document.createElement('option')).val(val.id).html(val.value);
  1753. if (selected[val.fk_product_attribute] == val.id) {
  1754. tag.attr('selected', 'selected');
  1755. }
  1756. html.append(tag);
  1757. });
  1758. span.append(html);
  1759. jQuery('div#attributes_box').append(span);
  1760. });
  1761. })
  1762. });
  1763. <?php if ($selected): ?>
  1764. jQuery("input#<?php echo $htmlname ?>").change();
  1765. <?php endif ?>
  1766. });
  1767. </script>
  1768. <?php
  1769. }
  1770. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  1771. else if ($hidelabel > 1) {
  1772. $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
  1773. if ($hidelabel == 2) {
  1774. print img_picto($langs->trans("Search"), 'search');
  1775. }
  1776. }
  1777. print '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1778. if ($hidelabel == 3) {
  1779. print img_picto($langs->trans("Search"), 'search');
  1780. }
  1781. }
  1782. else
  1783. {
  1784. print $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus);
  1785. }
  1786. }
  1787. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1788. /**
  1789. * Return list of products for a customer
  1790. *
  1791. * @param int $selected Preselected product
  1792. * @param string $htmlname Name of select html
  1793. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1794. * @param int $limit Limit on number of returned lines
  1795. * @param int $price_level Level of price to show
  1796. * @param string $filterkey Filter on product
  1797. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1798. * @param int $finished Filter on finished field: 2=No filter
  1799. * @param int $outputmode 0=HTML select string, 1=Array
  1800. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1801. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1802. * @param int $forcecombo Force to use combo box
  1803. * @param string $morecss Add more css on select
  1804. * @param int $hidepriceinlabel 1=Hide prices in label
  1805. * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used
  1806. * 'warehouseopen' = select products from open warehouses,
  1807. * 'warehouseclosed' = select products from closed warehouses,
  1808. * 'warehouseinternal' = select products from warehouses for internal correct/transfer only
  1809. * @return array Array of keys for json
  1810. */
  1811. 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='')
  1812. {
  1813. // phpcs:enable
  1814. global $langs,$conf,$user,$db;
  1815. $out='';
  1816. $outarray=array();
  1817. $warehouseStatusArray = array();
  1818. if (! empty($warehouseStatus))
  1819. {
  1820. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  1821. if (preg_match('/warehouseclosed/', $warehouseStatus))
  1822. {
  1823. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  1824. }
  1825. if (preg_match('/warehouseopen/', $warehouseStatus))
  1826. {
  1827. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  1828. }
  1829. if (preg_match('/warehouseinternal/', $warehouseStatus))
  1830. {
  1831. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  1832. }
  1833. }
  1834. $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression";
  1835. (count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock";
  1836. $sql = "SELECT ";
  1837. $sql.= $selectFields . $selectFieldsGrouped;
  1838. //Price by customer
  1839. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
  1840. {
  1841. $sql.=', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  1842. $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
  1843. $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
  1844. }
  1845. // Multilang : we add translation
  1846. if (! empty($conf->global->MAIN_MULTILANGS))
  1847. {
  1848. $sql.= ", pl.label as label_translated";
  1849. $selectFields.= ", label_translated";
  1850. }
  1851. // Price by quantity
  1852. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
  1853. {
  1854. $sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1855. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
  1856. $sql.= " ORDER BY date_price";
  1857. $sql.= " DESC LIMIT 1) as price_rowid";
  1858. $sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid"; // price_by_qty is 1 if some prices by qty exists in subtable
  1859. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
  1860. $sql.= " ORDER BY date_price";
  1861. $sql.= " DESC LIMIT 1) as price_by_qty";
  1862. $selectFields.= ", price_rowid, price_by_qty";
  1863. }
  1864. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  1865. if (count($warehouseStatusArray))
  1866. {
  1867. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
  1868. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid";
  1869. }
  1870. // include search in supplier ref
  1871. if(!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
  1872. {
  1873. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  1874. }
  1875. //Price by customer
  1876. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1877. $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
  1878. }
  1879. // Multilang : we add translation
  1880. if (! empty($conf->global->MAIN_MULTILANGS))
  1881. {
  1882. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
  1883. }
  1884. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1885. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  1886. }
  1887. $sql.= ' WHERE p.entity IN ('.getEntity('product').')';
  1888. if (count($warehouseStatusArray))
  1889. {
  1890. $sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))';
  1891. }
  1892. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1893. $sql .= " AND pac.rowid IS NULL";
  1894. }
  1895. if ($finished == 0)
  1896. {
  1897. $sql.= " AND p.finished = ".$finished;
  1898. }
  1899. elseif ($finished == 1)
  1900. {
  1901. $sql.= " AND p.finished = ".$finished;
  1902. if ($status >= 0) $sql.= " AND p.tosell = ".$status;
  1903. }
  1904. elseif ($status >= 0)
  1905. {
  1906. $sql.= " AND p.tosell = ".$status;
  1907. }
  1908. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
  1909. // Add criteria on ref/label
  1910. if ($filterkey != '')
  1911. {
  1912. $sql.=' AND (';
  1913. $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  1914. // For natural search
  1915. $scrit = explode(' ', $filterkey);
  1916. $i=0;
  1917. if (count($scrit) > 1) $sql.="(";
  1918. foreach ($scrit as $crit)
  1919. {
  1920. if ($i > 0) $sql.=" AND ";
  1921. $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
  1922. if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
  1923. if (! empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql.=" OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
  1924. $sql.=")";
  1925. $i++;
  1926. }
  1927. if (count($scrit) > 1) $sql.=")";
  1928. if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
  1929. $sql.=')';
  1930. }
  1931. if (count($warehouseStatusArray))
  1932. {
  1933. $sql.= ' GROUP BY'.$selectFields;
  1934. }
  1935. $sql.= $db->order("p.ref");
  1936. $sql.= $db->plimit($limit, 0);
  1937. // Build output string
  1938. dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
  1939. $result=$this->db->query($sql);
  1940. if ($result)
  1941. {
  1942. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1943. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1944. $num = $this->db->num_rows($result);
  1945. $events=null;
  1946. if (! $forcecombo)
  1947. {
  1948. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1949. $out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
  1950. }
  1951. $out.='<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  1952. $textifempty='';
  1953. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1954. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1955. if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1956. {
  1957. if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
  1958. else $textifempty.=$langs->trans("All");
  1959. }
  1960. else
  1961. {
  1962. if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
  1963. }
  1964. if ($showempty) $out.='<option value="0" selected>'.$textifempty.'</option>';
  1965. $i = 0;
  1966. while ($num && $i < $num)
  1967. {
  1968. $opt = '';
  1969. $optJson = array();
  1970. $objp = $this->db->fetch_object($result);
  1971. 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)
  1972. { // Price by quantity will return many prices for the same product
  1973. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  1974. $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
  1975. $sql.= " WHERE fk_product_price=".$objp->price_rowid;
  1976. $sql.= " ORDER BY quantity ASC";
  1977. dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
  1978. $result2 = $this->db->query($sql);
  1979. if ($result2)
  1980. {
  1981. $nb_prices = $this->db->num_rows($result2);
  1982. $j = 0;
  1983. while ($nb_prices && $j < $nb_prices) {
  1984. $objp2 = $this->db->fetch_object($result2);
  1985. $objp->price_by_qty_rowid = $objp2->rowid;
  1986. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  1987. $objp->price_by_qty_quantity = $objp2->quantity;
  1988. $objp->price_by_qty_unitprice = $objp2->unitprice;
  1989. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  1990. // For backward compatibility
  1991. $objp->quantity = $objp2->quantity;
  1992. $objp->price = $objp2->price;
  1993. $objp->unitprice = $objp2->unitprice;
  1994. $objp->remise_percent = $objp2->remise_percent;
  1995. $objp->remise = $objp2->remise;
  1996. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel);
  1997. $j++;
  1998. // Add new entry
  1999. // "key" value of json key array is used by jQuery automatically as selected value
  2000. // "label" value of json key array is used by jQuery automatically as text for combo box
  2001. $out.=$opt;
  2002. array_push($outarray, $optJson);
  2003. }
  2004. }
  2005. }
  2006. else
  2007. {
  2008. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2009. $price_product = new Product($this->db);
  2010. $price_product->fetch($objp->rowid, '', '', 1);
  2011. $priceparser = new PriceParser($this->db);
  2012. $price_result = $priceparser->parseProduct($price_product);
  2013. if ($price_result >= 0) {
  2014. $objp->price = $price_result;
  2015. $objp->unitprice = $price_result;
  2016. //Calculate the VAT
  2017. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2018. $objp->price_ttc = price2num($objp->price_ttc,'MU');
  2019. }
  2020. }
  2021. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);
  2022. // Add new entry
  2023. // "key" value of json key array is used by jQuery automatically as selected value
  2024. // "label" value of json key array is used by jQuery automatically as text for combo box
  2025. $out.=$opt;
  2026. array_push($outarray, $optJson);
  2027. }
  2028. $i++;
  2029. }
  2030. $out.='</select>';
  2031. $this->db->free($result);
  2032. if (empty($outputmode)) return $out;
  2033. return $outarray;
  2034. }
  2035. else
  2036. {
  2037. dol_print_error($db);
  2038. }
  2039. }
  2040. /**
  2041. * constructProductListOption
  2042. *
  2043. * @param resultset $objp Resultset of fetch
  2044. * @param string $opt Option (var used for returned value in string option format)
  2045. * @param string $optJson Option (var used for returned value in json format)
  2046. * @param int $price_level Price level
  2047. * @param string $selected Preselected value
  2048. * @param int $hidepriceinlabel Hide price in label
  2049. * @return void
  2050. */
  2051. private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)
  2052. {
  2053. global $langs,$conf,$user,$db;
  2054. $outkey='';
  2055. $outval='';
  2056. $outref='';
  2057. $outlabel='';
  2058. $outdesc='';
  2059. $outbarcode='';
  2060. $outtype='';
  2061. $outprice_ht='';
  2062. $outprice_ttc='';
  2063. $outpricebasetype='';
  2064. $outtva_tx='';
  2065. $outqty=1;
  2066. $outdiscount=0;
  2067. $maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2068. $label=$objp->label;
  2069. if (! empty($objp->label_translated)) $label=$objp->label_translated;
  2070. if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  2071. $outkey=$objp->rowid;
  2072. $outref=$objp->ref;
  2073. $outlabel=$objp->label;
  2074. $outdesc=$objp->description;
  2075. $outbarcode=$objp->barcode;
  2076. $outtype=$objp->fk_product_type;
  2077. $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
  2078. $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
  2079. $opt = '<option value="'.$objp->rowid.'"';
  2080. $opt.= ($objp->rowid == $selected)?' selected':'';
  2081. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)
  2082. {
  2083. $opt.= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
  2084. }
  2085. if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
  2086. {
  2087. if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
  2088. else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
  2089. }
  2090. $opt.= '>';
  2091. $opt.= $objp->ref;
  2092. if ($outbarcode) $opt.=' ('.$outbarcode.')';
  2093. $opt.=' - '.dol_trunc($label,$maxlengtharticle);
  2094. $objRef = $objp->ref;
  2095. if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  2096. $outval.=$objRef;
  2097. if ($outbarcode) $outval.=' ('.$outbarcode.')';
  2098. $outval.=' - '.dol_trunc($label,$maxlengtharticle);
  2099. $found=0;
  2100. // Multiprice
  2101. // If we need a particular price level (from 1 to 6)
  2102. if (empty($hidepriceinlabel) && $price_level >= 1 && (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
  2103. {
  2104. $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
  2105. $sql.= " FROM ".MAIN_DB_PREFIX."product_price";
  2106. $sql.= " WHERE fk_product='".$objp->rowid."'";
  2107. $sql.= " AND entity IN (".getEntity('productprice').")";
  2108. $sql.= " AND price_level=".$price_level;
  2109. $sql.= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2110. $sql.= " LIMIT 1";
  2111. dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
  2112. $result2 = $this->db->query($sql);
  2113. if ($result2)
  2114. {
  2115. $objp2 = $this->db->fetch_object($result2);
  2116. if ($objp2)
  2117. {
  2118. $found=1;
  2119. if ($objp2->price_base_type == 'HT')
  2120. {
  2121. $opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  2122. $outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  2123. }
  2124. else
  2125. {
  2126. $opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  2127. $outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  2128. }
  2129. $outprice_ht=price($objp2->price);
  2130. $outprice_ttc=price($objp2->price_ttc);
  2131. $outpricebasetype=$objp2->price_base_type;
  2132. $outtva_tx=$objp2->tva_tx;
  2133. }
  2134. }
  2135. else
  2136. {
  2137. dol_print_error($this->db);
  2138. }
  2139. }
  2140. // Price by quantity
  2141. 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)))
  2142. {
  2143. $found = 1;
  2144. $outqty=$objp->quantity;
  2145. $outdiscount=$objp->remise_percent;
  2146. if ($objp->quantity == 1)
  2147. {
  2148. $opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/";
  2149. $outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
  2150. $opt.= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2151. $outval.=$langs->transnoentities("Unit");
  2152. }
  2153. else
  2154. {
  2155. $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2156. $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2157. $opt.= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2158. $outval.=$langs->transnoentities("Units");
  2159. }
  2160. $outprice_ht=price($objp->unitprice);
  2161. $outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2162. $outpricebasetype=$objp->price_base_type;
  2163. $outtva_tx=$objp->tva_tx;
  2164. }
  2165. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
  2166. {
  2167. $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2168. $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2169. }
  2170. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
  2171. {
  2172. $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2173. $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2174. }
  2175. // Price by customer
  2176. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  2177. {
  2178. if (!empty($objp->idprodcustprice))
  2179. {
  2180. $found = 1;
  2181. if ($objp->custprice_base_type == 'HT')
  2182. {
  2183. $opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  2184. $outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  2185. }
  2186. else
  2187. {
  2188. $opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  2189. $outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  2190. }
  2191. $outprice_ht=price($objp->custprice);
  2192. $outprice_ttc=price($objp->custprice_ttc);
  2193. $outpricebasetype=$objp->custprice_base_type;
  2194. $outtva_tx=$objp->custtva_tx;
  2195. }
  2196. }
  2197. // If level no defined or multiprice not found, we used the default price
  2198. if (empty($hidepriceinlabel) && ! $found)
  2199. {
  2200. if ($objp->price_base_type == 'HT')
  2201. {
  2202. $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  2203. $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  2204. }
  2205. else
  2206. {
  2207. $opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  2208. $outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  2209. }
  2210. $outprice_ht=price($objp->price);
  2211. $outprice_ttc=price($objp->price_ttc);
  2212. $outpricebasetype=$objp->price_base_type;
  2213. $outtva_tx=$objp->tva_tx;
  2214. }
  2215. if (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
  2216. {
  2217. $opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
  2218. if ($objp->stock > 0) {
  2219. $outval.= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
  2220. }elseif ($objp->stock <= 0) {
  2221. $outval.= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
  2222. }
  2223. }
  2224. if ($outdurationvalue && $outdurationunit)
  2225. {
  2226. $da=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
  2227. if (isset($da[$outdurationunit]))
  2228. {
  2229. $key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');
  2230. $opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);
  2231. $outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);
  2232. }
  2233. }
  2234. $opt.= "</option>\n";
  2235. $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);
  2236. }
  2237. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2238. /**
  2239. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2240. *
  2241. * @param int $socid Id third party
  2242. * @param string $selected Preselected product
  2243. * @param string $htmlname Name of HTML Select
  2244. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2245. * @param string $filtre For a SQL filter
  2246. * @param array $ajaxoptions Options for ajax_autocompleter
  2247. * @param int $hidelabel Hide label (0=no, 1=yes)
  2248. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2249. * @param string $morecss More CSS
  2250. * @return void
  2251. */
  2252. function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0, $morecss='')
  2253. {
  2254. // phpcs:enable
  2255. global $langs,$conf;
  2256. global $price_level, $status, $finished;
  2257. $selected_input_value='';
  2258. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  2259. {
  2260. if ($selected > 0)
  2261. {
  2262. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2263. $producttmpselect = new Product($this->db);
  2264. $producttmpselect->fetch($selected);
  2265. $selected_input_value=$producttmpselect->ref;
  2266. unset($producttmpselect);
  2267. }
  2268. // mode=2 means suppliers products
  2269. $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2270. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2271. print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
  2272. }
  2273. else
  2274. {
  2275. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', -1, 0, 0, $alsoproductwithnosupplierprice, $morecss);
  2276. }
  2277. }
  2278. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2279. /**
  2280. * Return list of suppliers products
  2281. *
  2282. * @param int $socid Id societe fournisseur (0 pour aucun filtre)
  2283. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2284. * @param string $htmlname Nom de la zone select
  2285. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2286. * @param string $filtre Pour filtre sql
  2287. * @param string $filterkey Filtre des produits
  2288. * @param int $statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)
  2289. * @param int $outputmode 0=HTML select string, 1=Array
  2290. * @param int $limit Limit of line number
  2291. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2292. * @param string $morecss Add more CSS
  2293. * @return array Array of keys for json
  2294. */
  2295. function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0,$morecss='')
  2296. {
  2297. // phpcs:enable
  2298. global $langs,$conf,$db;
  2299. $out='';
  2300. $outarray=array();
  2301. $langs->load('stocks');
  2302. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,";
  2303. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2304. $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
  2305. $sql.= " pfp.supplier_reputation";
  2306. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  2307. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2308. if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
  2309. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2310. $sql.= " WHERE p.entity IN (".getEntity('product').")";
  2311. $sql.= " AND p.tobuy = 1";
  2312. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
  2313. if (! empty($filtre)) $sql.=" ".$filtre;
  2314. // Add criteria on ref/label
  2315. if ($filterkey != '')
  2316. {
  2317. $sql.=' AND (';
  2318. $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2319. // For natural search
  2320. $scrit = explode(' ', $filterkey);
  2321. $i=0;
  2322. if (count($scrit) > 1) $sql.="(";
  2323. foreach ($scrit as $crit)
  2324. {
  2325. if ($i > 0) $sql.=" AND ";
  2326. $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)."%')";
  2327. $i++;
  2328. }
  2329. if (count($scrit) > 1) $sql.=")";
  2330. if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2331. $sql.=')';
  2332. }
  2333. $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2334. $sql.= $db->plimit($limit, 0);
  2335. // Build output string
  2336. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2337. $result=$this->db->query($sql);
  2338. if ($result)
  2339. {
  2340. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2341. $num = $this->db->num_rows($result);
  2342. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2343. $out.='<select class="flat maxwidthonsmartphone'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2344. if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
  2345. else $out.='<option value="0">&nbsp;</option>';
  2346. $i = 0;
  2347. while ($i < $num)
  2348. {
  2349. $objp = $this->db->fetch_object($result);
  2350. $outkey=$objp->idprodfournprice; // id in table of price
  2351. if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid; // id of product
  2352. $outref=$objp->ref;
  2353. $outval='';
  2354. $outqty=1;
  2355. $outdiscount=0;
  2356. $outtype=$objp->fk_product_type;
  2357. $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
  2358. $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
  2359. $opt = '<option value="'.$outkey.'"';
  2360. if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
  2361. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';
  2362. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
  2363. {
  2364. $opt.= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqpercent="'.$objp->remise_percent.'"';
  2365. }
  2366. $opt.= '>';
  2367. $objRef = $objp->ref;
  2368. if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  2369. $objRefFourn = $objp->ref_fourn;
  2370. if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
  2371. $label = $objp->label;
  2372. if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  2373. $opt.=$objp->ref;
  2374. if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
  2375. $opt.=' ('.$objp->ref_fourn.')';
  2376. $opt.=' - ';
  2377. $outval.=$objRef;
  2378. if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
  2379. $outval.=' ('.$objRefFourn.')';
  2380. $outval.=' - ';
  2381. $opt.=dol_trunc($label, 72).' - ';
  2382. $outval.=dol_trunc($label, 72).' - ';
  2383. if (! empty($objp->idprodfournprice))
  2384. {
  2385. $outqty=$objp->quantity;
  2386. $outdiscount=$objp->remise_percent;
  2387. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2388. $prod_supplier = new ProductFournisseur($this->db);
  2389. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2390. $prod_supplier->id = $objp->fk_product;
  2391. $prod_supplier->fourn_qty = $objp->quantity;
  2392. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2393. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2394. $priceparser = new PriceParser($this->db);
  2395. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2396. if ($price_result >= 0) {
  2397. $objp->fprice = $price_result;
  2398. if ($objp->quantity >= 1)
  2399. {
  2400. $objp->unitprice = $objp->fprice / $objp->quantity;
  2401. }
  2402. }
  2403. }
  2404. if ($objp->quantity == 1)
  2405. {
  2406. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
  2407. $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
  2408. $opt.= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2409. $outval.=$langs->transnoentities("Unit");
  2410. }
  2411. else
  2412. {
  2413. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2414. $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2415. $opt.= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2416. $outval.= ' '.$langs->transnoentities("Units");
  2417. }
  2418. if ($objp->quantity >= 1)
  2419. {
  2420. $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2421. $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2422. }
  2423. if ($objp->remise_percent >= 1)
  2424. {
  2425. $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2426. $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2427. }
  2428. if ($objp->duration)
  2429. {
  2430. $opt .= " - ".$objp->duration;
  2431. $outval.=" - ".$objp->duration;
  2432. }
  2433. if (! $socid)
  2434. {
  2435. $opt .= " - ".dol_trunc($objp->name,8);
  2436. $outval.=" - ".dol_trunc($objp->name,8);
  2437. }
  2438. if ($objp->supplier_reputation)
  2439. {
  2440. //TODO dictionary
  2441. $reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  2442. $opt .= " - ".$reputations[$objp->supplier_reputation];
  2443. $outval.=" - ".$reputations[$objp->supplier_reputation];
  2444. }
  2445. }
  2446. else
  2447. {
  2448. if (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier
  2449. {
  2450. $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
  2451. $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2452. }
  2453. else // No supplier price defined for product, even on other suppliers
  2454. {
  2455. $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
  2456. $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2457. }
  2458. }
  2459. $opt .= "</option>\n";
  2460. // Add new entry
  2461. // "key" value of json key array is used by jQuery automatically as selected value
  2462. // "label" value of json key array is used by jQuery automatically as text for combo box
  2463. $out.=$opt;
  2464. array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));
  2465. // Exemple of var_dump $outarray
  2466. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  2467. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  2468. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  2469. //}
  2470. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2471. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  2472. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2473. $i++;
  2474. }
  2475. $out.='</select>';
  2476. $this->db->free($result);
  2477. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2478. $out.=ajax_combobox($htmlname);
  2479. if (empty($outputmode)) return $out;
  2480. return $outarray;
  2481. }
  2482. else
  2483. {
  2484. dol_print_error($this->db);
  2485. }
  2486. }
  2487. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2488. /**
  2489. * Return list of suppliers prices for a product
  2490. *
  2491. * @param int $productid Id of product
  2492. * @param string $htmlname Name of HTML field
  2493. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  2494. * @return void
  2495. */
  2496. function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')
  2497. {
  2498. // phpcs:enable
  2499. global $langs,$conf;
  2500. $langs->load('stocks');
  2501. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,";
  2502. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
  2503. $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  2504. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  2505. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2506. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2507. $sql.= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  2508. $sql.= " AND p.tobuy = 1";
  2509. $sql.= " AND s.fournisseur = 1";
  2510. $sql.= " AND p.rowid = ".$productid;
  2511. $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
  2512. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  2513. $result=$this->db->query($sql);
  2514. if ($result)
  2515. {
  2516. $num = $this->db->num_rows($result);
  2517. $form = '<select class="flat" name="'.$htmlname.'">';
  2518. if (! $num)
  2519. {
  2520. $form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  2521. }
  2522. else
  2523. {
  2524. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2525. $form.= '<option value="0">&nbsp;</option>';
  2526. $i = 0;
  2527. while ($i < $num)
  2528. {
  2529. $objp = $this->db->fetch_object($result);
  2530. $opt = '<option value="'.$objp->idprodfournprice.'"';
  2531. //if there is only one supplier, preselect it
  2532. if($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  2533. $opt .= ' selected';
  2534. }
  2535. $opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  2536. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2537. $prod_supplier = new ProductFournisseur($this->db);
  2538. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2539. $prod_supplier->id = $productid;
  2540. $prod_supplier->fourn_qty = $objp->quantity;
  2541. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2542. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2543. $priceparser = new PriceParser($this->db);
  2544. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2545. if ($price_result >= 0) {
  2546. $objp->fprice = $price_result;
  2547. if ($objp->quantity >= 1)
  2548. {
  2549. $objp->unitprice = $objp->fprice / $objp->quantity;
  2550. }
  2551. }
  2552. }
  2553. if ($objp->quantity == 1)
  2554. {
  2555. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
  2556. }
  2557. $opt.= $objp->quantity.' ';
  2558. if ($objp->quantity == 1)
  2559. {
  2560. $opt.= $langs->trans("Unit");
  2561. }
  2562. else
  2563. {
  2564. $opt.= $langs->trans("Units");
  2565. }
  2566. if ($objp->quantity > 1)
  2567. {
  2568. $opt.=" - ";
  2569. $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
  2570. }
  2571. if ($objp->duration) $opt .= " - ".$objp->duration;
  2572. $opt .= "</option>\n";
  2573. $form.= $opt;
  2574. $i++;
  2575. }
  2576. }
  2577. $form.= '</select>';
  2578. $this->db->free($result);
  2579. return $form;
  2580. }
  2581. else
  2582. {
  2583. dol_print_error($this->db);
  2584. }
  2585. }
  2586. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2587. /**
  2588. * Return list of delivery address
  2589. *
  2590. * @param string $selected Id contact pre-selectionn
  2591. * @param int $socid Id of company
  2592. * @param string $htmlname Name of HTML field
  2593. * @param int $showempty Add an empty field
  2594. * @return integer|null
  2595. */
  2596. function select_address($selected, $socid, $htmlname='address_id',$showempty=0)
  2597. {
  2598. // phpcs:enable
  2599. // looking for users
  2600. $sql = "SELECT a.rowid, a.label";
  2601. $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
  2602. $sql .= " WHERE a.fk_soc = ".$socid;
  2603. $sql .= " ORDER BY a.label ASC";
  2604. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  2605. $resql=$this->db->query($sql);
  2606. if ($resql)
  2607. {
  2608. print '<select class="flat" name="'.$htmlname.'">';
  2609. if ($showempty) print '<option value="0">&nbsp;</option>';
  2610. $num = $this->db->num_rows($resql);
  2611. $i = 0;
  2612. if ($num)
  2613. {
  2614. while ($i < $num)
  2615. {
  2616. $obj = $this->db->fetch_object($resql);
  2617. if ($selected && $selected == $obj->rowid)
  2618. {
  2619. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  2620. }
  2621. else
  2622. {
  2623. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  2624. }
  2625. $i++;
  2626. }
  2627. }
  2628. print '</select>';
  2629. return $num;
  2630. }
  2631. else
  2632. {
  2633. dol_print_error($this->db);
  2634. }
  2635. }
  2636. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2637. /**
  2638. * Load into cache list of payment terms
  2639. *
  2640. * @return int Nb of lines loaded, <0 if KO
  2641. */
  2642. function load_cache_conditions_paiements()
  2643. {
  2644. // phpcs:enable
  2645. global $langs;
  2646. $num = count($this->cache_conditions_paiements);
  2647. if ($num > 0) return 0; // Cache already loaded
  2648. dol_syslog(__METHOD__, LOG_DEBUG);
  2649. $sql = "SELECT rowid, code, libelle as label";
  2650. $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  2651. $sql.= " WHERE entity IN (".getEntity('c_payment_term').")";
  2652. $sql.= " AND active > 0";
  2653. $sql.= " ORDER BY sortorder";
  2654. $resql = $this->db->query($sql);
  2655. if ($resql)
  2656. {
  2657. $num = $this->db->num_rows($resql);
  2658. $i = 0;
  2659. while ($i < $num)
  2660. {
  2661. $obj = $this->db->fetch_object($resql);
  2662. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2663. $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:''));
  2664. $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
  2665. $this->cache_conditions_paiements[$obj->rowid]['label']=$label;
  2666. $i++;
  2667. }
  2668. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  2669. return $num;
  2670. }
  2671. else
  2672. {
  2673. dol_print_error($this->db);
  2674. return -1;
  2675. }
  2676. }
  2677. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2678. /**
  2679. * Charge dans cache la liste des délais de livraison possibles
  2680. *
  2681. * @return int Nb of lines loaded, <0 if KO
  2682. */
  2683. function load_cache_availability()
  2684. {
  2685. // phpcs:enable
  2686. global $langs;
  2687. $num = count($this->cache_availability);
  2688. if ($num > 0) return 0; // Cache already loaded
  2689. dol_syslog(__METHOD__, LOG_DEBUG);
  2690. $langs->load('propal');
  2691. $sql = "SELECT rowid, code, label";
  2692. $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
  2693. $sql.= " WHERE active > 0";
  2694. $resql = $this->db->query($sql);
  2695. if ($resql)
  2696. {
  2697. $num = $this->db->num_rows($resql);
  2698. $i = 0;
  2699. while ($i < $num)
  2700. {
  2701. $obj = $this->db->fetch_object($resql);
  2702. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2703. $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
  2704. $this->cache_availability[$obj->rowid]['code'] =$obj->code;
  2705. $this->cache_availability[$obj->rowid]['label']=$label;
  2706. $i++;
  2707. }
  2708. $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
  2709. return $num;
  2710. }
  2711. else
  2712. {
  2713. dol_print_error($this->db);
  2714. return -1;
  2715. }
  2716. }
  2717. /**
  2718. * Retourne la liste des types de delais de livraison possibles
  2719. *
  2720. * @param int $selected Id du type de delais pre-selectionne
  2721. * @param string $htmlname Nom de la zone select
  2722. * @param string $filtertype To add a filter
  2723. * @param int $addempty Add empty entry
  2724. * @return void
  2725. */
  2726. function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)
  2727. {
  2728. global $langs,$user;
  2729. $this->load_cache_availability();
  2730. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2731. print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  2732. if ($addempty) print '<option value="0">&nbsp;</option>';
  2733. foreach($this->cache_availability as $id => $arrayavailability)
  2734. {
  2735. if ($selected == $id)
  2736. {
  2737. print '<option value="'.$id.'" selected>';
  2738. }
  2739. else
  2740. {
  2741. print '<option value="'.$id.'">';
  2742. }
  2743. print $arrayavailability['label'];
  2744. print '</option>';
  2745. }
  2746. print '</select>';
  2747. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2748. }
  2749. /**
  2750. * Load into cache cache_demand_reason, array of input reasons
  2751. *
  2752. * @return int Nb of lines loaded, <0 if KO
  2753. */
  2754. function loadCacheInputReason()
  2755. {
  2756. global $langs;
  2757. $num = count($this->cache_demand_reason);
  2758. if ($num > 0) return 0; // Cache already loaded
  2759. $sql = "SELECT rowid, code, label";
  2760. $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  2761. $sql.= " WHERE active > 0";
  2762. $resql = $this->db->query($sql);
  2763. if ($resql)
  2764. {
  2765. $num = $this->db->num_rows($resql);
  2766. $i = 0;
  2767. $tmparray=array();
  2768. while ($i < $num)
  2769. {
  2770. $obj = $this->db->fetch_object($resql);
  2771. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2772. $label=($obj->label!='-'?$obj->label:'');
  2773. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  2774. if ($langs->trans($obj->code) != $obj->code) $label=$langs->trans($obj->code); // So translation key SRC_XXX will work
  2775. $tmparray[$obj->rowid]['id'] =$obj->rowid;
  2776. $tmparray[$obj->rowid]['code'] =$obj->code;
  2777. $tmparray[$obj->rowid]['label']=$label;
  2778. $i++;
  2779. }
  2780. $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  2781. unset($tmparray);
  2782. return $num;
  2783. }
  2784. else
  2785. {
  2786. dol_print_error($this->db);
  2787. return -1;
  2788. }
  2789. }
  2790. /**
  2791. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  2792. * List found into table c_input_reason loaded by loadCacheInputReason
  2793. *
  2794. * @param int $selected Id or code of type origin to select by default
  2795. * @param string $htmlname Nom de la zone select
  2796. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  2797. * @param int $addempty Add an empty entry
  2798. * @return void
  2799. */
  2800. function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
  2801. {
  2802. global $langs,$user;
  2803. $this->loadCacheInputReason();
  2804. print '<select class="flat" name="'.$htmlname.'">';
  2805. if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
  2806. foreach($this->cache_demand_reason as $id => $arraydemandreason)
  2807. {
  2808. if ($arraydemandreason['code']==$exclude) continue;
  2809. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
  2810. {
  2811. print '<option value="'.$arraydemandreason['id'].'" selected>';
  2812. }
  2813. else
  2814. {
  2815. print '<option value="'.$arraydemandreason['id'].'">';
  2816. }
  2817. $label=$arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  2818. print $langs->trans($label);
  2819. print '</option>';
  2820. }
  2821. print '</select>';
  2822. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2823. }
  2824. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2825. /**
  2826. * Charge dans cache la liste des types de paiements possibles
  2827. *
  2828. * @return int Nb of lines loaded, <0 if KO
  2829. */
  2830. function load_cache_types_paiements()
  2831. {
  2832. // phpcs:enable
  2833. global $langs;
  2834. $num=count($this->cache_types_paiements);
  2835. if ($num > 0) return $num; // Cache already loaded
  2836. dol_syslog(__METHOD__, LOG_DEBUG);
  2837. $this->cache_types_paiements = array();
  2838. $sql = "SELECT id, code, libelle as label, type, active";
  2839. $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
  2840. $sql.= " WHERE entity IN (".getEntity('c_paiement').")";
  2841. //if ($active >= 0) $sql.= " AND active = ".$active;
  2842. $resql = $this->db->query($sql);
  2843. if ($resql)
  2844. {
  2845. $num = $this->db->num_rows($resql);
  2846. $i = 0;
  2847. while ($i < $num)
  2848. {
  2849. $obj = $this->db->fetch_object($resql);
  2850. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2851. $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
  2852. $this->cache_types_paiements[$obj->id]['id'] =$obj->id;
  2853. $this->cache_types_paiements[$obj->id]['code'] =$obj->code;
  2854. $this->cache_types_paiements[$obj->id]['label']=$label;
  2855. $this->cache_types_paiements[$obj->id]['type'] =$obj->type;
  2856. $this->cache_types_paiements[$obj->id]['active'] =$obj->active;
  2857. $i++;
  2858. }
  2859. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  2860. return $num;
  2861. }
  2862. else
  2863. {
  2864. dol_print_error($this->db);
  2865. return -1;
  2866. }
  2867. }
  2868. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2869. /**
  2870. * Return list of payment modes.
  2871. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  2872. * See instead to force the default value by the caller.
  2873. *
  2874. * @param int $selected Id of payment term to preselect by default
  2875. * @param string $htmlname Nom de la zone select
  2876. * @param int $filtertype Not used
  2877. * @param int $addempty Add an empty entry
  2878. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  2879. * @param string $morecss Add more CSS on select tag
  2880. * @return void
  2881. */
  2882. function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='')
  2883. {
  2884. // phpcs:enable
  2885. global $langs, $user, $conf;
  2886. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2887. $this->load_cache_conditions_paiements();
  2888. // Set default value if not already set by caller
  2889. if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  2890. print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
  2891. if ($addempty) print '<option value="0">&nbsp;</option>';
  2892. foreach($this->cache_conditions_paiements as $id => $arrayconditions)
  2893. {
  2894. if ($selected == $id)
  2895. {
  2896. print '<option value="'.$id.'" selected>';
  2897. }
  2898. else
  2899. {
  2900. print '<option value="'.$id.'">';
  2901. }
  2902. print $arrayconditions['label'];
  2903. print '</option>';
  2904. }
  2905. print '</select>';
  2906. if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2907. }
  2908. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2909. /**
  2910. * Return list of payment methods
  2911. *
  2912. * @param string $selected Id du mode de paiement pre-selectionne
  2913. * @param string $htmlname Nom de la zone select
  2914. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  2915. * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
  2916. * @param int $empty 1=peut etre vide, 0 sinon
  2917. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  2918. * @param int $maxlength Max length of label
  2919. * @param int $active Active or not, -1 = all
  2920. * @param string $morecss Add more CSS on select tag
  2921. * @return void
  2922. */
  2923. function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=1, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')
  2924. {
  2925. // phpcs:enable
  2926. global $langs,$user;
  2927. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  2928. $filterarray=array();
  2929. if ($filtertype == 'CRDT') $filterarray=array(0,2,3);
  2930. elseif ($filtertype == 'DBIT') $filterarray=array(1,2,3);
  2931. elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
  2932. $this->load_cache_types_paiements();
  2933. print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
  2934. if ($empty) print '<option value="">&nbsp;</option>';
  2935. foreach($this->cache_types_paiements as $id => $arraytypes)
  2936. {
  2937. // If not good status
  2938. if ($active >= 0 && $arraytypes['active'] != $active) continue;
  2939. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  2940. if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
  2941. // We discard empty line if showempty is on because an empty line has already been output.
  2942. if ($empty && empty($arraytypes['code'])) continue;
  2943. if ($format == 0) print '<option value="'.$id.'"';
  2944. elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
  2945. elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
  2946. elseif ($format == 3) print '<option value="'.$id.'"';
  2947. // Si selected est text, on compare avec code, sinon avec id
  2948. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
  2949. elseif ($selected == $id) print ' selected';
  2950. print '>';
  2951. if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  2952. elseif ($format == 1) $value=$arraytypes['code'];
  2953. elseif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  2954. elseif ($format == 3) $value=$arraytypes['code'];
  2955. print $value?$value:'&nbsp;';
  2956. print '</option>';
  2957. }
  2958. print '</select>';
  2959. if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2960. }
  2961. /**
  2962. * Selection HT or TTC
  2963. *
  2964. * @param string $selected Id pre-selectionne
  2965. * @param string $htmlname Nom de la zone select
  2966. * @return string Code of HTML select to chose tax or not
  2967. */
  2968. function selectPriceBaseType($selected='',$htmlname='price_base_type')
  2969. {
  2970. global $langs;
  2971. $return='';
  2972. $return.= '<select class="flat" name="'.$htmlname.'">';
  2973. $options = array(
  2974. 'HT'=>$langs->trans("HT"),
  2975. 'TTC'=>$langs->trans("TTC")
  2976. );
  2977. foreach($options as $id => $value)
  2978. {
  2979. if ($selected == $id)
  2980. {
  2981. $return.= '<option value="'.$id.'" selected>'.$value;
  2982. }
  2983. else
  2984. {
  2985. $return.= '<option value="'.$id.'">'.$value;
  2986. }
  2987. $return.= '</option>';
  2988. }
  2989. $return.= '</select>';
  2990. return $return;
  2991. }
  2992. /**
  2993. * Return a HTML select list of shipping mode
  2994. *
  2995. * @param string $selected Id shipping mode pre-selected
  2996. * @param string $htmlname Name of select zone
  2997. * @param string $filtre To filter list
  2998. * @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.
  2999. * @param string $moreattrib To add more attribute on select
  3000. * @return void
  3001. */
  3002. function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')
  3003. {
  3004. global $langs, $conf, $user;
  3005. $langs->load("admin");
  3006. $langs->load("deliveries");
  3007. $sql = "SELECT rowid, code, libelle as label";
  3008. $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
  3009. $sql.= " WHERE active > 0";
  3010. if ($filtre) $sql.=" AND ".$filtre;
  3011. $sql.= " ORDER BY libelle ASC";
  3012. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3013. $result = $this->db->query($sql);
  3014. if ($result) {
  3015. $num = $this->db->num_rows($result);
  3016. $i = 0;
  3017. if ($num) {
  3018. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
  3019. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3020. print '<option value="-1">&nbsp;</option>';
  3021. }
  3022. while ($i < $num) {
  3023. $obj = $this->db->fetch_object($result);
  3024. if ($selected == $obj->rowid) {
  3025. print '<option value="'.$obj->rowid.'" selected>';
  3026. } else {
  3027. print '<option value="'.$obj->rowid.'">';
  3028. }
  3029. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3030. print '</option>';
  3031. $i++;
  3032. }
  3033. print "</select>";
  3034. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  3035. } else {
  3036. print $langs->trans("NoShippingMethodDefined");
  3037. }
  3038. } else {
  3039. dol_print_error($this->db);
  3040. }
  3041. }
  3042. /**
  3043. * Display form to select shipping mode
  3044. *
  3045. * @param string $page Page
  3046. * @param int $selected Id of shipping mode
  3047. * @param string $htmlname Name of select html field
  3048. * @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.
  3049. * @return void
  3050. */
  3051. function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
  3052. {
  3053. global $langs, $db;
  3054. $langs->load("deliveries");
  3055. if ($htmlname != "none") {
  3056. print '<form method="POST" action="'.$page.'">';
  3057. print '<input type="hidden" name="action" value="setshippingmethod">';
  3058. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3059. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3060. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3061. print '</form>';
  3062. } else {
  3063. if ($selected) {
  3064. $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
  3065. print $langs->trans("SendingMethod".strtoupper($code));
  3066. } else {
  3067. print "&nbsp;";
  3068. }
  3069. }
  3070. }
  3071. /**
  3072. * Creates HTML last in cycle situation invoices selector
  3073. *
  3074. * @param string $selected Preselected ID
  3075. * @param int $socid Company ID
  3076. *
  3077. * @return string HTML select
  3078. */
  3079. function selectSituationInvoices($selected = '', $socid = 0)
  3080. {
  3081. global $langs;
  3082. $langs->load('bills');
  3083. $opt = '<option value ="" selected></option>';
  3084. $sql = 'SELECT rowid, facnumber, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';
  3085. $sql.= ' ORDER by situation_cycle_ref, situation_counter desc';
  3086. $resql = $this->db->query($sql);
  3087. if ($resql && $this->db->num_rows($resql) > 0) {
  3088. // Last seen cycle
  3089. $ref = 0;
  3090. while ($obj = $this->db->fetch_object($resql)){
  3091. //Same company ?
  3092. if ($socid == $obj->fk_soc) {
  3093. //Same cycle ?
  3094. if ($obj->situation_cycle_ref != $ref) {
  3095. // Just seen this cycle
  3096. $ref = $obj->situation_cycle_ref;
  3097. //not final ?
  3098. if ($obj->situation_final != 1) {
  3099. //Not prov?
  3100. if (substr($obj->facnumber, 1, 4) != 'PROV') {
  3101. if ($selected == $obj->rowid) {
  3102. $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->facnumber . '</option>';
  3103. } else {
  3104. $opt .= '<option value="' . $obj->rowid . '">' . $obj->facnumber . '</option>';
  3105. }
  3106. }
  3107. }
  3108. }
  3109. }
  3110. }
  3111. }
  3112. else
  3113. {
  3114. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  3115. }
  3116. if ($opt == '<option value ="" selected></option>')
  3117. {
  3118. $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
  3119. }
  3120. return $opt;
  3121. }
  3122. /**
  3123. * Creates HTML units selector (code => label)
  3124. *
  3125. * @param string $selected Preselected Unit ID
  3126. * @param string $htmlname Select name
  3127. * @param int $showempty Add a nempty line
  3128. * @return string HTML select
  3129. */
  3130. function selectUnits($selected = '', $htmlname = 'units', $showempty=0)
  3131. {
  3132. global $langs;
  3133. $langs->load('products');
  3134. $return= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  3135. $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
  3136. $sql.= ' WHERE active > 0';
  3137. $resql = $this->db->query($sql);
  3138. if($resql && $this->db->num_rows($resql) > 0)
  3139. {
  3140. if ($showempty) $return .= '<option value="none"></option>';
  3141. while($res = $this->db->fetch_object($resql))
  3142. {
  3143. $unitLabel = $res->label;
  3144. if (! empty($langs->tab_translate['unit'.$res->code])) // check if Translation is available before
  3145. {
  3146. $unitLabel = $langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label;
  3147. }
  3148. if ($selected == $res->rowid)
  3149. {
  3150. $return.='<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  3151. }
  3152. else
  3153. {
  3154. $return.='<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  3155. }
  3156. }
  3157. $return.='</select>';
  3158. }
  3159. return $return;
  3160. }
  3161. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3162. /**
  3163. * Return a HTML select list of bank accounts
  3164. *
  3165. * @param string $selected Id account pre-selected
  3166. * @param string $htmlname Name of select zone
  3167. * @param int $statut Status of searched accounts (0=open, 1=closed, 2=both)
  3168. * @param string $filtre To filter list
  3169. * @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.
  3170. * @param string $moreattrib To add more attribute on select
  3171. * @param int $showcurrency Show currency in label
  3172. * @return void
  3173. */
  3174. function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0)
  3175. {
  3176. // phpcs:enable
  3177. global $langs, $conf;
  3178. $langs->load("admin");
  3179. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  3180. $sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
  3181. $sql.= " WHERE entity IN (".getEntity('bank_account').")";
  3182. if ($statut != 2) $sql.= " AND clos = '".$statut."'";
  3183. if ($filtre) $sql.=" AND ".$filtre;
  3184. $sql.= " ORDER BY label";
  3185. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  3186. $result = $this->db->query($sql);
  3187. if ($result)
  3188. {
  3189. $num = $this->db->num_rows($result);
  3190. $i = 0;
  3191. if ($num)
  3192. {
  3193. print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
  3194. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  3195. {
  3196. print '<option value="-1">&nbsp;</option>';
  3197. }
  3198. while ($i < $num)
  3199. {
  3200. $obj = $this->db->fetch_object($result);
  3201. if ($selected == $obj->rowid)
  3202. {
  3203. print '<option value="'.$obj->rowid.'" selected>';
  3204. }
  3205. else
  3206. {
  3207. print '<option value="'.$obj->rowid.'">';
  3208. }
  3209. print trim($obj->label);
  3210. if ($showcurrency) print ' ('.$obj->currency_code.')';
  3211. if ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  3212. print '</option>';
  3213. $i++;
  3214. }
  3215. print "</select>";
  3216. }
  3217. else
  3218. {
  3219. if ($statut == 0) print $langs->trans("NoActiveBankAccountDefined");
  3220. else print $langs->trans("NoBankAccountFound");
  3221. }
  3222. }
  3223. else {
  3224. dol_print_error($this->db);
  3225. }
  3226. }
  3227. /**
  3228. * Display form to select bank account
  3229. *
  3230. * @param string $page Page
  3231. * @param int $selected Id of bank account
  3232. * @param string $htmlname Name of select html field
  3233. * @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.
  3234. * @return void
  3235. */
  3236. function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
  3237. {
  3238. global $langs;
  3239. if ($htmlname != "none") {
  3240. print '<form method="POST" action="'.$page.'">';
  3241. print '<input type="hidden" name="action" value="setbankaccount">';
  3242. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3243. $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  3244. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3245. print '</form>';
  3246. } else {
  3247. $langs->load('banks');
  3248. if ($selected) {
  3249. require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
  3250. $bankstatic=new Account($this->db);
  3251. $result = $bankstatic->fetch($selected);
  3252. if ($result) print $bankstatic->getNomUrl(1);
  3253. } else {
  3254. print "&nbsp;";
  3255. }
  3256. }
  3257. }
  3258. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3259. /**
  3260. * Return list of categories having choosed type
  3261. *
  3262. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  3263. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element)
  3264. * @param string $htmlname HTML field name
  3265. * @param int $maxlength Maximum length for labels
  3266. * @param int $excludeafterid Exclude all categories after this leaf in category tree.
  3267. * @param int $outputmode 0=HTML select string, 1=Array
  3268. * @return string
  3269. * @see select_categories
  3270. */
  3271. function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0)
  3272. {
  3273. // phpcs:enable
  3274. global $conf, $langs;
  3275. $langs->load("categories");
  3276. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  3277. // For backward compatibility
  3278. if (is_numeric($type))
  3279. {
  3280. dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  3281. }
  3282. if ($type === Categorie::TYPE_BANK_LINE)
  3283. {
  3284. // TODO Move this into common category feature
  3285. $categids=array();
  3286. $sql = "SELECT c.label, c.rowid";
  3287. $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
  3288. $sql.= " WHERE entity = ".$conf->entity;
  3289. $sql.= " ORDER BY c.label";
  3290. $result = $this->db->query($sql);
  3291. if ($result)
  3292. {
  3293. $num = $this->db->num_rows($result);
  3294. $i = 0;
  3295. while ($i < $num)
  3296. {
  3297. $objp = $this->db->fetch_object($result);
  3298. if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  3299. $i++;
  3300. }
  3301. $this->db->free($result);
  3302. }
  3303. else dol_print_error($this->db);
  3304. }
  3305. else
  3306. {
  3307. $cat = new Categorie($this->db);
  3308. $cate_arbo = $cat->get_full_arbo($type, $excludeafterid);
  3309. }
  3310. $output = '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  3311. $outarray=array();
  3312. if (is_array($cate_arbo))
  3313. {
  3314. if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  3315. else
  3316. {
  3317. $output.= '<option value="-1">&nbsp;</option>';
  3318. foreach($cate_arbo as $key => $value)
  3319. {
  3320. if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
  3321. {
  3322. $add = 'selected ';
  3323. }
  3324. else
  3325. {
  3326. $add = '';
  3327. }
  3328. $output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
  3329. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  3330. }
  3331. }
  3332. }
  3333. $output.= '</select>';
  3334. $output.= "\n";
  3335. if ($outputmode) return $outarray;
  3336. return $output;
  3337. }
  3338. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3339. /**
  3340. * Show a confirmation HTML form or AJAX popup
  3341. *
  3342. * @param string $page Url of page to call if confirmation is OK
  3343. * @param string $title Title
  3344. * @param string $question Question
  3345. * @param string $action Action
  3346. * @param array $formquestion An array with forms complementary inputs
  3347. * @param string $selectedchoice "" or "no" or "yes"
  3348. * @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
  3349. * @param int $height Force height of box
  3350. * @param int $width Force width of box
  3351. * @return void
  3352. * @deprecated
  3353. * @see formconfirm()
  3354. */
  3355. function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
  3356. {
  3357. // phpcs:enable
  3358. dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  3359. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  3360. }
  3361. /**
  3362. * Show a confirmation HTML form or AJAX popup.
  3363. * Easiest way to use this is with useajax=1.
  3364. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  3365. * just after calling this method. For example:
  3366. * print '<script type="text/javascript">'."\n";
  3367. * print 'jQuery(document).ready(function() {'."\n";
  3368. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  3369. * print '});'."\n";
  3370. * print '</script>'."\n";
  3371. *
  3372. * @param string $page Url of page to call if confirmation is OK. Can contains paramaters (param 'action' and 'confirm' will be reformated)
  3373. * @param string $title Title
  3374. * @param string $question Question
  3375. * @param string $action Action
  3376. * @param array $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
  3377. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', ...
  3378. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  3379. * @param int $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
  3380. * @param int $height Force height of box
  3381. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  3382. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  3383. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  3384. */
  3385. function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=210, $width=500, $disableformtag=0)
  3386. {
  3387. global $langs,$conf;
  3388. global $useglobalvars;
  3389. $more='';
  3390. $formconfirm='';
  3391. $inputok=array();
  3392. $inputko=array();
  3393. // Clean parameters
  3394. $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
  3395. if ($conf->browser->layout == 'phone') $width='95%';
  3396. if (is_array($formquestion) && ! empty($formquestion))
  3397. {
  3398. // First add hidden fields and value
  3399. foreach ($formquestion as $key => $input)
  3400. {
  3401. if (is_array($input) && ! empty($input))
  3402. {
  3403. if ($input['type'] == 'hidden')
  3404. {
  3405. $more.='<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  3406. }
  3407. }
  3408. }
  3409. // Now add questions
  3410. $more.='<table class="paddingtopbottomonly" width="100%">'."\n";
  3411. if (! empty($formquestion['text'])) $more.='<tr><td colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  3412. foreach ($formquestion as $key => $input)
  3413. {
  3414. if (is_array($input) && ! empty($input))
  3415. {
  3416. $size=(! empty($input['size'])?' size="'.$input['size'].'"':'');
  3417. $moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:'');
  3418. $morecss=(! empty($input['morecss'])?' '.$input['morecss']:'');
  3419. if ($input['type'] == 'text')
  3420. {
  3421. $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="text" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
  3422. }
  3423. elseif ($input['type'] == 'password')
  3424. {
  3425. $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="password" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
  3426. }
  3427. elseif ($input['type'] == 'select')
  3428. {
  3429. $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
  3430. if (! empty($input['label'])) $more.=$input['label'].'</td><td class="tdtop" align="left">';
  3431. $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss);
  3432. $more.='</td></tr>'."\n";
  3433. }
  3434. elseif ($input['type'] == 'checkbox')
  3435. {
  3436. $more.='<tr>';
  3437. $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].' </td><td align="left">';
  3438. $more.='<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
  3439. if (! is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more.=' checked';
  3440. if (is_bool($input['value']) && $input['value']) $more.=' checked';
  3441. if (isset($input['disabled'])) $more.=' disabled';
  3442. $more.=' /></td>';
  3443. $more.='</tr>'."\n";
  3444. }
  3445. elseif ($input['type'] == 'radio')
  3446. {
  3447. $i=0;
  3448. foreach($input['values'] as $selkey => $selval)
  3449. {
  3450. $more.='<tr>';
  3451. if ($i==0) $more.='<td'.(empty($input['tdclass'])?' class="tdtop"':(' class="tdtop '.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
  3452. else $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>&nbsp;</td>';
  3453. $more.='<td><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
  3454. if ($input['disabled']) $more.=' disabled';
  3455. $more.=' /> ';
  3456. $more.=$selval;
  3457. $more.='</td></tr>'."\n";
  3458. $i++;
  3459. }
  3460. }
  3461. elseif ($input['type'] == 'date')
  3462. {
  3463. $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
  3464. $more.='<td align="left">';
  3465. $more.=$this->selectDate($input['value'],$input['name'],0,0,0,'',1,0);
  3466. $more.='</td></tr>'."\n";
  3467. $formquestion[] = array('name'=>$input['name'].'day');
  3468. $formquestion[] = array('name'=>$input['name'].'month');
  3469. $formquestion[] = array('name'=>$input['name'].'year');
  3470. $formquestion[] = array('name'=>$input['name'].'hour');
  3471. $formquestion[] = array('name'=>$input['name'].'min');
  3472. }
  3473. elseif ($input['type'] == 'other')
  3474. {
  3475. $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
  3476. if (! empty($input['label'])) $more.=$input['label'].'</td><td align="left">';
  3477. $more.=$input['value'];
  3478. $more.='</td></tr>'."\n";
  3479. }
  3480. elseif ($input['type'] == 'onecolumn')
  3481. {
  3482. $more.='<tr><td colspan="2" align="left">';
  3483. $more.=$input['value'];
  3484. $more.='</td></tr>'."\n";
  3485. }
  3486. }
  3487. }
  3488. $more.='</table>'."\n";
  3489. }
  3490. // JQUI method dialog is broken with jmobile, we use standard HTML.
  3491. // 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
  3492. // See page product/card.php for example
  3493. if (! empty($conf->dol_use_jmobile)) $useajax=0;
  3494. if (empty($conf->use_javascript_ajax)) $useajax=0;
  3495. if ($useajax)
  3496. {
  3497. $autoOpen=true;
  3498. $dialogconfirm='dialog-confirm';
  3499. $button='';
  3500. if (! is_numeric($useajax))
  3501. {
  3502. $button=$useajax;
  3503. $useajax=1;
  3504. $autoOpen=false;
  3505. $dialogconfirm.='-'.$button;
  3506. }
  3507. $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';
  3508. $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':'');
  3509. // Add input fields into list of fields to read during submit (inputok and inputko)
  3510. if (is_array($formquestion))
  3511. {
  3512. foreach ($formquestion as $key => $input)
  3513. {
  3514. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  3515. if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
  3516. if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
  3517. }
  3518. }
  3519. // Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
  3520. $formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  3521. if (! empty($more)) {
  3522. $formconfirm.= '<div class="confirmquestions">'.$more.'</div>';
  3523. }
  3524. $formconfirm.= ($question ? '<div class="confirmmessage">'.img_help('','').' '.$question . '</div>': '');
  3525. $formconfirm.= '</div>'."\n";
  3526. $formconfirm.= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
  3527. $formconfirm.= '<script type="text/javascript">'."\n";
  3528. $formconfirm.= 'jQuery(document).ready(function() {
  3529. $(function() {
  3530. $( "#'.$dialogconfirm.'" ).dialog(
  3531. {
  3532. autoOpen: '.($autoOpen ? "true" : "false").',';
  3533. if ($newselectedchoice == 'no')
  3534. {
  3535. $formconfirm.='
  3536. open: function() {
  3537. $(this).parent().find("button.ui-button:eq(2)").focus();
  3538. },';
  3539. }
  3540. $formconfirm.='
  3541. resizable: false,
  3542. height: "'.$height.'",
  3543. width: "'.$width.'",
  3544. modal: true,
  3545. closeOnEscape: false,
  3546. buttons: {
  3547. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  3548. var options="";
  3549. var inputok = '.json_encode($inputok).';
  3550. var pageyes = "'.dol_escape_js(! empty($pageyes)?$pageyes:'').'";
  3551. if (inputok.length>0) {
  3552. $.each(inputok, function(i, inputname) {
  3553. var more = "";
  3554. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3555. if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
  3556. var inputvalue = $("#" + inputname + more).val();
  3557. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3558. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  3559. });
  3560. }
  3561. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  3562. //alert(urljump);
  3563. if (pageyes.length > 0) { location.href = urljump; }
  3564. $(this).dialog("close");
  3565. },
  3566. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  3567. var options = "";
  3568. var inputko = '.json_encode($inputko).';
  3569. var pageno="'.dol_escape_js(! empty($pageno)?$pageno:'').'";
  3570. if (inputko.length>0) {
  3571. $.each(inputko, function(i, inputname) {
  3572. var more = "";
  3573. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3574. var inputvalue = $("#" + inputname + more).val();
  3575. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3576. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  3577. });
  3578. }
  3579. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  3580. //alert(urljump);
  3581. if (pageno.length > 0) { location.href = urljump; }
  3582. $(this).dialog("close");
  3583. }
  3584. }
  3585. }
  3586. );
  3587. var button = "'.$button.'";
  3588. if (button.length > 0) {
  3589. $( "#" + button ).click(function() {
  3590. $("#'.$dialogconfirm.'").dialog("open");
  3591. });
  3592. }
  3593. });
  3594. });
  3595. </script>';
  3596. $formconfirm.= "<!-- end ajax formconfirm -->\n";
  3597. }
  3598. else
  3599. {
  3600. $formconfirm.= "\n<!-- begin formconfirm page=".$page." -->\n";
  3601. if (empty($disableformtag)) $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  3602. $formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  3603. if (empty($disableformtag)) $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
  3604. $formconfirm.= '<table width="100%" class="valid">'."\n";
  3605. // Line title
  3606. $formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
  3607. // Line form fields
  3608. if ($more)
  3609. {
  3610. $formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
  3611. $formconfirm.=$more;
  3612. $formconfirm.='</td></tr>'."\n";
  3613. }
  3614. // Line with question
  3615. $formconfirm.= '<tr class="valid">';
  3616. $formconfirm.= '<td class="valid">'.$question.'</td>';
  3617. $formconfirm.= '<td class="valid">';
  3618. $formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
  3619. $formconfirm.= '</td>';
  3620. $formconfirm.= '<td class="valid" align="center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
  3621. $formconfirm.= '</tr>'."\n";
  3622. $formconfirm.= '</table>'."\n";
  3623. if (empty($disableformtag)) $formconfirm.= "</form>\n";
  3624. $formconfirm.= '<br>';
  3625. $formconfirm.= "<!-- end formconfirm -->\n";
  3626. }
  3627. return $formconfirm;
  3628. }
  3629. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3630. /**
  3631. * Show a form to select a project
  3632. *
  3633. * @param int $page Page
  3634. * @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)
  3635. * @param int $selected Id pre-selected project
  3636. * @param string $htmlname Name of select field
  3637. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  3638. * @param int $maxlength Max length
  3639. * @param int $forcefocus Force focus on field (works with javascript only)
  3640. * @param int $nooutput No print is done. String is returned.
  3641. * @return string Return html content
  3642. */
  3643. function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)
  3644. {
  3645. // phpcs:enable
  3646. global $langs;
  3647. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  3648. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  3649. $out='';
  3650. $formproject=new FormProjets($this->db);
  3651. $langs->load("project");
  3652. if ($htmlname != "none")
  3653. {
  3654. $out.="\n";
  3655. $out.='<form method="post" action="'.$page.'">';
  3656. $out.='<input type="hidden" name="action" value="classin">';
  3657. $out.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3658. $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  3659. $out.='<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3660. $out.='</form>';
  3661. }
  3662. else
  3663. {
  3664. if ($selected)
  3665. {
  3666. $projet = new Project($this->db);
  3667. $projet->fetch($selected);
  3668. //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
  3669. $out.=$projet->getNomUrl(0,'',1);
  3670. }
  3671. else
  3672. {
  3673. $out.="&nbsp;";
  3674. }
  3675. }
  3676. if (empty($nooutput))
  3677. {
  3678. print $out;
  3679. return '';
  3680. }
  3681. return $out;
  3682. }
  3683. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3684. /**
  3685. * Show a form to select payment conditions
  3686. *
  3687. * @param int $page Page
  3688. * @param string $selected Id condition pre-selectionne
  3689. * @param string $htmlname Name of select html field
  3690. * @param int $addempty Add empty entry
  3691. * @return void
  3692. */
  3693. function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
  3694. {
  3695. // phpcs:enable
  3696. global $langs;
  3697. if ($htmlname != "none")
  3698. {
  3699. print '<form method="post" action="'.$page.'">';
  3700. print '<input type="hidden" name="action" value="setconditions">';
  3701. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3702. $this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
  3703. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3704. print '</form>';
  3705. }
  3706. else
  3707. {
  3708. if ($selected)
  3709. {
  3710. $this->load_cache_conditions_paiements();
  3711. print $this->cache_conditions_paiements[$selected]['label'];
  3712. } else {
  3713. print "&nbsp;";
  3714. }
  3715. }
  3716. }
  3717. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3718. /**
  3719. * Show a form to select a delivery delay
  3720. *
  3721. * @param int $page Page
  3722. * @param string $selected Id condition pre-selectionne
  3723. * @param string $htmlname Name of select html field
  3724. * @param int $addempty Ajoute entree vide
  3725. * @return void
  3726. */
  3727. function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
  3728. {
  3729. // phpcs:enable
  3730. global $langs;
  3731. if ($htmlname != "none")
  3732. {
  3733. print '<form method="post" action="'.$page.'">';
  3734. print '<input type="hidden" name="action" value="setavailability">';
  3735. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3736. $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
  3737. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3738. print '</form>';
  3739. }
  3740. else
  3741. {
  3742. if ($selected)
  3743. {
  3744. $this->load_cache_availability();
  3745. print $this->cache_availability[$selected]['label'];
  3746. } else {
  3747. print "&nbsp;";
  3748. }
  3749. }
  3750. }
  3751. /**
  3752. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3753. * List found into table c_input_reason loaded by loadCacheInputReason
  3754. *
  3755. * @param string $page Page
  3756. * @param string $selected Id condition pre-selectionne
  3757. * @param string $htmlname Name of select html field
  3758. * @param int $addempty Add empty entry
  3759. * @return void
  3760. */
  3761. function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)
  3762. {
  3763. global $langs;
  3764. if ($htmlname != "none")
  3765. {
  3766. print '<form method="post" action="'.$page.'">';
  3767. print '<input type="hidden" name="action" value="setdemandreason">';
  3768. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3769. $this->selectInputReason($selected,$htmlname,-1,$addempty);
  3770. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3771. print '</form>';
  3772. }
  3773. else
  3774. {
  3775. if ($selected)
  3776. {
  3777. $this->loadCacheInputReason();
  3778. foreach ($this->cache_demand_reason as $key => $val)
  3779. {
  3780. if ($val['id'] == $selected)
  3781. {
  3782. print $val['label'];
  3783. break;
  3784. }
  3785. }
  3786. } else {
  3787. print "&nbsp;";
  3788. }
  3789. }
  3790. }
  3791. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3792. /**
  3793. * Show a form + html select a date
  3794. *
  3795. * @param string $page Page
  3796. * @param string $selected Date preselected
  3797. * @param string $htmlname Html name of date input fields or 'none'
  3798. * @param int $displayhour Display hour selector
  3799. * @param int $displaymin Display minutes selector
  3800. * @param int $nooutput 1=No print output, return string
  3801. * @return string
  3802. * @see selectDate
  3803. */
  3804. function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)
  3805. {
  3806. // phpcs:enable
  3807. global $langs;
  3808. $ret='';
  3809. if ($htmlname != "none")
  3810. {
  3811. $ret.='<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
  3812. $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
  3813. $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3814. $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3815. $ret.='<tr><td>';
  3816. $ret.=$this->selectDate($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0);
  3817. $ret.='</td>';
  3818. $ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3819. $ret.='</tr></table></form>';
  3820. }
  3821. else
  3822. {
  3823. if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
  3824. else $ret.=dol_print_date($selected,'day');
  3825. }
  3826. if (empty($nooutput)) print $ret;
  3827. return $ret;
  3828. }
  3829. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3830. /**
  3831. * Show a select form to choose a user
  3832. *
  3833. * @param string $page Page
  3834. * @param string $selected Id of user preselected
  3835. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  3836. * @param array $exclude List of users id to exclude
  3837. * @param array $include List of users id to include
  3838. * @return void
  3839. */
  3840. function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
  3841. {
  3842. // phpcs:enable
  3843. global $langs;
  3844. if ($htmlname != "none")
  3845. {
  3846. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  3847. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  3848. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3849. print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
  3850. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3851. print '</form>';
  3852. }
  3853. else
  3854. {
  3855. if ($selected)
  3856. {
  3857. require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
  3858. $theuser=new User($this->db);
  3859. $theuser->fetch($selected);
  3860. print $theuser->getNomUrl(1);
  3861. } else {
  3862. print "&nbsp;";
  3863. }
  3864. }
  3865. }
  3866. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3867. /**
  3868. * Show form with payment mode
  3869. *
  3870. * @param string $page Page
  3871. * @param int $selected Id mode pre-selectionne
  3872. * @param string $htmlname Name of select html field
  3873. * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
  3874. * @param int $active Active or not, -1 = all
  3875. * @param int $addempty 1=Add empty entry
  3876. * @return void
  3877. */
  3878. function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1, $addempty=0)
  3879. {
  3880. // phpcs:enable
  3881. global $langs;
  3882. if ($htmlname != "none")
  3883. {
  3884. print '<form method="POST" action="'.$page.'">';
  3885. print '<input type="hidden" name="action" value="setmode">';
  3886. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3887. $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active);
  3888. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3889. print '</form>';
  3890. }
  3891. else
  3892. {
  3893. if ($selected)
  3894. {
  3895. $this->load_cache_types_paiements();
  3896. print $this->cache_types_paiements[$selected]['label'];
  3897. } else {
  3898. print "&nbsp;";
  3899. }
  3900. }
  3901. }
  3902. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3903. /**
  3904. * Show form with multicurrency code
  3905. *
  3906. * @param string $page Page
  3907. * @param string $selected code pre-selectionne
  3908. * @param string $htmlname Name of select html field
  3909. * @return void
  3910. */
  3911. function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
  3912. {
  3913. // phpcs:enable
  3914. global $langs;
  3915. if ($htmlname != "none")
  3916. {
  3917. print '<form method="POST" action="'.$page.'">';
  3918. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  3919. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3920. print $this->selectMultiCurrency($selected, $htmlname, 0);
  3921. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3922. print '</form>';
  3923. }
  3924. else
  3925. {
  3926. dol_include_once('/core/lib/company.lib.php');
  3927. print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
  3928. }
  3929. }
  3930. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3931. /**
  3932. * Show form with multicurrency rate
  3933. *
  3934. * @param string $page Page
  3935. * @param double $rate Current rate
  3936. * @param string $htmlname Name of select html field
  3937. * @param string $currency Currency code to explain the rate
  3938. * @return void
  3939. */
  3940. function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
  3941. {
  3942. // phpcs:enable
  3943. global $langs, $mysoc, $conf;
  3944. if ($htmlname != "none")
  3945. {
  3946. print '<form method="POST" action="'.$page.'">';
  3947. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  3948. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3949. print '<input type="text" name="'.$htmlname.'" value="'.(!empty($rate) ? price($rate) : 1).'" size="10" /> ';
  3950. print '<select name="calculation_mode">';
  3951. print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
  3952. print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
  3953. print '</select> ';
  3954. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3955. print '</form>';
  3956. }
  3957. else
  3958. {
  3959. if (! empty($rate))
  3960. {
  3961. print price($rate, 1, $langs, 1, 0);
  3962. if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  3963. }
  3964. else
  3965. {
  3966. print 1;
  3967. }
  3968. }
  3969. }
  3970. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3971. /**
  3972. * Show a select box with available absolute discounts
  3973. *
  3974. * @param string $page Page URL where form is shown
  3975. * @param int $selected Value pre-selected
  3976. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  3977. * @param int $socid Third party id
  3978. * @param float $amount Total amount available
  3979. * @param string $filter SQL filter on discounts
  3980. * @param int $maxvalue Max value for lines that can be selected
  3981. * @param string $more More string to add
  3982. * @param int $hidelist 1=Hide list
  3983. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  3984. * @return void
  3985. */
  3986. function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0)
  3987. {
  3988. // phpcs:enable
  3989. global $conf,$langs;
  3990. if ($htmlname != "none")
  3991. {
  3992. print '<form method="post" action="'.$page.'">';
  3993. print '<input type="hidden" name="action" value="setabsolutediscount">';
  3994. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3995. print '<div class="inline-block">';
  3996. if(! empty($discount_type)) {
  3997. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  3998. {
  3999. if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4000. else $translationKey = 'HasCreditNoteFromSupplier';
  4001. }
  4002. else
  4003. {
  4004. if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
  4005. else $translationKey = 'HasCreditNoteFromSupplier';
  4006. }
  4007. } else {
  4008. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  4009. {
  4010. if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4011. else $translationKey = 'CompanyHasCreditNote';
  4012. }
  4013. else
  4014. {
  4015. if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
  4016. else $translationKey = 'CompanyHasCreditNote';
  4017. }
  4018. }
  4019. print $langs->trans($translationKey,price($amount,0,$langs,0,0,-1,$conf->currency));
  4020. if (empty($hidelist)) print ': ';
  4021. print '</div>';
  4022. if (empty($hidelist))
  4023. {
  4024. print '<div class="inline-block" style="padding-right: 10px">';
  4025. $newfilter = 'discount_type='.intval($discount_type);
  4026. if(! empty($discount_type)) {
  4027. $newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  4028. } else {
  4029. $newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  4030. }
  4031. if ($filter) $newfilter.=' AND ('.$filter.')';
  4032. $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
  4033. if ($nbqualifiedlines > 0)
  4034. {
  4035. print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  4036. if(! empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
  4037. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4038. if(empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
  4039. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4040. print '>';
  4041. }
  4042. print '</div>';
  4043. }
  4044. if ($more)
  4045. {
  4046. print '<div class="inline-block">';
  4047. print $more;
  4048. print '</div>';
  4049. }
  4050. print '</form>';
  4051. }
  4052. else
  4053. {
  4054. if ($selected)
  4055. {
  4056. print $selected;
  4057. }
  4058. else
  4059. {
  4060. print "0";
  4061. }
  4062. }
  4063. }
  4064. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  4065. /**
  4066. * Show forms to select a contact
  4067. *
  4068. * @param string $page Page
  4069. * @param Societe $societe Filter on third party
  4070. * @param int $selected Id contact pre-selectionne
  4071. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  4072. * @return void
  4073. */
  4074. function form_contacts($page, $societe, $selected='', $htmlname='contactid')
  4075. {
  4076. // phpcs:enable
  4077. global $langs, $conf;
  4078. if ($htmlname != "none")
  4079. {
  4080. print '<form method="post" action="'.$page.'">';
  4081. print '<input type="hidden" name="action" value="set_contact">';
  4082. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  4083. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  4084. print '<tr><td>';
  4085. $num=$this->select_contacts($societe->id, $selected, $htmlname);
  4086. if ($num==0)
  4087. {
  4088. $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  4089. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  4090. }
  4091. print '</td>';
  4092. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  4093. print '</tr></table></form>';
  4094. }
  4095. else
  4096. {
  4097. if ($selected)
  4098. {
  4099. require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
  4100. $contact=new Contact($this->db);
  4101. $contact->fetch($selected);
  4102. print $contact->getFullName($langs);
  4103. } else {
  4104. print "&nbsp;";
  4105. }
  4106. }
  4107. }
  4108. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  4109. /**
  4110. * Output html select to select thirdparty
  4111. *
  4112. * @param string $page Page
  4113. * @param string $selected Id preselected
  4114. * @param string $htmlname Name of HTML select
  4115. * @param string $filter optional filters criteras
  4116. * @param int $showempty Add an empty field
  4117. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  4118. * @param int $forcecombo Force to use combo box
  4119. * @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')))
  4120. * @param int $nooutput No print output. Return it only.
  4121. * @return void
  4122. */
  4123. function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array(), $nooutput=0)
  4124. {
  4125. // phpcs:enable
  4126. global $langs;
  4127. $out = '';
  4128. if ($htmlname != "none")
  4129. {
  4130. $out.='<form method="post" action="'.$page.'">';
  4131. $out.= '<input type="hidden" name="action" value="set_thirdparty">';
  4132. $out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  4133. $out.= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
  4134. $out.= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4135. $out.= '</form>';
  4136. }
  4137. else
  4138. {
  4139. if ($selected)
  4140. {
  4141. require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
  4142. $soc = new Societe($this->db);
  4143. $soc->fetch($selected);
  4144. $out.= $soc->getNomUrl($langs);
  4145. }
  4146. else
  4147. {
  4148. $out.= "&nbsp;";
  4149. }
  4150. }
  4151. if ($nooutput) return $out;
  4152. else print $out;
  4153. }
  4154. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  4155. /**
  4156. * Retourne la liste des devises, dans la langue de l'utilisateur
  4157. *
  4158. * @param string $selected preselected currency code
  4159. * @param string $htmlname name of HTML select list
  4160. * @deprecated
  4161. * @return void
  4162. */
  4163. function select_currency($selected='',$htmlname='currency_id')
  4164. {
  4165. // phpcs:enable
  4166. print $this->selectCurrency($selected,$htmlname);
  4167. }
  4168. /**
  4169. * Retourne la liste des devises, dans la langue de l'utilisateur
  4170. *
  4171. * @param string $selected preselected currency code
  4172. * @param string $htmlname name of HTML select list
  4173. * @return string
  4174. */
  4175. function selectCurrency($selected='',$htmlname='currency_id')
  4176. {
  4177. global $conf,$langs,$user;
  4178. $langs->loadCacheCurrencies('');
  4179. $out='';
  4180. if ($selected=='euro' || $selected=='euros') $selected='EUR'; // Pour compatibilite
  4181. $out.= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  4182. foreach ($langs->cache_currencies as $code_iso => $currency)
  4183. {
  4184. if ($selected && $selected == $code_iso)
  4185. {
  4186. $out.= '<option value="'.$code_iso.'" selected>';
  4187. }
  4188. else
  4189. {
  4190. $out.= '<option value="'.$code_iso.'">';
  4191. }
  4192. $out.= $currency['label'];
  4193. $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
  4194. $out.= '</option>';
  4195. }
  4196. $out.= '</select>';
  4197. if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  4198. // Make select dynamic
  4199. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  4200. $out .= ajax_combobox($htmlname);
  4201. return $out;
  4202. }
  4203. /**
  4204. * Return array of currencies in user language
  4205. *
  4206. * @param string $selected preselected currency code
  4207. * @param string $htmlname name of HTML select list
  4208. * @param integer $useempty 1=Add empty line
  4209. * @return string
  4210. */
  4211. function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)
  4212. {
  4213. global $db,$conf,$langs,$user;
  4214. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  4215. $TCurrency = array();
  4216. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
  4217. $sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  4218. $resql = $db->query($sql);
  4219. if ($resql)
  4220. {
  4221. while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
  4222. }
  4223. $out='';
  4224. $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  4225. if ($useempty) $out .= '<option value=""></option>';
  4226. // If company current currency not in table, we add it into list. Should always be available.
  4227. if (! in_array($conf->currency, $TCurrency))
  4228. {
  4229. $TCurrency[$conf->currency] = $conf->currency;
  4230. }
  4231. if (count($TCurrency) > 0)
  4232. {
  4233. foreach ($langs->cache_currencies as $code_iso => $currency)
  4234. {
  4235. if (isset($TCurrency[$code_iso]))
  4236. {
  4237. if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
  4238. else $out.= '<option value="'.$code_iso.'">';
  4239. $out.= $currency['label'];
  4240. $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
  4241. $out.= '</option>';
  4242. }
  4243. }
  4244. }
  4245. $out.= '</select>';
  4246. // Make select dynamic
  4247. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  4248. $out.= ajax_combobox($htmlname);
  4249. return $out;
  4250. }
  4251. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  4252. /**
  4253. * Load into the cache vat rates of a country
  4254. *
  4255. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  4256. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  4257. */
  4258. function load_cache_vatrates($country_code)
  4259. {
  4260. // phpcs:enable
  4261. global $langs;
  4262. $num = count($this->cache_vatrates);
  4263. if ($num > 0) return $num; // Cache already loaded
  4264. dol_syslog(__METHOD__, LOG_DEBUG);
  4265. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  4266. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4267. $sql.= " WHERE t.fk_pays = c.rowid";
  4268. $sql.= " AND t.active > 0";
  4269. $sql.= " AND c.code IN (".$country_code.")";
  4270. $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  4271. $resql=$this->db->query($sql);
  4272. if ($resql)
  4273. {
  4274. $num = $this->db->num_rows($resql);
  4275. if ($num)
  4276. {
  4277. for ($i = 0; $i < $num; $i++)
  4278. {
  4279. $obj = $this->db->fetch_object($resql);
  4280. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  4281. $this->cache_vatrates[$i]['code'] = $obj->code;
  4282. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  4283. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  4284. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  4285. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  4286. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  4287. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  4288. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or *
  4289. $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
  4290. $positiverates='';
  4291. if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;
  4292. if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;
  4293. if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;
  4294. if (empty($positiverates)) $positiverates='0';
  4295. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label
  4296. }
  4297. return $num;
  4298. }
  4299. else
  4300. {
  4301. $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
  4302. return -1;
  4303. }
  4304. }
  4305. else
  4306. {
  4307. $this->error = '<font class="error">'.$this->db->error().'</font>';
  4308. return -2;
  4309. }
  4310. }
  4311. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  4312. /**
  4313. * Output an HTML select vat rate.
  4314. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  4315. *
  4316. * @param string $htmlname Name of HTML select field
  4317. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  4318. * @param Societe $societe_vendeuse Thirdparty seller
  4319. * @param Societe $societe_acheteuse Thirdparty buyer
  4320. * @param int $idprod Id product. O if unknown of NA.
  4321. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  4322. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  4323. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4324. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4325. * 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.
  4326. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  4327. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  4328. * Sinon la TVA proposee par defaut=0. Fin de regle.
  4329. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  4330. * @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
  4331. * @return string
  4332. */
  4333. function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)
  4334. {
  4335. // phpcs:enable
  4336. global $langs,$conf,$mysoc;
  4337. $langs->load('errors');
  4338. $return='';
  4339. // Define defaultnpr, defaultttx and defaultcode
  4340. $defaultnpr=($info_bits & 0x01);
  4341. $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
  4342. $defaulttx=str_replace('*','',$selectedrate);
  4343. $defaultcode='';
  4344. if (preg_match('/\((.*)\)/', $defaulttx, $reg))
  4345. {
  4346. $defaultcode=$reg[1];
  4347. $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
  4348. }
  4349. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  4350. // Check parameters
  4351. if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
  4352. {
  4353. if ($societe_vendeuse->id == $mysoc->id)
  4354. {
  4355. $return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
  4356. }
  4357. else
  4358. {
  4359. $return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
  4360. }
  4361. return $return;
  4362. }
  4363. //var_dump($societe_acheteuse);
  4364. //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";
  4365. //exit;
  4366. // Define list of countries to use to search VAT rates to show
  4367. // First we defined code_country to use to find list
  4368. if (is_object($societe_vendeuse))
  4369. {
  4370. $code_country="'".$societe_vendeuse->country_code."'";
  4371. }
  4372. else
  4373. {
  4374. $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  4375. }
  4376. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on
  4377. {
  4378. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4379. if (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany())))
  4380. {
  4381. // We also add the buyer
  4382. if (is_numeric($type))
  4383. {
  4384. if ($type == 1) // We know product is a service
  4385. {
  4386. $code_country.=",'".$societe_acheteuse->country_code."'";
  4387. }
  4388. }
  4389. else if (! $idprod) // We don't know type of product
  4390. {
  4391. $code_country.=",'".$societe_acheteuse->country_code."'";
  4392. }
  4393. else
  4394. {
  4395. $prodstatic=new Product($this->db);
  4396. $prodstatic->fetch($idprod);
  4397. if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service
  4398. {
  4399. $code_country.=",'".$societe_acheteuse->country_code."'";
  4400. }
  4401. }
  4402. }
  4403. }
  4404. // Now we get list
  4405. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  4406. if ($num > 0)
  4407. {
  4408. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  4409. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4410. {
  4411. $tmpthirdparty=new Societe($this->db);
  4412. $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
  4413. $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
  4414. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  4415. $defaultcode=$reg[1];
  4416. $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
  4417. }
  4418. if (empty($defaulttx)) $defaultnpr=0;
  4419. }
  4420. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  4421. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  4422. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4423. {
  4424. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
  4425. else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  4426. }
  4427. // Disabled if seller is not subject to VAT
  4428. $disabled=false; $title='';
  4429. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
  4430. {
  4431. $title=' title="'.$langs->trans('VATIsNotUsed').'"';
  4432. $disabled=true;
  4433. }
  4434. if (! $options_only) $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
  4435. $selectedfound=false;
  4436. foreach ($this->cache_vatrates as $rate)
  4437. {
  4438. // Keep only 0 if seller is not subject to VAT
  4439. if ($disabled && $rate['txtva'] != 0) continue;
  4440. // Define key to use into select list
  4441. $key = $rate['txtva'];
  4442. $key.= $rate['nprtva'] ? '*': '';
  4443. if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';
  4444. if ($mode < 0) $key = $rate['rowid'];
  4445. $return.= '<option value="'.$key.'"';
  4446. if (! $selectedfound)
  4447. {
  4448. if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  4449. {
  4450. if ($defaultcode == $rate['code'])
  4451. {
  4452. $return.= ' selected';
  4453. $selectedfound=true;
  4454. }
  4455. }
  4456. elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
  4457. {
  4458. $return.= ' selected';
  4459. $selectedfound=true;
  4460. }
  4461. }
  4462. $return.= '>';
  4463. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  4464. if ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
  4465. {
  4466. $return.= $rate['labelpositiverates'];
  4467. }
  4468. else
  4469. {
  4470. $return.= vatrate($rate['label']);
  4471. }
  4472. //$return.=($rate['code']?' '.$rate['code']:'');
  4473. $return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': ''; // We show the * (old behaviour only if new vat code is not used)
  4474. $return.= '</option>';
  4475. }
  4476. if (! $options_only) $return.= '</select>';
  4477. }
  4478. else
  4479. {
  4480. $return.= $this->error;
  4481. }
  4482. $this->num = $num;
  4483. return $return;
  4484. }
  4485. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  4486. /**
  4487. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4488. * Fields are preselected with :
  4489. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4490. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4491. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4492. *
  4493. * @param timestamp $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).
  4494. * @param string $prefix Prefix for fields name
  4495. * @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
  4496. * @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
  4497. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4498. * @param string $form_name Not used
  4499. * @param int $d 1=Show days, month, years
  4500. * @param int $addnowlink Add a link "Now"
  4501. * @param int $nooutput Do not output html string but return it
  4502. * @param int $disabled Disable input fields
  4503. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  4504. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  4505. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  4506. * @return string|void Nothing or string if nooutput is 1
  4507. * @deprecated
  4508. * @see form_date, select_month, select_year, select_dayofweek
  4509. */
  4510. 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='')
  4511. {
  4512. // phpcs:enable
  4513. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  4514. if (! empty($nooutput)) {
  4515. return $retstring;
  4516. }
  4517. print $retstring;
  4518. return;
  4519. }
  4520. /**
  4521. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4522. * Fields are preselected with :
  4523. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4524. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4525. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4526. *
  4527. * @param timestamp $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).
  4528. * @param string $prefix Prefix for fields name
  4529. * @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
  4530. * @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
  4531. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4532. * @param string $form_name Not used
  4533. * @param int $d 1=Show days, month, years
  4534. * @param int $addnowlink Add a link "Now"
  4535. * @param int $disabled Disable input fields
  4536. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  4537. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  4538. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  4539. * @return string Html for selectDate
  4540. * @see form_date, select_month, select_year, select_dayofweek
  4541. */
  4542. function selectDate($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
  4543. {
  4544. global $conf,$langs;
  4545. $retstring='';
  4546. if ($prefix=='') $prefix='re';
  4547. if ($h == '') $h=0;
  4548. if ($m == '') $m=0;
  4549. $emptydate=0;
  4550. $emptyhours=0;
  4551. if ($empty == 1) { $emptydate=1; $emptyhours=1; }
  4552. if ($empty == 2) { $emptydate=0; $emptyhours=1; }
  4553. $orig_set_time=$set_time;
  4554. if ($set_time === '' && $emptydate == 0)
  4555. {
  4556. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4557. $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone
  4558. }
  4559. // Analysis of the pre-selection date
  4560. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg)) // deprecated usage
  4561. {
  4562. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  4563. $syear = (! empty($reg[1])?$reg[1]:'');
  4564. $smonth = (! empty($reg[2])?$reg[2]:'');
  4565. $sday = (! empty($reg[3])?$reg[3]:'');
  4566. $shour = (! empty($reg[4])?$reg[4]:'');
  4567. $smin = (! empty($reg[5])?$reg[5]:'');
  4568. }
  4569. elseif (strval($set_time) != '' && $set_time != -1)
  4570. {
  4571. // set_time est un timestamps (0 possible)
  4572. $syear = dol_print_date($set_time, "%Y");
  4573. $smonth = dol_print_date($set_time, "%m");
  4574. $sday = dol_print_date($set_time, "%d");
  4575. if ($orig_set_time != '')
  4576. {
  4577. $shour = dol_print_date($set_time, "%H");
  4578. $smin = dol_print_date($set_time, "%M");
  4579. $ssec = dol_print_date($set_time, "%S");
  4580. }
  4581. else
  4582. {
  4583. $shour = '';
  4584. $smin = '';
  4585. $ssec = '';
  4586. }
  4587. }
  4588. else
  4589. {
  4590. // Date est '' ou vaut -1
  4591. $syear = '';
  4592. $smonth = '';
  4593. $sday = '';
  4594. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  4595. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  4596. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  4597. }
  4598. if ($h == 3) $shour = '';
  4599. if ($m == 3) $smin = '';
  4600. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  4601. $usecalendar='combo';
  4602. if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  4603. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR);
  4604. }
  4605. if ($d)
  4606. {
  4607. // Show date with popup
  4608. if ($usecalendar != 'combo')
  4609. {
  4610. $formated_date='';
  4611. //print "e".$set_time." t ".$conf->format_date_short;
  4612. if (strval($set_time) != '' && $set_time != -1)
  4613. {
  4614. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  4615. $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4616. }
  4617. // Calendrier popup version eldy
  4618. if ($usecalendar == "eldy")
  4619. {
  4620. // Zone de saisie manuelle de la date
  4621. $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
  4622. $retstring.=($disabled?' disabled':'');
  4623. $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4624. $retstring.='>';
  4625. // Icone calendrier
  4626. if (! $disabled)
  4627. {
  4628. $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  4629. $base=DOL_URL_ROOT.'/core/';
  4630. $retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  4631. $retstring.='>'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
  4632. }
  4633. else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
  4634. $retstring.='<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  4635. $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  4636. $retstring.='<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  4637. }
  4638. elseif ($usecalendar == 'jquery')
  4639. {
  4640. if (! $disabled)
  4641. {
  4642. // Output javascript for datepicker
  4643. $retstring.="<script type='text/javascript'>";
  4644. $retstring.="$(function(){ $('#".$prefix."').datepicker({
  4645. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  4646. autoclose: true,
  4647. todayHighlight: true,";
  4648. if (! empty($conf->dol_use_jmobile))
  4649. {
  4650. $retstring.="
  4651. beforeShow: function (input, datePicker) {
  4652. input.disabled = true;
  4653. },
  4654. onClose: function (dateText, datePicker) {
  4655. this.disabled = false;
  4656. },
  4657. ";
  4658. }
  4659. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  4660. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))
  4661. {
  4662. $retstring.="
  4663. showOn: 'button',
  4664. buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
  4665. buttonImageOnly: true";
  4666. }
  4667. $retstring.="
  4668. }) });";
  4669. $retstring.="</script>";
  4670. }
  4671. // Zone de saisie manuelle de la date
  4672. $retstring.='<div class="nowrap inline-block">';
  4673. $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
  4674. $retstring.=($disabled?' disabled':'');
  4675. $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4676. $retstring.='>';
  4677. // Icone calendrier
  4678. if (! $disabled)
  4679. {
  4680. /* Not required. Managed by option buttonImage of jquery
  4681. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  4682. $retstring.="<script type='text/javascript'>";
  4683. $retstring.="jQuery(document).ready(function() {";
  4684. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  4685. $retstring.=" jQuery('#".$prefix."').focus();";
  4686. $retstring.=' });';
  4687. $retstring.='});';
  4688. $retstring.="</script>";*/
  4689. }
  4690. else
  4691. {
  4692. $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
  4693. }
  4694. $retstring.='</div>';
  4695. $retstring.='<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  4696. $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  4697. $retstring.='<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  4698. }
  4699. else
  4700. {
  4701. $retstring.="Bad value of MAIN_POPUP_CALENDAR";
  4702. }
  4703. }
  4704. // Show date with combo selects
  4705. else
  4706. {
  4707. //$retstring.='<div class="inline-block">';
  4708. // Day
  4709. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  4710. if ($emptydate || $set_time == -1)
  4711. {
  4712. $retstring.='<option value="0" selected>&nbsp;</option>';
  4713. }
  4714. for ($day = 1 ; $day <= 31; $day++)
  4715. {
  4716. $retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
  4717. }
  4718. $retstring.="</select>";
  4719. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  4720. if ($emptydate || $set_time == -1)
  4721. {
  4722. $retstring.='<option value="0" selected>&nbsp;</option>';
  4723. }
  4724. // Month
  4725. for ($month = 1 ; $month <= 12 ; $month++)
  4726. {
  4727. $retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
  4728. $retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
  4729. $retstring.="</option>";
  4730. }
  4731. $retstring.="</select>";
  4732. // Year
  4733. if ($emptydate || $set_time == -1)
  4734. {
  4735. $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.'">';
  4736. }
  4737. else
  4738. {
  4739. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  4740. for ($year = $syear - 10; $year < $syear + 10 ; $year++)
  4741. {
  4742. $retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
  4743. }
  4744. $retstring.="</select>\n";
  4745. }
  4746. //$retstring.='</div>';
  4747. }
  4748. }
  4749. if ($d && $h) $retstring.=($h==2?'<br>':' ');
  4750. if ($h)
  4751. {
  4752. // Show hour
  4753. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  4754. if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
  4755. for ($hour = 0; $hour < 24; $hour++)
  4756. {
  4757. if (strlen($hour) < 2) $hour = "0" . $hour;
  4758. $retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
  4759. }
  4760. $retstring.='</select>';
  4761. if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
  4762. }
  4763. if ($m)
  4764. {
  4765. // Show minutes
  4766. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  4767. if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
  4768. for ($min = 0; $min < 60 ; $min++)
  4769. {
  4770. if (strlen($min) < 2) $min = "0" . $min;
  4771. $retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
  4772. }
  4773. $retstring.='</select>';
  4774. $retstring.='<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  4775. }
  4776. // Add a "Now" link
  4777. if ($conf->use_javascript_ajax && $addnowlink)
  4778. {
  4779. // Script which will be inserted in the onClick of the "Now" link
  4780. $reset_scripts = "";
  4781. // Generate the date part, depending on the use or not of the javascript calendar
  4782. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
  4783. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
  4784. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
  4785. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
  4786. /*if ($usecalendar == "eldy")
  4787. {
  4788. $base=DOL_URL_ROOT.'/core/';
  4789. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  4790. }
  4791. else
  4792. {
  4793. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  4794. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  4795. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  4796. }*/
  4797. // Update the hour part
  4798. if ($h)
  4799. {
  4800. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4801. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  4802. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
  4803. if ($fullday) $reset_scripts .= ' } ';
  4804. }
  4805. // Update the minute part
  4806. if ($m)
  4807. {
  4808. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4809. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  4810. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
  4811. if ($fullday) $reset_scripts .= ' } ';
  4812. }
  4813. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  4814. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  4815. {
  4816. $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  4817. $retstring.=$langs->trans("Now");
  4818. $retstring.='</button> ';
  4819. }
  4820. }
  4821. // Add a "Plus one hour" link
  4822. if ($conf->use_javascript_ajax && $addplusone)
  4823. {
  4824. // Script which will be inserted in the onClick of the "Add plusone" link
  4825. $reset_scripts = "";
  4826. // Generate the date part, depending on the use or not of the javascript calendar
  4827. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
  4828. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
  4829. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
  4830. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
  4831. // Update the hour part
  4832. if ($h)
  4833. {
  4834. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4835. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
  4836. if ($fullday) $reset_scripts .= ' } ';
  4837. }
  4838. // Update the minute part
  4839. if ($m)
  4840. {
  4841. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4842. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
  4843. if ($fullday) $reset_scripts .= ' } ';
  4844. }
  4845. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  4846. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  4847. {
  4848. $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  4849. $retstring.=$langs->trans("DateStartPlusOne");
  4850. $retstring.='</button> ';
  4851. }
  4852. }
  4853. // Add a "Plus one hour" link
  4854. if ($conf->use_javascript_ajax && $adddateof)
  4855. {
  4856. $tmparray=dol_getdate($adddateof);
  4857. $retstring.=' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof,'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$langs->trans("DateInvoice").'</a>';
  4858. }
  4859. return $retstring;
  4860. }
  4861. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  4862. /**
  4863. * Function to show a form to select a duration on a page
  4864. *
  4865. * @param string $prefix Prefix for input fields
  4866. * @param int $iSecond Default preselected duration (number of seconds or '')
  4867. * @param int $disabled Disable the combo box
  4868. * @param string $typehour If 'select' then input hour and input min is a combo,
  4869. * if 'text' input hour is in text and input min is a text,
  4870. * if 'textselect' input hour is in text and input min is a combo
  4871. * @param integer $minunderhours If 1, show minutes selection under the hours
  4872. * @param int $nooutput Do not output html string but return it
  4873. * @return string|void
  4874. */
  4875. function select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)
  4876. {
  4877. // phpcs:enable
  4878. global $langs;
  4879. $retstring='';
  4880. $hourSelected=0; $minSelected=0;
  4881. // Hours
  4882. if ($iSecond != '')
  4883. {
  4884. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4885. $hourSelected = convertSecondToTime($iSecond,'allhour');
  4886. $minSelected = convertSecondToTime($iSecond,'min');
  4887. }
  4888. if ($typehour=='select' )
  4889. {
  4890. $retstring.='<select class="flat" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
  4891. for ($hour = 0; $hour < 25; $hour++) // For a duration, we allow 24 hours
  4892. {
  4893. $retstring.='<option value="'.$hour.'"';
  4894. if ($hourSelected == $hour)
  4895. {
  4896. $retstring.=" selected";
  4897. }
  4898. $retstring.=">".$hour."</option>";
  4899. }
  4900. $retstring.="</select>";
  4901. }
  4902. elseif ($typehour=='text' || $typehour=='textselect')
  4903. {
  4904. $retstring.='<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '')?((int) $hourSelected):'').'">';
  4905. }
  4906. else return 'BadValueForParameterTypeHour';
  4907. if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');
  4908. else $retstring.='<span class="hideonsmartphone">:</span>';
  4909. // Minutes
  4910. if ($minunderhours) $retstring.='<br>';
  4911. else $retstring.='<span class="hideonsmartphone">&nbsp;</span>';
  4912. if ($typehour=='select' || $typehour=='textselect')
  4913. {
  4914. $retstring.='<select class="flat" name="'.$prefix.'min"'.($disabled?' disabled':'').'>';
  4915. for ($min = 0; $min <= 55; $min=$min+5)
  4916. {
  4917. $retstring.='<option value="'.$min.'"';
  4918. if ($minSelected == $min) $retstring.=' selected';
  4919. $retstring.='>'.$min.'</option>';
  4920. }
  4921. $retstring.="</select>";
  4922. }
  4923. elseif ($typehour=='text' )
  4924. {
  4925. $retstring.='<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '')?((int) $minSelected):'').'">';
  4926. }
  4927. if ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');
  4928. //$retstring.="&nbsp;";
  4929. if (! empty($nooutput)) return $retstring;
  4930. print $retstring;
  4931. return;
  4932. }
  4933. /**
  4934. * Generic method to select a component from a combo list.
  4935. * This is the generic method that will replace all specific existing methods.
  4936. *
  4937. * @param string $objectdesc Objectclassname:Objectclasspath
  4938. * @param string $htmlname Name of HTML select component
  4939. * @param int $preselectedvalue Preselected value (ID of element)
  4940. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  4941. * @param string $searchkey Search criteria
  4942. * @param string $placeholder Place holder
  4943. * @param string $morecss More CSS
  4944. * @param string $moreparams More params provided to ajax call
  4945. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  4946. * @return string Return HTML string
  4947. * @see selectForFormsList select_thirdparty
  4948. */
  4949. function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0)
  4950. {
  4951. global $conf, $user;
  4952. $objecttmp = null;
  4953. $InfoFieldList = explode(":", $objectdesc);
  4954. $classname=$InfoFieldList[0];
  4955. $classpath=$InfoFieldList[1];
  4956. if (! empty($classpath))
  4957. {
  4958. dol_include_once($classpath);
  4959. if ($classname && class_exists($classname))
  4960. {
  4961. $objecttmp = new $classname($this->db);
  4962. }
  4963. }
  4964. if (! is_object($objecttmp))
  4965. {
  4966. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  4967. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  4968. }
  4969. $prefixforautocompletemode=$objecttmp->element;
  4970. if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
  4971. $confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  4972. dol_syslog(get_class($this)."::selectForForms", LOG_DEBUG);
  4973. $out='';
  4974. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->$confkeyforautocompletemode) && ! $forcecombo)
  4975. {
  4976. $objectdesc=$classname.':'.$classpath;
  4977. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  4978. //if ($objecttmp->element == 'societe') $urlforajaxcall = DOL_URL_ROOT.'/societe/ajax/company.php';
  4979. // No immediate load of all database
  4980. $urloption='htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams?$moreparams:'');
  4981. // Activate the auto complete using ajax call.
  4982. $out.= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  4983. $out.= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
  4984. if ($placeholder) $placeholder=' placeholder="'.$placeholder.'"';
  4985. $out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$preselectedvalue.'"'.$placeholder.' />';
  4986. }
  4987. else
  4988. {
  4989. // Immediate load of all database
  4990. $out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);
  4991. }
  4992. return $out;
  4993. }
  4994. /**
  4995. * Output html form to select an object.
  4996. * Note, this function is called by selectForForms or by ajax selectobject.php
  4997. *
  4998. * @param Object $objecttmp Object
  4999. * @param string $htmlname Name of HTML select component
  5000. * @param int $preselectedvalue Preselected value (ID of element)
  5001. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  5002. * @param string $searchkey Search value
  5003. * @param string $placeholder Place holder
  5004. * @param string $morecss More CSS
  5005. * @param string $moreparams More params provided to ajax call
  5006. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  5007. * @param int $outputmode 0=HTML select string, 1=Array
  5008. * @return string Return HTML string
  5009. * @see selectForForms
  5010. */
  5011. function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0)
  5012. {
  5013. global $conf, $langs, $user;
  5014. $prefixforautocompletemode=$objecttmp->element;
  5015. if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
  5016. $confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  5017. $fieldstoshow='t.ref';
  5018. if (! empty($objecttmp->fields)) // For object that declare it, it is better to use declared fields ( like societe, contact, ...)
  5019. {
  5020. $tmpfieldstoshow='';
  5021. foreach($objecttmp->fields as $key => $val)
  5022. {
  5023. if ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;
  5024. }
  5025. if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
  5026. }
  5027. $out='';
  5028. $outarray=array();
  5029. $num=0;
  5030. // Search data
  5031. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX .$objecttmp->table_element." as t";
  5032. if ($objecttmp->ismultientitymanaged == 2)
  5033. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  5034. $sql.= " WHERE 1=1";
  5035. if(! empty($objecttmp->ismultientitymanaged)) $sql.= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  5036. if ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id))
  5037. {
  5038. if ($objecttmp->element == 'societe') $sql.= " AND t.rowid = ".$user->societe_id;
  5039. else $sql.= " AND t.fk_soc = ".$user->societe_id;
  5040. }
  5041. if ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);
  5042. if ($objecttmp->ismultientitymanaged == 2)
  5043. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND t.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
  5044. $sql.=$this->db->order($fieldstoshow,"ASC");
  5045. //$sql.=$this->db->plimit($limit, 0);
  5046. // Build output string
  5047. $resql=$this->db->query($sql);
  5048. if ($resql)
  5049. {
  5050. if (! $forcecombo)
  5051. {
  5052. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5053. $out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);
  5054. }
  5055. // Construct $out and $outarray
  5056. $out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparams?' '.$moreparams:'').' name="'.$htmlname.'">'."\n";
  5057. // 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
  5058. $textifempty='&nbsp;';
  5059. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  5060. if (! empty($conf->global->$confkeyforautocompletemode))
  5061. {
  5062. if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
  5063. else $textifempty.=$langs->trans("All");
  5064. }
  5065. if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
  5066. $num = $this->db->num_rows($resql);
  5067. $i = 0;
  5068. if ($num)
  5069. {
  5070. while ($i < $num)
  5071. {
  5072. $obj = $this->db->fetch_object($resql);
  5073. $label='';
  5074. $tmparray=explode(',', $fieldstoshow);
  5075. foreach($tmparray as $key => $val)
  5076. {
  5077. $val = preg_replace('/t\./','',$val);
  5078. $label .= (($label && $obj->$val)?' - ':'').$obj->$val;
  5079. }
  5080. if (empty($outputmode))
  5081. {
  5082. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
  5083. {
  5084. $out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  5085. }
  5086. else
  5087. {
  5088. $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  5089. }
  5090. }
  5091. else
  5092. {
  5093. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  5094. }
  5095. $i++;
  5096. if (($i % 10) == 0) $out.="\n";
  5097. }
  5098. }
  5099. $out.= '</select>'."\n";
  5100. }
  5101. else
  5102. {
  5103. dol_print_error($this->db);
  5104. }
  5105. $this->result=array('nbofelement'=>$num);
  5106. if ($outputmode) return $outarray;
  5107. return $out;
  5108. }
  5109. /**
  5110. * Return a HTML select string, built from an array of key+value.
  5111. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  5112. *
  5113. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  5114. * @param array $array Array (key => value)
  5115. * @param string|string[] $id Preselected key or preselected keys for multiselect
  5116. * @param int|string $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.
  5117. * @param int $key_in_label 1 to show key into label with format "[key] value"
  5118. * @param int $value_as_key 1 to use value as key
  5119. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  5120. * @param int $translate 1=Translate and encode value
  5121. * @param int $maxlen Length maximum for labels
  5122. * @param int $disabled Html select box is disabled
  5123. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  5124. * @param string $morecss Add more class to css styles
  5125. * @param int $addjscombo Add js combo
  5126. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  5127. * @param int $disablebademail Check if an email is found into value and if not disable and colorize entry
  5128. * @param int $nohtmlescape No html escaping.
  5129. * @return string HTML select string.
  5130. * @see multiselectarray, selectArrayAjax, selectArrayFilter
  5131. */
  5132. static function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='', $addjscombo=0, $moreparamonempty='',$disablebademail=0, $nohtmlescape=0)
  5133. {
  5134. global $conf, $langs;
  5135. // Do we want a multiselect ?
  5136. //$jsbeautify = 0;
  5137. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  5138. $jsbeautify = 1;
  5139. if ($value_as_key) $array=array_combine($array, $array);
  5140. $out='';
  5141. // Add code for jquery to use multiselect
  5142. if ($addjscombo && $jsbeautify)
  5143. {
  5144. $minLengthToAutocomplete=0;
  5145. $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
  5146. // Enhance with select2
  5147. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5148. $out .= ajax_combobox($htmlname);
  5149. }
  5150. $out.='<select id="'.preg_replace('/^\./','',$htmlname).'" '.($disabled?'disabled ':'').'class="flat '.(preg_replace('/^\./','',$htmlname)).($morecss?' '.$morecss:'').'"';
  5151. $out.=' name="'.preg_replace('/^\./','',$htmlname).'" '.($moreparam?$moreparam:'');
  5152. $out.='>';
  5153. if ($show_empty)
  5154. {
  5155. $textforempty=' ';
  5156. if (! empty($conf->use_javascript_ajax)) $textforempty='&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  5157. if (! is_numeric($show_empty)) $textforempty=$show_empty;
  5158. $out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
  5159. }
  5160. if (is_array($array))
  5161. {
  5162. // Translate
  5163. if ($translate)
  5164. {
  5165. foreach($array as $key => $value)
  5166. {
  5167. $array[$key]=$langs->trans($value);
  5168. }
  5169. }
  5170. // Sort
  5171. if ($sort == 'ASC') asort($array);
  5172. elseif ($sort == 'DESC') arsort($array);
  5173. foreach($array as $key => $value)
  5174. {
  5175. $disabled=''; $style='';
  5176. if (! empty($disablebademail))
  5177. {
  5178. if (! preg_match('/&lt;.+@.+&gt;/', $value))
  5179. {
  5180. //$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);
  5181. $disabled=' disabled';
  5182. $style=' class="warning"';
  5183. }
  5184. }
  5185. if ($key_in_label)
  5186. {
  5187. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
  5188. else $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
  5189. }
  5190. else
  5191. {
  5192. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
  5193. else $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
  5194. if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
  5195. }
  5196. $out.='<option value="'.$key.'"';
  5197. $out.=$style.$disabled;
  5198. if ($id != '' && $id == $key && ! $disabled) $out.=' selected'; // To preselect a value
  5199. if ($nohtmlescape) $out.=' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  5200. $out.='>';
  5201. //var_dump($selectOptionValue);
  5202. $out.=$selectOptionValue;
  5203. $out.="</option>\n";
  5204. }
  5205. }
  5206. $out.="</select>";
  5207. return $out;
  5208. }
  5209. /**
  5210. * 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.
  5211. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  5212. *
  5213. * @param string $htmlname Name of html select area
  5214. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  5215. * @param string $id Preselected key
  5216. * @param string $moreparam Add more parameters onto the select tag
  5217. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  5218. * @param int $disabled Html select box is disabled
  5219. * @param int $minimumInputLength Minimum Input Length
  5220. * @param string $morecss Add more class to css styles
  5221. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  5222. * @param string $placeholder String to use as placeholder
  5223. * @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)
  5224. * @return string HTML select string
  5225. * @see selectArrayFilter, ajax_combobox in ajax.lib.php
  5226. */
  5227. static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
  5228. {
  5229. global $conf, $langs;
  5230. global $delayedhtmlcontent;
  5231. // TODO Use an internal dolibarr component instead of select2
  5232. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
  5233. $out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"></select>';
  5234. $tmpplugin='select2';
  5235. $outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  5236. <script type="text/javascript">
  5237. $(document).ready(function () {
  5238. '.($callurlonselect ? 'var saveRemoteData = [];':'').'
  5239. $(".'.$htmlname.'").select2({
  5240. ajax: {
  5241. dir: "ltr",
  5242. url: "'.$url.'",
  5243. dataType: \'json\',
  5244. delay: 250,
  5245. data: function (params) {
  5246. return {
  5247. q: params.term, // search term
  5248. page: params.page
  5249. };
  5250. },
  5251. processResults: function (data) {
  5252. // parse the results into the format expected by Select2.
  5253. // since we are using custom formatting functions we do not need to alter the remote JSON data
  5254. //console.log(data);
  5255. saveRemoteData = data;
  5256. /* format json result for select2 */
  5257. result = []
  5258. $.each( data, function( key, value ) {
  5259. result.push({id: key, text: value.text});
  5260. });
  5261. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  5262. //console.log(result);
  5263. return {results: result, more: false}
  5264. },
  5265. cache: true
  5266. },
  5267. language: select2arrayoflanguage,
  5268. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  5269. placeholder: "'.dol_escape_js($placeholder).'",
  5270. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  5271. minimumInputLength: '.$minimumInputLength.',
  5272. formatResult: function(result, container, query, escapeMarkup) {
  5273. return escapeMarkup(result.text);
  5274. },
  5275. });
  5276. '.($callurlonselect ? '
  5277. /* Code to execute a GET when we select a value */
  5278. $(".'.$htmlname.'").change(function() {
  5279. var selected = $(".'.$htmlname.'").val();
  5280. console.log("We select in selectArrayAjax the entry "+selected)
  5281. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  5282. $.each( saveRemoteData, function( key, value ) {
  5283. if (key == selected)
  5284. {
  5285. console.log("selectArrayAjax - Do a redirect to "+value.url)
  5286. location.assign(value.url);
  5287. }
  5288. });
  5289. });' : '' ) . '
  5290. });
  5291. </script>';
  5292. if ($acceptdelayedhtml)
  5293. {
  5294. $delayedhtmlcontent.=$outdelayed;
  5295. }
  5296. else
  5297. {
  5298. $out.=$outdelayed;
  5299. }
  5300. return $out;
  5301. }
  5302. /**
  5303. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  5304. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  5305. *
  5306. * @param string $htmlname Name of html select area
  5307. * @param string $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  5308. * @param string $id Preselected key
  5309. * @param string $moreparam Add more parameters onto the select tag
  5310. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  5311. * @param int $disabled Html select box is disabled
  5312. * @param int $minimumInputLength Minimum Input Length
  5313. * @param string $morecss Add more class to css styles
  5314. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  5315. * @param string $placeholder String to use as placeholder
  5316. * @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)
  5317. * @return string HTML select string
  5318. * @see selectArrayAjax, ajax_combobox in ajax.lib.php
  5319. */
  5320. static function selectArrayFilter($htmlname, $array, $id='', $moreparam='', $disableFiltering=0, $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
  5321. {
  5322. global $conf, $langs;
  5323. global $delayedhtmlcontent;
  5324. // TODO Use an internal dolibarr component instead of select2
  5325. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
  5326. $out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"><option></option></select>';
  5327. $formattedarrayresult = array();
  5328. foreach($array as $key => $value) {
  5329. $o = new stdClass();
  5330. $o->id = $key;
  5331. $o->text = $value['text'];
  5332. $o->url = $value['url'];
  5333. $formattedarrayresult[] = $o;
  5334. }
  5335. $tmpplugin='select2';
  5336. $outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  5337. <script type="text/javascript">
  5338. $(document).ready(function () {
  5339. var data = '.json_encode($formattedarrayresult).';
  5340. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';':'').'
  5341. $(".'.$htmlname.'").select2({
  5342. data: data,
  5343. language: select2arrayoflanguage,
  5344. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  5345. placeholder: "'.dol_escape_js($placeholder).'",
  5346. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  5347. minimumInputLength: '.$minimumInputLength.',
  5348. formatResult: function(result, container, query, escapeMarkup) {
  5349. return escapeMarkup(result.text);
  5350. },
  5351. matcher: function (params, data) {
  5352. if(! data.id) return null;';
  5353. if($callurlonselect) {
  5354. $outdelayed.='
  5355. var urlBase = data.url;
  5356. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  5357. /* console.log("params.term="+params.term); */
  5358. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  5359. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term);';
  5360. }
  5361. if(! $disableFiltering) {
  5362. $outdelayed.='
  5363. if(data.text.match(new RegExp(params.term))) {
  5364. return data;
  5365. }
  5366. return null;';
  5367. } else {
  5368. $outdelayed.='
  5369. return data;';
  5370. }
  5371. $outdelayed.='
  5372. }
  5373. });
  5374. '.($callurlonselect ? '
  5375. /* Code to execute a GET when we select a value */
  5376. $(".'.$htmlname.'").change(function() {
  5377. var selected = $(".'.$htmlname.'").val();
  5378. console.log("We select "+selected)
  5379. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  5380. $.each( saveRemoteData, function( key, value ) {
  5381. if (key == selected)
  5382. {
  5383. console.log("selectArrayAjax - Do a redirect to "+value.url)
  5384. location.assign(value.url);
  5385. }
  5386. });
  5387. });' : '' ) . '
  5388. });
  5389. </script>';
  5390. if ($acceptdelayedhtml)
  5391. {
  5392. $delayedhtmlcontent.=$outdelayed;
  5393. }
  5394. else
  5395. {
  5396. $out.=$outdelayed;
  5397. }
  5398. return $out;
  5399. }
  5400. /**
  5401. * Show a multiselect form from an array.
  5402. *
  5403. * @param string $htmlname Name of select
  5404. * @param array $array Array with key+value
  5405. * @param array $selected Array with key+value preselected
  5406. * @param int $key_in_label 1 pour afficher la key dans la valeur "[key] value"
  5407. * @param int $value_as_key 1 to use value as key
  5408. * @param string $morecss Add more css style
  5409. * @param int $translate Translate and encode value
  5410. * @param int $width Force width of select box. May be used only when using jquery couch. Example: 250, 95%
  5411. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  5412. * @param string $elemtype Type of element we show ('category', ...)
  5413. * @param string $placeholder String to use as placeholder
  5414. * @param int $addjscombo Add js combo
  5415. * @return string HTML multiselect string
  5416. * @see selectarray, selectArrayAjax, selectArrayFilter
  5417. */
  5418. 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)
  5419. {
  5420. global $conf, $langs;
  5421. $out = '';
  5422. if ($addjscombo < 0) {
  5423. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $addjscombo = 1;
  5424. else $addjscombo = 0;
  5425. }
  5426. // Add code for jquery to use multiselect
  5427. if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
  5428. {
  5429. $out.="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  5430. <script type="text/javascript">'."\n";
  5431. if ($addjscombo == 1)
  5432. {
  5433. $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
  5434. $out.= 'function formatResult(record) {'."\n";
  5435. if ($elemtype == 'category')
  5436. {
  5437. $out.=' //return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
  5438. return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
  5439. }
  5440. else
  5441. {
  5442. $out.='return record.text;';
  5443. }
  5444. $out.= '};'."\n";
  5445. $out.= 'function formatSelection(record) {'."\n";
  5446. if ($elemtype == 'category')
  5447. {
  5448. $out.=' //return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
  5449. return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
  5450. }
  5451. else
  5452. {
  5453. $out.='return record.text;';
  5454. }
  5455. $out.= '};'."\n";
  5456. $out.= '$(document).ready(function () {
  5457. $(\'#'.$htmlname.'\').'.$tmpplugin.'({
  5458. dir: \'ltr\',
  5459. // Specify format function for dropdown item
  5460. formatResult: formatResult,
  5461. templateResult: formatResult, /* For 4.0 */
  5462. // Specify format function for selected item
  5463. formatSelection: formatSelection,
  5464. templateResult: formatSelection /* For 4.0 */
  5465. });
  5466. });'."\n";
  5467. }
  5468. elseif ($addjscombo == 2)
  5469. {
  5470. // Add other js lib
  5471. // ...
  5472. $out.= '$(document).ready(function () {
  5473. $(\'#'.$htmlname.'\').multiSelect({
  5474. containerHTML: \'<div class="multi-select-container">\',
  5475. menuHTML: \'<div class="multi-select-menu">\',
  5476. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  5477. menuItemHTML: \'<label class="multi-select-menuitem">\',
  5478. activeClass: \'multi-select-container--open\',
  5479. noneText: \''.$placeholder.'\'
  5480. });
  5481. })';
  5482. }
  5483. $out.= '</script>';
  5484. }
  5485. // Try also magic suggest
  5486. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
  5487. if (is_array($array) && ! empty($array))
  5488. {
  5489. if ($value_as_key) $array=array_combine($array, $array);
  5490. if (! empty($array))
  5491. {
  5492. foreach ($array as $key => $value)
  5493. {
  5494. $out.= '<option value="'.$key.'"';
  5495. if (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))
  5496. {
  5497. $out.= ' selected';
  5498. }
  5499. $out.= '>';
  5500. $newval = ($translate ? $langs->trans($value) : $value);
  5501. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  5502. $out.= dol_htmlentitiesbr($newval);
  5503. $out.= '</option>'."\n";
  5504. }
  5505. }
  5506. }
  5507. $out.= '</select>'."\n";
  5508. return $out;
  5509. }
  5510. /**
  5511. * Show a multiselect dropbox from an array.
  5512. *
  5513. * @param string $htmlname Name of HTML field
  5514. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  5515. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  5516. * @return string HTML multiselect string
  5517. * @see selectarray
  5518. */
  5519. static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  5520. {
  5521. global $conf,$langs,$user;
  5522. if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
  5523. $tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
  5524. if (! empty($user->conf->$tmpvar))
  5525. {
  5526. $tmparray=explode(',', $user->conf->$tmpvar);
  5527. foreach($array as $key => $val)
  5528. {
  5529. //var_dump($key);
  5530. //var_dump($tmparray);
  5531. if (in_array($key, $tmparray)) $array[$key]['checked']=1;
  5532. else $array[$key]['checked']=0;
  5533. }
  5534. }
  5535. //var_dump($array);
  5536. $lis='';
  5537. $listcheckedstring='';
  5538. foreach($array as $key => $val)
  5539. {
  5540. /* var_dump($val);
  5541. var_dump(array_key_exists('enabled', $val));
  5542. var_dump(!$val['enabled']);*/
  5543. if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
  5544. {
  5545. unset($array[$key]); // We don't want this field
  5546. continue;
  5547. }
  5548. if ($val['label'])
  5549. {
  5550. $lis.='<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
  5551. $listcheckedstring.=(empty($val['checked'])?'':$key.',');
  5552. }
  5553. }
  5554. $out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  5555. <dl class="dropdown">
  5556. <dt>
  5557. <a href="#">
  5558. '.img_picto('','list').'
  5559. </a>
  5560. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  5561. </dt>
  5562. <dd class="dropdowndd">
  5563. <div class="multiselectcheckbox'.$htmlname.'">
  5564. <ul class="ul'.$htmlname.'">
  5565. '.$lis.'
  5566. </ul>
  5567. </div>
  5568. </dd>
  5569. </dl>
  5570. <script type="text/javascript">
  5571. jQuery(document).ready(function () {
  5572. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  5573. console.log("A new field was added/removed")
  5574. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\')
  5575. var title = $(this).val() + ",";
  5576. if ($(this).is(\':checked\')) {
  5577. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  5578. }
  5579. else {
  5580. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  5581. }
  5582. // Now, we submit page
  5583. $(this).parents(\'form:first\').submit();
  5584. });
  5585. });
  5586. </script>
  5587. ';
  5588. return $out;
  5589. }
  5590. /**
  5591. * Render list of categories linked to object with id $id and type $type
  5592. *
  5593. * @param int $id Id of object
  5594. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  5595. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  5596. * @return string String with categories
  5597. */
  5598. function showCategories($id, $type, $rendermode=0)
  5599. {
  5600. global $db;
  5601. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  5602. $cat = new Categorie($db);
  5603. $categories = $cat->containing($id, $type);
  5604. if ($rendermode == 1)
  5605. {
  5606. $toprint = array();
  5607. foreach($categories as $c)
  5608. {
  5609. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  5610. foreach($ways as $way)
  5611. {
  5612. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color?' style="background: #'.$c->color.';"':' style="background: #aaa"').'>'.img_object('','category').' '.$way.'</li>';
  5613. }
  5614. }
  5615. return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5616. }
  5617. if ($rendermode == 0)
  5618. {
  5619. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  5620. foreach($categories as $c) {
  5621. $arrayselected[] = $c->id;
  5622. }
  5623. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  5624. }
  5625. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  5626. }
  5627. /**
  5628. * Show linked object block.
  5629. *
  5630. * @param CommonObject $object Object we want to show links to
  5631. * @param string $morehtmlright More html to show on right of title
  5632. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  5633. * @return int <0 if KO, >=0 if OK
  5634. */
  5635. function showLinkedObjectBlock($object, $morehtmlright='',$compatibleImportElementsList=false)
  5636. {
  5637. global $conf,$langs,$hookmanager;
  5638. global $bc;
  5639. $object->fetchObjectLinked();
  5640. // Bypass the default method
  5641. $hookmanager->initHooks(array('commonobject'));
  5642. $parameters=array(
  5643. 'morehtmlright' => $morehtmlright,
  5644. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  5645. );
  5646. $reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
  5647. if (empty($reshook))
  5648. {
  5649. $nbofdifferenttypes = count($object->linkedObjects);
  5650. print '<!-- showLinkedObjectBlock -->';
  5651. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  5652. print '<div class="div-table-responsive-no-min">';
  5653. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  5654. print '<tr class="liste_titre">';
  5655. print '<td>'.$langs->trans("Type").'</td>';
  5656. print '<td>'.$langs->trans("Ref").'</td>';
  5657. print '<td align="center"></td>';
  5658. print '<td align="center">'.$langs->trans("Date").'</td>';
  5659. print '<td align="right">'.$langs->trans("AmountHTShort").'</td>';
  5660. print '<td align="right">'.$langs->trans("Status").'</td>';
  5661. print '<td></td>';
  5662. print '</tr>';
  5663. $nboftypesoutput=0;
  5664. foreach($object->linkedObjects as $objecttype => $objects)
  5665. {
  5666. $tplpath = $element = $subelement = $objecttype;
  5667. // to display inport button on tpl
  5668. $showImportButton=false;
  5669. if(!empty($compatibleImportElementsList) && in_array($element,$compatibleImportElementsList)){
  5670. $showImportButton=true;
  5671. }
  5672. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
  5673. {
  5674. $element = $regs[1];
  5675. $subelement = $regs[2];
  5676. $tplpath = $element.'/'.$subelement;
  5677. }
  5678. $tplname='linkedobjectblock';
  5679. // To work with non standard path
  5680. if ($objecttype == 'facture') {
  5681. $tplpath = 'compta/'.$element;
  5682. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  5683. }
  5684. else if ($objecttype == 'facturerec') {
  5685. $tplpath = 'compta/facture';
  5686. $tplname = 'linkedobjectblockForRec';
  5687. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  5688. }
  5689. else if ($objecttype == 'propal') {
  5690. $tplpath = 'comm/'.$element;
  5691. if (empty($conf->propal->enabled)) continue; // Do not show if module disabled
  5692. }
  5693. else if ($objecttype == 'supplier_proposal') {
  5694. if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled
  5695. }
  5696. else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
  5697. $tplpath = 'expedition';
  5698. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  5699. }
  5700. else if ($objecttype == 'delivery') {
  5701. $tplpath = 'livraison';
  5702. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  5703. }
  5704. else if ($objecttype == 'invoice_supplier') {
  5705. $tplpath = 'fourn/facture';
  5706. }
  5707. else if ($objecttype == 'order_supplier') {
  5708. $tplpath = 'fourn/commande';
  5709. }
  5710. else if ($objecttype == 'expensereport') {
  5711. $tplpath = 'expensereport';
  5712. }
  5713. else if ($objecttype == 'subscription') {
  5714. $tplpath = 'adherents';
  5715. }
  5716. global $linkedObjectBlock;
  5717. $linkedObjectBlock = $objects;
  5718. // Output template part (modules that overwrite templates must declare this into descriptor)
  5719. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
  5720. foreach($dirtpls as $reldir)
  5721. {
  5722. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) // No more type to show after
  5723. {
  5724. global $noMoreLinkedObjectBlockAfter;
  5725. $noMoreLinkedObjectBlockAfter=1;
  5726. }
  5727. $res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  5728. if ($res)
  5729. {
  5730. $nboftypesoutput++;
  5731. break;
  5732. }
  5733. }
  5734. }
  5735. if (! $nboftypesoutput)
  5736. {
  5737. print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
  5738. }
  5739. print '</table>';
  5740. if(!empty($compatibleImportElementsList))
  5741. {
  5742. $res=@include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  5743. }
  5744. print '</div>';
  5745. return $nbofdifferenttypes;
  5746. }
  5747. }
  5748. /**
  5749. * Show block with links to link to other objects.
  5750. *
  5751. * @param CommonObject $object Object we want to show links to
  5752. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  5753. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  5754. * @return string <0 if KO, >0 if OK
  5755. */
  5756. function showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())
  5757. {
  5758. global $conf, $langs, $hookmanager;
  5759. global $bc;
  5760. $linktoelem='';
  5761. $linktoelemlist='';
  5762. $listofidcompanytoscan='';
  5763. if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
  5764. $possiblelinks=array();
  5765. if (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)
  5766. {
  5767. $listofidcompanytoscan=$object->thirdparty->id;
  5768. if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;
  5769. if (($object->fk_project > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
  5770. {
  5771. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  5772. $tmpproject=new Project($this->db);
  5773. $tmpproject->fetch($object->fk_project);
  5774. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan.=','.$tmpproject->socid;
  5775. unset($tmpproject);
  5776. }
  5777. $possiblelinks=array(
  5778. 'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),
  5779. 'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),
  5780. '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.facnumber as ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture').')'),
  5781. 'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture').')'),
  5782. 'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
  5783. 'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),
  5784. 'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled , 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
  5785. 'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled , 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
  5786. 'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled , 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')')
  5787. );
  5788. }
  5789. global $action;
  5790. // Can complete the possiblelink array
  5791. $hookmanager->initHooks(array('commonobject'));
  5792. $parameters=array('listofidcompanytoscan' => $listofidcompanytoscan);
  5793. $reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
  5794. if (empty($reshook))
  5795. {
  5796. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  5797. {
  5798. $possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);
  5799. }
  5800. }
  5801. else if ($reshook > 0)
  5802. {
  5803. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  5804. {
  5805. $possiblelinks=$hookmanager->resArray;
  5806. }
  5807. }
  5808. foreach($possiblelinks as $key => $possiblelink)
  5809. {
  5810. $num = 0;
  5811. if (empty($possiblelink['enabled'])) continue;
  5812. if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))
  5813. {
  5814. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax)?'':' style="display:none"').'>';
  5815. $sql = $possiblelink['sql'];
  5816. $resqllist = $this->db->query($sql);
  5817. if ($resqllist)
  5818. {
  5819. $num = $this->db->num_rows($resqllist);
  5820. $i = 0;
  5821. print '<br>';
  5822. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  5823. print '<input type="hidden" name="action" value="addlink">';
  5824. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  5825. print '<input type="hidden" name="id" value="'.$object->id.'">';
  5826. print '<input type="hidden" name="addlink" value="'.$key.'">';
  5827. print '<table class="noborder">';
  5828. print '<tr class="liste_titre">';
  5829. print '<td class="nowrap"></td>';
  5830. print '<td align="center">' . $langs->trans("Ref") . '</td>';
  5831. print '<td align="left">' . $langs->trans("RefCustomer") . '</td>';
  5832. print '<td align="right">' . $langs->trans("AmountHTShort") . '</td>';
  5833. print '<td align="left">' . $langs->trans("Company") . '</td>';
  5834. print '</tr>';
  5835. while ($i < $num)
  5836. {
  5837. $objp = $this->db->fetch_object($resqllist);
  5838. print '<tr class="oddeven">';
  5839. print '<td aling="left">';
  5840. print '<input type="radio" name="idtolinkto" value=' . $objp->rowid . '>';
  5841. print '</td>';
  5842. print '<td align="center">' . $objp->ref . '</td>';
  5843. print '<td>' . $objp->ref_client . '</td>';
  5844. print '<td align="right">' . price($objp->total_ht) . '</td>';
  5845. print '<td>' . $objp->name . '</td>';
  5846. print '</tr>';
  5847. $i++;
  5848. }
  5849. print '</table>';
  5850. print '<div class="center"><input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
  5851. print '</form>';
  5852. $this->db->free($resqllist);
  5853. } else {
  5854. dol_print_error($this->db);
  5855. }
  5856. print '</div>';
  5857. if ($num > 0)
  5858. {
  5859. }
  5860. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  5861. if ($num > 0) $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
  5862. //else $linktoelem.=$langs->trans($possiblelink['label']);
  5863. else $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
  5864. }
  5865. }
  5866. if ($linktoelemlist)
  5867. {
  5868. $linktoelem='
  5869. <dl class="dropdown" id="linktoobjectname">
  5870. ';
  5871. if (! empty($conf->use_javascript_ajax)) $linktoelem.='<dt><a href="#linktoobjectname">'.$langs->trans("LinkTo").'...</a></dt>';
  5872. $linktoelem.='<dd>
  5873. <div class="multiselectlinkto">
  5874. <ul class="ulselectedfields">'.$linktoelemlist.'
  5875. </ul>
  5876. </div>
  5877. </dd>
  5878. </dl>';
  5879. }
  5880. else
  5881. {
  5882. $linktoelem='';
  5883. }
  5884. if (! empty($conf->use_javascript_ajax))
  5885. {
  5886. print '<!-- Add js to show linkto box -->
  5887. <script type="text/javascript" language="javascript">
  5888. jQuery(document).ready(function() {
  5889. jQuery(".linkto").click(function() {
  5890. console.log("We choose to show/hide link for rel="+jQuery(this).attr(\'rel\'));
  5891. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  5892. jQuery(this).toggle();
  5893. });
  5894. });
  5895. </script>
  5896. ';
  5897. }
  5898. return $linktoelem;
  5899. }
  5900. /**
  5901. * Return an html string with a select combo box to choose yes or no
  5902. *
  5903. * @param string $htmlname Name of html select field
  5904. * @param string $value Pre-selected value
  5905. * @param int $option 0 return yes/no, 1 return 1/0
  5906. * @param bool $disabled true or false
  5907. * @param int $useempty 1=Add empty line
  5908. * @return string See option
  5909. */
  5910. function selectyesno($htmlname, $value='', $option=0, $disabled=false, $useempty=0)
  5911. {
  5912. global $langs;
  5913. $yes="yes"; $no="no";
  5914. if ($option)
  5915. {
  5916. $yes="1";
  5917. $no="0";
  5918. }
  5919. $disabled = ($disabled ? ' disabled' : '');
  5920. $resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  5921. if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'>&nbsp;</option>'."\n";
  5922. if (("$value" == 'yes') || ($value == 1))
  5923. {
  5924. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  5925. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  5926. }
  5927. else
  5928. {
  5929. $selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
  5930. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  5931. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  5932. }
  5933. $resultyesno .= '</select>'."\n";
  5934. return $resultyesno;
  5935. }
  5936. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  5937. /**
  5938. * Return list of export templates
  5939. *
  5940. * @param string $selected Id modele pre-selectionne
  5941. * @param string $htmlname Name of HTML select
  5942. * @param string $type Type of searched templates
  5943. * @param int $useempty Affiche valeur vide dans liste
  5944. * @return void
  5945. */
  5946. function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
  5947. {
  5948. // phpcs:enable
  5949. $sql = "SELECT rowid, label";
  5950. $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
  5951. $sql.= " WHERE type = '".$type."'";
  5952. $sql.= " ORDER BY rowid";
  5953. $result = $this->db->query($sql);
  5954. if ($result)
  5955. {
  5956. print '<select class="flat" name="'.$htmlname.'">';
  5957. if ($useempty)
  5958. {
  5959. print '<option value="-1">&nbsp;</option>';
  5960. }
  5961. $num = $this->db->num_rows($result);
  5962. $i = 0;
  5963. while ($i < $num)
  5964. {
  5965. $obj = $this->db->fetch_object($result);
  5966. if ($selected == $obj->rowid)
  5967. {
  5968. print '<option value="'.$obj->rowid.'" selected>';
  5969. }
  5970. else
  5971. {
  5972. print '<option value="'.$obj->rowid.'">';
  5973. }
  5974. print $obj->label;
  5975. print '</option>';
  5976. $i++;
  5977. }
  5978. print "</select>";
  5979. }
  5980. else {
  5981. dol_print_error($this->db);
  5982. }
  5983. }
  5984. /**
  5985. * Return a HTML area with the reference of object and a navigation bar for a business object
  5986. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  5987. *
  5988. * @param object $object Object to show.
  5989. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  5990. * @param string $morehtml More html content to output just before the nav bar.
  5991. * @param int $shownav Show Condition (navigation is shown if value is 1).
  5992. * @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.
  5993. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  5994. * @param string $morehtmlref More html to show after ref.
  5995. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  5996. * @param int $nodbprefix Do not include DB prefix to forge table name.
  5997. * @param string $morehtmlleft More html code to show before ref.
  5998. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  5999. * @param string $morehtmlright More html code to show after ref.
  6000. * @return string Portion HTML with ref + navigation buttons
  6001. */
  6002. function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')
  6003. {
  6004. global $langs,$conf,$hookmanager;
  6005. $ret='';
  6006. if (empty($fieldid)) $fieldid='rowid';
  6007. if (empty($fieldref)) $fieldref='ref';
  6008. // Add where from hooks
  6009. if (is_object($hookmanager))
  6010. {
  6011. $parameters=array();
  6012. $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters, $object); // Note that $action and $object may have been modified by hook
  6013. $object->next_prev_filter.=$hookmanager->resPrint;
  6014. }
  6015. $previous_ref = $next_ref = '';
  6016. if ($shownav)
  6017. {
  6018. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  6019. $object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''), $fieldid, $nodbprefix);
  6020. $navurl = $_SERVER["PHP_SELF"];
  6021. // Special case for project/task page
  6022. if ($paramid == 'project_ref')
  6023. {
  6024. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/','/tasks.php',$navurl);
  6025. $paramid='ref';
  6026. }
  6027. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  6028. // accesskey is for Mac: CTRL + key for all browsers
  6029. $previous_ref = $object->ref_previous?'<a accesskey="p" title="'.$langs->trans("KeyboardShortcut").' ALT+p|ALT+SHIFT+p|CTRL+p" 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>';
  6030. $next_ref = $object->ref_next?'<a accesskey="n" title="'.$langs->trans("KeyboardShortcut").' ALT+n|ALT+SHIFT+n|CTRL+n" 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>';
  6031. }
  6032. //print "xx".$previous_ref."x".$next_ref;
  6033. $ret.='<!-- Start banner content --><div style="vertical-align: middle">';
  6034. // Right part of banner
  6035. if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  6036. if ($previous_ref || $next_ref || $morehtml)
  6037. {
  6038. $ret.='<div class="pagination paginationref"><ul class="right">';
  6039. }
  6040. if ($morehtml)
  6041. {
  6042. $ret.='<li class="noborder litext">'.$morehtml.'</li>';
  6043. }
  6044. if ($shownav && ($previous_ref || $next_ref))
  6045. {
  6046. $ret.='<li class="pagination">'.$previous_ref.'</li>';
  6047. $ret.='<li class="pagination">'.$next_ref.'</li>';
  6048. }
  6049. if ($previous_ref || $next_ref || $morehtml)
  6050. {
  6051. $ret.='</ul></div>';
  6052. }
  6053. $parameters=array();
  6054. $reshook=$hookmanager->executeHooks('moreHtmlStatus',$parameters, $object); // Note that $action and $object may have been modified by hook
  6055. if (empty($reshook)) $morehtmlstatus.=$hookmanager->resPrint;
  6056. else $morehtmlstatus=$hookmanager->resPrint;
  6057. if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
  6058. $parameters = array();
  6059. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  6060. if (empty($reshook)) $morehtmlref.=$hookmanager->resPrint;
  6061. elseif ($reshook > 0) $morehtmlref=$hookmanager->resPrint;
  6062. // Left part of banner
  6063. if ($morehtmlleft)
  6064. {
  6065. if ($conf->browser->layout == 'phone') $ret.='<div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  6066. else $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  6067. }
  6068. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  6069. $ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
  6070. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  6071. if ($object->element == 'societe')
  6072. {
  6073. $ret.=dol_htmlentities($object->name);
  6074. }
  6075. else if ($object->element == 'member')
  6076. {
  6077. $ret.=$object->ref.'<br>';
  6078. $fullname=$object->getFullName($langs);
  6079. if ($object->morphy == 'mor' && $object->societe) {
  6080. $ret.= dol_htmlentities($object->societe) . ((! empty($fullname) && $object->societe != $fullname)?' ('.dol_htmlentities($fullname).')':'');
  6081. } else {
  6082. $ret.= dol_htmlentities($fullname) . ((! empty($object->societe) && $object->societe != $fullname)?' ('.dol_htmlentities($object->societe).')':'');
  6083. }
  6084. }
  6085. else if (in_array($object->element, array('contact', 'user', 'usergroup')))
  6086. {
  6087. $ret.=dol_htmlentities($object->getFullName($langs));
  6088. }
  6089. else if (in_array($object->element, array('action', 'agenda')))
  6090. {
  6091. $ret.=$object->ref.'<br>'.$object->label;
  6092. }
  6093. else if (in_array($object->element, array('adherent_type')))
  6094. {
  6095. $ret.=$object->label;
  6096. }
  6097. else if ($object->element == 'ecm_directories')
  6098. {
  6099. $ret.='';
  6100. }
  6101. else if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);
  6102. if ($morehtmlref)
  6103. {
  6104. $ret.=' '.$morehtmlref;
  6105. }
  6106. $ret.='</div>';
  6107. $ret.='</div><!-- End banner content -->';
  6108. return $ret;
  6109. }
  6110. /**
  6111. * Return HTML code to output a barcode
  6112. *
  6113. * @param Object $object Object containing data to retrieve file name
  6114. * @param int $width Width of photo
  6115. * @return string HTML code to output barcode
  6116. */
  6117. function showbarcode(&$object,$width=100)
  6118. {
  6119. global $conf;
  6120. //Check if barcode is filled in the card
  6121. if (empty($object->barcode)) return '';
  6122. // Complete object if not complete
  6123. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
  6124. {
  6125. $result = $object->fetch_barcode();
  6126. //Check if fetch_barcode() failed
  6127. if ($result < 1) return '<!-- ErrorFetchBarcode -->';
  6128. }
  6129. // Barcode image
  6130. $url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  6131. $out ='<!-- url barcode = '.$url.' -->';
  6132. $out.='<img src="'.$url.'">';
  6133. return $out;
  6134. }
  6135. /**
  6136. * Return HTML code to output a photo
  6137. *
  6138. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  6139. * @param object $object Object containing data to retrieve file name
  6140. * @param int $width Width of photo
  6141. * @param int $height Height of photo (auto if 0)
  6142. * @param int $caneditfield Add edit fields
  6143. * @param string $cssclass CSS name to use on img for photo
  6144. * @param string $imagesize 'mini', 'small' or '' (original)
  6145. * @param int $addlinktofullsize Add link to fullsize image
  6146. * @param int $cache 1=Accept to use image in cache
  6147. * @param string $forcecapture Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if empty.
  6148. * @return string HTML code to output photo
  6149. */
  6150. static function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='')
  6151. {
  6152. global $conf,$langs;
  6153. $entity = (! empty($object->entity) ? $object->entity : $conf->entity);
  6154. $id = (! empty($object->id) ? $object->id : $object->rowid);
  6155. $ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';$capture='';
  6156. if ($modulepart=='societe')
  6157. {
  6158. $dir=$conf->societe->multidir_output[$entity];
  6159. if (! empty($object->logo))
  6160. {
  6161. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  6162. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
  6163. else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  6164. $originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  6165. }
  6166. $email=$object->email;
  6167. }
  6168. else if ($modulepart=='contact')
  6169. {
  6170. $dir=$conf->societe->multidir_output[$entity].'/contact';
  6171. if (! empty($object->photo))
  6172. {
  6173. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
  6174. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
  6175. else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  6176. $originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  6177. }
  6178. $email=$object->email;
  6179. $capture='user';
  6180. }
  6181. else if ($modulepart=='userphoto')
  6182. {
  6183. $dir=$conf->user->dir_output;
  6184. if (! empty($object->photo))
  6185. {
  6186. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
  6187. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
  6188. else $file=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
  6189. $originalfile=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
  6190. }
  6191. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  6192. $email=$object->email;
  6193. $capture='user';
  6194. }
  6195. else if ($modulepart=='memberphoto')
  6196. {
  6197. $dir=$conf->adherent->dir_output;
  6198. if (! empty($object->photo))
  6199. {
  6200. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  6201. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  6202. else $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  6203. $originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  6204. }
  6205. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  6206. $email=$object->email;
  6207. $capture='user';
  6208. }
  6209. else
  6210. {
  6211. // Generic case to show photos
  6212. $dir=$conf->$modulepart->dir_output;
  6213. if (! empty($object->photo))
  6214. {
  6215. if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  6216. else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  6217. else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  6218. $originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  6219. }
  6220. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  6221. $email=$object->email;
  6222. }
  6223. if ($forcecapture) $capture = $forcecapture;
  6224. if ($dir)
  6225. {
  6226. if ($file && file_exists($dir."/".$file))
  6227. {
  6228. if ($addlinktofullsize)
  6229. {
  6230. $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  6231. if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
  6232. else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  6233. }
  6234. $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo" id="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.'">';
  6235. if ($addlinktofullsize) $ret.='</a>';
  6236. }
  6237. else if ($altfile && file_exists($dir."/".$altfile))
  6238. {
  6239. if ($addlinktofullsize)
  6240. {
  6241. $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  6242. if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
  6243. else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  6244. }
  6245. $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.'">';
  6246. if ($addlinktofullsize) $ret.='</a>';
  6247. }
  6248. else
  6249. {
  6250. $nophoto='/public/theme/common/nophoto.png';
  6251. if (in_array($modulepart,array('userphoto','contact'))) // For module that are "physical" users
  6252. {
  6253. $nophoto='/public/theme/common/user_anonymous.png';
  6254. if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
  6255. if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
  6256. }
  6257. if (! empty($conf->gravatar->enabled) && $email)
  6258. {
  6259. /**
  6260. * @see https://gravatar.com/site/implement/images/php/
  6261. */
  6262. global $dolibarr_main_url_root;
  6263. $ret.='<!-- Put link to gravatar -->';
  6264. //$defaultimg=urlencode(dol_buildpath($nophoto,3));
  6265. $defaultimg='mm';
  6266. $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.$defaultimg.'">'; // gravatar need md5 hash
  6267. }
  6268. else
  6269. {
  6270. $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
  6271. }
  6272. }
  6273. if ($caneditfield)
  6274. {
  6275. if ($object->photo) $ret.="<br>\n";
  6276. $ret.='<table class="nobordernopadding centpercent">';
  6277. if ($object->photo) $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
  6278. $ret.='<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"'.($capture?' capture="'.$capture.'"':'').'></td></tr>';
  6279. $ret.='</table>';
  6280. }
  6281. }
  6282. else dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
  6283. return $ret;
  6284. }
  6285. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  6286. /**
  6287. * Return select list of groups
  6288. *
  6289. * @param string $selected Id group preselected
  6290. * @param string $htmlname Field name in form
  6291. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  6292. * @param string $exclude Array list of groups id to exclude
  6293. * @param int $disabled If select list must be disabled
  6294. * @param string $include Array list of groups id to include
  6295. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  6296. * @param string $force_entity '0' or Ids of environment to force
  6297. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  6298. * @return string
  6299. * @see select_dolusers
  6300. */
  6301. function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity='0', $multiple=false)
  6302. {
  6303. // phpcs:enable
  6304. global $conf,$user,$langs;
  6305. // Permettre l'exclusion de groupes
  6306. if (is_array($exclude)) $excludeGroups = implode("','",$exclude);
  6307. // Permettre l'inclusion de groupes
  6308. if (is_array($include)) $includeGroups = implode("','",$include);
  6309. if (!is_array($selected)) $selected = array($selected);
  6310. $out='';
  6311. // On recherche les groupes
  6312. $sql = "SELECT ug.rowid, ug.nom as name";
  6313. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  6314. {
  6315. $sql.= ", e.label";
  6316. }
  6317. $sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  6318. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  6319. {
  6320. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
  6321. if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
  6322. else $sql.= " WHERE ug.entity IS NOT NULL";
  6323. }
  6324. else
  6325. {
  6326. $sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
  6327. }
  6328. if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
  6329. if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
  6330. $sql.= " ORDER BY ug.nom ASC";
  6331. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  6332. $resql=$this->db->query($sql);
  6333. if ($resql)
  6334. {
  6335. // Enhance with select2
  6336. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6337. $out .= ajax_combobox($htmlname);
  6338. $out.= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
  6339. $num = $this->db->num_rows($resql);
  6340. $i = 0;
  6341. if ($num)
  6342. {
  6343. if ($show_empty && !$multiple) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'>&nbsp;</option>'."\n";
  6344. while ($i < $num)
  6345. {
  6346. $obj = $this->db->fetch_object($resql);
  6347. $disableline=0;
  6348. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
  6349. $out.= '<option value="'.$obj->rowid.'"';
  6350. if ($disableline) $out.= ' disabled';
  6351. if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (! is_object($selected[0]) && in_array($obj->rowid,$selected) ))
  6352. {
  6353. $out.= ' selected';
  6354. }
  6355. $out.= '>';
  6356. $out.= $obj->name;
  6357. if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
  6358. {
  6359. $out.= " (".$obj->label.")";
  6360. }
  6361. $out.= '</option>';
  6362. $i++;
  6363. }
  6364. }
  6365. else
  6366. {
  6367. if ($show_empty) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'></option>'."\n";
  6368. $out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  6369. }
  6370. $out.= '</select>';
  6371. }
  6372. else
  6373. {
  6374. dol_print_error($this->db);
  6375. }
  6376. return $out;
  6377. }
  6378. /**
  6379. * Return HTML to show the search and clear seach button
  6380. *
  6381. * @return string
  6382. */
  6383. function showFilterButtons()
  6384. {
  6385. global $conf, $langs;
  6386. $out='<div class="nowrap">';
  6387. $out.='<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
  6388. $out.='<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
  6389. $out.='</div>';
  6390. return $out;
  6391. }
  6392. /**
  6393. * Return HTML to show the search and clear seach button
  6394. *
  6395. * @param string $cssclass CSS class
  6396. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  6397. * @return string
  6398. */
  6399. function showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)
  6400. {
  6401. global $conf, $langs;
  6402. $out='';
  6403. if (! empty($conf->use_javascript_ajax)) $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
  6404. $out.='<script type="text/javascript">
  6405. $(document).ready(function() {
  6406. $("#checkallactions").click(function() {
  6407. if($(this).is(\':checked\')){
  6408. console.log("We check all");
  6409. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  6410. }
  6411. else
  6412. {
  6413. console.log("We uncheck all");
  6414. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  6415. }'."\n";
  6416. if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  6417. $out.=' });
  6418. $(".checkforselect").change(function() {
  6419. $(this).closest("tr").toggleClass("highlight", this.checked);
  6420. });
  6421. });
  6422. </script>';
  6423. return $out;
  6424. }
  6425. /**
  6426. * Return HTML to show the search and clear seach button
  6427. *
  6428. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  6429. * @param string $cssclass CSS class
  6430. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  6431. * @return string
  6432. */
  6433. function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
  6434. {
  6435. $out.=$this->showFilterButtons();
  6436. if ($addcheckuncheckall)
  6437. {
  6438. $out.=$this->showCheckAddButtons($cssclass, $calljsfunction);
  6439. }
  6440. return $out;
  6441. }
  6442. /**
  6443. * Return HTML to show the select of expense categories
  6444. *
  6445. * @param string $selected preselected category
  6446. * @param string $htmlname name of HTML select list
  6447. * @param integer $useempty 1=Add empty line
  6448. * @param array $excludeid id to exclude
  6449. * @param string $target htmlname of target select to bind event
  6450. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  6451. * @param array $params param to give
  6452. * @return string
  6453. */
  6454. function selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array())
  6455. {
  6456. global $db, $conf, $langs, $user;
  6457. $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
  6458. $sql.= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
  6459. if (!empty($excludeid)) $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
  6460. $sql.= ' ORDER BY label';
  6461. $resql = $db->query($sql);
  6462. if ($resql)
  6463. {
  6464. $out = '<select name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  6465. if ($useempty) $out.= '<option value="0">&nbsp;</option>';
  6466. while ($obj = $db->fetch_object($resql))
  6467. {
  6468. $out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  6469. }
  6470. $out.= '</select>';
  6471. if (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  6472. if (!empty($target))
  6473. {
  6474. $sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  6475. $resql = $db->query($sql);
  6476. if ($resql)
  6477. {
  6478. if ($db->num_rows($resql) > 0)
  6479. {
  6480. $obj = $db->fetch_object($resql);
  6481. $out.= '<script type="text/javascript">
  6482. $(function() {
  6483. $("select[name='.$target.']").on("change", function() {
  6484. var current_val = $(this).val();
  6485. if (current_val == '.$obj->id.') {';
  6486. if (!empty($default_selected) || !empty($selected)) $out.= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  6487. $out.= '
  6488. $("select[name='.$htmlname.']").change();
  6489. }
  6490. });
  6491. $("select[name='.$htmlname.']").change(function() {
  6492. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  6493. // get price of kilometer to fill the unit price
  6494. var data = '.json_encode($params).';
  6495. data.fk_c_exp_tax_cat = $(this).val();
  6496. $.ajax({
  6497. method: "POST",
  6498. dataType: "json",
  6499. data: data,
  6500. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php').'",
  6501. }).done(function( data, textStatus, jqXHR ) {
  6502. console.log(data);
  6503. if (typeof data.up != "undefined") {
  6504. $("input[name=value_unit]").val(data.up);
  6505. $("select[name='.$htmlname.']").attr("title", data.title);
  6506. } else {
  6507. $("input[name=value_unit]").val("");
  6508. $("select[name='.$htmlname.']").attr("title", "");
  6509. }
  6510. });
  6511. }
  6512. });
  6513. });
  6514. </script>';
  6515. }
  6516. }
  6517. }
  6518. }
  6519. else
  6520. {
  6521. dol_print_error($db);
  6522. }
  6523. return $out;
  6524. }
  6525. /**
  6526. * Return HTML to show the select ranges of expense range
  6527. *
  6528. * @param string $selected preselected category
  6529. * @param string $htmlname name of HTML select list
  6530. * @param integer $useempty 1=Add empty line
  6531. * @return string
  6532. */
  6533. function selectExpenseRanges($selected='', $htmlname='fk_range', $useempty=0)
  6534. {
  6535. global $db,$conf,$langs;
  6536. $sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
  6537. $sql.= ' WHERE entity = '.$conf->entity.' AND active = 1';
  6538. $resql = $db->query($sql);
  6539. if ($resql)
  6540. {
  6541. $out = '<select name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  6542. if ($useempty) $out.= '<option value="0"></option>';
  6543. while ($obj = $db->fetch_object($resql))
  6544. {
  6545. $out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  6546. }
  6547. $out.= '</select>';
  6548. }
  6549. else
  6550. {
  6551. dol_print_error($db);
  6552. }
  6553. return $out;
  6554. }
  6555. /**
  6556. * Return HTML to show a select of expense
  6557. *
  6558. * @param string $selected preselected category
  6559. * @param string $htmlname name of HTML select list
  6560. * @param integer $useempty 1=Add empty choice
  6561. * @param integer $allchoice 1=Add all choice
  6562. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  6563. * @return string
  6564. */
  6565. function selectExpense($selected='', $htmlname='fk_c_type_fees', $useempty=0, $allchoice=1, $useid=0)
  6566. {
  6567. global $db,$langs;
  6568. $sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
  6569. $sql.= ' WHERE active = 1';
  6570. $resql = $db->query($sql);
  6571. if ($resql)
  6572. {
  6573. $out = '<select name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  6574. if ($useempty) $out.= '<option value="0"></option>';
  6575. if ($allchoice) $out.= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  6576. $field = 'code';
  6577. if ($useid) $field = 'id';
  6578. while ($obj = $db->fetch_object($resql))
  6579. {
  6580. $key = $langs->trans($obj->code);
  6581. $out.= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  6582. }
  6583. $out.= '</select>';
  6584. }
  6585. else
  6586. {
  6587. dol_print_error($db);
  6588. }
  6589. return $out;
  6590. }
  6591. }