html.form.class.php 289 KB

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