html.form.class.php 279 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321
  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@capnetworks.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. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/core/class/html.form.class.php
  35. * \ingroup core
  36. * \brief File of class with all html predefined components
  37. */
  38. /**
  39. * Class to manage generation of HTML components
  40. * Only common components must be here.
  41. *
  42. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  43. */
  44. class Form
  45. {
  46. var $db;
  47. var $error;
  48. var $num;
  49. // Cache arrays
  50. var $cache_types_paiements=array();
  51. var $cache_conditions_paiements=array();
  52. var $cache_availability=array();
  53. var $cache_demand_reason=array();
  54. var $cache_types_fees=array();
  55. var $cache_vatrates=array();
  56. /**
  57. * Constructor
  58. *
  59. * @param DoliDB $db Database handler
  60. */
  61. public function __construct($db)
  62. {
  63. $this->db = $db;
  64. }
  65. /**
  66. * Output key field for an editable field
  67. *
  68. * @param string $text Text of label or key to translate
  69. * @param string $htmlname Name of select field ('edit' prefix will be added)
  70. * @param string $preselected Value to show/edit (not used in this function)
  71. * @param object $object Object
  72. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  73. * @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]'...)
  74. * @param string $moreparam More param to add on a href URL.
  75. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  76. * @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 ' '
  77. * @return string HTML edit field
  78. */
  79. function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0)
  80. {
  81. global $conf,$langs;
  82. $ret='';
  83. // TODO change for compatibility
  84. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))
  85. {
  86. if (! empty($perm))
  87. {
  88. $tmp=explode(':',$typeofdata);
  89. $ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  90. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  91. $ret.= $langs->trans($text);
  92. if ($fieldrequired) $ret.='</span>';
  93. $ret.= '</div>'."\n";
  94. }
  95. else
  96. {
  97. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  98. $ret.= $langs->trans($text);
  99. if ($fieldrequired) $ret.='</span>';
  100. }
  101. }
  102. else
  103. {
  104. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
  105. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  106. $ret.=$langs->trans($text);
  107. if ($fieldrequired) $ret.='</span>';
  108. if (! empty($notabletag)) $ret.=' ';
  109. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
  110. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align="right">';
  111. if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;id='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  112. if (! empty($notabletag) && $notabletag == 1) $ret.=' : ';
  113. if (! empty($notabletag) && $notabletag == 3) $ret.=' ';
  114. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
  115. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
  116. }
  117. return $ret;
  118. }
  119. /**
  120. * Output val field for an editable field
  121. *
  122. * @param string $text Text of label (not used in this function)
  123. * @param string $htmlname Name of select field
  124. * @param string $value Value to show/edit
  125. * @param object $object Object
  126. * @param boolean $perm Permission to allow button to edit parameter
  127. * @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'...)
  128. * @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
  129. * @param object $extObject External object
  130. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  131. * @param string $moreparam More param to add on a href URL
  132. * @param int $notabletag Do no output table tags
  133. * @return string HTML edit field
  134. */
  135. function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0)
  136. {
  137. global $conf,$langs,$db;
  138. $ret='';
  139. // Check parameters
  140. if (empty($typeofdata)) return 'ErrorBadParameter';
  141. // When option to edit inline is activated
  142. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
  143. {
  144. $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  145. }
  146. else
  147. {
  148. if (GETPOST('action','aZ09') == 'edit'.$htmlname)
  149. {
  150. $ret.="\n";
  151. $ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam?'?'.$moreparam:'').'">';
  152. $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
  153. $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  154. $ret.='<input type="hidden" name="id" value="'.$object->id.'">';
  155. if (empty($notabletag)) $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  156. if (empty($notabletag)) $ret.='<tr><td>';
  157. if (preg_match('/^(string|email)/',$typeofdata))
  158. {
  159. $tmp=explode(':',$typeofdata);
  160. $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
  161. }
  162. else if (preg_match('/^(numeric|amount)/',$typeofdata))
  163. {
  164. $tmp=explode(':',$typeofdata);
  165. $valuetoshow=price2num($editvalue?$editvalue:$value);
  166. $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
  167. }
  168. else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
  169. {
  170. $tmp=explode(':',$typeofdata);
  171. $cols=$tmp[2];
  172. $morealt='';
  173. if (preg_match('/%/',$cols))
  174. {
  175. $morealt=' style="width: '.$cols.'"';
  176. $cols='';
  177. }
  178. $ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'"'.($cols?' cols="'.$cols.'"':'').$morealt.'">'.($editvalue?$editvalue:$value).'</textarea>';
  179. }
  180. else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
  181. {
  182. $ret.=$this->select_date($value,$htmlname,0,0,1,'form'.$htmlname,1,0,1);
  183. }
  184. else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
  185. {
  186. $ret.=$this->select_date($value,$htmlname,1,1,1,'form'.$htmlname,1,0,1);
  187. }
  188. else if (preg_match('/^select;/',$typeofdata))
  189. {
  190. $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
  191. foreach($arraydata as $val)
  192. {
  193. $tmp=explode(':',$val);
  194. $arraylist[$tmp[0]]=$tmp[1];
  195. }
  196. $ret.=$this->selectarray($htmlname,$arraylist,$value);
  197. }
  198. else if (preg_match('/^ckeditor/',$typeofdata))
  199. {
  200. $tmp=explode(':',$typeofdata);
  201. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  202. $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'));
  203. $ret.=$doleditor->Create(1);
  204. }
  205. if (empty($notabletag)) $ret.='</td>';
  206. if (empty($notabletag)) $ret.='<td align="left">';
  207. //else $ret.='<div class="clearboth"></div>';
  208. $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  209. if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'."\n";
  210. $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  211. if (empty($notabletag)) $ret.='</td>';
  212. if (empty($notabletag)) $ret.='</tr></table>'."\n";
  213. $ret.='</form>'."\n";
  214. }
  215. else
  216. {
  217. if (preg_match('/^(email)/',$typeofdata)) $ret.=dol_print_email($value,0,0,0,0,1);
  218. elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
  219. elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value);
  220. elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
  221. elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
  222. else if (preg_match('/^select;/',$typeofdata))
  223. {
  224. $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
  225. foreach($arraydata as $val)
  226. {
  227. $tmp=explode(':',$val);
  228. $arraylist[$tmp[0]]=$tmp[1];
  229. }
  230. $ret.=$arraylist[$value];
  231. }
  232. else if (preg_match('/^ckeditor/',$typeofdata))
  233. {
  234. $tmpcontent=dol_htmlentitiesbr($value);
  235. if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
  236. {
  237. $firstline=preg_replace('/<br>.*/','',$tmpcontent);
  238. $firstline=preg_replace('/[\n\r].*/','',$firstline);
  239. $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
  240. }
  241. $ret.=$tmpcontent;
  242. }
  243. else $ret.=$value;
  244. }
  245. }
  246. return $ret;
  247. }
  248. /**
  249. * Output edit in place form
  250. *
  251. * @param object $object Object
  252. * @param string $value Value to show/edit
  253. * @param string $htmlname DIV ID (field name)
  254. * @param int $condition Condition to edit
  255. * @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')
  256. * @param string $editvalue When in edit mode, use this value as $value instead of value
  257. * @param object $extObject External object
  258. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  259. * @return string HTML edit in place
  260. */
  261. private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
  262. {
  263. global $conf;
  264. $out='';
  265. // Check parameters
  266. if ($inputType == 'textarea') $value = dol_nl2br($value);
  267. else if (preg_match('/^numeric/',$inputType)) $value = price($value);
  268. else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
  269. if ($condition)
  270. {
  271. $element = false;
  272. $table_element = false;
  273. $fk_element = false;
  274. $loadmethod = false;
  275. $savemethod = false;
  276. $ext_element = false;
  277. $button_only = false;
  278. $inputOption = '';
  279. if (is_object($object))
  280. {
  281. $element = $object->element;
  282. $table_element = $object->table_element;
  283. $fk_element = $object->id;
  284. }
  285. if (is_object($extObject))
  286. {
  287. $ext_element = $extObject->element;
  288. }
  289. if (preg_match('/^(string|email|numeric)/',$inputType))
  290. {
  291. $tmp=explode(':',$inputType);
  292. $inputType=$tmp[0];
  293. if (! empty($tmp[1])) $inputOption=$tmp[1];
  294. if (! empty($tmp[2])) $savemethod=$tmp[2];
  295. $out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  296. }
  297. else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
  298. {
  299. $tmp=explode(':',$inputType);
  300. $inputType=$tmp[0];
  301. if (! empty($tmp[1])) $inputOption=$tmp[1];
  302. if (! empty($tmp[2])) $savemethod=$tmp[2];
  303. $out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  304. }
  305. else if (preg_match('/^(select|autocomplete)/',$inputType))
  306. {
  307. $tmp=explode(':',$inputType);
  308. $inputType=$tmp[0]; $loadmethod=$tmp[1];
  309. if (! empty($tmp[2])) $savemethod=$tmp[2];
  310. if (! empty($tmp[3])) $button_only=true;
  311. }
  312. else if (preg_match('/^textarea/',$inputType))
  313. {
  314. $tmp=explode(':',$inputType);
  315. $inputType=$tmp[0];
  316. $rows=(empty($tmp[1])?'8':$tmp[1]);
  317. $cols=(empty($tmp[2])?'80':$tmp[2]);
  318. }
  319. else if (preg_match('/^ckeditor/',$inputType))
  320. {
  321. $tmp=explode(':',$inputType);
  322. $inputType=$tmp[0]; $toolbar=$tmp[1];
  323. if (! empty($tmp[2])) $width=$tmp[2];
  324. if (! empty($tmp[3])) $heigth=$tmp[3];
  325. if (! empty($tmp[4])) $savemethod=$tmp[4];
  326. if (! empty($conf->fckeditor->enabled))
  327. {
  328. $out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  329. }
  330. else
  331. {
  332. $inputType = 'textarea';
  333. }
  334. }
  335. $out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  336. $out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  337. $out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  338. $out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  339. if (! empty($savemethod)) $out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  340. if (! empty($ext_element)) $out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  341. if (! empty($custommsg))
  342. {
  343. if (is_array($custommsg))
  344. {
  345. if (!empty($custommsg['success']))
  346. $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  347. if (!empty($custommsg['error']))
  348. $out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  349. }
  350. else
  351. $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  352. }
  353. if ($inputType == 'textarea') {
  354. $out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  355. $out.= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  356. }
  357. $out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  358. $out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  359. }
  360. else
  361. {
  362. $out = $value;
  363. }
  364. return $out;
  365. }
  366. /**
  367. * Show a text and picto with tooltip on text or picto.
  368. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  369. *
  370. * @param string $text Text to show
  371. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  372. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  373. * @param int $direction -1=image is before, 0=no image, 1=image is after
  374. * @param string $img Html code for image (use img_xxx() function to get it)
  375. * @param string $extracss Add a CSS style to td tags
  376. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  377. * @param string $incbefore Include code before the text
  378. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  379. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  380. * @return string Code html du tooltip (texte+picto)
  381. * @see Use function textwithpicto if you can.
  382. * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
  383. */
  384. function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='')
  385. {
  386. global $conf;
  387. if ($incbefore) $text = $incbefore.$text;
  388. if (! $htmltext) return $text;
  389. $tag='td';
  390. if ($notabs == 2) $tag='div';
  391. if ($notabs == 3) $tag='span';
  392. // Sanitize tooltip
  393. $htmltext=str_replace("\\","\\\\",$htmltext);
  394. $htmltext=str_replace("\r","",$htmltext);
  395. $htmltext=str_replace("\n","",$htmltext);
  396. $extrastyle='';
  397. if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }
  398. if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }
  399. $classfortooltip='classfortooltip';
  400. $s='';$textfordialog='';
  401. $htmltext=str_replace('"',"&quot;",$htmltext);
  402. if ($tooltiptrigger != '')
  403. {
  404. $classfortooltip='classfortooltiponclick';
  405. $textfordialog.='<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  406. }
  407. if ($tooltipon == 2 || $tooltipon == 3)
  408. {
  409. $paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"';
  410. if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
  411. else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
  412. }
  413. else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
  414. if ($tooltipon == 1 || $tooltipon == 3)
  415. {
  416. $paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" ';
  417. if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
  418. else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
  419. }
  420. else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
  421. if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
  422. elseif ($notabs == 2) $s.='<div class="inline-block">';
  423. // Define value if value is before
  424. if ($direction < 0) {
  425. $s.='<'.$tag.$paramfortooltipimg;
  426. if ($tag == 'td') {
  427. $s .= ' valign="top" width="14"';
  428. }
  429. $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
  430. }
  431. // Use another method to help avoid having a space in value in order to use this value with jquery
  432. // Define label
  433. if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  434. // Define value if value is after
  435. if ($direction > 0) {
  436. $s.='<'.$tag.$paramfortooltipimg;
  437. if ($tag == 'td') $s .= ' valign="middle" width="14"';
  438. $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
  439. }
  440. if (empty($notabs)) $s.='</tr></table>';
  441. elseif ($notabs == 2) $s.='</div>';
  442. return $s;
  443. }
  444. /**
  445. * Show a text with a picto and a tooltip on picto
  446. *
  447. * @param string $text Text to show
  448. * @param string $htmltext Content of tooltip
  449. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  450. * @param string $type Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath
  451. * @param string $extracss Add a CSS style to td, div or span tag
  452. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  453. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  454. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  455. * @return string HTML code of text, picto, tooltip
  456. */
  457. function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='')
  458. {
  459. global $conf, $langs;
  460. $alt = '';
  461. if ($tooltiptrigger) $alt=$langs->trans("ClickToShowHelp");
  462. //For backwards compatibility
  463. if ($type == '0') $type = 'info';
  464. elseif ($type == '1') $type = 'help';
  465. // If info or help with no javascript, show only text
  466. if (empty($conf->use_javascript_ajax))
  467. {
  468. if ($type == 'info' || $type == 'help') return $text;
  469. else
  470. {
  471. $alt = $htmltext;
  472. $htmltext = '';
  473. }
  474. }
  475. // If info or help with smartphone, show only text (tooltip can't works)
  476. if (! empty($conf->dol_no_mouse_hover))
  477. {
  478. if ($type == 'info' || $type == 'help') return $text;
  479. }
  480. if ($type == 'info') $img = img_help(0, $alt);
  481. elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  482. elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
  483. elseif ($type == 'admin') $img = img_picto($alt, 'star');
  484. elseif ($type == 'warning') $img = img_warning($alt);
  485. else $img = img_picto($alt, $type);
  486. return $this->textwithtooltip($text, $htmltext, ($tooltiptrigger?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger);
  487. }
  488. /**
  489. * Generate select HTML to choose massaction
  490. *
  491. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  492. * @param int $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  493. * @param int $alwaysvisible 1=select button always visible
  494. * @return string Select list
  495. */
  496. function selectMassAction($selected, $arrayofaction, $alwaysvisible=0)
  497. {
  498. global $conf,$langs,$hookmanager;
  499. if (count($arrayofaction) == 0) return;
  500. $disabled=0;
  501. $ret='<div class="centpercent center">';
  502. $ret.='<select data-role="none" class="flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
  503. // 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.
  504. $parameters=array();
  505. $reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters); // Note that $action and $object may have been modified by hook
  506. if (empty($reshook))
  507. {
  508. $ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
  509. foreach($arrayofaction as $code => $label)
  510. {
  511. $ret.='<option value="'.$code.'"'.($disabled?' disabled="disabled"':'').'>'.$label.'</option>';
  512. }
  513. }
  514. $ret.=$hookmanager->resPrint;
  515. $ret.='</select>';
  516. // Warning: if you set submit button to disabled, post using 'Enter' will no more work.
  517. $ret.='<input type="submit" data-role="none" name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  518. $ret.='</div>';
  519. if (! empty($conf->use_javascript_ajax))
  520. {
  521. $ret.='<!-- JS CODE TO ENABLE mass action select -->
  522. <script type="text/javascript">
  523. function initCheckForSelect()
  524. {
  525. atleastoneselected=0;
  526. jQuery(".checkforselect").each(function( index ) {
  527. /* console.log( index + ": " + $( this ).text() ); */
  528. if ($(this).is(\':checked\')) atleastoneselected++;
  529. });
  530. if (atleastoneselected || '.$alwaysvisible.')
  531. {
  532. jQuery(".massaction").show();
  533. '.($selected ? 'if (atleastoneselected) jQuery(".massactionselect").val("'.$selected.'");' : '').'
  534. '.($selected ? 'if (! atleastoneselected) jQuery(".massactionselect").val("0");' : '').'
  535. }
  536. else
  537. {
  538. jQuery(".massaction").hide();
  539. }
  540. }
  541. jQuery(document).ready(function () {
  542. initCheckForSelect();
  543. jQuery(".checkforselect").click(function() {
  544. initCheckForSelect();
  545. });
  546. jQuery(".massactionselect").change(function() {
  547. var massaction = $( this ).val();
  548. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  549. if (massaction == "builddoc")
  550. {
  551. urlform = urlform + "#show_files";
  552. }
  553. $( this ).closest("form").attr("action", urlform);
  554. console.log("we select a mass action "+massaction+" - "+urlform);
  555. /* Warning: if you set submit button to disabled, post using Enter will no more work
  556. if ($(this).val() != \'0\')
  557. {
  558. jQuery(".massactionconfirmed").prop(\'disabled\', false);
  559. }
  560. else
  561. {
  562. jQuery(".massactionconfirmed").prop(\'disabled\', true);
  563. }
  564. */
  565. });
  566. });
  567. </script>
  568. ';
  569. }
  570. return $ret;
  571. }
  572. /**
  573. * Return combo list of activated countries, into language of user
  574. *
  575. * @param string $selected Id or Code or Label of preselected country
  576. * @param string $htmlname Name of html select object
  577. * @param string $htmloption Options html on select object
  578. * @param integer $maxlength Max length for labels (0=no limit)
  579. * @param string $morecss More css class
  580. * @return string HTML string with select
  581. */
  582. function select_country($selected='',$htmlname='country_id',$htmloption='',$maxlength=0,$morecss='minwidth300')
  583. {
  584. global $conf,$langs;
  585. $langs->load("dict");
  586. $out='';
  587. $countryArray=array();
  588. $favorite=array();
  589. $label=array();
  590. $atleastonefavorite=0;
  591. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
  592. $sql.= " FROM ".MAIN_DB_PREFIX."c_country";
  593. $sql.= " WHERE active > 0";
  594. //$sql.= " ORDER BY code ASC";
  595. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  596. $resql=$this->db->query($sql);
  597. if ($resql)
  598. {
  599. $out.= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" '.$htmloption.'>';
  600. $num = $this->db->num_rows($resql);
  601. $i = 0;
  602. if ($num)
  603. {
  604. $foundselected=false;
  605. while ($i < $num)
  606. {
  607. $obj = $this->db->fetch_object($resql);
  608. $countryArray[$i]['rowid'] = $obj->rowid;
  609. $countryArray[$i]['code_iso'] = $obj->code_iso;
  610. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  611. $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:''));
  612. $countryArray[$i]['favorite'] = $obj->favorite;
  613. $favorite[$i] = $obj->favorite;
  614. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  615. $i++;
  616. }
  617. array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  618. foreach ($countryArray as $row)
  619. {
  620. if ($row['favorite'] && $row['code_iso']) $atleastonefavorite++;
  621. if (empty($row['favorite']) && $atleastonefavorite)
  622. {
  623. $atleastonefavorite=0;
  624. $out.= '<option value="" disabled class="selectoptiondisabledwhite">----------------------</option>';
  625. }
  626. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )
  627. {
  628. $foundselected=true;
  629. $out.= '<option value="'.$row['rowid'].'" selected>';
  630. }
  631. else
  632. {
  633. $out.= '<option value="'.$row['rowid'].'">';
  634. }
  635. $out.= dol_trunc($row['label'],$maxlength,'middle');
  636. if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
  637. $out.= '</option>';
  638. }
  639. }
  640. $out.= '</select>';
  641. }
  642. else
  643. {
  644. dol_print_error($this->db);
  645. }
  646. // Make select dynamic
  647. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  648. $out .= ajax_combobox('select'.$htmlname);
  649. return $out;
  650. }
  651. /**
  652. * Return select list of incoterms
  653. *
  654. * @param string $selected Id or Code of preselected incoterm
  655. * @param string $location_incoterms Value of input location
  656. * @param string $page Defined the form action
  657. * @param string $htmlname Name of html select object
  658. * @param string $htmloption Options html on select object
  659. * @param int $forcecombo Force to use standard combo box (no ajax use)
  660. * @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')))
  661. * @return string HTML string with select and input
  662. */
  663. function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())
  664. {
  665. global $conf,$langs;
  666. $langs->load("dict");
  667. $out='';
  668. $incotermArray=array();
  669. $sql = "SELECT rowid, code";
  670. $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms";
  671. $sql.= " WHERE active > 0";
  672. $sql.= " ORDER BY code ASC";
  673. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  674. $resql=$this->db->query($sql);
  675. if ($resql)
  676. {
  677. if ($conf->use_javascript_ajax && ! $forcecombo)
  678. {
  679. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  680. $out .= ajax_combobox($htmlname, $events);
  681. }
  682. if (!empty($page))
  683. {
  684. $out .= '<form method="post" action="'.$page.'">';
  685. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  686. $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  687. }
  688. $out.= '<select id="'.$htmlname.'" class="flat selectincoterm noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
  689. $out.= '<option value="0">&nbsp;</option>';
  690. $num = $this->db->num_rows($resql);
  691. $i = 0;
  692. if ($num)
  693. {
  694. $foundselected=false;
  695. while ($i < $num)
  696. {
  697. $obj = $this->db->fetch_object($resql);
  698. $incotermArray[$i]['rowid'] = $obj->rowid;
  699. $incotermArray[$i]['code'] = $obj->code;
  700. $i++;
  701. }
  702. foreach ($incotermArray as $row)
  703. {
  704. if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
  705. {
  706. $out.= '<option value="'.$row['rowid'].'" selected>';
  707. }
  708. else
  709. {
  710. $out.= '<option value="'.$row['rowid'].'">';
  711. }
  712. if ($row['code']) $out.= $row['code'];
  713. $out.= '</option>';
  714. }
  715. }
  716. $out.= '</select>';
  717. $out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
  718. if (!empty($page))
  719. {
  720. $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
  721. }
  722. }
  723. else
  724. {
  725. dol_print_error($this->db);
  726. }
  727. return $out;
  728. }
  729. /**
  730. * Return list of types of lines (product or service)
  731. * Example: 0=product, 1=service, 9=other (for external module)
  732. *
  733. * @param string $selected Preselected type
  734. * @param string $htmlname Name of field in html form
  735. * @param int $showempty Add an empty field
  736. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  737. * @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')
  738. * @return void
  739. */
  740. function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
  741. {
  742. global $db,$langs,$user,$conf;
  743. // If product & services are enabled or both disabled.
  744. if ($forceall > 0 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
  745. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
  746. {
  747. if (empty($hidetext)) print $langs->trans("Type").': ';
  748. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  749. if ($showempty)
  750. {
  751. print '<option value="-1"';
  752. if ($selected == -1) print ' selected';
  753. print '>&nbsp;</option>';
  754. }
  755. print '<option value="0"';
  756. if (0 == $selected) print ' selected';
  757. print '>'.$langs->trans("Product");
  758. print '<option value="1"';
  759. if (1 == $selected) print ' selected';
  760. print '>'.$langs->trans("Service");
  761. print '</select>';
  762. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  763. }
  764. if (empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled))
  765. {
  766. print $langs->trans("Service");
  767. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  768. }
  769. if (empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled))
  770. {
  771. print $langs->trans("Product");
  772. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  773. }
  774. if ($forceall < 0) // This should happened only for contracts when both predefined product and service are disabled.
  775. {
  776. 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
  777. }
  778. }
  779. /**
  780. * Load into cache cache_types_fees, array of types of fees
  781. *
  782. * @return int Nb of lines loaded, <0 if KO
  783. */
  784. function load_cache_types_fees()
  785. {
  786. global $langs;
  787. $num = count($this->cache_types_fees);
  788. if ($num > 0) return 0; // Cache already loaded
  789. dol_syslog(__METHOD__, LOG_DEBUG);
  790. $langs->load("trips");
  791. $sql = "SELECT c.code, c.label";
  792. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  793. $sql.= " WHERE active > 0";
  794. $resql=$this->db->query($sql);
  795. if ($resql)
  796. {
  797. $num = $this->db->num_rows($resql);
  798. $i = 0;
  799. while ($i < $num)
  800. {
  801. $obj = $this->db->fetch_object($resql);
  802. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  803. $label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  804. $this->cache_types_fees[$obj->code] = $label;
  805. $i++;
  806. }
  807. asort($this->cache_types_fees);
  808. return $num;
  809. }
  810. else
  811. {
  812. dol_print_error($this->db);
  813. return -1;
  814. }
  815. }
  816. /**
  817. * Return list of types of notes
  818. *
  819. * @param string $selected Preselected type
  820. * @param string $htmlname Name of field in form
  821. * @param int $showempty Add an empty field
  822. * @return void
  823. */
  824. function select_type_fees($selected='',$htmlname='type',$showempty=0)
  825. {
  826. global $user, $langs;
  827. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  828. $this->load_cache_types_fees();
  829. print '<select class="flat" name="'.$htmlname.'">';
  830. if ($showempty)
  831. {
  832. print '<option value="-1"';
  833. if ($selected == -1) print ' selected';
  834. print '>&nbsp;</option>';
  835. }
  836. foreach($this->cache_types_fees as $key => $value)
  837. {
  838. print '<option value="'.$key.'"';
  839. if ($key == $selected) print ' selected';
  840. print '>';
  841. print $value;
  842. print '</option>';
  843. }
  844. print '</select>';
  845. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  846. }
  847. /**
  848. * Return HTML code to select a company.
  849. *
  850. * @param int $selected Preselected products
  851. * @param string $htmlname Name of HTML select field (must be unique in page)
  852. * @param int $filter Filter on thirdparty
  853. * @param int $limit Limit on number of returned lines
  854. * @param array $ajaxoptions Options for ajax_autocompleter
  855. * @param int $forcecombo Force to use combo box
  856. * @return string Return select box for thirdparty.
  857. * @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)
  858. */
  859. function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)
  860. {
  861. return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0,$limit);
  862. }
  863. /**
  864. * Output html form to select a third party
  865. *
  866. * @param string $selected Preselected type
  867. * @param string $htmlname Name of field in form
  868. * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')
  869. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  870. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  871. * @param int $forcecombo Force to use combo box
  872. * @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')))
  873. * @param int $limit Maximum number of elements
  874. * @param string $morecss Add more css styles to the SELECT component
  875. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  876. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  877. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  878. * @param array $ajaxoptions Options for ajax_autocompleter
  879. * @return string HTML string with select box for thirdparty.
  880. */
  881. 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())
  882. {
  883. global $conf,$user,$langs;
  884. $out='';
  885. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)
  886. {
  887. // No immediate load of all database
  888. $placeholder='';
  889. if ($selected && empty($selected_input_value))
  890. {
  891. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  892. $societetmp = new Societe($this->db);
  893. $societetmp->fetch($selected);
  894. $selected_input_value=$societetmp->name;
  895. unset($societetmp);
  896. }
  897. // mode 1
  898. $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');
  899. $out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  900. $out.='<style type="text/css">
  901. .ui-autocomplete {
  902. z-index: 250;
  903. }
  904. </style>';
  905. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  906. else if ($hidelabel > 1) {
  907. if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
  908. else $placeholder=' title="'.$langs->trans("RefOrLabel").'"';
  909. if ($hidelabel == 2) {
  910. $out.= img_picto($langs->trans("Search"), 'search');
  911. }
  912. }
  913. $out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  914. if ($hidelabel == 3) {
  915. $out.= img_picto($langs->trans("Search"), 'search');
  916. }
  917. }
  918. else
  919. {
  920. // Immediate load of all database
  921. $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam);
  922. }
  923. return $out;
  924. }
  925. /**
  926. * Output html form to select a third party.
  927. * 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.
  928. *
  929. * @param string $selected Preselected type
  930. * @param string $htmlname Name of field in form
  931. * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
  932. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  933. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  934. * @param int $forcecombo Force to use combo box
  935. * @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')))
  936. * @param string $filterkey Filter on key value
  937. * @param int $outputmode 0=HTML select string, 1=Array
  938. * @param int $limit Limit number of answers
  939. * @param string $morecss Add more css styles to the SELECT component
  940. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  941. * @return string HTML string with
  942. */
  943. function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='')
  944. {
  945. global $conf,$user,$langs;
  946. $out='';
  947. $num=0;
  948. $outarray=array();
  949. // On recherche les societes
  950. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  951. $sql.= " FROM ".MAIN_DB_PREFIX ."societe as s";
  952. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  953. $sql.= " WHERE s.entity IN (".getEntity('societe').")";
  954. if (! empty($user->societe_id)) $sql.= " AND s.rowid = ".$user->societe_id;
  955. if ($filter) $sql.= " AND (".$filter.")";
  956. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
  957. if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
  958. // Add criteria
  959. if ($filterkey && $filterkey != '')
  960. {
  961. $sql.=" AND (";
  962. $prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  963. // For natural search
  964. $scrit = explode(' ', $filterkey);
  965. $i=0;
  966. if (count($scrit) > 1) $sql.="(";
  967. foreach ($scrit as $crit) {
  968. if ($i > 0) $sql.=" AND ";
  969. $sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  970. $i++;
  971. }
  972. if (count($scrit) > 1) $sql.=")";
  973. if (! empty($conf->barcode->enabled))
  974. {
  975. $sql .= " OR s.barcode LIKE '".$this->db->escape($filterkey)."%'";
  976. }
  977. $sql.=")";
  978. }
  979. $sql.=$this->db->order("nom","ASC");
  980. if ($limit > 0) $sql.=$this->db->plimit($limit);
  981. // Build output string
  982. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  983. $resql=$this->db->query($sql);
  984. if ($resql)
  985. {
  986. if ($conf->use_javascript_ajax && ! $forcecombo)
  987. {
  988. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  989. $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
  990. $out.= $comboenhancement;
  991. }
  992. // Construct $out and $outarray
  993. $out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparam?' '.$moreparam:'').' name="'.$htmlname.'">'."\n";
  994. $textifempty='';
  995. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  996. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  997. if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
  998. {
  999. if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
  1000. else $textifempty.=$langs->trans("All");
  1001. }
  1002. if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
  1003. $num = $this->db->num_rows($resql);
  1004. $i = 0;
  1005. if ($num)
  1006. {
  1007. while ($i < $num)
  1008. {
  1009. $obj = $this->db->fetch_object($resql);
  1010. $label='';
  1011. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1012. if (($obj->client) && (!empty($obj->code_client))) {
  1013. $label = $obj->code_client. ' - ';
  1014. }
  1015. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1016. $label .= $obj->code_fournisseur. ' - ';
  1017. }
  1018. $label.=' '.$obj->name;
  1019. }
  1020. else
  1021. {
  1022. $label=$obj->name;
  1023. }
  1024. if(!empty($obj->name_alias)) {
  1025. $label.=' ('.$obj->name_alias.')';
  1026. }
  1027. if ($showtype)
  1028. {
  1029. if ($obj->client || $obj->fournisseur) $label.=' (';
  1030. if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
  1031. if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
  1032. if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
  1033. if ($obj->client || $obj->fournisseur) $label.=')';
  1034. }
  1035. if ($selected > 0 && $selected == $obj->rowid)
  1036. {
  1037. $out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1038. }
  1039. else
  1040. {
  1041. $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1042. }
  1043. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1044. $i++;
  1045. if (($i % 10) == 0) $out.="\n";
  1046. }
  1047. }
  1048. $out.= '</select>'."\n";
  1049. }
  1050. else
  1051. {
  1052. dol_print_error($this->db);
  1053. }
  1054. $this->result=array('nbofthirdparties'=>$num);
  1055. if ($outputmode) return $outarray;
  1056. return $out;
  1057. }
  1058. /**
  1059. * Return HTML combo list of absolute discounts
  1060. *
  1061. * @param string $selected Id remise fixe pre-selectionnee
  1062. * @param string $htmlname Nom champ formulaire
  1063. * @param string $filter Criteres optionnels de filtre
  1064. * @param int $socid Id of thirdparty
  1065. * @param int $maxvalue Max value for lines that can be selected
  1066. * @return int Return number of qualifed lines in list
  1067. */
  1068. function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
  1069. {
  1070. global $langs,$conf;
  1071. // On recherche les remises
  1072. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1073. $sql.= " re.description, re.fk_facture_source";
  1074. $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
  1075. $sql.= " WHERE re.fk_soc = ".(int) $socid;
  1076. $sql.= " AND re.entity = " . $conf->entity;
  1077. if ($filter) $sql.= " AND ".$filter;
  1078. $sql.= " ORDER BY re.description ASC";
  1079. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1080. $resql=$this->db->query($sql);
  1081. if ($resql)
  1082. {
  1083. print '<select class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1084. $num = $this->db->num_rows($resql);
  1085. $qualifiedlines=$num;
  1086. $i = 0;
  1087. if ($num)
  1088. {
  1089. print '<option value="0">&nbsp;</option>';
  1090. while ($i < $num)
  1091. {
  1092. $obj = $this->db->fetch_object($resql);
  1093. $desc=dol_trunc($obj->description,40);
  1094. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1095. if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1096. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1097. $selectstring='';
  1098. if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
  1099. $disabled='';
  1100. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
  1101. {
  1102. $qualifiedlines--;
  1103. $disabled=' disabled';
  1104. }
  1105. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1106. $i++;
  1107. }
  1108. }
  1109. print '</select>';
  1110. return $qualifiedlines;
  1111. }
  1112. else
  1113. {
  1114. dol_print_error($this->db);
  1115. return -1;
  1116. }
  1117. }
  1118. /**
  1119. * Return list of all contacts (for a third party or all)
  1120. *
  1121. * @param int $socid Id ot third party or 0 for all
  1122. * @param string $selected Id contact pre-selectionne
  1123. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1124. * @param int $showempty 0=no empty value, 1=add an empty value
  1125. * @param string $exclude List of contacts id to exclude
  1126. * @param string $limitto Disable answers that are not id in this array list
  1127. * @param integer $showfunction Add function into label
  1128. * @param string $moreclass Add more class to class style
  1129. * @param integer $showsoc Add company into label
  1130. * @param int $forcecombo Force to use combo box
  1131. * @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')))
  1132. * @param bool $options_only Return options only (for ajax treatment)
  1133. * @return int <0 if KO, Nb of contact in list if OK
  1134. */
  1135. function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false)
  1136. {
  1137. print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events);
  1138. return $this->num;
  1139. }
  1140. /**
  1141. * Return list of all contacts (for a third party or all)
  1142. *
  1143. * @param int $socid Id ot third party or 0 for all
  1144. * @param string $selected Id contact pre-selectionne
  1145. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1146. * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit)
  1147. * @param string $exclude List of contacts id to exclude
  1148. * @param string $limitto Disable answers that are not id in this array list
  1149. * @param integer $showfunction Add function into label
  1150. * @param string $moreclass Add more class to class style
  1151. * @param bool $options_only Return options only (for ajax treatment)
  1152. * @param integer $showsoc Add company into label
  1153. * @param int $forcecombo Force to use combo box
  1154. * @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')))
  1155. * @return int <0 if KO, Nb of contact in list if OK
  1156. */
  1157. function selectcontacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array())
  1158. {
  1159. global $conf,$langs;
  1160. $langs->load('companies');
  1161. $out='';
  1162. // On recherche les societes
  1163. $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
  1164. if ($showsoc > 0) $sql.= " , s.nom as company";
  1165. $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
  1166. if ($showsoc > 0) $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
  1167. $sql.= " WHERE sp.entity IN (".getEntity('societe').")";
  1168. if ($socid > 0) $sql.= " AND sp.fk_soc=".$socid;
  1169. if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
  1170. $sql.= " ORDER BY sp.lastname ASC";
  1171. dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
  1172. $resql=$this->db->query($sql);
  1173. if ($resql)
  1174. {
  1175. $num=$this->db->num_rows($resql);
  1176. if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)
  1177. {
  1178. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1179. $comboenhancement = ajax_combobox($htmlname, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
  1180. $out.= $comboenhancement;
  1181. }
  1182. if ($htmlname != 'none' || $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  1183. if ($showempty == 1) $out.= '<option value="0"'.($selected=='0'?' selected':'').'></option>';
  1184. if ($showempty == 2) $out.= '<option value="0"'.($selected=='0'?' selected':'').'>'.$langs->trans("Internal").'</option>';
  1185. $num = $this->db->num_rows($resql);
  1186. $i = 0;
  1187. if ($num)
  1188. {
  1189. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1190. $contactstatic=new Contact($this->db);
  1191. while ($i < $num)
  1192. {
  1193. $obj = $this->db->fetch_object($resql);
  1194. $contactstatic->id=$obj->rowid;
  1195. $contactstatic->lastname=$obj->lastname;
  1196. $contactstatic->firstname=$obj->firstname;
  1197. if ($obj->statut == 1){
  1198. if ($htmlname != 'none')
  1199. {
  1200. $disabled=0;
  1201. if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
  1202. if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
  1203. if ($selected && $selected == $obj->rowid)
  1204. {
  1205. $out.= '<option value="'.$obj->rowid.'"';
  1206. if ($disabled) $out.= ' disabled';
  1207. $out.= ' selected>';
  1208. $out.= $contactstatic->getFullName($langs);
  1209. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1210. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1211. $out.= '</option>';
  1212. }
  1213. else
  1214. {
  1215. $out.= '<option value="'.$obj->rowid.'"';
  1216. if ($disabled) $out.= ' disabled';
  1217. $out.= '>';
  1218. $out.= $contactstatic->getFullName($langs);
  1219. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1220. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1221. $out.= '</option>';
  1222. }
  1223. }
  1224. else
  1225. {
  1226. if ($selected == $obj->rowid)
  1227. {
  1228. $out.= $contactstatic->getFullName($langs);
  1229. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1230. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1231. }
  1232. }
  1233. }
  1234. $i++;
  1235. }
  1236. }
  1237. else
  1238. {
  1239. $out.= '<option value="-1"'.($showempty==2?'':' selected').' disabled>'.$langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined").'</option>';
  1240. }
  1241. if ($htmlname != 'none' || $options_only)
  1242. {
  1243. $out.= '</select>';
  1244. }
  1245. $this->num = $num;
  1246. return $out;
  1247. }
  1248. else
  1249. {
  1250. dol_print_error($this->db);
  1251. return -1;
  1252. }
  1253. }
  1254. /**
  1255. * Return select list of users
  1256. *
  1257. * @param string $selected Id user preselected
  1258. * @param string $htmlname Field name in form
  1259. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1260. * @param array $exclude Array list of users id to exclude
  1261. * @param int $disabled If select list must be disabled
  1262. * @param array $include Array list of users id to include
  1263. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1264. * @param int $force_entity 0 or Id of environment to force
  1265. * @return void
  1266. * @deprecated
  1267. * @see select_dolusers()
  1268. */
  1269. function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity=0)
  1270. {
  1271. print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
  1272. }
  1273. /**
  1274. * Return select list of users
  1275. *
  1276. * @param string $selected User id or user object of user preselected. If -1, we use id of current user.
  1277. * @param string $htmlname Field name in form
  1278. * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list
  1279. * @param array $exclude Array list of users id to exclude
  1280. * @param int $disabled If select list must be disabled
  1281. * @param array|string $include Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1282. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1283. * @param int $force_entity 0 or Id of environment to force
  1284. * @param int $maxlength Maximum length of string into list (0=no limit)
  1285. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1286. * @param string $morefilter Add more filters into sql request
  1287. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1288. * @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.
  1289. * @param string $morecss More css
  1290. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1291. * @return string HTML select string
  1292. * @see select_dolgroups
  1293. */
  1294. 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)
  1295. {
  1296. global $conf,$user,$langs;
  1297. // If no preselected user defined, we take current user
  1298. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
  1299. $excludeUsers=null;
  1300. $includeUsers=null;
  1301. // Permettre l'exclusion d'utilisateurs
  1302. if (is_array($exclude)) $excludeUsers = implode(",",$exclude);
  1303. // Permettre l'inclusion d'utilisateurs
  1304. if (is_array($include)) $includeUsers = implode(",",$include);
  1305. else if ($include == 'hierarchy')
  1306. {
  1307. // Build list includeUsers to have only hierarchy
  1308. $includeUsers = implode(",",$user->getAllChildIds(0));
  1309. }
  1310. else if ($include == 'hierarchyme')
  1311. {
  1312. // Build list includeUsers to have only hierarchy and current user
  1313. $includeUsers = implode(",",$user->getAllChildIds(1));
  1314. }
  1315. $out='';
  1316. // On recherche les utilisateurs
  1317. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
  1318. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1319. {
  1320. $sql.= ", e.label";
  1321. }
  1322. $sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
  1323. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1324. {
  1325. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
  1326. if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
  1327. else $sql.= " WHERE u.entity IS NOT NULL";
  1328. }
  1329. else
  1330. {
  1331. if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
  1332. {
  1333. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
  1334. $sql.= " ON ug.fk_user = u.rowid";
  1335. $sql.= " WHERE ug.entity = ".$conf->entity;
  1336. }
  1337. else
  1338. {
  1339. $sql.= " WHERE u.entity IN (0,".$conf->entity.")";
  1340. }
  1341. }
  1342. if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
  1343. if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
  1344. if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")";
  1345. if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
  1346. if (! empty($morefilter)) $sql.=" ".$morefilter;
  1347. if(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){
  1348. $sql.= " ORDER BY u.firstname ASC";
  1349. }else{
  1350. $sql.= " ORDER BY u.lastname ASC";
  1351. }
  1352. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1353. $resql=$this->db->query($sql);
  1354. if ($resql)
  1355. {
  1356. $num = $this->db->num_rows($resql);
  1357. $i = 0;
  1358. if ($num)
  1359. {
  1360. // Enhance with select2
  1361. if ($conf->use_javascript_ajax)
  1362. {
  1363. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1364. $comboenhancement = ajax_combobox($htmlname);
  1365. $out.=$comboenhancement;
  1366. }
  1367. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1368. $out.= '<select class="flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').'>';
  1369. if ($show_empty) $out.= '<option value="-1"'.((empty($selected) || $selected==-1)?' selected':'').'>&nbsp;</option>'."\n";
  1370. if ($show_every) $out.= '<option value="-2"'.(($selected==-2)?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1371. $userstatic=new User($this->db);
  1372. while ($i < $num)
  1373. {
  1374. $obj = $this->db->fetch_object($resql);
  1375. $userstatic->id=$obj->rowid;
  1376. $userstatic->lastname=$obj->lastname;
  1377. $userstatic->firstname=$obj->firstname;
  1378. $disableline='';
  1379. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
  1380. if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))
  1381. {
  1382. $out.= '<option value="'.$obj->rowid.'"';
  1383. if ($disableline) $out.= ' disabled';
  1384. $out.= ' selected>';
  1385. }
  1386. else
  1387. {
  1388. $out.= '<option value="'.$obj->rowid.'"';
  1389. if ($disableline) $out.= ' disabled';
  1390. $out.= '>';
  1391. }
  1392. $fullNameMode = 0; //Lastname + firstname
  1393. if(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){
  1394. $fullNameMode = 1; //firstname + lastname
  1395. }
  1396. $out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1397. // Complete name with more info
  1398. $moreinfo=0;
  1399. if (! empty($conf->global->MAIN_SHOW_LOGIN))
  1400. {
  1401. $out.= ($moreinfo?' - ':' (').$obj->login;
  1402. $moreinfo++;
  1403. }
  1404. if ($showstatus >= 0)
  1405. {
  1406. if ($obj->statut == 1 && $showstatus == 1)
  1407. {
  1408. $out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
  1409. $moreinfo++;
  1410. }
  1411. if ($obj->statut == 0)
  1412. {
  1413. $out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
  1414. $moreinfo++;
  1415. }
  1416. }
  1417. if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1418. {
  1419. if ($obj->admin && ! $obj->entity)
  1420. {
  1421. $out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
  1422. $moreinfo++;
  1423. }
  1424. else
  1425. {
  1426. $out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
  1427. $moreinfo++;
  1428. }
  1429. }
  1430. $out.=($moreinfo?')':'');
  1431. if ($disableline && $disableline != '1')
  1432. {
  1433. $out.=' - '.$disableline; // This is text from $enableonlytext parameter
  1434. }
  1435. $out.= '</option>';
  1436. $i++;
  1437. }
  1438. }
  1439. else
  1440. {
  1441. $out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1442. $out.= '<option value="">'.$langs->trans("None").'</option>';
  1443. }
  1444. $out.= '</select>';
  1445. }
  1446. else
  1447. {
  1448. dol_print_error($this->db);
  1449. }
  1450. return $out;
  1451. }
  1452. /**
  1453. * Return select list of users. Selected users are stored into session.
  1454. * List of users are provided into $_SESSION['assignedtouser'].
  1455. *
  1456. * @param string $action Value for $action
  1457. * @param string $htmlname Field name in form
  1458. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1459. * @param array $exclude Array list of users id to exclude
  1460. * @param int $disabled If select list must be disabled
  1461. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1462. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1463. * @param int $force_entity 0 or Id of environment to force
  1464. * @param int $maxlength Maximum length of string into list (0=no limit)
  1465. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1466. * @param string $morefilter Add more filters into sql request
  1467. * @return string HTML select string
  1468. * @see select_dolgroups
  1469. */
  1470. function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='')
  1471. {
  1472. global $conf,$user,$langs;
  1473. $userstatic=new User($this->db);
  1474. $out='';
  1475. // Method with no ajax
  1476. //$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
  1477. if ($action == 'view')
  1478. {
  1479. $out.='';
  1480. }
  1481. else
  1482. {
  1483. $out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1484. $out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () { jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });})</script>';
  1485. $out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1486. $out.=' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1487. }
  1488. $assignedtouser=array();
  1489. if (!empty($_SESSION['assignedtouser']))
  1490. {
  1491. $assignedtouser=json_decode($_SESSION['assignedtouser'], true);
  1492. }
  1493. $nbassignetouser=count($assignedtouser);
  1494. if ($nbassignetouser && $action != 'view') $out.='<br>';
  1495. if ($nbassignetouser) $out.='<div class="myavailability">';
  1496. $i=0; $ownerid=0;
  1497. foreach($assignedtouser as $key => $value)
  1498. {
  1499. if ($value['id'] == $ownerid) continue;
  1500. $userstatic->fetch($value['id']);
  1501. $out.=$userstatic->getNomUrl(-1);
  1502. if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; }
  1503. if ($nbassignetouser > 1 && $action != 'view') $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.'">';
  1504. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1505. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1506. $out.='<br>';
  1507. $i++;
  1508. }
  1509. if ($nbassignetouser) $out.='</div>';
  1510. //$out.='</form>';
  1511. return $out;
  1512. }
  1513. /**
  1514. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1515. *
  1516. * @param int $selected Preselected products
  1517. * @param string $htmlname Name of HTML select field (must be unique in page)
  1518. * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1519. * @param int $limit Limit on number of returned lines
  1520. * @param int $price_level Level of price to show
  1521. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1522. * @param int $finished 2=all, 1=finished, 0=raw material
  1523. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1524. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1525. * @param array $ajaxoptions Options for ajax_autocompleter
  1526. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1527. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1528. * @param int $forcecombo Force to use combo box
  1529. * @param string $morecss Add more css on select
  1530. * @param int $hidepriceinlabel 1=Hide prices in label
  1531. * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used
  1532. * 'warehouseopen' = select products from open warehouses,
  1533. * 'warehouseclosed' = select products from closed warehouses,
  1534. * 'warehouseinternal' = select products from warehouses for internal correct/transfer only
  1535. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  1536. * @return void
  1537. */
  1538. 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())
  1539. {
  1540. global $langs,$conf;
  1541. $price_level = (! empty($price_level) ? $price_level : 0);
  1542. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1543. {
  1544. $placeholder='';
  1545. if ($selected && empty($selected_input_value))
  1546. {
  1547. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1548. $producttmpselect = new Product($this->db);
  1549. $producttmpselect->fetch($selected);
  1550. $selected_input_value=$producttmpselect->ref;
  1551. unset($producttmpselect);
  1552. }
  1553. // mode=1 means customers products
  1554. $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&warehousestatus='.$warehouseStatus;
  1555. //Price by customer
  1556. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1557. $urloption.='&socid='.$socid;
  1558. }
  1559. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1560. if (!empty($conf->variants->enabled)) {
  1561. ?>
  1562. <script>
  1563. selected = <?php echo json_encode($selected_combinations) ?>;
  1564. combvalues = {};
  1565. jQuery(document).ready(function () {
  1566. jQuery("input[name='prod_entry_mode']").change(function () {
  1567. if (jQuery(this).val() == 'free') {
  1568. jQuery('div#attributes_box').empty();
  1569. }
  1570. });
  1571. jQuery("input#<?php echo $htmlname ?>").change(function () {
  1572. if (!jQuery(this).val()) {
  1573. jQuery('div#attributes_box').empty();
  1574. return;
  1575. }
  1576. jQuery.getJSON("<?php echo dol_buildpath('/variants/ajax/getCombinations.php', 2) ?>", {
  1577. id: jQuery(this).val()
  1578. }, function (data) {
  1579. jQuery('div#attributes_box').empty();
  1580. jQuery.each(data, function (key, val) {
  1581. combvalues[val.id] = val.values;
  1582. var span = jQuery(document.createElement('div')).css({
  1583. 'display': 'table-row'
  1584. });
  1585. span.append(
  1586. jQuery(document.createElement('div')).text(val.label).css({
  1587. 'font-weight': 'bold',
  1588. 'display': 'table-cell',
  1589. 'text-align': 'right'
  1590. })
  1591. );
  1592. var html = jQuery(document.createElement('select')).attr('name', 'combinations[' + val.id + ']').css({
  1593. 'margin-left': '15px',
  1594. 'white-space': 'pre'
  1595. }).append(
  1596. jQuery(document.createElement('option')).val('')
  1597. );
  1598. jQuery.each(combvalues[val.id], function (key, val) {
  1599. var tag = jQuery(document.createElement('option')).val(val.id).html(val.value);
  1600. if (selected[val.fk_product_attribute] == val.id) {
  1601. tag.attr('selected', 'selected');
  1602. }
  1603. html.append(tag);
  1604. });
  1605. span.append(html);
  1606. jQuery('div#attributes_box').append(span);
  1607. });
  1608. })
  1609. });
  1610. <?php if ($selected): ?>
  1611. jQuery("input#<?php echo $htmlname ?>").change();
  1612. <?php endif ?>
  1613. });
  1614. </script>
  1615. <?php
  1616. }
  1617. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  1618. else if ($hidelabel > 1) {
  1619. if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
  1620. else $placeholder=' title="'.$langs->trans("RefOrLabel").'"';
  1621. if ($hidelabel == 2) {
  1622. print img_picto($langs->trans("Search"), 'search');
  1623. }
  1624. }
  1625. print '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1626. if ($hidelabel == 3) {
  1627. print img_picto($langs->trans("Search"), 'search');
  1628. }
  1629. }
  1630. else
  1631. {
  1632. print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);
  1633. }
  1634. }
  1635. /**
  1636. * Return list of products for a customer
  1637. *
  1638. * @param int $selected Preselected product
  1639. * @param string $htmlname Name of select html
  1640. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1641. * @param int $limit Limit on number of returned lines
  1642. * @param int $price_level Level of price to show
  1643. * @param string $filterkey Filter on product
  1644. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1645. * @param int $finished Filter on finished field: 2=No filter
  1646. * @param int $outputmode 0=HTML select string, 1=Array
  1647. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1648. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1649. * @param int $forcecombo Force to use combo box
  1650. * @param string $morecss Add more css on select
  1651. * @param int $hidepriceinlabel 1=Hide prices in label
  1652. * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used
  1653. * 'warehouseopen' = select products from open warehouses,
  1654. * 'warehouseclosed' = select products from closed warehouses,
  1655. * 'warehouseinternal' = select products from warehouses for internal correct/transfer only
  1656. * @return array Array of keys for json
  1657. */
  1658. 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='')
  1659. {
  1660. global $langs,$conf,$user,$db;
  1661. $out='';
  1662. $outarray=array();
  1663. $warehouseStatusArray = array();
  1664. if (! empty($warehouseStatus))
  1665. {
  1666. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  1667. if (preg_match('/warehouseclosed/', $warehouseStatus))
  1668. {
  1669. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  1670. }
  1671. if (preg_match('/warehouseopen/', $warehouseStatus))
  1672. {
  1673. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  1674. }
  1675. if (preg_match('/warehouseinternal/', $warehouseStatus))
  1676. {
  1677. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  1678. }
  1679. }
  1680. $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";
  1681. (count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock";
  1682. $sql = "SELECT ";
  1683. $sql.= $selectFields . $selectFieldsGrouped;
  1684. //Price by customer
  1685. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1686. $sql.=' ,pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  1687. $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
  1688. $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
  1689. }
  1690. // Multilang : we add translation
  1691. if (! empty($conf->global->MAIN_MULTILANGS))
  1692. {
  1693. $sql.= ", pl.label as label_translated";
  1694. $selectFields.= ", label_translated";
  1695. }
  1696. // Price by quantity
  1697. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))
  1698. {
  1699. $sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1700. if ($price_level >= 1 && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
  1701. $sql.= " ORDER BY date_price";
  1702. $sql.= " DESC LIMIT 1) as price_rowid";
  1703. $sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1704. if ($price_level >= 1 && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
  1705. $sql.= " ORDER BY date_price";
  1706. $sql.= " DESC LIMIT 1) as price_by_qty";
  1707. $selectFields.= ", price_rowid, price_by_qty";
  1708. }
  1709. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  1710. if (count($warehouseStatusArray))
  1711. {
  1712. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
  1713. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid";
  1714. }
  1715. //Price by customer
  1716. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1717. $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
  1718. }
  1719. // Multilang : we add translation
  1720. if (! empty($conf->global->MAIN_MULTILANGS))
  1721. {
  1722. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
  1723. }
  1724. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1725. $sql .= " LEFT JOIN llx_product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  1726. }
  1727. $sql.= ' WHERE p.entity IN ('.getEntity('product').')';
  1728. if (count($warehouseStatusArray))
  1729. {
  1730. $sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.implode(',',$warehouseStatusArray).'))';
  1731. }
  1732. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1733. $sql .= " AND pac.rowid IS NULL";
  1734. }
  1735. if ($finished == 0)
  1736. {
  1737. $sql.= " AND p.finished = ".$finished;
  1738. }
  1739. elseif ($finished == 1)
  1740. {
  1741. $sql.= " AND p.finished = ".$finished;
  1742. if ($status >= 0) $sql.= " AND p.tosell = ".$status;
  1743. }
  1744. elseif ($status >= 0)
  1745. {
  1746. $sql.= " AND p.tosell = ".$status;
  1747. }
  1748. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
  1749. // Add criteria on ref/label
  1750. if ($filterkey != '')
  1751. {
  1752. $sql.=' AND (';
  1753. $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  1754. // For natural search
  1755. $scrit = explode(' ', $filterkey);
  1756. $i=0;
  1757. if (count($scrit) > 1) $sql.="(";
  1758. foreach ($scrit as $crit)
  1759. {
  1760. if ($i > 0) $sql.=" AND ";
  1761. $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
  1762. if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
  1763. $sql.=")";
  1764. $i++;
  1765. }
  1766. if (count($scrit) > 1) $sql.=")";
  1767. if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
  1768. $sql.=')';
  1769. }
  1770. if (count($warehouseStatusArray))
  1771. {
  1772. $sql.= ' GROUP BY'.$selectFields;
  1773. }
  1774. $sql.= $db->order("p.ref");
  1775. $sql.= $db->plimit($limit);
  1776. // Build output string
  1777. dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
  1778. $result=$this->db->query($sql);
  1779. if ($result)
  1780. {
  1781. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1782. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1783. $num = $this->db->num_rows($result);
  1784. $events=null;
  1785. if ($conf->use_javascript_ajax && ! $forcecombo)
  1786. {
  1787. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1788. $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
  1789. $out.= $comboenhancement;
  1790. }
  1791. $out.='<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  1792. $textifempty='';
  1793. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1794. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1795. if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1796. {
  1797. if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
  1798. else $textifempty.=$langs->trans("All");
  1799. }
  1800. if ($showempty) $out.='<option value="0" selected>'.$textifempty.'</option>';
  1801. $i = 0;
  1802. while ($num && $i < $num)
  1803. {
  1804. $opt = '';
  1805. $optJson = array();
  1806. $objp = $this->db->fetch_object($result);
  1807. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)
  1808. { // Price by quantity will return many prices for the same product
  1809. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise";
  1810. $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
  1811. $sql.= " WHERE fk_product_price=".$objp->price_rowid;
  1812. $sql.= " ORDER BY quantity ASC";
  1813. dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
  1814. $result2 = $this->db->query($sql);
  1815. if ($result2)
  1816. {
  1817. $nb_prices = $this->db->num_rows($result2);
  1818. $j = 0;
  1819. while ($nb_prices && $j < $nb_prices) {
  1820. $objp2 = $this->db->fetch_object($result2);
  1821. $objp->quantity = $objp2->quantity;
  1822. $objp->price = $objp2->price;
  1823. $objp->unitprice = $objp2->unitprice;
  1824. $objp->remise_percent = $objp2->remise_percent;
  1825. $objp->remise = $objp2->remise;
  1826. $objp->price_by_qty_rowid = $objp2->rowid;
  1827. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel);
  1828. $j++;
  1829. // Add new entry
  1830. // "key" value of json key array is used by jQuery automatically as selected value
  1831. // "label" value of json key array is used by jQuery automatically as text for combo box
  1832. $out.=$opt;
  1833. array_push($outarray, $optJson);
  1834. }
  1835. }
  1836. }
  1837. else
  1838. {
  1839. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  1840. $price_product = new Product($this->db);
  1841. $price_product->fetch($objp->rowid, '', '', 1);
  1842. $priceparser = new PriceParser($this->db);
  1843. $price_result = $priceparser->parseProduct($price_product);
  1844. if ($price_result >= 0) {
  1845. $objp->price = $price_result;
  1846. $objp->unitprice = $price_result;
  1847. //Calculate the VAT
  1848. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  1849. $objp->price_ttc = price2num($objp->price_ttc,'MU');
  1850. }
  1851. }
  1852. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);
  1853. // Add new entry
  1854. // "key" value of json key array is used by jQuery automatically as selected value
  1855. // "label" value of json key array is used by jQuery automatically as text for combo box
  1856. $out.=$opt;
  1857. array_push($outarray, $optJson);
  1858. }
  1859. $i++;
  1860. }
  1861. $out.='</select>';
  1862. $this->db->free($result);
  1863. if (empty($outputmode)) return $out;
  1864. return $outarray;
  1865. }
  1866. else
  1867. {
  1868. dol_print_error($db);
  1869. }
  1870. }
  1871. /**
  1872. * constructProductListOption
  1873. *
  1874. * @param resultset $objp Resultset of fetch
  1875. * @param string $opt Option (var used for returned value in string option format)
  1876. * @param string $optJson Option (var used for returned value in json format)
  1877. * @param int $price_level Price level
  1878. * @param string $selected Preselected value
  1879. * @param int $hidepriceinlabel Hide price in label
  1880. * @return void
  1881. */
  1882. private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)
  1883. {
  1884. global $langs,$conf,$user,$db;
  1885. $outkey='';
  1886. $outval='';
  1887. $outref='';
  1888. $outlabel='';
  1889. $outdesc='';
  1890. $outbarcode='';
  1891. $outtype='';
  1892. $outprice_ht='';
  1893. $outprice_ttc='';
  1894. $outpricebasetype='';
  1895. $outtva_tx='';
  1896. $outqty=1;
  1897. $outdiscount=0;
  1898. $maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
  1899. $label=$objp->label;
  1900. if (! empty($objp->label_translated)) $label=$objp->label_translated;
  1901. if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  1902. $outkey=$objp->rowid;
  1903. $outref=$objp->ref;
  1904. $outlabel=$objp->label;
  1905. $outdesc=$objp->description;
  1906. $outbarcode=$objp->barcode;
  1907. $outtype=$objp->fk_product_type;
  1908. $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
  1909. $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
  1910. $opt = '<option value="'.$objp->rowid.'"';
  1911. $opt.= ($objp->rowid == $selected)?' selected':'';
  1912. $opt.= (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)?' pbq="'.$objp->price_by_qty_rowid.'"':'';
  1913. if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
  1914. {
  1915. if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
  1916. else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
  1917. }
  1918. $opt.= '>';
  1919. $opt.= $objp->ref;
  1920. if ($outbarcode) $opt.=' ('.$outbarcode.')';
  1921. $opt.=' - '.dol_trunc($label,$maxlengtharticle);
  1922. $objRef = $objp->ref;
  1923. if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  1924. $outval.=$objRef;
  1925. if ($outbarcode) $outval.=' ('.$outbarcode.')';
  1926. $outval.=' - '.dol_trunc($label,$maxlengtharticle);
  1927. $found=0;
  1928. // Multiprice
  1929. if (empty($hidepriceinlabel) && $price_level >= 1 && $conf->global->PRODUIT_MULTIPRICES) // If we need a particular price level (from 1 to 6)
  1930. {
  1931. $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
  1932. $sql.= " FROM ".MAIN_DB_PREFIX."product_price";
  1933. $sql.= " WHERE fk_product='".$objp->rowid."'";
  1934. $sql.= " AND entity IN (".getEntity('productprice').")";
  1935. $sql.= " AND price_level=".$price_level;
  1936. $sql.= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  1937. $sql.= " LIMIT 1";
  1938. dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
  1939. $result2 = $this->db->query($sql);
  1940. if ($result2)
  1941. {
  1942. $objp2 = $this->db->fetch_object($result2);
  1943. if ($objp2)
  1944. {
  1945. $found=1;
  1946. if ($objp2->price_base_type == 'HT')
  1947. {
  1948. $opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  1949. $outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  1950. }
  1951. else
  1952. {
  1953. $opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  1954. $outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  1955. }
  1956. $outprice_ht=price($objp2->price);
  1957. $outprice_ttc=price($objp2->price_ttc);
  1958. $outpricebasetype=$objp2->price_base_type;
  1959. $outtva_tx=$objp2->tva_tx;
  1960. }
  1961. }
  1962. else
  1963. {
  1964. dol_print_error($this->db);
  1965. }
  1966. }
  1967. // Price by quantity
  1968. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))
  1969. {
  1970. $found = 1;
  1971. $outqty=$objp->quantity;
  1972. $outdiscount=$objp->remise_percent;
  1973. if ($objp->quantity == 1)
  1974. {
  1975. $opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/";
  1976. $outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
  1977. $opt.= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  1978. $outval.=$langs->transnoentities("Unit");
  1979. }
  1980. else
  1981. {
  1982. $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  1983. $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  1984. $opt.= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  1985. $outval.=$langs->transnoentities("Units");
  1986. }
  1987. $outprice_ht=price($objp->unitprice);
  1988. $outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  1989. $outpricebasetype=$objp->price_base_type;
  1990. $outtva_tx=$objp->tva_tx;
  1991. }
  1992. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
  1993. {
  1994. $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  1995. $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  1996. }
  1997. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
  1998. {
  1999. $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2000. $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2001. }
  2002. // Price by customer
  2003. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  2004. {
  2005. if (!empty($objp->idprodcustprice))
  2006. {
  2007. $found = 1;
  2008. if ($objp->custprice_base_type == 'HT')
  2009. {
  2010. $opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  2011. $outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  2012. }
  2013. else
  2014. {
  2015. $opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  2016. $outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  2017. }
  2018. $outprice_ht=price($objp->custprice);
  2019. $outprice_ttc=price($objp->custprice_ttc);
  2020. $outpricebasetype=$objp->custprice_base_type;
  2021. $outtva_tx=$objp->custtva_tx;
  2022. }
  2023. }
  2024. // If level no defined or multiprice not found, we used the default price
  2025. if (empty($hidepriceinlabel) && ! $found)
  2026. {
  2027. if ($objp->price_base_type == 'HT')
  2028. {
  2029. $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  2030. $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  2031. }
  2032. else
  2033. {
  2034. $opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  2035. $outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  2036. }
  2037. $outprice_ht=price($objp->price);
  2038. $outprice_ttc=price($objp->price_ttc);
  2039. $outpricebasetype=$objp->price_base_type;
  2040. $outtva_tx=$objp->tva_tx;
  2041. }
  2042. if (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
  2043. {
  2044. $opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
  2045. if ($objp->stock > 0) {
  2046. $outval.= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
  2047. }elseif ($objp->stock <= 0) {
  2048. $outval.= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
  2049. }
  2050. }
  2051. if ($outdurationvalue && $outdurationunit)
  2052. {
  2053. $da=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
  2054. if (isset($da[$outdurationunit]))
  2055. {
  2056. $key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');
  2057. $opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);
  2058. $outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);
  2059. }
  2060. }
  2061. $opt.= "</option>\n";
  2062. $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);
  2063. }
  2064. /**
  2065. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2066. *
  2067. * @param int $socid Id third party
  2068. * @param string $selected Preselected product
  2069. * @param string $htmlname Name of HTML Select
  2070. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2071. * @param string $filtre For a SQL filter
  2072. * @param array $ajaxoptions Options for ajax_autocompleter
  2073. * @param int $hidelabel Hide label (0=no, 1=yes)
  2074. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2075. * @return void
  2076. */
  2077. function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0)
  2078. {
  2079. global $langs,$conf;
  2080. global $price_level, $status, $finished;
  2081. $selected_input_value='';
  2082. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  2083. {
  2084. if ($selected > 0)
  2085. {
  2086. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2087. $producttmpselect = new Product($this->db);
  2088. $producttmpselect->fetch($selected);
  2089. $selected_input_value=$producttmpselect->ref;
  2090. unset($producttmpselect);
  2091. }
  2092. if (!empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED))
  2093. {
  2094. print '<input type="hidden" id="idprod" name="idprod" value="0" />';
  2095. }
  2096. // mode=2 means suppliers products
  2097. $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2098. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2099. print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
  2100. }
  2101. else
  2102. {
  2103. if (!empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED))
  2104. {
  2105. print '<input type="hidden" id="idprod" name="idprod" value="0" />';
  2106. print '<script type="text/javascript">$("#'.$htmlname.'").change(function() { $("#idprod").val($(this).val());});</script>';
  2107. }
  2108. print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);
  2109. }
  2110. }
  2111. /**
  2112. * Return list of suppliers products
  2113. *
  2114. * @param int $socid Id societe fournisseur (0 pour aucun filtre)
  2115. * @param int $selected Produit pre-selectionne
  2116. * @param string $htmlname Nom de la zone select
  2117. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2118. * @param string $filtre Pour filtre sql
  2119. * @param string $filterkey Filtre des produits
  2120. * @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)
  2121. * @param int $outputmode 0=HTML select string, 1=Array
  2122. * @param int $limit Limit of line number
  2123. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2124. * @return array Array of keys for json
  2125. */
  2126. function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0)
  2127. {
  2128. global $langs,$conf,$db;
  2129. $out='';
  2130. $outarray=array();
  2131. $langs->load('stocks');
  2132. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,";
  2133. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2134. $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
  2135. $sql.= " pfp.supplier_reputation";
  2136. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  2137. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2138. if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
  2139. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2140. $sql.= " WHERE p.entity IN (".getEntity('product').")";
  2141. $sql.= " AND p.tobuy = 1";
  2142. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
  2143. if (! empty($filtre)) $sql.=" ".$filtre;
  2144. // Add criteria on ref/label
  2145. if ($filterkey != '')
  2146. {
  2147. $sql.=' AND (';
  2148. $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2149. // For natural search
  2150. $scrit = explode(' ', $filterkey);
  2151. $i=0;
  2152. if (count($scrit) > 1) $sql.="(";
  2153. foreach ($scrit as $crit)
  2154. {
  2155. if ($i > 0) $sql.=" AND ";
  2156. $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)."%')";
  2157. $i++;
  2158. }
  2159. if (count($scrit) > 1) $sql.=")";
  2160. if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2161. $sql.=')';
  2162. }
  2163. $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2164. $sql.= $db->plimit($limit);
  2165. // Build output string
  2166. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2167. $result=$this->db->query($sql);
  2168. if ($result)
  2169. {
  2170. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2171. $num = $this->db->num_rows($result);
  2172. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2173. $out.='<select class="flat maxwidthonsmartphone" id="'.$htmlname.'" name="'.$htmlname.'">';
  2174. if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
  2175. else $out.='<option value="0">&nbsp;</option>';
  2176. $i = 0;
  2177. while ($i < $num)
  2178. {
  2179. $objp = $this->db->fetch_object($result);
  2180. $outkey=$objp->idprodfournprice; // id in table of price
  2181. if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid; // id of product
  2182. $outref=$objp->ref;
  2183. $outval='';
  2184. $outqty=1;
  2185. $outdiscount=0;
  2186. $outtype=$objp->fk_product_type;
  2187. $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
  2188. $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
  2189. $opt = '<option value="'.$outkey.'"';
  2190. if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
  2191. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';
  2192. $opt.= '>';
  2193. $objRef = $objp->ref;
  2194. if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  2195. $objRefFourn = $objp->ref_fourn;
  2196. if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
  2197. $label = $objp->label;
  2198. if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  2199. $opt.=$objp->ref;
  2200. if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
  2201. $opt.=' ('.$objp->ref_fourn.')';
  2202. $opt.=' - ';
  2203. $outval.=$objRef;
  2204. if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
  2205. $outval.=' ('.$objRefFourn.')';
  2206. $outval.=' - ';
  2207. $opt.=dol_trunc($label, 72).' - ';
  2208. $outval.=dol_trunc($label, 72).' - ';
  2209. if (! empty($objp->idprodfournprice))
  2210. {
  2211. $outqty=$objp->quantity;
  2212. $outdiscount=$objp->remise_percent;
  2213. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2214. $prod_supplier = new ProductFournisseur($this->db);
  2215. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2216. $prod_supplier->id = $objp->fk_product;
  2217. $prod_supplier->fourn_qty = $objp->quantity;
  2218. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2219. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2220. $priceparser = new PriceParser($this->db);
  2221. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2222. if ($price_result >= 0) {
  2223. $objp->fprice = $price_result;
  2224. if ($objp->quantity >= 1)
  2225. {
  2226. $objp->unitprice = $objp->fprice / $objp->quantity;
  2227. }
  2228. }
  2229. }
  2230. if ($objp->quantity == 1)
  2231. {
  2232. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
  2233. $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
  2234. $opt.= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2235. $outval.=$langs->transnoentities("Unit");
  2236. }
  2237. else
  2238. {
  2239. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2240. $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2241. $opt.= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2242. $outval.= ' '.$langs->transnoentities("Units");
  2243. }
  2244. if ($objp->quantity >= 1)
  2245. {
  2246. $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2247. $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2248. }
  2249. if ($objp->remise_percent >= 1)
  2250. {
  2251. $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2252. $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2253. }
  2254. if ($objp->duration)
  2255. {
  2256. $opt .= " - ".$objp->duration;
  2257. $outval.=" - ".$objp->duration;
  2258. }
  2259. if (! $socid)
  2260. {
  2261. $opt .= " - ".dol_trunc($objp->name,8);
  2262. $outval.=" - ".dol_trunc($objp->name,8);
  2263. }
  2264. if ($objp->supplier_reputation)
  2265. {
  2266. //TODO dictionary
  2267. $reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  2268. $opt .= " - ".$reputations[$objp->supplier_reputation];
  2269. $outval.=" - ".$reputations[$objp->supplier_reputation];
  2270. }
  2271. }
  2272. else
  2273. {
  2274. if (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier
  2275. {
  2276. $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
  2277. $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2278. }
  2279. else // No supplier price defined for product, even on other suppliers
  2280. {
  2281. $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
  2282. $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2283. }
  2284. }
  2285. $opt .= "</option>\n";
  2286. // Add new entry
  2287. // "key" value of json key array is used by jQuery automatically as selected value
  2288. // "label" value of json key array is used by jQuery automatically as text for combo box
  2289. $out.=$opt;
  2290. 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)));
  2291. // Exemple of var_dump $outarray
  2292. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  2293. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  2294. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  2295. //}
  2296. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2297. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  2298. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2299. $i++;
  2300. }
  2301. $out.='</select>';
  2302. $this->db->free($result);
  2303. if (empty($outputmode)) return $out;
  2304. return $outarray;
  2305. }
  2306. else
  2307. {
  2308. dol_print_error($this->db);
  2309. }
  2310. }
  2311. /**
  2312. * Return list of suppliers prices for a product
  2313. *
  2314. * @param int $productid Id of product
  2315. * @param string $htmlname Name of HTML field
  2316. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  2317. * @return void
  2318. */
  2319. function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')
  2320. {
  2321. global $langs,$conf;
  2322. $langs->load('stocks');
  2323. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,";
  2324. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
  2325. $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  2326. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  2327. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2328. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2329. $sql.= " WHERE p.entity IN (".getEntity('productprice').")";
  2330. $sql.= " AND p.tobuy = 1";
  2331. $sql.= " AND s.fournisseur = 1";
  2332. $sql.= " AND p.rowid = ".$productid;
  2333. $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
  2334. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  2335. $result=$this->db->query($sql);
  2336. if ($result)
  2337. {
  2338. $num = $this->db->num_rows($result);
  2339. $form = '<select class="flat" name="'.$htmlname.'">';
  2340. if (! $num)
  2341. {
  2342. $form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  2343. }
  2344. else
  2345. {
  2346. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2347. $form.= '<option value="0">&nbsp;</option>';
  2348. $i = 0;
  2349. while ($i < $num)
  2350. {
  2351. $objp = $this->db->fetch_object($result);
  2352. $opt = '<option value="'.$objp->idprodfournprice.'"';
  2353. //if there is only one supplier, preselect it
  2354. if($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  2355. $opt .= ' selected';
  2356. }
  2357. $opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  2358. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2359. $prod_supplier = new ProductFournisseur($this->db);
  2360. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2361. $prod_supplier->id = $productid;
  2362. $prod_supplier->fourn_qty = $objp->quantity;
  2363. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2364. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2365. $priceparser = new PriceParser($this->db);
  2366. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2367. if ($price_result >= 0) {
  2368. $objp->fprice = $price_result;
  2369. if ($objp->quantity >= 1)
  2370. {
  2371. $objp->unitprice = $objp->fprice / $objp->quantity;
  2372. }
  2373. }
  2374. }
  2375. if ($objp->quantity == 1)
  2376. {
  2377. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
  2378. }
  2379. $opt.= $objp->quantity.' ';
  2380. if ($objp->quantity == 1)
  2381. {
  2382. $opt.= $langs->trans("Unit");
  2383. }
  2384. else
  2385. {
  2386. $opt.= $langs->trans("Units");
  2387. }
  2388. if ($objp->quantity > 1)
  2389. {
  2390. $opt.=" - ";
  2391. $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
  2392. }
  2393. if ($objp->duration) $opt .= " - ".$objp->duration;
  2394. $opt .= "</option>\n";
  2395. $form.= $opt;
  2396. $i++;
  2397. }
  2398. }
  2399. $form.= '</select>';
  2400. $this->db->free($result);
  2401. return $form;
  2402. }
  2403. else
  2404. {
  2405. dol_print_error($this->db);
  2406. }
  2407. }
  2408. /**
  2409. * Return list of delivery address
  2410. *
  2411. * @param string $selected Id contact pre-selectionn
  2412. * @param int $socid Id of company
  2413. * @param string $htmlname Name of HTML field
  2414. * @param int $showempty Add an empty field
  2415. * @return integer|null
  2416. */
  2417. function select_address($selected, $socid, $htmlname='address_id',$showempty=0)
  2418. {
  2419. // On recherche les utilisateurs
  2420. $sql = "SELECT a.rowid, a.label";
  2421. $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
  2422. $sql .= " WHERE a.fk_soc = ".$socid;
  2423. $sql .= " ORDER BY a.label ASC";
  2424. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  2425. $resql=$this->db->query($sql);
  2426. if ($resql)
  2427. {
  2428. print '<select class="flat" name="'.$htmlname.'">';
  2429. if ($showempty) print '<option value="0">&nbsp;</option>';
  2430. $num = $this->db->num_rows($resql);
  2431. $i = 0;
  2432. if ($num)
  2433. {
  2434. while ($i < $num)
  2435. {
  2436. $obj = $this->db->fetch_object($resql);
  2437. if ($selected && $selected == $obj->rowid)
  2438. {
  2439. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  2440. }
  2441. else
  2442. {
  2443. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  2444. }
  2445. $i++;
  2446. }
  2447. }
  2448. print '</select>';
  2449. return $num;
  2450. }
  2451. else
  2452. {
  2453. dol_print_error($this->db);
  2454. }
  2455. }
  2456. /**
  2457. * Load into cache list of payment terms
  2458. *
  2459. * @return int Nb of lines loaded, <0 if KO
  2460. */
  2461. function load_cache_conditions_paiements()
  2462. {
  2463. global $langs;
  2464. $num = count($this->cache_conditions_paiements);
  2465. if ($num > 0) return 0; // Cache already loaded
  2466. dol_syslog(__METHOD__, LOG_DEBUG);
  2467. $sql = "SELECT rowid, code, libelle as label";
  2468. $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  2469. $sql.= " WHERE active > 0";
  2470. $sql.= " ORDER BY sortorder";
  2471. $resql = $this->db->query($sql);
  2472. if ($resql)
  2473. {
  2474. $num = $this->db->num_rows($resql);
  2475. $i = 0;
  2476. while ($i < $num)
  2477. {
  2478. $obj = $this->db->fetch_object($resql);
  2479. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2480. $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:''));
  2481. $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
  2482. $this->cache_conditions_paiements[$obj->rowid]['label']=$label;
  2483. $i++;
  2484. }
  2485. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  2486. return $num;
  2487. }
  2488. else
  2489. {
  2490. dol_print_error($this->db);
  2491. return -1;
  2492. }
  2493. }
  2494. /**
  2495. * Charge dans cache la liste des délais de livraison possibles
  2496. *
  2497. * @return int Nb of lines loaded, <0 if KO
  2498. */
  2499. function load_cache_availability()
  2500. {
  2501. global $langs;
  2502. $num = count($this->cache_availability);
  2503. if ($num > 0) return 0; // Cache already loaded
  2504. dol_syslog(__METHOD__, LOG_DEBUG);
  2505. $langs->load('propal');
  2506. $sql = "SELECT rowid, code, label";
  2507. $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
  2508. $sql.= " WHERE active > 0";
  2509. $resql = $this->db->query($sql);
  2510. if ($resql)
  2511. {
  2512. $num = $this->db->num_rows($resql);
  2513. $i = 0;
  2514. while ($i < $num)
  2515. {
  2516. $obj = $this->db->fetch_object($resql);
  2517. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2518. $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
  2519. $this->cache_availability[$obj->rowid]['code'] =$obj->code;
  2520. $this->cache_availability[$obj->rowid]['label']=$label;
  2521. $i++;
  2522. }
  2523. $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
  2524. return $num;
  2525. }
  2526. else
  2527. {
  2528. dol_print_error($this->db);
  2529. return -1;
  2530. }
  2531. }
  2532. /**
  2533. * Retourne la liste des types de delais de livraison possibles
  2534. *
  2535. * @param int $selected Id du type de delais pre-selectionne
  2536. * @param string $htmlname Nom de la zone select
  2537. * @param string $filtertype To add a filter
  2538. * @param int $addempty Add empty entry
  2539. * @return void
  2540. */
  2541. function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)
  2542. {
  2543. global $langs,$user;
  2544. $this->load_cache_availability();
  2545. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2546. print '<select class="flat" name="'.$htmlname.'">';
  2547. if ($addempty) print '<option value="0">&nbsp;</option>';
  2548. foreach($this->cache_availability as $id => $arrayavailability)
  2549. {
  2550. if ($selected == $id)
  2551. {
  2552. print '<option value="'.$id.'" selected>';
  2553. }
  2554. else
  2555. {
  2556. print '<option value="'.$id.'">';
  2557. }
  2558. print $arrayavailability['label'];
  2559. print '</option>';
  2560. }
  2561. print '</select>';
  2562. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2563. }
  2564. /**
  2565. * Load into cache cache_demand_reason, array of input reasons
  2566. *
  2567. * @return int Nb of lines loaded, <0 if KO
  2568. */
  2569. function loadCacheInputReason()
  2570. {
  2571. global $langs;
  2572. $num = count($this->cache_demand_reason);
  2573. if ($num > 0) return 0; // Cache already loaded
  2574. $sql = "SELECT rowid, code, label";
  2575. $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  2576. $sql.= " WHERE active > 0";
  2577. $resql = $this->db->query($sql);
  2578. if ($resql)
  2579. {
  2580. $num = $this->db->num_rows($resql);
  2581. $i = 0;
  2582. $tmparray=array();
  2583. while ($i < $num)
  2584. {
  2585. $obj = $this->db->fetch_object($resql);
  2586. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2587. $label=($langs->trans("DemandReasonType".$obj->code)!=("DemandReasonType".$obj->code)?$langs->trans("DemandReasonType".$obj->code):($obj->label!='-'?$obj->label:''));
  2588. $tmparray[$obj->rowid]['id'] =$obj->rowid;
  2589. $tmparray[$obj->rowid]['code'] =$obj->code;
  2590. $tmparray[$obj->rowid]['label']=$label;
  2591. $i++;
  2592. }
  2593. $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  2594. unset($tmparray);
  2595. return $num;
  2596. }
  2597. else
  2598. {
  2599. dol_print_error($this->db);
  2600. return -1;
  2601. }
  2602. }
  2603. /**
  2604. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  2605. * List found into table c_input_reason loaded by loadCacheInputReason
  2606. *
  2607. * @param int $selected Id or code of type origin to select by default
  2608. * @param string $htmlname Nom de la zone select
  2609. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  2610. * @param int $addempty Add an empty entry
  2611. * @return void
  2612. */
  2613. function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
  2614. {
  2615. global $langs,$user;
  2616. $this->loadCacheInputReason();
  2617. print '<select class="flat" name="'.$htmlname.'">';
  2618. if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
  2619. foreach($this->cache_demand_reason as $id => $arraydemandreason)
  2620. {
  2621. if ($arraydemandreason['code']==$exclude) continue;
  2622. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
  2623. {
  2624. print '<option value="'.$arraydemandreason['id'].'" selected>';
  2625. }
  2626. else
  2627. {
  2628. print '<option value="'.$arraydemandreason['id'].'">';
  2629. }
  2630. print $arraydemandreason['label'];
  2631. print '</option>';
  2632. }
  2633. print '</select>';
  2634. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2635. }
  2636. /**
  2637. * Charge dans cache la liste des types de paiements possibles
  2638. *
  2639. * @return int Nb of lines loaded, <0 if KO
  2640. */
  2641. function load_cache_types_paiements()
  2642. {
  2643. global $langs;
  2644. $num=count($this->cache_types_paiements);
  2645. if ($num > 0) return $num; // Cache already loaded
  2646. dol_syslog(__METHOD__, LOG_DEBUG);
  2647. $this->cache_types_paiements = array();
  2648. $sql = "SELECT id, code, libelle as label, type, active";
  2649. $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
  2650. //if ($active >= 0) $sql.= " WHERE active = ".$active;
  2651. $resql = $this->db->query($sql);
  2652. if ($resql)
  2653. {
  2654. $num = $this->db->num_rows($resql);
  2655. $i = 0;
  2656. while ($i < $num)
  2657. {
  2658. $obj = $this->db->fetch_object($resql);
  2659. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2660. $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
  2661. $this->cache_types_paiements[$obj->id]['id'] =$obj->id;
  2662. $this->cache_types_paiements[$obj->id]['code'] =$obj->code;
  2663. $this->cache_types_paiements[$obj->id]['label']=$label;
  2664. $this->cache_types_paiements[$obj->id]['type'] =$obj->type;
  2665. $this->cache_types_paiements[$obj->id]['active'] =$obj->active;
  2666. $i++;
  2667. }
  2668. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  2669. return $num;
  2670. }
  2671. else
  2672. {
  2673. dol_print_error($this->db);
  2674. return -1;
  2675. }
  2676. }
  2677. /**
  2678. * Return list of payment modes.
  2679. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  2680. * See instead to force the default value by the caller.
  2681. *
  2682. * @param int $selected Id of payment term to preselect by default
  2683. * @param string $htmlname Nom de la zone select
  2684. * @param int $filtertype Not used
  2685. * @param int $addempty Add an empty entry
  2686. * @return void
  2687. */
  2688. function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0)
  2689. {
  2690. global $langs, $user, $conf;
  2691. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2692. $this->load_cache_conditions_paiements();
  2693. // Set default value if not already set by caller
  2694. if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  2695. print '<select class="flat" name="'.$htmlname.'">';
  2696. if ($addempty) print '<option value="0">&nbsp;</option>';
  2697. foreach($this->cache_conditions_paiements as $id => $arrayconditions)
  2698. {
  2699. if ($selected == $id)
  2700. {
  2701. print '<option value="'.$id.'" selected>';
  2702. }
  2703. else
  2704. {
  2705. print '<option value="'.$id.'">';
  2706. }
  2707. print $arrayconditions['label'];
  2708. print '</option>';
  2709. }
  2710. print '</select>';
  2711. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2712. }
  2713. /**
  2714. * Return list of payment methods
  2715. *
  2716. * @param string $selected Id du mode de paiement pre-selectionne
  2717. * @param string $htmlname Nom de la zone select
  2718. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  2719. * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
  2720. * @param int $empty 1=peut etre vide, 0 sinon
  2721. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  2722. * @param int $maxlength Max length of label
  2723. * @param int $active Active or not, -1 = all
  2724. * @param string $morecss Add more css
  2725. * @return void
  2726. */
  2727. function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')
  2728. {
  2729. global $langs,$user;
  2730. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  2731. $filterarray=array();
  2732. if ($filtertype == 'CRDT') $filterarray=array(0,2,3);
  2733. elseif ($filtertype == 'DBIT') $filterarray=array(1,2,3);
  2734. elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
  2735. $this->load_cache_types_paiements();
  2736. print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
  2737. if ($empty) print '<option value="">&nbsp;</option>';
  2738. foreach($this->cache_types_paiements as $id => $arraytypes)
  2739. {
  2740. // If not good status
  2741. if ($active >= 0 && $arraytypes['active'] != $active) continue;
  2742. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  2743. if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
  2744. // We discard empty line if showempty is on because an empty line has already been output.
  2745. if ($empty && empty($arraytypes['code'])) continue;
  2746. if ($format == 0) print '<option value="'.$id.'"';
  2747. if ($format == 1) print '<option value="'.$arraytypes['code'].'"';
  2748. if ($format == 2) print '<option value="'.$arraytypes['code'].'"';
  2749. if ($format == 3) print '<option value="'.$id.'"';
  2750. // Si selected est text, on compare avec code, sinon avec id
  2751. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
  2752. elseif ($selected == $id) print ' selected';
  2753. print '>';
  2754. if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  2755. if ($format == 1) $value=$arraytypes['code'];
  2756. if ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  2757. if ($format == 3) $value=$arraytypes['code'];
  2758. print $value?$value:'&nbsp;';
  2759. print '</option>';
  2760. }
  2761. print '</select>';
  2762. if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2763. }
  2764. /**
  2765. * Selection HT or TTC
  2766. *
  2767. * @param string $selected Id pre-selectionne
  2768. * @param string $htmlname Nom de la zone select
  2769. * @return string Code of HTML select to chose tax or not
  2770. */
  2771. function selectPriceBaseType($selected='',$htmlname='price_base_type')
  2772. {
  2773. global $langs;
  2774. $return='';
  2775. $return.= '<select class="flat" name="'.$htmlname.'">';
  2776. $options = array(
  2777. 'HT'=>$langs->trans("HT"),
  2778. 'TTC'=>$langs->trans("TTC")
  2779. );
  2780. foreach($options as $id => $value)
  2781. {
  2782. if ($selected == $id)
  2783. {
  2784. $return.= '<option value="'.$id.'" selected>'.$value;
  2785. }
  2786. else
  2787. {
  2788. $return.= '<option value="'.$id.'">'.$value;
  2789. }
  2790. $return.= '</option>';
  2791. }
  2792. $return.= '</select>';
  2793. return $return;
  2794. }
  2795. /**
  2796. * Return a HTML select list of shipping mode
  2797. *
  2798. * @param string $selected Id shipping mode pre-selected
  2799. * @param string $htmlname Name of select zone
  2800. * @param string $filtre To filter list
  2801. * @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.
  2802. * @param string $moreattrib To add more attribute on select
  2803. * @return void
  2804. */
  2805. function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')
  2806. {
  2807. global $langs, $conf, $user;
  2808. $langs->load("admin");
  2809. $langs->load("deliveries");
  2810. $sql = "SELECT rowid, code, libelle as label";
  2811. $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
  2812. $sql.= " WHERE active > 0";
  2813. if ($filtre) $sql.=" AND ".$filtre;
  2814. $sql.= " ORDER BY libelle ASC";
  2815. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  2816. $result = $this->db->query($sql);
  2817. if ($result) {
  2818. $num = $this->db->num_rows($result);
  2819. $i = 0;
  2820. if ($num) {
  2821. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
  2822. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  2823. print '<option value="-1">&nbsp;</option>';
  2824. }
  2825. while ($i < $num) {
  2826. $obj = $this->db->fetch_object($result);
  2827. if ($selected == $obj->rowid) {
  2828. print '<option value="'.$obj->rowid.'" selected>';
  2829. } else {
  2830. print '<option value="'.$obj->rowid.'">';
  2831. }
  2832. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  2833. print '</option>';
  2834. $i++;
  2835. }
  2836. print "</select>";
  2837. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2838. } else {
  2839. print $langs->trans("NoShippingMethodDefined");
  2840. }
  2841. } else {
  2842. dol_print_error($this->db);
  2843. }
  2844. }
  2845. /**
  2846. * Display form to select shipping mode
  2847. *
  2848. * @param string $page Page
  2849. * @param int $selected Id of shipping mode
  2850. * @param string $htmlname Name of select html field
  2851. * @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.
  2852. * @return void
  2853. */
  2854. function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
  2855. {
  2856. global $langs, $db;
  2857. $langs->load("deliveries");
  2858. if ($htmlname != "none") {
  2859. print '<form method="POST" action="'.$page.'">';
  2860. print '<input type="hidden" name="action" value="setshippingmethod">';
  2861. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2862. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  2863. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  2864. print '</form>';
  2865. } else {
  2866. if ($selected) {
  2867. $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
  2868. print $langs->trans("SendingMethod".strtoupper($code));
  2869. } else {
  2870. print "&nbsp;";
  2871. }
  2872. }
  2873. }
  2874. /**
  2875. * Creates HTML last in cycle situation invoices selector
  2876. *
  2877. * @param string $selected Preselected ID
  2878. * @param int $socid Company ID
  2879. *
  2880. * @return string HTML select
  2881. */
  2882. function selectSituationInvoices($selected = '', $socid = 0)
  2883. {
  2884. global $langs;
  2885. $langs->load('bills');
  2886. $opt = '<option value ="" selected></option>';
  2887. $sql = 'SELECT rowid, facnumber, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';
  2888. $sql.= ' ORDER by situation_cycle_ref, situation_counter desc';
  2889. $resql = $this->db->query($sql);
  2890. if ($resql && $this->db->num_rows($resql) > 0) {
  2891. // Last seen cycle
  2892. $ref = 0;
  2893. while ($res = $this->db->fetch_array($resql, MYSQL_NUM)) {
  2894. //Same company ?
  2895. if ($socid == $res[5]) {
  2896. //Same cycle ?
  2897. if ($res[2] != $ref) {
  2898. // Just seen this cycle
  2899. $ref = $res[2];
  2900. //not final ?
  2901. if ($res[4] != 1) {
  2902. //Not prov?
  2903. if (substr($res[1], 1, 4) != 'PROV') {
  2904. if ($selected == $res[0]) {
  2905. $opt .= '<option value="' . $res[0] . '" selected>' . $res[1] . '</option>';
  2906. } else {
  2907. $opt .= '<option value="' . $res[0] . '">' . $res[1] . '</option>';
  2908. }
  2909. }
  2910. }
  2911. }
  2912. }
  2913. }
  2914. }
  2915. else
  2916. {
  2917. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  2918. }
  2919. if ($opt == '<option value ="" selected></option>')
  2920. {
  2921. $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
  2922. }
  2923. return $opt;
  2924. }
  2925. /**
  2926. * Creates HTML units selector (code => label)
  2927. *
  2928. * @param string $selected Preselected Unit ID
  2929. * @param string $htmlname Select name
  2930. * @param int $showempty Add a nempty line
  2931. * @return string HTML select
  2932. */
  2933. function selectUnits($selected = '', $htmlname = 'units', $showempty=0)
  2934. {
  2935. global $langs;
  2936. $langs->load('products');
  2937. $return= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  2938. $sql = 'SELECT rowid, label from '.MAIN_DB_PREFIX.'c_units';
  2939. $sql.= ' WHERE active > 0';
  2940. $resql = $this->db->query($sql);
  2941. if($resql && $this->db->num_rows($resql) > 0)
  2942. {
  2943. if ($showempty) $return .= '<option value="none"></option>';
  2944. while($res = $this->db->fetch_object($resql))
  2945. {
  2946. if ($selected == $res->rowid)
  2947. {
  2948. $return.='<option value="'.$res->rowid.'" selected>'.($langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label).'</option>';
  2949. }
  2950. else
  2951. {
  2952. $return.='<option value="'.$res->rowid.'">'.($langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label).'</option>';
  2953. }
  2954. }
  2955. $return.='</select>';
  2956. }
  2957. return $return;
  2958. }
  2959. /**
  2960. * Return a HTML select list of bank accounts
  2961. *
  2962. * @param string $selected Id account pre-selected
  2963. * @param string $htmlname Name of select zone
  2964. * @param int $statut Status of searched accounts (0=open, 1=closed, 2=both)
  2965. * @param string $filtre To filter list
  2966. * @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.
  2967. * @param string $moreattrib To add more attribute on select
  2968. * @return void
  2969. */
  2970. function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='')
  2971. {
  2972. global $langs, $conf;
  2973. $langs->load("admin");
  2974. $sql = "SELECT rowid, label, bank, clos as status";
  2975. $sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
  2976. $sql.= " WHERE entity IN (".getEntity('bank_account').")";
  2977. if ($statut != 2) $sql.= " AND clos = '".$statut."'";
  2978. if ($filtre) $sql.=" AND ".$filtre;
  2979. $sql.= " ORDER BY label";
  2980. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  2981. $result = $this->db->query($sql);
  2982. if ($result)
  2983. {
  2984. $num = $this->db->num_rows($result);
  2985. $i = 0;
  2986. if ($num)
  2987. {
  2988. print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
  2989. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  2990. {
  2991. print '<option value="-1">&nbsp;</option>';
  2992. }
  2993. while ($i < $num)
  2994. {
  2995. $obj = $this->db->fetch_object($result);
  2996. if ($selected == $obj->rowid)
  2997. {
  2998. print '<option value="'.$obj->rowid.'" selected>';
  2999. }
  3000. else
  3001. {
  3002. print '<option value="'.$obj->rowid.'">';
  3003. }
  3004. print trim($obj->label);
  3005. if ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  3006. print '</option>';
  3007. $i++;
  3008. }
  3009. print "</select>";
  3010. }
  3011. else
  3012. {
  3013. print $langs->trans("NoActiveBankAccountDefined");
  3014. }
  3015. }
  3016. else {
  3017. dol_print_error($this->db);
  3018. }
  3019. }
  3020. /**
  3021. * Display form to select bank account
  3022. *
  3023. * @param string $page Page
  3024. * @param int $selected Id of bank account
  3025. * @param string $htmlname Name of select html field
  3026. * @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.
  3027. * @return void
  3028. */
  3029. function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
  3030. {
  3031. global $langs;
  3032. if ($htmlname != "none") {
  3033. print '<form method="POST" action="'.$page.'">';
  3034. print '<input type="hidden" name="action" value="setbankaccount">';
  3035. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3036. $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  3037. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3038. print '</form>';
  3039. } else {
  3040. $langs->load('banks');
  3041. if ($selected) {
  3042. require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
  3043. $bankstatic=new Account($this->db);
  3044. $bankstatic->fetch($selected);
  3045. print $this->textwithpicto($bankstatic->getNomUrl(1),$langs->trans("AccountCurrency").'&nbsp;'.$bankstatic->currency_code);
  3046. } else {
  3047. print "&nbsp;";
  3048. }
  3049. }
  3050. }
  3051. /**
  3052. * Return list of categories having choosed type
  3053. *
  3054. * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  3055. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element)
  3056. * @param string $htmlname HTML field name
  3057. * @param int $maxlength Maximum length for labels
  3058. * @param int $excludeafterid Exclude all categories after this leaf in category tree.
  3059. * @param int $outputmode 0=HTML select string, 1=Array
  3060. * @return string
  3061. * @see select_categories
  3062. */
  3063. function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0)
  3064. {
  3065. global $conf, $langs;
  3066. $langs->load("categories");
  3067. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  3068. // For backward compatibility
  3069. if (is_numeric($type))
  3070. {
  3071. dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  3072. }
  3073. if ($type === Categorie::TYPE_BANK_LINE)
  3074. {
  3075. // TODO Move this into common category feature
  3076. $categids=array();
  3077. $sql = "SELECT c.label, c.rowid";
  3078. $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
  3079. $sql.= " WHERE entity = ".$conf->entity;
  3080. $sql.= " ORDER BY c.label";
  3081. $result = $this->db->query($sql);
  3082. if ($result)
  3083. {
  3084. $num = $this->db->num_rows($result);
  3085. $i = 0;
  3086. while ($i < $num)
  3087. {
  3088. $objp = $this->db->fetch_object($result);
  3089. if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  3090. $i++;
  3091. }
  3092. $this->db->free($result);
  3093. }
  3094. else dol_print_error($this->db);
  3095. }
  3096. else
  3097. {
  3098. $cat = new Categorie($this->db);
  3099. $cate_arbo = $cat->get_full_arbo($type,$excludeafterid);
  3100. }
  3101. $output = '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  3102. $outarray=array();
  3103. if (is_array($cate_arbo))
  3104. {
  3105. if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  3106. else
  3107. {
  3108. $output.= '<option value="-1">&nbsp;</option>';
  3109. foreach($cate_arbo as $key => $value)
  3110. {
  3111. if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
  3112. {
  3113. $add = 'selected ';
  3114. }
  3115. else
  3116. {
  3117. $add = '';
  3118. }
  3119. $output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
  3120. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  3121. }
  3122. }
  3123. }
  3124. $output.= '</select>';
  3125. $output.= "\n";
  3126. if ($outputmode) return $outarray;
  3127. return $output;
  3128. }
  3129. /**
  3130. * Show a confirmation HTML form or AJAX popup
  3131. *
  3132. * @param string $page Url of page to call if confirmation is OK
  3133. * @param string $title Title
  3134. * @param string $question Question
  3135. * @param string $action Action
  3136. * @param array $formquestion An array with forms complementary inputs
  3137. * @param string $selectedchoice "" or "no" or "yes"
  3138. * @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
  3139. * @param int $height Force height of box
  3140. * @param int $width Force width of box
  3141. * @return void
  3142. * @deprecated
  3143. * @see formconfirm()
  3144. */
  3145. function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
  3146. {
  3147. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  3148. }
  3149. /**
  3150. * Show a confirmation HTML form or AJAX popup.
  3151. * Easiest way to use this is with useajax=1.
  3152. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  3153. * just after calling this method. For example:
  3154. * print '<script type="text/javascript">'."\n";
  3155. * print 'jQuery(document).ready(function() {'."\n";
  3156. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  3157. * print '});'."\n";
  3158. * print '</script>'."\n";
  3159. *
  3160. * @param string $page Url of page to call if confirmation is OK
  3161. * @param string $title Title
  3162. * @param string $question Question
  3163. * @param string $action Action
  3164. * @param array $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
  3165. * @param string $selectedchoice "" or "no" or "yes"
  3166. * @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
  3167. * @param int $height Force height of box
  3168. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  3169. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  3170. */
  3171. function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=200, $width=500)
  3172. {
  3173. global $langs,$conf;
  3174. global $useglobalvars;
  3175. $more='';
  3176. $formconfirm='';
  3177. $inputok=array();
  3178. $inputko=array();
  3179. // Clean parameters
  3180. $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
  3181. if ($conf->browser->layout == 'phone') $width='95%';
  3182. if (is_array($formquestion) && ! empty($formquestion))
  3183. {
  3184. // First add hidden fields and value
  3185. foreach ($formquestion as $key => $input)
  3186. {
  3187. if (is_array($input) && ! empty($input))
  3188. {
  3189. if ($input['type'] == 'hidden')
  3190. {
  3191. $more.='<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  3192. }
  3193. }
  3194. }
  3195. // Now add questions
  3196. $more.='<table class="paddingtopbottomonly" width="100%">'."\n";
  3197. $more.='<tr><td colspan="3">'.(! empty($formquestion['text'])?$formquestion['text']:'').'</td></tr>'."\n";
  3198. foreach ($formquestion as $key => $input)
  3199. {
  3200. if (is_array($input) && ! empty($input))
  3201. {
  3202. $size=(! empty($input['size'])?' size="'.$input['size'].'"':'');
  3203. if ($input['type'] == 'text')
  3204. {
  3205. $more.='<tr><td>'.$input['label'].'</td><td colspan="2" align="left"><input type="text" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'" /></td></tr>'."\n";
  3206. }
  3207. else if ($input['type'] == 'password')
  3208. {
  3209. $more.='<tr><td>'.$input['label'].'</td><td colspan="2" align="left"><input type="password" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'" /></td></tr>'."\n";
  3210. }
  3211. else if ($input['type'] == 'select')
  3212. {
  3213. $more.='<tr><td>';
  3214. if (! empty($input['label'])) $more.=$input['label'].'</td><td valign="top" colspan="2" align="left">';
  3215. $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1);
  3216. $more.='</td></tr>'."\n";
  3217. }
  3218. else if ($input['type'] == 'checkbox')
  3219. {
  3220. $more.='<tr>';
  3221. $more.='<td>'.$input['label'].' </td><td align="left">';
  3222. $more.='<input type="checkbox" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"';
  3223. if (! is_bool($input['value']) && $input['value'] != 'false') $more.=' checked';
  3224. if (is_bool($input['value']) && $input['value']) $more.=' checked';
  3225. if (isset($input['disabled'])) $more.=' disabled';
  3226. $more.=' /></td>';
  3227. $more.='<td align="left">&nbsp;</td>';
  3228. $more.='</tr>'."\n";
  3229. }
  3230. else if ($input['type'] == 'radio')
  3231. {
  3232. $i=0;
  3233. foreach($input['values'] as $selkey => $selval)
  3234. {
  3235. $more.='<tr>';
  3236. if ($i==0) $more.='<td class="tdtop">'.$input['label'].'</td>';
  3237. else $more.='<td>&nbsp;</td>';
  3238. $more.='<td width="20"><input type="radio" class="flat" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"';
  3239. if ($input['disabled']) $more.=' disabled';
  3240. $more.=' /></td>';
  3241. $more.='<td align="left">';
  3242. $more.=$selval;
  3243. $more.='</td></tr>'."\n";
  3244. $i++;
  3245. }
  3246. }
  3247. else if ($input['type'] == 'date')
  3248. {
  3249. $more.='<tr><td>'.$input['label'].'</td>';
  3250. $more.='<td colspan="2" align="left">';
  3251. $more.=$this->select_date($input['value'],$input['name'],0,0,0,'',1,0,1);
  3252. $more.='</td></tr>'."\n";
  3253. $formquestion[] = array('name'=>$input['name'].'day');
  3254. $formquestion[] = array('name'=>$input['name'].'month');
  3255. $formquestion[] = array('name'=>$input['name'].'year');
  3256. $formquestion[] = array('name'=>$input['name'].'hour');
  3257. $formquestion[] = array('name'=>$input['name'].'min');
  3258. }
  3259. else if ($input['type'] == 'other')
  3260. {
  3261. $more.='<tr><td>';
  3262. if (! empty($input['label'])) $more.=$input['label'].'</td><td colspan="2" align="left">';
  3263. $more.=$input['value'];
  3264. $more.='</td></tr>'."\n";
  3265. }
  3266. }
  3267. }
  3268. $more.='</table>'."\n";
  3269. }
  3270. // JQUI method dialog is broken with jmobile, we use standard HTML.
  3271. // 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
  3272. // See page product/card.php for example
  3273. if (! empty($conf->dol_use_jmobile)) $useajax=0;
  3274. if (empty($conf->use_javascript_ajax)) $useajax=0;
  3275. if ($useajax)
  3276. {
  3277. $autoOpen=true;
  3278. $dialogconfirm='dialog-confirm';
  3279. $button='';
  3280. if (! is_numeric($useajax))
  3281. {
  3282. $button=$useajax;
  3283. $useajax=1;
  3284. $autoOpen=false;
  3285. $dialogconfirm.='-'.$button;
  3286. }
  3287. $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';
  3288. $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':'');
  3289. // Add input fields into list of fields to read during submit (inputok and inputko)
  3290. if (is_array($formquestion))
  3291. {
  3292. foreach ($formquestion as $key => $input)
  3293. {
  3294. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  3295. if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
  3296. if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
  3297. }
  3298. }
  3299. // Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
  3300. $formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  3301. if (! empty($more)) {
  3302. $formconfirm.= '<div class="confirmquestions">'.$more.'</div>';
  3303. }
  3304. $formconfirm.= ($question ? '<div class="confirmmessage">'.img_help('','').' '.$question . '</div>': '');
  3305. $formconfirm.= '</div>'."\n";
  3306. $formconfirm.= "\n<!-- begin ajax form_confirm page=".$page." -->\n";
  3307. $formconfirm.= '<script type="text/javascript">'."\n";
  3308. $formconfirm.= 'jQuery(document).ready(function() {
  3309. $(function() {
  3310. $( "#'.$dialogconfirm.'" ).dialog(
  3311. {
  3312. autoOpen: '.($autoOpen ? "true" : "false").',';
  3313. if ($newselectedchoice == 'no')
  3314. {
  3315. $formconfirm.='
  3316. open: function() {
  3317. $(this).parent().find("button.ui-button:eq(2)").focus();
  3318. },';
  3319. }
  3320. $formconfirm.='
  3321. resizable: false,
  3322. height: "'.$height.'",
  3323. width: "'.$width.'",
  3324. modal: true,
  3325. closeOnEscape: false,
  3326. buttons: {
  3327. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  3328. var options="";
  3329. var inputok = '.json_encode($inputok).';
  3330. var pageyes = "'.dol_escape_js(! empty($pageyes)?$pageyes:'').'";
  3331. if (inputok.length>0) {
  3332. $.each(inputok, function(i, inputname) {
  3333. var more = "";
  3334. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3335. if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
  3336. var inputvalue = $("#" + inputname + more).val();
  3337. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3338. options += "&" + inputname + "=" + inputvalue;
  3339. });
  3340. }
  3341. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  3342. //alert(urljump);
  3343. if (pageyes.length > 0) { location.href = urljump; }
  3344. $(this).dialog("close");
  3345. },
  3346. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  3347. var options = "";
  3348. var inputko = '.json_encode($inputko).';
  3349. var pageno="'.dol_escape_js(! empty($pageno)?$pageno:'').'";
  3350. if (inputko.length>0) {
  3351. $.each(inputko, function(i, inputname) {
  3352. var more = "";
  3353. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3354. var inputvalue = $("#" + inputname + more).val();
  3355. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3356. options += "&" + inputname + "=" + inputvalue;
  3357. });
  3358. }
  3359. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  3360. //alert(urljump);
  3361. if (pageno.length > 0) { location.href = urljump; }
  3362. $(this).dialog("close");
  3363. }
  3364. }
  3365. }
  3366. );
  3367. var button = "'.$button.'";
  3368. if (button.length > 0) {
  3369. $( "#" + button ).click(function() {
  3370. $("#'.$dialogconfirm.'").dialog("open");
  3371. });
  3372. }
  3373. });
  3374. });
  3375. </script>';
  3376. $formconfirm.= "<!-- end ajax form_confirm -->\n";
  3377. }
  3378. else
  3379. {
  3380. $formconfirm.= "\n<!-- begin form_confirm page=".$page." -->\n";
  3381. $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  3382. $formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  3383. $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
  3384. $formconfirm.= '<table width="100%" class="valid">'."\n";
  3385. // Line title
  3386. $formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
  3387. // Line form fields
  3388. if ($more)
  3389. {
  3390. $formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
  3391. $formconfirm.=$more;
  3392. $formconfirm.='</td></tr>'."\n";
  3393. }
  3394. // Line with question
  3395. $formconfirm.= '<tr class="valid">';
  3396. $formconfirm.= '<td class="valid">'.$question.'</td>';
  3397. $formconfirm.= '<td class="valid">';
  3398. $formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
  3399. $formconfirm.= '</td>';
  3400. $formconfirm.= '<td class="valid" align="center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
  3401. $formconfirm.= '</tr>'."\n";
  3402. $formconfirm.= '</table>'."\n";
  3403. $formconfirm.= "</form>\n";
  3404. $formconfirm.= '<br>';
  3405. $formconfirm.= "<!-- end form_confirm -->\n";
  3406. }
  3407. return $formconfirm;
  3408. }
  3409. /**
  3410. * Show a form to select a project
  3411. *
  3412. * @param int $page Page
  3413. * @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)
  3414. * @param int $selected Id pre-selected project
  3415. * @param string $htmlname Name of select field
  3416. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  3417. * @param int $maxlength Max length
  3418. * @param int $forcefocus Force focus on field (works with javascript only)
  3419. * @param int $nooutput No print is done. String is returned.
  3420. * @return string Return html content
  3421. */
  3422. function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)
  3423. {
  3424. global $langs;
  3425. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  3426. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  3427. $out='';
  3428. $formproject=new FormProjets($this->db);
  3429. $langs->load("project");
  3430. if ($htmlname != "none")
  3431. {
  3432. $out.="\n";
  3433. $out.='<form method="post" action="'.$page.'">';
  3434. $out.='<input type="hidden" name="action" value="classin">';
  3435. $out.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3436. $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  3437. $out.='<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3438. $out.='</form>';
  3439. }
  3440. else
  3441. {
  3442. if ($selected)
  3443. {
  3444. $projet = new Project($this->db);
  3445. $projet->fetch($selected);
  3446. //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
  3447. $out.=$projet->getNomUrl(0,'',1);
  3448. }
  3449. else
  3450. {
  3451. $out.="&nbsp;";
  3452. }
  3453. }
  3454. if (empty($nooutput))
  3455. {
  3456. print $out;
  3457. return '';
  3458. }
  3459. return $out;
  3460. }
  3461. /**
  3462. * Show a form to select payment conditions
  3463. *
  3464. * @param int $page Page
  3465. * @param string $selected Id condition pre-selectionne
  3466. * @param string $htmlname Name of select html field
  3467. * @param int $addempty Add empty entry
  3468. * @return void
  3469. */
  3470. function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
  3471. {
  3472. global $langs;
  3473. if ($htmlname != "none")
  3474. {
  3475. print '<form method="post" action="'.$page.'">';
  3476. print '<input type="hidden" name="action" value="setconditions">';
  3477. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3478. $this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
  3479. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3480. print '</form>';
  3481. }
  3482. else
  3483. {
  3484. if ($selected)
  3485. {
  3486. $this->load_cache_conditions_paiements();
  3487. print $this->cache_conditions_paiements[$selected]['label'];
  3488. } else {
  3489. print "&nbsp;";
  3490. }
  3491. }
  3492. }
  3493. /**
  3494. * Show a form to select a delivery delay
  3495. *
  3496. * @param int $page Page
  3497. * @param string $selected Id condition pre-selectionne
  3498. * @param string $htmlname Name of select html field
  3499. * @param int $addempty Ajoute entree vide
  3500. * @return void
  3501. */
  3502. function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
  3503. {
  3504. global $langs;
  3505. if ($htmlname != "none")
  3506. {
  3507. print '<form method="post" action="'.$page.'">';
  3508. print '<input type="hidden" name="action" value="setavailability">';
  3509. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3510. $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
  3511. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3512. print '</form>';
  3513. }
  3514. else
  3515. {
  3516. if ($selected)
  3517. {
  3518. $this->load_cache_availability();
  3519. print $this->cache_availability[$selected]['label'];
  3520. } else {
  3521. print "&nbsp;";
  3522. }
  3523. }
  3524. }
  3525. /**
  3526. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3527. * List found into table c_input_reason loaded by loadCacheInputReason
  3528. *
  3529. * @param string $page Page
  3530. * @param string $selected Id condition pre-selectionne
  3531. * @param string $htmlname Name of select html field
  3532. * @param int $addempty Add empty entry
  3533. * @return void
  3534. */
  3535. function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)
  3536. {
  3537. global $langs;
  3538. if ($htmlname != "none")
  3539. {
  3540. print '<form method="post" action="'.$page.'">';
  3541. print '<input type="hidden" name="action" value="setdemandreason">';
  3542. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3543. $this->selectInputReason($selected,$htmlname,-1,$addempty);
  3544. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3545. print '</form>';
  3546. }
  3547. else
  3548. {
  3549. if ($selected)
  3550. {
  3551. $this->loadCacheInputReason();
  3552. foreach ($this->cache_demand_reason as $key => $val)
  3553. {
  3554. if ($val['id'] == $selected)
  3555. {
  3556. print $val['label'];
  3557. break;
  3558. }
  3559. }
  3560. } else {
  3561. print "&nbsp;";
  3562. }
  3563. }
  3564. }
  3565. /**
  3566. * Show a form + html select a date
  3567. *
  3568. * @param string $page Page
  3569. * @param string $selected Date preselected
  3570. * @param string $htmlname Html name of date input fields or 'none'
  3571. * @param int $displayhour Display hour selector
  3572. * @param int $displaymin Display minutes selector
  3573. * @param int $nooutput 1=No print output, return string
  3574. * @return string
  3575. * @see select_date
  3576. */
  3577. function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)
  3578. {
  3579. global $langs;
  3580. $ret='';
  3581. if ($htmlname != "none")
  3582. {
  3583. $ret.='<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
  3584. $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
  3585. $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3586. $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3587. $ret.='<tr><td>';
  3588. $ret.=$this->select_date($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0,1);
  3589. $ret.='</td>';
  3590. $ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3591. $ret.='</tr></table></form>';
  3592. }
  3593. else
  3594. {
  3595. if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
  3596. else $ret.=dol_print_date($selected,'day');
  3597. }
  3598. if (empty($nooutput)) print $ret;
  3599. return $ret;
  3600. }
  3601. /**
  3602. * Show a select form to choose a user
  3603. *
  3604. * @param string $page Page
  3605. * @param string $selected Id of user preselected
  3606. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  3607. * @param array $exclude List of users id to exclude
  3608. * @param array $include List of users id to include
  3609. * @return void
  3610. */
  3611. function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
  3612. {
  3613. global $langs;
  3614. if ($htmlname != "none")
  3615. {
  3616. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  3617. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  3618. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3619. print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
  3620. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3621. print '</form>';
  3622. }
  3623. else
  3624. {
  3625. if ($selected)
  3626. {
  3627. require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
  3628. $theuser=new User($this->db);
  3629. $theuser->fetch($selected);
  3630. print $theuser->getNomUrl(1);
  3631. } else {
  3632. print "&nbsp;";
  3633. }
  3634. }
  3635. }
  3636. /**
  3637. * Show form with payment mode
  3638. *
  3639. * @param string $page Page
  3640. * @param int $selected Id mode pre-selectionne
  3641. * @param string $htmlname Name of select html field
  3642. * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
  3643. * @param int $active Active or not, -1 = all
  3644. * @return void
  3645. */
  3646. function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)
  3647. {
  3648. global $langs;
  3649. if ($htmlname != "none")
  3650. {
  3651. print '<form method="POST" action="'.$page.'">';
  3652. print '<input type="hidden" name="action" value="setmode">';
  3653. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3654. $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);
  3655. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3656. print '</form>';
  3657. }
  3658. else
  3659. {
  3660. if ($selected)
  3661. {
  3662. $this->load_cache_types_paiements();
  3663. print $this->cache_types_paiements[$selected]['label'];
  3664. } else {
  3665. print "&nbsp;";
  3666. }
  3667. }
  3668. }
  3669. /**
  3670. * Show form with multicurrency code
  3671. *
  3672. * @param string $page Page
  3673. * @param string $selected code pre-selectionne
  3674. * @param string $htmlname Name of select html field
  3675. * @return void
  3676. */
  3677. function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
  3678. {
  3679. global $langs;
  3680. if ($htmlname != "none")
  3681. {
  3682. print '<form method="POST" action="'.$page.'">';
  3683. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  3684. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3685. print $this->selectMultiCurrency($selected, $htmlname, 0);
  3686. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3687. print '</form>';
  3688. }
  3689. else
  3690. {
  3691. dol_include_once('/core/lib/company.lib.php');
  3692. print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
  3693. }
  3694. }
  3695. /**
  3696. * Show form with multicurrency rate
  3697. *
  3698. * @param string $page Page
  3699. * @param double $rate Current rate
  3700. * @param string $htmlname Name of select html field
  3701. * @param string $currency Currency code to explain the rate
  3702. * @return void
  3703. */
  3704. function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
  3705. {
  3706. global $langs, $mysoc, $conf;
  3707. if ($htmlname != "none")
  3708. {
  3709. print '<form method="POST" action="'.$page.'">';
  3710. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  3711. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3712. print '<input type="text" name="'.$htmlname.'" value="'.(!empty($rate) ? price($rate) : 1).'" size="10" /> ';
  3713. print '<select name="calculation_mode">';
  3714. print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
  3715. print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
  3716. print '</select> ';
  3717. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3718. print '</form>';
  3719. }
  3720. else
  3721. {
  3722. if (! empty($rate))
  3723. {
  3724. print price($rate, 1, $langs, 1, 0);
  3725. if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  3726. }
  3727. else
  3728. {
  3729. print 1;
  3730. }
  3731. }
  3732. }
  3733. /**
  3734. * Show a select box with available absolute discounts
  3735. *
  3736. * @param string $page Page URL where form is shown
  3737. * @param int $selected Value pre-selected
  3738. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  3739. * @param int $socid Third party id
  3740. * @param float $amount Total amount available
  3741. * @param string $filter SQL filter on discounts
  3742. * @param int $maxvalue Max value for lines that can be selected
  3743. * @param string $more More string to add
  3744. * @param int $hidelist 1=Hide list
  3745. * @return void
  3746. */
  3747. function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0)
  3748. {
  3749. global $conf,$langs;
  3750. if ($htmlname != "none")
  3751. {
  3752. print '<form method="post" action="'.$page.'">';
  3753. print '<input type="hidden" name="action" value="setabsolutediscount">';
  3754. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3755. print '<div class="inline-block">';
  3756. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  3757. {
  3758. if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice
  3759. else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency));
  3760. }
  3761. else
  3762. {
  3763. if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%'))") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency));
  3764. else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency));
  3765. }
  3766. if (empty($hidelist)) print ': ';
  3767. print '</div>';
  3768. if (empty($hidelist))
  3769. {
  3770. print '<div class="inline-block" style="padding-right: 10px">';
  3771. $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles
  3772. if ($filter) $newfilter.=' AND ('.$filter.')';
  3773. $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
  3774. if ($nbqualifiedlines > 0)
  3775. {
  3776. print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  3777. if ($filter && $filter != "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')") print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  3778. print '>';
  3779. }
  3780. print '</div>';
  3781. }
  3782. if ($more)
  3783. {
  3784. print '<div class="inline-block">';
  3785. print $more;
  3786. print '</div>';
  3787. }
  3788. print '</form>';
  3789. }
  3790. else
  3791. {
  3792. if ($selected)
  3793. {
  3794. print $selected;
  3795. }
  3796. else
  3797. {
  3798. print "0";
  3799. }
  3800. }
  3801. }
  3802. /**
  3803. * Show forms to select a contact
  3804. *
  3805. * @param string $page Page
  3806. * @param Societe $societe Filter on third party
  3807. * @param int $selected Id contact pre-selectionne
  3808. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  3809. * @return void
  3810. */
  3811. function form_contacts($page, $societe, $selected='', $htmlname='contactid')
  3812. {
  3813. global $langs, $conf;
  3814. if ($htmlname != "none")
  3815. {
  3816. print '<form method="post" action="'.$page.'">';
  3817. print '<input type="hidden" name="action" value="set_contact">';
  3818. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3819. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3820. print '<tr><td>';
  3821. $num=$this->select_contacts($societe->id, $selected, $htmlname);
  3822. if ($num==0)
  3823. {
  3824. $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  3825. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  3826. }
  3827. print '</td>';
  3828. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3829. print '</tr></table></form>';
  3830. }
  3831. else
  3832. {
  3833. if ($selected)
  3834. {
  3835. require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
  3836. $contact=new Contact($this->db);
  3837. $contact->fetch($selected);
  3838. print $contact->getFullName($langs);
  3839. } else {
  3840. print "&nbsp;";
  3841. }
  3842. }
  3843. }
  3844. /**
  3845. * Output html select to select thirdparty
  3846. *
  3847. * @param string $page Page
  3848. * @param string $selected Id preselected
  3849. * @param string $htmlname Name of HTML select
  3850. * @param string $filter optional filters criteras
  3851. * @param int $showempty Add an empty field
  3852. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  3853. * @param int $forcecombo Force to use combo box
  3854. * @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')))
  3855. * @return void
  3856. */
  3857. function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array())
  3858. {
  3859. global $langs;
  3860. if ($htmlname != "none")
  3861. {
  3862. print '<form method="post" action="'.$page.'">';
  3863. print '<input type="hidden" name="action" value="set_thirdparty">';
  3864. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3865. print $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
  3866. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3867. print '</form>';
  3868. }
  3869. else
  3870. {
  3871. if ($selected)
  3872. {
  3873. require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
  3874. $soc = new Societe($this->db);
  3875. $soc->fetch($selected);
  3876. print $soc->getNomUrl($langs);
  3877. }
  3878. else
  3879. {
  3880. print "&nbsp;";
  3881. }
  3882. }
  3883. }
  3884. /**
  3885. * Retourne la liste des devises, dans la langue de l'utilisateur
  3886. *
  3887. * @param string $selected preselected currency code
  3888. * @param string $htmlname name of HTML select list
  3889. * @return void
  3890. */
  3891. function select_currency($selected='',$htmlname='currency_id')
  3892. {
  3893. print $this->selectcurrency($selected,$htmlname);
  3894. }
  3895. /**
  3896. * Retourne la liste des devises, dans la langue de l'utilisateur
  3897. *
  3898. * @param string $selected preselected currency code
  3899. * @param string $htmlname name of HTML select list
  3900. * @return string
  3901. */
  3902. function selectCurrency($selected='',$htmlname='currency_id')
  3903. {
  3904. global $conf,$langs,$user;
  3905. $langs->loadCacheCurrencies('');
  3906. $out='';
  3907. if ($selected=='euro' || $selected=='euros') $selected='EUR'; // Pour compatibilite
  3908. $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  3909. foreach ($langs->cache_currencies as $code_iso => $currency)
  3910. {
  3911. if ($selected && $selected == $code_iso)
  3912. {
  3913. $out.= '<option value="'.$code_iso.'" selected>';
  3914. }
  3915. else
  3916. {
  3917. $out.= '<option value="'.$code_iso.'">';
  3918. }
  3919. $out.= $currency['label'];
  3920. $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
  3921. $out.= '</option>';
  3922. }
  3923. $out.= '</select>';
  3924. if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  3925. return $out;
  3926. }
  3927. /**
  3928. * Return array of currencies in user language
  3929. *
  3930. * @param string $selected preselected currency code
  3931. * @param string $htmlname name of HTML select list
  3932. * @param integer $useempty 1=Add empty line
  3933. * @return string
  3934. */
  3935. function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)
  3936. {
  3937. global $db,$conf,$langs,$user;
  3938. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  3939. $TCurrency = array();
  3940. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
  3941. $sql.= " WHERE entity IN ('".getEntity('mutlicurrency', 0)."')";
  3942. $resql = $db->query($sql);
  3943. if ($resql)
  3944. {
  3945. while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
  3946. }
  3947. $out='';
  3948. $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  3949. if ($useempty) $out .= '<option value=""></option>';
  3950. // If company current currency not in table, we add it into list. Should always be available.
  3951. if (! in_array($conf->currency, $TCurrency))
  3952. {
  3953. $TCurrency[$conf->currency] = $conf->currency;
  3954. }
  3955. if (count($TCurrency) > 0)
  3956. {
  3957. foreach ($langs->cache_currencies as $code_iso => $currency)
  3958. {
  3959. if (isset($TCurrency[$code_iso]))
  3960. {
  3961. if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
  3962. else $out.= '<option value="'.$code_iso.'">';
  3963. $out.= $currency['label'];
  3964. $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
  3965. $out.= '</option>';
  3966. }
  3967. }
  3968. }
  3969. $out.= '</select>';
  3970. // Make select dynamic
  3971. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  3972. $out.= ajax_combobox($htmlname);
  3973. return $out;
  3974. }
  3975. /**
  3976. * Load into the cache vat rates of a country
  3977. *
  3978. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  3979. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  3980. */
  3981. function load_cache_vatrates($country_code)
  3982. {
  3983. global $langs;
  3984. $num = count($this->cache_vatrates);
  3985. if ($num > 0) return $num; // Cache already loaded
  3986. dol_syslog(__METHOD__, LOG_DEBUG);
  3987. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  3988. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  3989. $sql.= " WHERE t.fk_pays = c.rowid";
  3990. $sql.= " AND t.active > 0";
  3991. $sql.= " AND c.code IN (".$country_code.")";
  3992. $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  3993. $resql=$this->db->query($sql);
  3994. if ($resql)
  3995. {
  3996. $num = $this->db->num_rows($resql);
  3997. if ($num)
  3998. {
  3999. for ($i = 0; $i < $num; $i++)
  4000. {
  4001. $obj = $this->db->fetch_object($resql);
  4002. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  4003. $this->cache_vatrates[$i]['code'] = $obj->code;
  4004. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  4005. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  4006. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  4007. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  4008. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  4009. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  4010. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or *
  4011. $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
  4012. $positiverates='';
  4013. if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;
  4014. if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;
  4015. if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;
  4016. if (empty($positiverates)) $positiverates='0';
  4017. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label
  4018. }
  4019. return $num;
  4020. }
  4021. else
  4022. {
  4023. $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
  4024. return -1;
  4025. }
  4026. }
  4027. else
  4028. {
  4029. $this->error = '<font class="error">'.$this->db->error().'</font>';
  4030. return -2;
  4031. }
  4032. }
  4033. /**
  4034. * Output an HTML select vat rate.
  4035. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  4036. *
  4037. * @param string $htmlname Name of HTML select field
  4038. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  4039. * @param Societe $societe_vendeuse Thirdparty seller
  4040. * @param Societe $societe_acheteuse Thirdparty buyer
  4041. * @param int $idprod Id product. O if unknown of NA.
  4042. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  4043. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  4044. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4045. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4046. * 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.
  4047. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  4048. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  4049. * Sinon la TVA proposee par defaut=0. Fin de regle.
  4050. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  4051. * @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
  4052. * @return string
  4053. */
  4054. function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)
  4055. {
  4056. global $langs,$conf,$mysoc;
  4057. $return='';
  4058. // Define defaultnpr, defaultttx and defaultcode
  4059. $defaultnpr=($info_bits & 0x01);
  4060. $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
  4061. $defaulttx=str_replace('*','',$selectedrate);
  4062. $defaultcode='';
  4063. if (preg_match('/\((.*)\)/', $defaulttx, $reg))
  4064. {
  4065. $defaultcode=$reg[1];
  4066. $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
  4067. }
  4068. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  4069. // Check parameters
  4070. if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
  4071. {
  4072. if ($societe_vendeuse->id == $mysoc->id)
  4073. {
  4074. $return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
  4075. }
  4076. else
  4077. {
  4078. $return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
  4079. }
  4080. return $return;
  4081. }
  4082. //var_dump($societe_acheteuse);
  4083. //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";
  4084. //exit;
  4085. // Define list of countries to use to search VAT rates to show
  4086. // First we defined code_country to use to find list
  4087. if (is_object($societe_vendeuse))
  4088. {
  4089. $code_country="'".$societe_vendeuse->country_code."'";
  4090. }
  4091. else
  4092. {
  4093. $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  4094. }
  4095. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on
  4096. {
  4097. if (! $societe_vendeuse->isInEEC() && (! is_object($societe_acheteuse) || ($societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany())))
  4098. {
  4099. // We also add the buyer
  4100. if (is_numeric($type))
  4101. {
  4102. if ($type == 1) // We know product is a service
  4103. {
  4104. $code_country.=",'".$societe_acheteuse->country_code."'";
  4105. }
  4106. }
  4107. else if (! $idprod) // We don't know type of product
  4108. {
  4109. $code_country.=",'".$societe_acheteuse->country_code."'";
  4110. }
  4111. else
  4112. {
  4113. $prodstatic=new Product($this->db);
  4114. $prodstatic->fetch($idprod);
  4115. if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service
  4116. {
  4117. $code_country.=",'".$societe_acheteuse->country_code."'";
  4118. }
  4119. }
  4120. }
  4121. }
  4122. // Now we get list
  4123. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  4124. if ($num > 0)
  4125. {
  4126. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  4127. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4128. {
  4129. $tmpthirdparty=new Societe($this->db);
  4130. $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
  4131. $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
  4132. if (empty($defaulttx)) $defaultnpr=0;
  4133. }
  4134. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  4135. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  4136. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4137. {
  4138. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
  4139. else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  4140. }
  4141. // Disabled if seller is not subject to VAT
  4142. $disabled=false; $title='';
  4143. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
  4144. {
  4145. $title=' title="'.$langs->trans('VATIsNotUsed').'"';
  4146. $disabled=true;
  4147. }
  4148. if (! $options_only) $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
  4149. $selectedfound=false;
  4150. foreach ($this->cache_vatrates as $rate)
  4151. {
  4152. // Keep only 0 if seller is not subject to VAT
  4153. if ($disabled && $rate['txtva'] != 0) continue;
  4154. // Define key to use into select list
  4155. $key = $rate['txtva'];
  4156. $key.= $rate['nprtva'] ? '*': '';
  4157. if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';
  4158. if ($mode < 0) $key = $rate['rowid'];
  4159. $return.= '<option value="'.$key.'"';
  4160. if (! $selectedfound)
  4161. {
  4162. if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  4163. {
  4164. if ($defaultcode == $rate['code'])
  4165. {
  4166. $return.= ' selected';
  4167. $selectedfound=true;
  4168. }
  4169. }
  4170. elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
  4171. {
  4172. $return.= ' selected';
  4173. $selectedfound=true;
  4174. }
  4175. }
  4176. $return.= '>';
  4177. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  4178. if ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
  4179. {
  4180. $return.= $rate['labelpositiverates'];
  4181. }
  4182. else
  4183. {
  4184. $return.= vatrate($rate['label']);
  4185. }
  4186. //$return.=($rate['code']?' '.$rate['code']:'');
  4187. $return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': ''; // We show the * (old behaviour only if new vat code is not used)
  4188. $return.= '</option>';
  4189. }
  4190. if (! $options_only) $return.= '</select>';
  4191. }
  4192. else
  4193. {
  4194. $return.= $this->error;
  4195. }
  4196. $this->num = $num;
  4197. return $return;
  4198. }
  4199. /**
  4200. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4201. * Fields are preselected with :
  4202. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4203. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4204. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4205. *
  4206. * @param timestamp $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date (emptydate must be 0).
  4207. * @param string $prefix Prefix for fields name
  4208. * @param int $h 1=Show also hours
  4209. * @param int $m 1=Show also minutes
  4210. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4211. * @param string $form_name Not used
  4212. * @param int $d 1=Show days, month, years
  4213. * @param int $addnowlink Add a link "Now"
  4214. * @param int $nooutput Do not output html string but return it
  4215. * @param int $disabled Disable input fields
  4216. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  4217. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  4218. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  4219. * @return string|null Nothing or string if nooutput is 1
  4220. * @see form_date
  4221. */
  4222. 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='')
  4223. {
  4224. global $conf,$langs;
  4225. $retstring='';
  4226. if($prefix=='') $prefix='re';
  4227. if($h == '') $h=0;
  4228. if($m == '') $m=0;
  4229. $emptydate=0;
  4230. $emptyhours=0;
  4231. if ($empty == 1) { $emptydate=1; $emptyhours=1; }
  4232. if ($empty == 2) { $emptydate=0; $emptyhours=1; }
  4233. $orig_set_time=$set_time;
  4234. if ($set_time === '' && $emptydate == 0)
  4235. {
  4236. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4237. $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone
  4238. }
  4239. // Analysis of the pre-selection date
  4240. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))
  4241. {
  4242. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  4243. $syear = (! empty($reg[1])?$reg[1]:'');
  4244. $smonth = (! empty($reg[2])?$reg[2]:'');
  4245. $sday = (! empty($reg[3])?$reg[3]:'');
  4246. $shour = (! empty($reg[4])?$reg[4]:'');
  4247. $smin = (! empty($reg[5])?$reg[5]:'');
  4248. }
  4249. elseif (strval($set_time) != '' && $set_time != -1)
  4250. {
  4251. // set_time est un timestamps (0 possible)
  4252. $syear = dol_print_date($set_time, "%Y");
  4253. $smonth = dol_print_date($set_time, "%m");
  4254. $sday = dol_print_date($set_time, "%d");
  4255. if ($orig_set_time != '')
  4256. {
  4257. $shour = dol_print_date($set_time, "%H");
  4258. $smin = dol_print_date($set_time, "%M");
  4259. }
  4260. }
  4261. else
  4262. {
  4263. // Date est '' ou vaut -1
  4264. $syear = '';
  4265. $smonth = '';
  4266. $sday = '';
  4267. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? '' : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  4268. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? '' : $conf->global->MAIN_DEFAULT_DATE_MIN;
  4269. }
  4270. $usecalendar='combo';
  4271. if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) $usecalendar=empty($conf->global->MAIN_POPUP_CALENDAR)?'eldy':$conf->global->MAIN_POPUP_CALENDAR;
  4272. if ($conf->browser->phone) $usecalendar='combo';
  4273. if ($d)
  4274. {
  4275. // Show date with popup
  4276. if ($usecalendar != 'combo')
  4277. {
  4278. $formated_date='';
  4279. //print "e".$set_time." t ".$conf->format_date_short;
  4280. if (strval($set_time) != '' && $set_time != -1)
  4281. {
  4282. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  4283. $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4284. }
  4285. // Calendrier popup version eldy
  4286. if ($usecalendar == "eldy")
  4287. {
  4288. // Zone de saisie manuelle de la date
  4289. $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
  4290. $retstring.=($disabled?' disabled':'');
  4291. $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4292. $retstring.='>';
  4293. // Icone calendrier
  4294. if (! $disabled)
  4295. {
  4296. $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  4297. $base=DOL_URL_ROOT.'/core/';
  4298. $retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');">'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
  4299. }
  4300. else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
  4301. $retstring.='<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  4302. $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  4303. $retstring.='<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  4304. }
  4305. else
  4306. {
  4307. print "Bad value of MAIN_POPUP_CALENDAR";
  4308. }
  4309. }
  4310. // Show date with combo selects
  4311. else
  4312. {
  4313. //$retstring.='<div class="inline-block">';
  4314. // Day
  4315. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  4316. if ($emptydate || $set_time == -1)
  4317. {
  4318. $retstring.='<option value="0" selected>&nbsp;</option>';
  4319. }
  4320. for ($day = 1 ; $day <= 31; $day++)
  4321. {
  4322. $retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
  4323. }
  4324. $retstring.="</select>";
  4325. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  4326. if ($emptydate || $set_time == -1)
  4327. {
  4328. $retstring.='<option value="0" selected>&nbsp;</option>';
  4329. }
  4330. // Month
  4331. for ($month = 1 ; $month <= 12 ; $month++)
  4332. {
  4333. $retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
  4334. $retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
  4335. $retstring.="</option>";
  4336. }
  4337. $retstring.="</select>";
  4338. // Year
  4339. if ($emptydate || $set_time == -1)
  4340. {
  4341. $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.'">';
  4342. }
  4343. else
  4344. {
  4345. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  4346. for ($year = $syear - 10; $year < $syear + 10 ; $year++)
  4347. {
  4348. $retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
  4349. }
  4350. $retstring.="</select>\n";
  4351. }
  4352. //$retstring.='</div>';
  4353. }
  4354. }
  4355. if ($d && $h) $retstring.=($h==2?'<br>':' ');
  4356. if ($h)
  4357. {
  4358. // Show hour
  4359. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  4360. if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
  4361. for ($hour = 0; $hour < 24; $hour++)
  4362. {
  4363. if (strlen($hour) < 2) $hour = "0" . $hour;
  4364. $retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
  4365. }
  4366. $retstring.='</select>';
  4367. if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
  4368. }
  4369. if ($m)
  4370. {
  4371. // Show minutes
  4372. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  4373. if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
  4374. for ($min = 0; $min < 60 ; $min++)
  4375. {
  4376. if (strlen($min) < 2) $min = "0" . $min;
  4377. $retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
  4378. }
  4379. $retstring.='</select>';
  4380. }
  4381. // Add a "Now" link
  4382. if ($conf->use_javascript_ajax && $addnowlink)
  4383. {
  4384. // Script which will be inserted in the onClick of the "Now" link
  4385. $reset_scripts = "";
  4386. // Generate the date part, depending on the use or not of the javascript calendar
  4387. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
  4388. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
  4389. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
  4390. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
  4391. /*if ($usecalendar == "eldy")
  4392. {
  4393. $base=DOL_URL_ROOT.'/core/';
  4394. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  4395. }
  4396. else
  4397. {
  4398. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  4399. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  4400. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  4401. }*/
  4402. // Update the hour part
  4403. if ($h)
  4404. {
  4405. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4406. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  4407. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
  4408. if ($fullday) $reset_scripts .= ' } ';
  4409. }
  4410. // Update the minute part
  4411. if ($m)
  4412. {
  4413. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4414. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  4415. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
  4416. if ($fullday) $reset_scripts .= ' } ';
  4417. }
  4418. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  4419. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  4420. {
  4421. $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  4422. $retstring.=$langs->trans("Now");
  4423. $retstring.='</button> ';
  4424. }
  4425. }
  4426. // Add a "Plus one hour" link
  4427. if ($conf->use_javascript_ajax && $addplusone)
  4428. {
  4429. // Script which will be inserted in the onClick of the "Add plusone" link
  4430. $reset_scripts = "";
  4431. // Generate the date part, depending on the use or not of the javascript calendar
  4432. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
  4433. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
  4434. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
  4435. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
  4436. // Update the hour part
  4437. if ($h)
  4438. {
  4439. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4440. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
  4441. if ($fullday) $reset_scripts .= ' } ';
  4442. }
  4443. // Update the minute part
  4444. if ($m)
  4445. {
  4446. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4447. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
  4448. if ($fullday) $reset_scripts .= ' } ';
  4449. }
  4450. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  4451. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  4452. {
  4453. $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  4454. $retstring.=$langs->trans("DateStartPlusOne");
  4455. $retstring.='</button> ';
  4456. }
  4457. }
  4458. // Add a "Plus one hour" link
  4459. if ($conf->use_javascript_ajax && $adddateof)
  4460. {
  4461. $tmparray=dol_getdate($adddateof);
  4462. $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>';
  4463. }
  4464. if (! empty($nooutput)) return $retstring;
  4465. print $retstring;
  4466. return;
  4467. }
  4468. /**
  4469. * Function to show a form to select a duration on a page
  4470. *
  4471. * @param string $prefix Prefix for input fields
  4472. * @param int $iSecond Default preselected duration (number of seconds or '')
  4473. * @param int $disabled Disable the combo box
  4474. * @param string $typehour If 'select' then input hour and input min is a combo,
  4475. * if 'text' input hour is in text and input min is a text,
  4476. * if 'textselect' input hour is in text and input min is a combo
  4477. * @param integer $minunderhours If 1, show minutes selection under the hours
  4478. * @param int $nooutput Do not output html string but return it
  4479. * @return string|null
  4480. */
  4481. function select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)
  4482. {
  4483. global $langs;
  4484. $retstring='';
  4485. $hourSelected=0; $minSelected=0;
  4486. // Hours
  4487. if ($iSecond != '')
  4488. {
  4489. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4490. $hourSelected = convertSecondToTime($iSecond,'allhour');
  4491. $minSelected = convertSecondToTime($iSecond,'min');
  4492. }
  4493. if ($typehour=='select' )
  4494. {
  4495. $retstring.='<select class="flat" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
  4496. for ($hour = 0; $hour < 25; $hour++) // For a duration, we allow 24 hours
  4497. {
  4498. $retstring.='<option value="'.$hour.'"';
  4499. if ($hourSelected == $hour)
  4500. {
  4501. $retstring.=" selected";
  4502. }
  4503. $retstring.=">".$hour."</option>";
  4504. }
  4505. $retstring.="</select>";
  4506. }
  4507. elseif ($typehour=='text' || $typehour=='textselect')
  4508. {
  4509. $retstring.='<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat maxwidth50" value="'.(($hourSelected != '')?((int) $hourSelected):'').'">';
  4510. }
  4511. else return 'BadValueForParameterTypeHour';
  4512. if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');
  4513. else $retstring.=':';
  4514. // Minutes
  4515. if ($minunderhours) $retstring.='<br>';
  4516. else $retstring.="&nbsp;";
  4517. if ($typehour=='select' || $typehour=='textselect')
  4518. {
  4519. $retstring.='<select class="flat" name="'.$prefix.'min"'.($disabled?' disabled':'').'>';
  4520. for ($min = 0; $min <= 55; $min=$min+5)
  4521. {
  4522. $retstring.='<option value="'.$min.'"';
  4523. if ($minSelected == $min) $retstring.=' selected';
  4524. $retstring.='>'.$min.'</option>';
  4525. }
  4526. $retstring.="</select>";
  4527. }
  4528. elseif ($typehour=='text' )
  4529. {
  4530. $retstring.='<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat maxwidth50" value="'.(($minSelected != '')?((int) $minSelected):'').'">';
  4531. }
  4532. if ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');
  4533. //$retstring.="&nbsp;";
  4534. if (! empty($nooutput)) return $retstring;
  4535. print $retstring;
  4536. return;
  4537. }
  4538. /**
  4539. * Return a HTML select string, built from an array of key+value.
  4540. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  4541. *
  4542. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  4543. * @param array $array Array (key => value)
  4544. * @param string|string[] $id Preselected key or preselected keys for multiselect
  4545. * @param int $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (value is '' or '&nbsp;' if 1), <0 to add an empty value with key that is this value.
  4546. * @param int $key_in_label 1 to show key into label with format "[key] value"
  4547. * @param int $value_as_key 1 to use value as key
  4548. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  4549. * @param int $translate 1=Translate and encode value
  4550. * @param int $maxlen Length maximum for labels
  4551. * @param int $disabled Html select box is disabled
  4552. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  4553. * @param string $morecss Add more class to css styles
  4554. * @param int $addjscombo Add js combo
  4555. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  4556. * @param int $disablebademail Check if an email is found into value and if not disable and colorize entry
  4557. * @param int $nohtmlescape No html escaping.
  4558. * @return string HTML select string.
  4559. * @see multiselectarray
  4560. */
  4561. 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)
  4562. {
  4563. global $conf, $langs;
  4564. // Do we want a multiselect ?
  4565. //$jsbeautify = 0;
  4566. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  4567. $jsbeautify = 1;
  4568. if ($value_as_key) $array=array_combine($array, $array);
  4569. $out='';
  4570. // Add code for jquery to use multiselect
  4571. if ($addjscombo && empty($conf->dol_use_jmobile) && $jsbeautify)
  4572. {
  4573. $minLengthToAutocomplete=0;
  4574. $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
  4575. // Enhance with select2
  4576. if ($conf->use_javascript_ajax)
  4577. {
  4578. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  4579. $comboenhancement = ajax_combobox($htmlname);
  4580. $out.=$comboenhancement;
  4581. }
  4582. }
  4583. $out.='<select id="'.preg_replace('/^\./','',$htmlname).'" '.($disabled?'disabled ':'').'class="flat '.(preg_replace('/^\./','',$htmlname)).($morecss?' '.$morecss:'').'" name="'.preg_replace('/^\./','',$htmlname).'" '.($moreparam?$moreparam:'').'>';
  4584. if ($show_empty)
  4585. {
  4586. $textforempty=' ';
  4587. 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.
  4588. if (! is_numeric($show_empty)) $textforempty=$show_empty;
  4589. $out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
  4590. }
  4591. if (is_array($array))
  4592. {
  4593. // Translate
  4594. if ($translate)
  4595. {
  4596. foreach($array as $key => $value)
  4597. {
  4598. $array[$key]=$langs->trans($value);
  4599. }
  4600. }
  4601. // Sort
  4602. if ($sort == 'ASC') asort($array);
  4603. elseif ($sort == 'DESC') arsort($array);
  4604. foreach($array as $key => $value)
  4605. {
  4606. $disabled=''; $style='';
  4607. if (! empty($disablebademail))
  4608. {
  4609. if (! preg_match('/&lt;.+@.+&gt;/', $value))
  4610. {
  4611. //$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);
  4612. $disabled=' disabled';
  4613. $style=' class="warning"';
  4614. }
  4615. }
  4616. $out.='<option value="'.$key.'"';
  4617. $out.=$style.$disabled;
  4618. if ($id != '' && $id == $key && ! $disabled) $out.=' selected'; // To preselect a value
  4619. $out.='>';
  4620. if ($key_in_label)
  4621. {
  4622. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
  4623. else $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
  4624. }
  4625. else
  4626. {
  4627. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
  4628. else $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
  4629. if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
  4630. }
  4631. //var_dump($selectOptionValue);
  4632. $out.=$selectOptionValue;
  4633. $out.="</option>\n";
  4634. }
  4635. }
  4636. $out.="</select>";
  4637. return $out;
  4638. }
  4639. /**
  4640. * 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.
  4641. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  4642. *
  4643. * @param string $htmlname Name of html select area
  4644. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  4645. * @param string $id Preselected key
  4646. * @param string $moreparam Add more parameters onto the select tag
  4647. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  4648. * @param int $disabled Html select box is disabled
  4649. * @param int $minimumInputLength Minimum Input Length
  4650. * @param string $morecss Add more class to css styles
  4651. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  4652. * @param string $placeholder String to use as placeholder
  4653. * @param integer $acceptdelayedhtml 1 if caller request 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)
  4654. * @return string HTML select string
  4655. */
  4656. static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
  4657. {
  4658. global $langs;
  4659. global $delayedhtmlcontent;
  4660. $tmpplugin='select2';
  4661. $out='<input type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'">';
  4662. // TODO Use an internal dolibarr component instead of select2
  4663. $outdelayed='<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  4664. <script type="text/javascript">
  4665. $(document).ready(function () {
  4666. '.($callurlonselect ? 'var saveRemoteData = [];':'').'
  4667. $(".'.$htmlname.'").select2({
  4668. ajax: {
  4669. dir: "ltr",
  4670. url: "'.$url.'",
  4671. dataType: \'json\',
  4672. delay: 250,
  4673. data: function (searchTerm, pageNumber, context) {
  4674. return {
  4675. q: searchTerm, // search term
  4676. page: pageNumber
  4677. };
  4678. },
  4679. results: function (remoteData, pageNumber, query) {
  4680. console.log(remoteData);
  4681. saveRemoteData = remoteData;
  4682. /* format json result for select2 */
  4683. result = []
  4684. $.each( remoteData, function( key, value ) {
  4685. result.push({id: key, text: value.text});
  4686. });
  4687. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  4688. return {results: result, more:false}
  4689. },
  4690. /*processResults: function (data, page) {
  4691. // parse the results into the format expected by Select2.
  4692. // since we are using custom formatting functions we do not need to
  4693. // alter the remote JSON data
  4694. console.log(data);
  4695. return {
  4696. results: data.items
  4697. };
  4698. },*/
  4699. cache: true
  4700. },
  4701. dropdownCssClass: "css-'.$htmlname.'",
  4702. placeholder: "'.dol_escape_js($placeholder).'",
  4703. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  4704. minimumInputLength: '.$minimumInputLength.',
  4705. formatResult: function(result, container, query, escapeMarkup) {
  4706. return escapeMarkup(result.text);
  4707. }
  4708. });
  4709. '.($callurlonselect ? '
  4710. $(".'.$htmlname.'").change(function() {
  4711. var selected = $(".'.$htmlname.'").select2("val");
  4712. $(".'.$htmlname.'").select2("val",""); /* reset visible combo value */
  4713. $.each( saveRemoteData, function( key, value ) {
  4714. if (key == selected)
  4715. {
  4716. console.log("Do a redirect into selectArrayAjax to "+value.url)
  4717. location.assign(value.url);
  4718. }
  4719. });
  4720. });' : '' ) . '
  4721. });
  4722. </script>';
  4723. if ($acceptdelayedhtml)
  4724. {
  4725. $delayedhtmlcontent.=$outdelayed;
  4726. }
  4727. else
  4728. {
  4729. $out.=$outdelayed;
  4730. }
  4731. return $out;
  4732. }
  4733. /**
  4734. * Show a multiselect form from an array.
  4735. *
  4736. * @param string $htmlname Name of select
  4737. * @param array $array Array with key+value
  4738. * @param array $selected Array with key+value preselected
  4739. * @param int $key_in_label 1 pour afficher la key dans la valeur "[key] value"
  4740. * @param int $value_as_key 1 to use value as key
  4741. * @param string $morecss Add more css style
  4742. * @param int $translate Translate and encode value
  4743. * @param int $width Force width of select box. May be used only when using jquery couch. Example: 250, 95%
  4744. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  4745. * @param string $elemtype Type of element we show ('category', ...)
  4746. * @return string HTML multiselect string
  4747. * @see selectarray
  4748. */
  4749. static function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='',$elemtype='')
  4750. {
  4751. global $conf, $langs;
  4752. $out = '';
  4753. // Add code for jquery to use multiselect
  4754. if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
  4755. {
  4756. $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
  4757. $out.='<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  4758. <script type="text/javascript">
  4759. function formatResult(record) {'."\n";
  4760. if ($elemtype == 'category')
  4761. {
  4762. $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>\';
  4763. return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
  4764. }
  4765. else
  4766. {
  4767. $out.='return record.text;';
  4768. }
  4769. $out.= ' };
  4770. function formatSelection(record) {'."\n";
  4771. if ($elemtype == 'category')
  4772. {
  4773. $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>\';
  4774. return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
  4775. }
  4776. else
  4777. {
  4778. $out.='return record.text;';
  4779. }
  4780. $out.= ' };
  4781. $(document).ready(function () {
  4782. $(\'#'.$htmlname.'\').'.$tmpplugin.'({
  4783. dir: \'ltr\',
  4784. // Specify format function for dropdown item
  4785. formatResult: formatResult,
  4786. templateResult: formatResult, /* For 4.0 */
  4787. // Specify format function for selected item
  4788. formatSelection: formatSelection,
  4789. templateResult: formatSelection /* For 4.0 */
  4790. });
  4791. });
  4792. </script>';
  4793. }
  4794. // Try also magic suggest
  4795. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
  4796. if (is_array($array) && ! empty($array))
  4797. {
  4798. if ($value_as_key) $array=array_combine($array, $array);
  4799. if (! empty($array))
  4800. {
  4801. foreach ($array as $key => $value)
  4802. {
  4803. $out.= '<option value="'.$key.'"';
  4804. if (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))
  4805. {
  4806. $out.= ' selected';
  4807. }
  4808. $out.= '>';
  4809. $newval = ($translate ? $langs->trans($value) : $value);
  4810. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  4811. $out.= dol_htmlentitiesbr($newval);
  4812. $out.= '</option>'."\n";
  4813. }
  4814. }
  4815. }
  4816. $out.= '</select>'."\n";
  4817. return $out;
  4818. }
  4819. /**
  4820. * Show a multiselect form from an array.
  4821. *
  4822. * @param string $htmlname Name of select
  4823. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  4824. * @param string $varpage Id of context for page. Can be set with $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
  4825. * @return string HTML multiselect string
  4826. * @see selectarray
  4827. */
  4828. static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  4829. {
  4830. global $conf,$langs,$user;
  4831. if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
  4832. $tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
  4833. if (! empty($user->conf->$tmpvar))
  4834. {
  4835. $tmparray=explode(',', $user->conf->$tmpvar);
  4836. foreach($array as $key => $val)
  4837. {
  4838. //var_dump($key);
  4839. //var_dump($tmparray);
  4840. if (in_array($key, $tmparray)) $array[$key]['checked']=1;
  4841. else $array[$key]['checked']=0;
  4842. }
  4843. }
  4844. //var_dump($array);
  4845. $lis='';
  4846. $listcheckedstring='';
  4847. foreach($array as $key => $val)
  4848. {
  4849. /* var_dump($val);
  4850. var_dump(array_key_exists('enabled', $val));
  4851. var_dump(!$val['enabled']);*/
  4852. if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
  4853. {
  4854. unset($array[$key]); // We don't want this field
  4855. continue;
  4856. }
  4857. if ($val['label'])
  4858. {
  4859. $lis.='<li><input type="checkbox" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/>'.dol_escape_htmltag($langs->trans($val['label'])).'</li>';
  4860. $listcheckedstring.=(empty($val['checked'])?'':$key.',');
  4861. }
  4862. }
  4863. $out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  4864. <dl class="dropdown">
  4865. <dt>
  4866. <a href="#">
  4867. '.img_picto('','list').'
  4868. </a>
  4869. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  4870. </dt>
  4871. <dd class="dropowndd">
  4872. <div class="multiselectcheckbox'.$htmlname.'">
  4873. <ul class="ul'.$htmlname.'">
  4874. '.$lis.'
  4875. </ul>
  4876. </div>
  4877. </dd>
  4878. </dl>
  4879. <script type="text/javascript">
  4880. jQuery(document).ready(function () {
  4881. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  4882. console.log("A new field was added/removed")
  4883. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\')
  4884. var title = $(this).val() + ",";
  4885. if ($(this).is(\':checked\')) {
  4886. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  4887. }
  4888. else {
  4889. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  4890. }
  4891. // Now, we submit page
  4892. $(this).parents(\'form:first\').submit();
  4893. });
  4894. });
  4895. </script>
  4896. ';
  4897. return $out;
  4898. }
  4899. /**
  4900. * Render list of categories linked to object with id $id and type $type
  4901. *
  4902. * @param int $id Id of object
  4903. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  4904. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  4905. * @return string String with categories
  4906. */
  4907. function showCategories($id, $type, $rendermode=0)
  4908. {
  4909. global $db;
  4910. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4911. $cat = new Categorie($db);
  4912. $categories = $cat->containing($id, $type);
  4913. if ($rendermode == 1)
  4914. {
  4915. $toprint = array();
  4916. foreach($categories as $c)
  4917. {
  4918. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  4919. foreach($ways as $way)
  4920. {
  4921. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color?' style="background: #'.$c->color.';"':' style="background: #aaa"').'>'.img_object('','category').' '.$way.'</li>';
  4922. }
  4923. }
  4924. return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  4925. }
  4926. if ($rendermode == 0)
  4927. {
  4928. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  4929. foreach($categories as $c) {
  4930. $arrayselected[] = $c->id;
  4931. }
  4932. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  4933. }
  4934. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  4935. }
  4936. /**
  4937. * Show linked object block.
  4938. *
  4939. * @param CommonObject $object Object we want to show links to
  4940. * @param string $morehtmlright More html to show on right of title
  4941. * @return int <0 if KO, >=0 if OK
  4942. */
  4943. function showLinkedObjectBlock($object, $morehtmlright='')
  4944. {
  4945. global $conf,$langs,$hookmanager;
  4946. global $bc;
  4947. $object->fetchObjectLinked();
  4948. // Bypass the default method
  4949. $hookmanager->initHooks(array('commonobject'));
  4950. $parameters=array();
  4951. $reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
  4952. if (empty($reshook))
  4953. {
  4954. $nbofdifferenttypes = count($object->linkedObjects);
  4955. print '<br><!-- showLinkedObjectBlock -->';
  4956. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '');
  4957. print '<table class="noborder allwidth">';
  4958. print '<tr class="liste_titre">';
  4959. print '<td>'.$langs->trans("Type").'</td>';
  4960. print '<td>'.$langs->trans("Ref").'</td>';
  4961. print '<td align="center"></td>';
  4962. print '<td align="center">'.$langs->trans("Date").'</td>';
  4963. print '<td align="right">'.$langs->trans("AmountHTShort").'</td>';
  4964. print '<td align="right">'.$langs->trans("Status").'</td>';
  4965. print '<td></td>';
  4966. print '</tr>';
  4967. $nboftypesoutput=0;
  4968. foreach($object->linkedObjects as $objecttype => $objects)
  4969. {
  4970. $tplpath = $element = $subelement = $objecttype;
  4971. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
  4972. {
  4973. $element = $regs[1];
  4974. $subelement = $regs[2];
  4975. $tplpath = $element.'/'.$subelement;
  4976. }
  4977. $tplname='linkedobjectblock';
  4978. // To work with non standard path
  4979. if ($objecttype == 'facture') {
  4980. $tplpath = 'compta/'.$element;
  4981. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  4982. }
  4983. else if ($objecttype == 'facturerec') {
  4984. $tplpath = 'compta/facture';
  4985. $tplname = 'linkedobjectblockForRec';
  4986. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  4987. }
  4988. else if ($objecttype == 'propal') {
  4989. $tplpath = 'comm/'.$element;
  4990. if (empty($conf->propal->enabled)) continue; // Do not show if module disabled
  4991. }
  4992. else if ($objecttype == 'supplier_proposal') {
  4993. if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled
  4994. }
  4995. else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
  4996. $tplpath = 'expedition';
  4997. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  4998. }
  4999. else if ($objecttype == 'delivery') {
  5000. $tplpath = 'livraison';
  5001. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  5002. }
  5003. else if ($objecttype == 'invoice_supplier') {
  5004. $tplpath = 'fourn/facture';
  5005. }
  5006. else if ($objecttype == 'order_supplier') {
  5007. $tplpath = 'fourn/commande';
  5008. }
  5009. else if ($objecttype == 'expensereport') {
  5010. $tplpath = 'expensereport';
  5011. }
  5012. else if ($objecttype == 'subscription') {
  5013. $tplpath = 'adherents';
  5014. }
  5015. global $linkedObjectBlock;
  5016. $linkedObjectBlock = $objects;
  5017. // Output template part (modules that overwrite templates must declare this into descriptor)
  5018. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
  5019. foreach($dirtpls as $reldir)
  5020. {
  5021. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) // No more type to show after
  5022. {
  5023. global $noMoreLinkedObjectBlockAfter;
  5024. $noMoreLinkedObjectBlockAfter=1;
  5025. }
  5026. $res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  5027. if ($res)
  5028. {
  5029. $nboftypesoutput++;
  5030. break;
  5031. }
  5032. }
  5033. }
  5034. if (! $nboftypesoutput)
  5035. {
  5036. print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
  5037. }
  5038. print '</table>';
  5039. return $nbofdifferenttypes;
  5040. }
  5041. }
  5042. /**
  5043. * Show block with links to link to other objects.
  5044. *
  5045. * @param CommonObject $object Object we want to show links to
  5046. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  5047. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  5048. * @return string <0 if KO, >0 if OK
  5049. */
  5050. function showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())
  5051. {
  5052. global $conf, $langs, $hookmanager;
  5053. global $bc;
  5054. $linktoelem='';
  5055. $linktoelemlist='';
  5056. if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
  5057. $possiblelinks=array();
  5058. if (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)
  5059. {
  5060. $listofidcompanytoscan=$object->thirdparty->id;
  5061. if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;
  5062. $possiblelinks=array(
  5063. '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').')'),
  5064. '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').')'),
  5065. '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').')'),
  5066. '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').')'),
  5067. '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').')'),
  5068. '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').')'),
  5069. 'order_supplier'=>array('enabled'=>$conf->fournisseur->commande->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').')'),
  5070. 'invoice_supplier'=>array('enabled'=>$conf->fournisseur->facture->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').')')
  5071. );
  5072. }
  5073. global $action;
  5074. // Can complete the possiblelink array
  5075. $hookmanager->initHooks(array('commonobject'));
  5076. $parameters=array();
  5077. $reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
  5078. if (empty($reshook))
  5079. {
  5080. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  5081. {
  5082. $possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);
  5083. }
  5084. }
  5085. else if ($reshook > 0)
  5086. {
  5087. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  5088. {
  5089. $possiblelinks=$hookmanager->resArray;
  5090. }
  5091. }
  5092. foreach($possiblelinks as $key => $possiblelink)
  5093. {
  5094. $num = 0;
  5095. if (empty($possiblelink['enabled'])) continue;
  5096. if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))
  5097. {
  5098. print '<div id="'.$key.'list"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
  5099. $sql = $possiblelink['sql'];
  5100. $resqllist = $this->db->query($sql);
  5101. if ($resqllist)
  5102. {
  5103. $num = $this->db->num_rows($resqllist);
  5104. $i = 0;
  5105. print '<br><form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  5106. print '<input type="hidden" name="id" value="'.$object->id.'">';
  5107. print '<input type="hidden" name="action" value="addlink">';
  5108. print '<input type="hidden" name="addlink" value="'.$key.'">';
  5109. print '<table class="noborder">';
  5110. print '<tr class="liste_titre">';
  5111. print '<td class="nowrap"></td>';
  5112. print '<td align="center">' . $langs->trans("Ref") . '</td>';
  5113. print '<td align="left">' . $langs->trans("RefCustomer") . '</td>';
  5114. print '<td align="right">' . $langs->trans("AmountHTShort") . '</td>';
  5115. print '<td align="left">' . $langs->trans("Company") . '</td>';
  5116. print '</tr>';
  5117. while ($i < $num)
  5118. {
  5119. $objp = $this->db->fetch_object($resqlorderlist);
  5120. $var = ! $var;
  5121. print '<tr ' . $bc [$var] . '>';
  5122. print '<td aling="left">';
  5123. print '<input type="radio" name="idtolinkto" value=' . $objp->rowid . '>';
  5124. print '</td>';
  5125. print '<td align="center">' . $objp->ref . '</td>';
  5126. print '<td>' . $objp->ref_client . '</td>';
  5127. print '<td align="right">' . price($objp->total_ht) . '</td>';
  5128. print '<td>' . $objp->name . '</td>';
  5129. print '</tr>';
  5130. $i++;
  5131. }
  5132. print '</table>';
  5133. 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>';
  5134. print '</form>';
  5135. $this->db->free($resqllist);
  5136. } else {
  5137. dol_print_error($this->db);
  5138. }
  5139. print '</div>';
  5140. if ($num > 0)
  5141. {
  5142. }
  5143. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  5144. if ($num > 0) $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
  5145. //else $linktoelem.=$langs->trans($possiblelink['label']);
  5146. else $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
  5147. }
  5148. }
  5149. if ($linktoelemlist)
  5150. {
  5151. $linktoelem='
  5152. <dl class="dropdown" id="linktoobjectname">
  5153. <dt><a href="#linktoobjectname">'.$langs->trans("LinkTo").'...</a></dt>
  5154. <dd>
  5155. <div class="multiselectlinkto">
  5156. <ul class="ulselectedfields">'.$linktoelemlist.'
  5157. </ul>
  5158. </div>
  5159. </dd>
  5160. </dl>';
  5161. }
  5162. else
  5163. {
  5164. $linktoelem='';
  5165. }
  5166. print '<!-- Add js to show linkto box -->
  5167. <script type="text/javascript" language="javascript">
  5168. jQuery(document).ready(function() {
  5169. jQuery(".linkto").click(function() {
  5170. console.log("We choose to show/hide link for rel="+jQuery(this).attr(\'rel\'));
  5171. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  5172. jQuery(this).toggle();
  5173. });
  5174. });
  5175. </script>
  5176. ';
  5177. return $linktoelem;
  5178. }
  5179. /**
  5180. * Return an html string with a select combo box to choose yes or no
  5181. *
  5182. * @param string $htmlname Name of html select field
  5183. * @param string $value Pre-selected value
  5184. * @param int $option 0 return yes/no, 1 return 1/0
  5185. * @param bool $disabled true or false
  5186. * @param int $useempty 1=Add empty line
  5187. * @return string See option
  5188. */
  5189. function selectyesno($htmlname,$value='',$option=0,$disabled=false,$useempty='')
  5190. {
  5191. global $langs;
  5192. $yes="yes"; $no="no";
  5193. if ($option)
  5194. {
  5195. $yes="1";
  5196. $no="0";
  5197. }
  5198. $disabled = ($disabled ? ' disabled' : '');
  5199. $resultyesno = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  5200. if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'>&nbsp;</option>'."\n";
  5201. if (("$value" == 'yes') || ($value == 1))
  5202. {
  5203. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  5204. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  5205. }
  5206. else
  5207. {
  5208. $selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
  5209. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  5210. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  5211. }
  5212. $resultyesno .= '</select>'."\n";
  5213. return $resultyesno;
  5214. }
  5215. /**
  5216. * Return list of export templates
  5217. *
  5218. * @param string $selected Id modele pre-selectionne
  5219. * @param string $htmlname Name of HTML select
  5220. * @param string $type Type of searched templates
  5221. * @param int $useempty Affiche valeur vide dans liste
  5222. * @return void
  5223. */
  5224. function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
  5225. {
  5226. $sql = "SELECT rowid, label";
  5227. $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
  5228. $sql.= " WHERE type = '".$type."'";
  5229. $sql.= " ORDER BY rowid";
  5230. $result = $this->db->query($sql);
  5231. if ($result)
  5232. {
  5233. print '<select class="flat" name="'.$htmlname.'">';
  5234. if ($useempty)
  5235. {
  5236. print '<option value="-1">&nbsp;</option>';
  5237. }
  5238. $num = $this->db->num_rows($result);
  5239. $i = 0;
  5240. while ($i < $num)
  5241. {
  5242. $obj = $this->db->fetch_object($result);
  5243. if ($selected == $obj->rowid)
  5244. {
  5245. print '<option value="'.$obj->rowid.'" selected>';
  5246. }
  5247. else
  5248. {
  5249. print '<option value="'.$obj->rowid.'">';
  5250. }
  5251. print $obj->label;
  5252. print '</option>';
  5253. $i++;
  5254. }
  5255. print "</select>";
  5256. }
  5257. else {
  5258. dol_print_error($this->db);
  5259. }
  5260. }
  5261. /**
  5262. * Return a HTML area with the reference of object and a navigation bar for a business object
  5263. * Note: To add a particular filter on select, you can have $object->next_prev_filter set to add SQL criterias.
  5264. *
  5265. * @param object $object Object to show.
  5266. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  5267. * @param string $morehtml More html content to output just before the nav bar.
  5268. * @param int $shownav Show Condition (navigation is shown if value is 1).
  5269. * @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).
  5270. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  5271. * @param string $morehtmlref More html to show after ref.
  5272. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  5273. * @param int $nodbprefix Do not include DB prefix to forge table name.
  5274. * @param string $morehtmlleft More html code to show before ref.
  5275. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  5276. * @param string $morehtmlright More html code to show after ref.
  5277. * @return string Portion HTML with ref + navigation buttons
  5278. */
  5279. function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')
  5280. {
  5281. global $langs,$conf,$hookmanager;
  5282. $ret='';
  5283. if (empty($fieldid)) $fieldid='rowid';
  5284. if (empty($fieldref)) $fieldref='ref';
  5285. // Add where from hooks
  5286. if (is_object($hookmanager))
  5287. {
  5288. $parameters=array();
  5289. $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters, $object); // Note that $action and $object may have been modified by hook
  5290. $object->next_prev_filter.=$hookmanager->resPrint;
  5291. }
  5292. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  5293. $object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''),$fieldid,$nodbprefix);
  5294. $navurl = $_SERVER["PHP_SELF"];
  5295. // Special case for project/task page
  5296. if ($paramid == 'project_ref')
  5297. {
  5298. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document).php/','/tasks.php',$navurl);
  5299. $paramid='ref';
  5300. }
  5301. $previous_ref = $object->ref_previous?'<a 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>';
  5302. $next_ref = $object->ref_next?'<a 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>';
  5303. //print "xx".$previous_ref."x".$next_ref;
  5304. $ret.='<!-- Start banner content --><div style="vertical-align: middle">';
  5305. // Right part of banner
  5306. if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  5307. if ($previous_ref || $next_ref || $morehtml)
  5308. {
  5309. $ret.='<div class="pagination"><ul>';
  5310. }
  5311. if ($morehtml)
  5312. {
  5313. $ret.='<li class="noborder litext">'.$morehtml.'</li>';
  5314. }
  5315. if ($shownav && ($previous_ref || $next_ref))
  5316. {
  5317. $ret.='<li class="pagination">'.$previous_ref.'</li>';
  5318. $ret.='<li class="pagination">'.$next_ref.'</li>';
  5319. }
  5320. if ($previous_ref || $next_ref || $morehtml)
  5321. {
  5322. $ret.='</ul></div>';
  5323. }
  5324. if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
  5325. // Left part of banner
  5326. if ($morehtmlleft)
  5327. {
  5328. if ($conf->browser->layout == 'phone') $ret.='<div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  5329. else $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  5330. }
  5331. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  5332. $ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
  5333. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  5334. if ($object->element == 'societe')
  5335. {
  5336. $ret.=dol_htmlentities($object->name);
  5337. }
  5338. else if (in_array($object->element, array('contact', 'user', 'usergroup', 'member')))
  5339. {
  5340. $ret.=dol_htmlentities($object->getFullName($langs));
  5341. }
  5342. else if (in_array($object->element, array('action', 'agenda')))
  5343. {
  5344. $ret.=$object->ref.'<br>'.$object->label;
  5345. }
  5346. else if (in_array($object->element, array('adherent_type')))
  5347. {
  5348. $ret.=$object->label;
  5349. }
  5350. else if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);
  5351. if ($morehtmlref)
  5352. {
  5353. $ret.=' '.$morehtmlref;
  5354. }
  5355. $ret.='</div>';
  5356. $ret.='</div><!-- End banner content -->';
  5357. return $ret;
  5358. }
  5359. /**
  5360. * Return HTML code to output a barcode
  5361. *
  5362. * @param Object $object Object containing data to retrieve file name
  5363. * @param int $width Width of photo
  5364. * @return string HTML code to output barcode
  5365. */
  5366. function showbarcode(&$object,$width=100)
  5367. {
  5368. global $conf;
  5369. //Check if barcode is filled in the card
  5370. if (empty($object->barcode)) return '';
  5371. // Complete object if not complete
  5372. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
  5373. {
  5374. $result = $object->fetch_barcode();
  5375. //Check if fetch_barcode() failed
  5376. if ($result < 1) return '<!-- ErrorFetchBarcode -->';
  5377. }
  5378. // Barcode image
  5379. $url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  5380. $out ='<!-- url barcode = '.$url.' -->';
  5381. $out.='<img src="'.$url.'">';
  5382. return $out;
  5383. }
  5384. /**
  5385. * Return HTML code to output a photo
  5386. *
  5387. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  5388. * @param object $object Object containing data to retrieve file name
  5389. * @param int $width Width of photo
  5390. * @param int $height Height of photo (auto if 0)
  5391. * @param int $caneditfield Add edit fields
  5392. * @param string $cssclass CSS name to use on img for photo
  5393. * @param string $imagesize 'mini', 'small' or '' (original)
  5394. * @param int $addlinktofullsize Add link to fullsize image
  5395. * @param int $cache 1=Accept to use image in cache
  5396. * @return string HTML code to output photo
  5397. */
  5398. static function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0)
  5399. {
  5400. global $conf,$langs;
  5401. $entity = (! empty($object->entity) ? $object->entity : $conf->entity);
  5402. $id = (! empty($object->id) ? $object->id : $object->rowid);
  5403. $ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';
  5404. if ($modulepart=='societe')
  5405. {
  5406. $dir=$conf->societe->multidir_output[$entity];
  5407. if (! empty($object->logo))
  5408. {
  5409. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  5410. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
  5411. else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  5412. $originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  5413. }
  5414. $email=$object->email;
  5415. }
  5416. else if ($modulepart=='contact')
  5417. {
  5418. $dir=$conf->societe->multidir_output[$entity].'/contact';
  5419. if (! empty($object->photo))
  5420. {
  5421. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
  5422. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
  5423. else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  5424. $originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  5425. }
  5426. $email=$object->email;
  5427. }
  5428. else if ($modulepart=='userphoto')
  5429. {
  5430. $dir=$conf->user->dir_output;
  5431. if (! empty($object->photo))
  5432. {
  5433. if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_mini');
  5434. else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_small');
  5435. else $file=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;
  5436. $originalfile=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;
  5437. }
  5438. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  5439. $email=$object->email;
  5440. }
  5441. else if ($modulepart=='memberphoto')
  5442. {
  5443. $dir=$conf->adherent->dir_output;
  5444. if (! empty($object->photo))
  5445. {
  5446. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  5447. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  5448. else $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  5449. $originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  5450. }
  5451. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  5452. $email=$object->email;
  5453. }
  5454. else
  5455. {
  5456. // Generic case to show photos
  5457. $dir=$conf->$modulepart->dir_output;
  5458. if (! empty($object->photo))
  5459. {
  5460. if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  5461. else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  5462. else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  5463. $originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  5464. }
  5465. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  5466. $email=$object->email;
  5467. }
  5468. if ($dir)
  5469. {
  5470. if ($file && file_exists($dir."/".$file))
  5471. {
  5472. if ($addlinktofullsize)
  5473. {
  5474. $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  5475. if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
  5476. else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  5477. }
  5478. $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.'">';
  5479. if ($addlinktofullsize) $ret.='</a>';
  5480. }
  5481. else if ($altfile && file_exists($dir."/".$altfile))
  5482. {
  5483. if ($addlinktofullsize)
  5484. {
  5485. $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  5486. if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
  5487. else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  5488. }
  5489. $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.'">';
  5490. if ($addlinktofullsize) $ret.='</a>';
  5491. }
  5492. else
  5493. {
  5494. $nophoto='/public/theme/common/nophoto.png';
  5495. if (in_array($modulepart,array('userphoto','contact'))) // For module that are "physical" users
  5496. {
  5497. $nophoto='/public/theme/common/user_anonymous.png';
  5498. if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
  5499. if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
  5500. }
  5501. if (! empty($conf->gravatar->enabled) && $email)
  5502. {
  5503. /**
  5504. * @see https://gravatar.com/site/implement/images/php/
  5505. */
  5506. global $dolibarr_main_url_root;
  5507. $ret.='<!-- Put link to gravatar -->';
  5508. //$defaultimg=urlencode(dol_buildpath($nophoto,3));
  5509. $defaultimg='mm';
  5510. $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
  5511. }
  5512. else
  5513. {
  5514. $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
  5515. }
  5516. }
  5517. if ($caneditfield)
  5518. {
  5519. if ($object->photo) $ret.="<br>\n";
  5520. $ret.='<table class="nobordernopadding centpercent">';
  5521. if ($object->photo) $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
  5522. $ret.='<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"></td></tr>';
  5523. $ret.='</table>';
  5524. }
  5525. }
  5526. else dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
  5527. return $ret;
  5528. }
  5529. /**
  5530. * Return select list of groups
  5531. *
  5532. * @param string $selected Id group preselected
  5533. * @param string $htmlname Field name in form
  5534. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  5535. * @param string $exclude Array list of groups id to exclude
  5536. * @param int $disabled If select list must be disabled
  5537. * @param string $include Array list of groups id to include
  5538. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  5539. * @param int $force_entity 0 or Id of environment to force
  5540. * @return string
  5541. * @see select_dolusers
  5542. */
  5543. function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity=0)
  5544. {
  5545. global $conf,$user,$langs;
  5546. // Permettre l'exclusion de groupes
  5547. if (is_array($exclude)) $excludeGroups = implode("','",$exclude);
  5548. // Permettre l'inclusion de groupes
  5549. if (is_array($include)) $includeGroups = implode("','",$include);
  5550. $out='';
  5551. // On recherche les groupes
  5552. $sql = "SELECT ug.rowid, ug.nom as name";
  5553. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  5554. {
  5555. $sql.= ", e.label";
  5556. }
  5557. $sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  5558. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  5559. {
  5560. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
  5561. if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
  5562. else $sql.= " WHERE ug.entity IS NOT NULL";
  5563. }
  5564. else
  5565. {
  5566. $sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
  5567. }
  5568. if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
  5569. if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
  5570. $sql.= " ORDER BY ug.nom ASC";
  5571. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  5572. $resql=$this->db->query($sql);
  5573. if ($resql)
  5574. {
  5575. // Enhance with select2
  5576. if ($conf->use_javascript_ajax)
  5577. {
  5578. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5579. $comboenhancement = ajax_combobox($htmlname);
  5580. $out.= $comboenhancement;
  5581. }
  5582. $out.= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').'>';
  5583. $num = $this->db->num_rows($resql);
  5584. $i = 0;
  5585. if ($num)
  5586. {
  5587. if ($show_empty) $out.= '<option value="-1"'.($selected==-1?' selected':'').'>&nbsp;</option>'."\n";
  5588. while ($i < $num)
  5589. {
  5590. $obj = $this->db->fetch_object($resql);
  5591. $disableline=0;
  5592. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
  5593. $out.= '<option value="'.$obj->rowid.'"';
  5594. if ($disableline) $out.= ' disabled';
  5595. if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))
  5596. {
  5597. $out.= ' selected';
  5598. }
  5599. $out.= '>';
  5600. $out.= $obj->name;
  5601. if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
  5602. {
  5603. $out.= " (".$obj->label.")";
  5604. }
  5605. $out.= '</option>';
  5606. $i++;
  5607. }
  5608. }
  5609. else
  5610. {
  5611. if ($show_empty) $out.= '<option value="-1"'.($selected==-1?' selected':'').'></option>'."\n";
  5612. $out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  5613. }
  5614. $out.= '</select>';
  5615. }
  5616. else
  5617. {
  5618. dol_print_error($this->db);
  5619. }
  5620. return $out;
  5621. }
  5622. /**
  5623. * Return HTML to show the search and clear seach button
  5624. *
  5625. * @return string
  5626. */
  5627. function showFilterButtons()
  5628. {
  5629. global $conf, $langs;
  5630. $out='<div class="nowrap">';
  5631. $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")).'">';
  5632. $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")).'">';
  5633. $out.='</div>';
  5634. return $out;
  5635. }
  5636. /**
  5637. * Return HTML to show the search and clear seach button
  5638. *
  5639. * @param string $cssclass CSS class
  5640. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  5641. * @return string
  5642. */
  5643. function showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)
  5644. {
  5645. global $conf, $langs;
  5646. $out='';
  5647. if (! empty($conf->use_javascript_ajax)) $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
  5648. $out.='<script type="text/javascript">
  5649. $(document).ready(function() {
  5650. $("#checkallactions").click(function() {
  5651. if($(this).is(\':checked\')){
  5652. console.log("We check all");
  5653. $(".'.$cssclass.'").prop(\'checked\', true);
  5654. }
  5655. else
  5656. {
  5657. console.log("We uncheck all");
  5658. $(".'.$cssclass.'").prop(\'checked\', false);
  5659. }'."\n";
  5660. if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  5661. $out.=' });
  5662. });
  5663. </script>';
  5664. return $out;
  5665. }
  5666. /**
  5667. * Return HTML to show the search and clear seach button
  5668. *
  5669. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  5670. * @param string $cssclass CSS class
  5671. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  5672. * @return string
  5673. */
  5674. function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
  5675. {
  5676. $out.=$this->showFilterButtons();
  5677. if ($addcheckuncheckall)
  5678. {
  5679. $out.=$this->showCheckAddButtons($cssclass, $calljsfunction);
  5680. }
  5681. return $out;
  5682. }
  5683. }