html.form.class.php 271 KB

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