html.form.class.php 462 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023
  1. <?php
  2. /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  7. * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>
  10. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
  11. * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
  12. * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
  13. * Copyright (C) 2010-2021 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  15. * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
  16. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  17. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  18. * Copyright (C) 2014-2023 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018-2022 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  21. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  22. * Copyright (C) 2018 Christophe Battarel <christophe@altairis.fr>
  23. * Copyright (C) 2018 Josep Lluis Amador <joseplluis@lliuretic.cat>
  24. * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
  25. * Copyright (C) 2023 Nick Fragoulis
  26. *
  27. * This program is free software; you can redistribute it and/or modify
  28. * it under the terms of the GNU General Public License as published by
  29. * the Free Software Foundation; either version 3 of the License, or
  30. * (at your option) any later version.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU General Public License
  38. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  39. */
  40. /**
  41. * \file htdocs/core/class/html.form.class.php
  42. * \ingroup core
  43. * \brief File of class with all html predefined components
  44. */
  45. /**
  46. * Class to manage generation of HTML components
  47. * Only common components must be here.
  48. *
  49. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  50. */
  51. class Form
  52. {
  53. /**
  54. * @var DoliDB Database handler.
  55. */
  56. public $db;
  57. /**
  58. * @var string Error code (or message)
  59. */
  60. public $error = '';
  61. /**
  62. * @var string[] Array of error strings
  63. */
  64. public $errors = array();
  65. // Some properties used to return data by some methods
  66. public $result;
  67. public $num;
  68. // Cache arrays
  69. public $cache_types_paiements = array();
  70. public $cache_conditions_paiements = array();
  71. public $cache_transport_mode = array();
  72. public $cache_availability = array();
  73. public $cache_demand_reason = array();
  74. public $cache_types_fees = array();
  75. public $cache_vatrates = array();
  76. public $cache_invoice_subtype = array();
  77. /**
  78. * Constructor
  79. *
  80. * @param DoliDB $db Database handler
  81. */
  82. public function __construct($db)
  83. {
  84. $this->db = $db;
  85. }
  86. /**
  87. * Output key field for an editable field
  88. *
  89. * @param string $text Text of label or key to translate
  90. * @param string $htmlname Name of select field ('edit' prefix will be added)
  91. * @param string $preselected Value to show/edit (not used in this function)
  92. * @param object $object Object (on the page we show)
  93. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  94. * @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 'datehourpicker' 'checkbox:ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  95. * @param string $moreparam More param to add on a href URL.
  96. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  97. * @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 ' '
  98. * @param string $paramid Key of parameter for id ('id', 'socid')
  99. * @param string $help Tooltip help
  100. * @return string HTML edit field
  101. */
  102. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  103. {
  104. global $conf, $langs;
  105. $ret = '';
  106. // TODO change for compatibility
  107. if (getDolGlobalString('MAIN_USE_JQUERY_JEDITABLE') && !preg_match('/^select;/', $typeofdata)) {
  108. if (!empty($perm)) {
  109. $tmp = explode(':', $typeofdata);
  110. $ret .= '<div class="editkey_' . $tmp[0] . (!empty($tmp[1]) ? ' ' . $tmp[1] : '') . '" id="' . $htmlname . '">';
  111. if ($fieldrequired) {
  112. $ret .= '<span class="fieldrequired">';
  113. }
  114. if ($help) {
  115. $ret .= $this->textwithpicto($langs->trans($text), $help);
  116. } else {
  117. $ret .= $langs->trans($text);
  118. }
  119. if ($fieldrequired) {
  120. $ret .= '</span>';
  121. }
  122. $ret .= '</div>' . "\n";
  123. } else {
  124. if ($fieldrequired) {
  125. $ret .= '<span class="fieldrequired">';
  126. }
  127. if ($help) {
  128. $ret .= $this->textwithpicto($langs->trans($text), $help);
  129. } else {
  130. $ret .= $langs->trans($text);
  131. }
  132. if ($fieldrequired) {
  133. $ret .= '</span>';
  134. }
  135. }
  136. } else {
  137. if (empty($notabletag) && $perm) {
  138. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  139. }
  140. if ($fieldrequired) {
  141. $ret .= '<span class="fieldrequired">';
  142. }
  143. if ($help) {
  144. $ret .= $this->textwithpicto($langs->trans($text), $help);
  145. } else {
  146. $ret .= $langs->trans($text);
  147. }
  148. if ($fieldrequired) {
  149. $ret .= '</span>';
  150. }
  151. if (!empty($notabletag)) {
  152. $ret .= ' ';
  153. }
  154. if (empty($notabletag) && $perm) {
  155. $ret .= '</td>';
  156. }
  157. if (empty($notabletag) && $perm) {
  158. $ret .= '<td class="right">';
  159. }
  160. if ($htmlname && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
  161. $ret .= '<a class="editfielda reposition" href="' . $_SERVER["PHP_SELF"] . '?action=edit' . $htmlname . '&token=' . newToken() . '&' . $paramid . '=' . $object->id . $moreparam . '">' . img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)) . '</a>';
  162. }
  163. if (!empty($notabletag) && $notabletag == 1) {
  164. if ($text) {
  165. $ret .= ' : ';
  166. } else {
  167. $ret .= ' ';
  168. }
  169. }
  170. if (!empty($notabletag) && $notabletag == 3) {
  171. $ret .= ' ';
  172. }
  173. if (empty($notabletag) && $perm) {
  174. $ret .= '</td>';
  175. }
  176. if (empty($notabletag) && $perm) {
  177. $ret .= '</tr></table>';
  178. }
  179. }
  180. return $ret;
  181. }
  182. /**
  183. * Output value of a field for an editable field
  184. *
  185. * @param string $text Text of label (not used in this function)
  186. * @param string $htmlname Name of select field
  187. * @param string $value Value to show/edit
  188. * @param object $object Object (that we want to show)
  189. * @param boolean $perm Permission to allow button to edit parameter
  190. * @param string $typeofdata Type of data ('string' by default, 'checkbox', 'email', 'phone', 'amount:99', 'numeric:99',
  191. * 'text' or 'textarea:rows:cols%', 'safehtmlstring', 'restricthtml',
  192. * 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datehourpicker', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select;xkey:xval,ykey:yval,...')
  193. * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of numeric value, or a select combo). Use '' to use same than $value
  194. * @param object $extObject External object ???
  195. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  196. * @param string $moreparam More param to add on the form on action href URL parameter
  197. * @param int $notabletag Do no output table tags
  198. * @param string $formatfunc Call a specific method of $object->$formatfunc to output field in view mode (For example: 'dol_print_email')
  199. * @param string $paramid Key of parameter for id ('id', 'socid')
  200. * @param string $gm 'auto' or 'tzuser' or 'tzuserrel' or 'tzserver' (when $typeofdata is a date)
  201. * @param array $moreoptions Array with more options. For example array('addnowlink'=>1), array('valuealreadyhtmlescaped'=>1)
  202. * @param string $editaction [=''] use GETPOST default action or set action to edit mode
  203. * @return string HTML edit field
  204. */
  205. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 1, $formatfunc = '', $paramid = 'id', $gm = 'auto', $moreoptions = array(), $editaction = '')
  206. {
  207. global $conf, $langs;
  208. $ret = '';
  209. // Check parameters
  210. if (empty($typeofdata)) {
  211. return 'ErrorBadParameter typeofdata is empty';
  212. }
  213. // Clean paramater $typeofdata
  214. if ($typeofdata == 'datetime') {
  215. $typeofdata = 'dayhour';
  216. }
  217. $reg = array();
  218. if (preg_match('/^(\w+)\((\d+)\)$/', $typeofdata, $reg)) {
  219. if ($reg[1] == 'varchar') {
  220. $typeofdata = 'string';
  221. } elseif ($reg[1] == 'int') {
  222. $typeofdata = 'numeric';
  223. } else {
  224. return 'ErrorBadParameter ' . $typeofdata;
  225. }
  226. }
  227. // When option to edit inline is activated
  228. if (getDolGlobalString('MAIN_USE_JQUERY_JEDITABLE') && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  229. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  230. } else {
  231. if ($editaction == '') {
  232. $editaction = GETPOST('action', 'aZ09');
  233. }
  234. $editmode = ($editaction == 'edit' . $htmlname);
  235. if ($editmode) { // edit mode
  236. $ret .= "\n";
  237. $ret .= '<form method="post" action="' . $_SERVER["PHP_SELF"] . ($moreparam ? '?' . $moreparam : '') . '">';
  238. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  239. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  240. $ret .= '<input type="hidden" name="' . $paramid . '" value="' . $object->id . '">';
  241. if (empty($notabletag)) {
  242. $ret .= '<table class="nobordernopadding centpercent">';
  243. }
  244. if (empty($notabletag)) {
  245. $ret .= '<tr><td>';
  246. }
  247. if (preg_match('/^(string|safehtmlstring|email|phone|url)/', $typeofdata)) {
  248. $tmp = explode(':', $typeofdata);
  249. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($editvalue ? $editvalue : $value) . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  250. } elseif (preg_match('/^(integer)/', $typeofdata)) {
  251. $tmp = explode(':', $typeofdata);
  252. $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
  253. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $valuetoshow . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  254. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  255. $tmp = explode(':', $typeofdata);
  256. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  257. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($valuetoshow != '' ? price($valuetoshow) : '') . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  258. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  259. $tmp = explode(':', $typeofdata);
  260. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($value ? $value : 'on') . '"' . ($value ? ' checked' : '') . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
  261. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  262. $tmp = explode(':', $typeofdata);
  263. $cols = (empty($tmp[2]) ? '' : $tmp[2]);
  264. $morealt = '';
  265. if (preg_match('/%/', $cols)) {
  266. $morealt = ' style="width: ' . $cols . '"';
  267. $cols = '';
  268. }
  269. $valuetoshow = ($editvalue ? $editvalue : $value);
  270. $ret .= '<textarea id="' . $htmlname . '" name="' . $htmlname . '" wrap="soft" rows="' . (empty($tmp[1]) ? '20' : $tmp[1]) . '"' . ($cols ? ' cols="' . $cols . '"' : 'class="quatrevingtpercent"') . $morealt . '" autofocus>';
  271. // textarea convert automatically entities chars into simple chars.
  272. // So we convert & into &amp; so a string like 'a &lt; <b>b</b><br>é<br>&lt;script&gt;alert('X');&lt;script&gt;' stay a correct html and is not converted by textarea component when wysiwig is off.
  273. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  274. $ret .= dol_htmlwithnojs(dol_string_neverthesehtmltags($valuetoshow, array('textarea')));
  275. $ret .= '</textarea>';
  276. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  277. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  278. $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
  279. $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
  280. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
  281. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  282. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  283. $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
  284. $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
  285. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
  286. } elseif (preg_match('/^select;/', $typeofdata)) {
  287. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  288. $arraylist = array();
  289. foreach ($arraydata as $val) {
  290. $tmp = explode(':', $val);
  291. $tmpkey = str_replace('|', ':', $tmp[0]);
  292. $arraylist[$tmpkey] = $tmp[1];
  293. }
  294. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  295. } elseif (preg_match('/^link/', $typeofdata)) {
  296. // TODO Not yet implemented. See code for extrafields
  297. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  298. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  299. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  300. $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), (empty($tmp[2]) ? '' : $tmp[2]), (empty($tmp[3]) ? '100' : $tmp[3]), (empty($tmp[1]) ? 'dolibarr_notes' : $tmp[1]), 'In', (empty($tmp[5]) ? 0 : $tmp[5]), (isset($tmp[8]) ? ($tmp[8] ? true : false) : true), true, (empty($tmp[6]) ? '20' : $tmp[6]), (empty($tmp[7]) ? '100' : $tmp[7]));
  301. $ret .= $doleditor->Create(1);
  302. } elseif ($typeofdata == 'asis') {
  303. $ret .= ($editvalue ? $editvalue : $value);
  304. }
  305. if (empty($notabletag)) {
  306. $ret .= '</td>';
  307. }
  308. // Button save-cancel
  309. if (empty($notabletag)) {
  310. $ret .= '<td>';
  311. }
  312. //else $ret.='<div class="clearboth"></div>';
  313. $ret .= '<input type="submit" class="smallpaddingimp button' . (empty($notabletag) ? '' : ' ') . '" name="modify" value="' . $langs->trans("Modify") . '">';
  314. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  315. $ret .= '<br>' . "\n";
  316. }
  317. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel' . (empty($notabletag) ? '' : ' ') . '" name="cancel" value="' . $langs->trans("Cancel") . '">';
  318. if (empty($notabletag)) {
  319. $ret .= '</td>';
  320. }
  321. if (empty($notabletag)) {
  322. $ret .= '</tr></table>' . "\n";
  323. }
  324. $ret .= '</form>' . "\n";
  325. } else { // view mode
  326. if (preg_match('/^email/', $typeofdata)) {
  327. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  328. } elseif (preg_match('/^phone/', $typeofdata)) {
  329. $ret .= dol_print_phone($value, '_blank', 32, 1);
  330. } elseif (preg_match('/^url/', $typeofdata)) {
  331. $ret .= dol_print_url($value, '_blank', 32, 1);
  332. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  333. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  334. } elseif (preg_match('/^checkbox/', $typeofdata)) {
  335. $tmp = explode(':', $typeofdata);
  336. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($value ? ' checked' : '') . ($tmp[1] ? $tmp[1] : '') . '/>';
  337. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  338. $ret .= dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($value), 1, 1, 1));
  339. } elseif (preg_match('/^(safehtmlstring|restricthtml)/', $typeofdata)) { // 'restricthtml' is not an allowed type for editfieldval. Value is 'safehtmlstring'
  340. $ret .= dol_htmlwithnojs(dol_string_onlythesehtmltags($value));
  341. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  342. $ret .= '<span class="valuedate">' . dol_print_date($value, 'day', $gm) . '</span>';
  343. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  344. $ret .= '<span class="valuedate">' . dol_print_date($value, 'dayhour', $gm) . '</span>';
  345. } elseif (preg_match('/^select;/', $typeofdata)) {
  346. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  347. $arraylist = array();
  348. foreach ($arraydata as $val) {
  349. $tmp = explode(':', $val);
  350. $arraylist[$tmp[0]] = $tmp[1];
  351. }
  352. $ret .= $arraylist[$value];
  353. if ($htmlname == 'fk_product_type') {
  354. if ($value == 0) {
  355. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  356. } else {
  357. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  358. }
  359. }
  360. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  361. $tmpcontent = dol_htmlentitiesbr($value);
  362. if (getDolGlobalString('MAIN_DISABLE_NOTES_TAB')) {
  363. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  364. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  365. $tmpcontent = $firstline . ((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  366. }
  367. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  368. // clean data from some dangerous html
  369. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  370. } else {
  371. if (empty($moreoptions['valuealreadyhtmlescaped'])) {
  372. $ret .= dol_escape_htmltag($value);
  373. } else {
  374. $ret .= $value; // $value must be already html escaped.
  375. }
  376. }
  377. // Custom format if parameter $formatfunc has been provided
  378. if ($formatfunc && method_exists($object, $formatfunc)) {
  379. $ret = $object->$formatfunc($ret);
  380. }
  381. }
  382. }
  383. return $ret;
  384. }
  385. /**
  386. * Output edit in place form
  387. *
  388. * @param string $fieldname Name of the field
  389. * @param object $object Object
  390. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  391. * @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]'...)
  392. * @param string $check Same coe than $check parameter of GETPOST()
  393. * @param string $morecss More CSS
  394. * @return string HTML code for the edit of alternative language
  395. */
  396. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  397. {
  398. global $conf, $langs, $extralanguages;
  399. $result = '';
  400. // List of extra languages
  401. $arrayoflangcode = array();
  402. if (getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE')) {
  403. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  404. }
  405. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  406. if (!is_object($extralanguages)) {
  407. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  408. $extralanguages = new ExtraLanguages($this->db);
  409. }
  410. $extralanguages->fetch_name_extralanguages('societe');
  411. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  412. return ''; // No extralang field to show
  413. }
  414. $result .= '<!-- Widget for translation -->' . "\n";
  415. $result .= '<div class="inline-block paddingleft image-' . $object->element . '-' . $fieldname . '">';
  416. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  417. $result .= $s;
  418. $result .= '</div>';
  419. $result .= '<div class="inline-block hidden field-' . $object->element . '-' . $fieldname . '">';
  420. $resultforextrlang = '';
  421. foreach ($arrayoflangcode as $langcode) {
  422. $valuetoshow = GETPOSTISSET('field-' . $object->element . "-" . $fieldname . "-" . $langcode) ? GETPOST('field-' . $object->element . '-' . $fieldname . "-" . $langcode, $check) : '';
  423. if (empty($valuetoshow)) {
  424. $object->fetchValuesForExtraLanguages();
  425. //var_dump($object->array_languages);
  426. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  427. }
  428. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  429. $resultforextrlang .= $s;
  430. // TODO Use the showInputField() method of ExtraLanguages object
  431. if ($typeofdata == 'textarea') {
  432. $resultforextrlang .= '<textarea name="field-' . $object->element . "-" . $fieldname . "-" . $langcode . '" id="' . $fieldname . "-" . $langcode . '" class="' . $morecss . '" rows="' . ROWS_2 . '" wrap="soft">';
  433. $resultforextrlang .= $valuetoshow;
  434. $resultforextrlang .= '</textarea>';
  435. } else {
  436. $resultforextrlang .= '<input type="text" class="inputfieldforlang ' . ($morecss ? ' ' . $morecss : '') . '" name="field-' . $object->element . '-' . $fieldname . '-' . $langcode . '" value="' . $valuetoshow . '">';
  437. }
  438. }
  439. $result .= $resultforextrlang;
  440. $result .= '</div>';
  441. $result .= '<script nonce="' . getNonce() . '">$(".image-' . $object->element . '-' . $fieldname . '").click(function() { console.log("Toggle lang widget"); jQuery(".field-' . $object->element . '-' . $fieldname . '").toggle(); });</script>';
  442. }
  443. return $result;
  444. }
  445. /**
  446. * Output edit in place form
  447. *
  448. * @param object $object Object
  449. * @param string $value Value to show/edit
  450. * @param string $htmlname DIV ID (field name)
  451. * @param int $condition Condition to edit
  452. * @param string $inputType Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:loadmethod:savemethod:buttononly')
  453. * @param string $editvalue When in edit mode, use this value as $value instead of value
  454. * @param object $extObject External object
  455. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  456. * @return string HTML edit in place
  457. */
  458. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  459. {
  460. global $conf;
  461. $out = '';
  462. // Check parameters
  463. if (preg_match('/^text/', $inputType)) {
  464. $value = dol_nl2br($value);
  465. } elseif (preg_match('/^numeric/', $inputType)) {
  466. $value = price($value);
  467. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  468. $value = dol_print_date($value, 'day');
  469. }
  470. if ($condition) {
  471. $element = false;
  472. $table_element = false;
  473. $fk_element = false;
  474. $loadmethod = false;
  475. $savemethod = false;
  476. $ext_element = false;
  477. $button_only = false;
  478. $inputOption = '';
  479. $rows = '';
  480. $cols = '';
  481. if (is_object($object)) {
  482. $element = $object->element;
  483. $table_element = $object->table_element;
  484. $fk_element = $object->id;
  485. }
  486. if (is_object($extObject)) {
  487. $ext_element = $extObject->element;
  488. }
  489. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  490. $tmp = explode(':', $inputType);
  491. $inputType = $tmp[0];
  492. if (!empty($tmp[1])) {
  493. $inputOption = $tmp[1];
  494. }
  495. if (!empty($tmp[2])) {
  496. $savemethod = $tmp[2];
  497. }
  498. $out .= '<input id="width_' . $htmlname . '" value="' . $inputOption . '" type="hidden"/>' . "\n";
  499. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  500. $tmp = explode(':', $inputType);
  501. $inputType = $tmp[0];
  502. if (!empty($tmp[1])) {
  503. $inputOption = $tmp[1];
  504. }
  505. if (!empty($tmp[2])) {
  506. $savemethod = $tmp[2];
  507. }
  508. $out .= '<input id="timestamp" type="hidden"/>' . "\n"; // Use for timestamp format
  509. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  510. $tmp = explode(':', $inputType);
  511. $inputType = $tmp[0];
  512. $loadmethod = $tmp[1];
  513. if (!empty($tmp[2])) {
  514. $savemethod = $tmp[2];
  515. }
  516. if (!empty($tmp[3])) {
  517. $button_only = true;
  518. }
  519. } elseif (preg_match('/^textarea/', $inputType)) {
  520. $tmp = explode(':', $inputType);
  521. $inputType = $tmp[0];
  522. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  523. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  524. } elseif (preg_match('/^ckeditor/', $inputType)) {
  525. $tmp = explode(':', $inputType);
  526. $inputType = $tmp[0];
  527. $toolbar = $tmp[1];
  528. if (!empty($tmp[2])) {
  529. $width = $tmp[2];
  530. }
  531. if (!empty($tmp[3])) {
  532. $heigth = $tmp[3];
  533. }
  534. if (!empty($tmp[4])) {
  535. $savemethod = $tmp[4];
  536. }
  537. if (isModEnabled('fckeditor')) {
  538. $out .= '<input id="ckeditor_toolbar" value="' . $toolbar . '" type="hidden"/>' . "\n";
  539. } else {
  540. $inputType = 'textarea';
  541. }
  542. }
  543. $out .= '<input id="element_' . $htmlname . '" value="' . $element . '" type="hidden"/>' . "\n";
  544. $out .= '<input id="table_element_' . $htmlname . '" value="' . $table_element . '" type="hidden"/>' . "\n";
  545. $out .= '<input id="fk_element_' . $htmlname . '" value="' . $fk_element . '" type="hidden"/>' . "\n";
  546. $out .= '<input id="loadmethod_' . $htmlname . '" value="' . $loadmethod . '" type="hidden"/>' . "\n";
  547. if (!empty($savemethod)) {
  548. $out .= '<input id="savemethod_' . $htmlname . '" value="' . $savemethod . '" type="hidden"/>' . "\n";
  549. }
  550. if (!empty($ext_element)) {
  551. $out .= '<input id="ext_element_' . $htmlname . '" value="' . $ext_element . '" type="hidden"/>' . "\n";
  552. }
  553. if (!empty($custommsg)) {
  554. if (is_array($custommsg)) {
  555. if (!empty($custommsg['success'])) {
  556. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg['success'] . '" type="hidden"/>' . "\n";
  557. }
  558. if (!empty($custommsg['error'])) {
  559. $out .= '<input id="errormsg_' . $htmlname . '" value="' . $custommsg['error'] . '" type="hidden"/>' . "\n";
  560. }
  561. } else {
  562. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg . '" type="hidden"/>' . "\n";
  563. }
  564. }
  565. if ($inputType == 'textarea') {
  566. $out .= '<input id="textarea_' . $htmlname . '_rows" value="' . $rows . '" type="hidden"/>' . "\n";
  567. $out .= '<input id="textarea_' . $htmlname . '_cols" value="' . $cols . '" type="hidden"/>' . "\n";
  568. }
  569. $out .= '<span id="viewval_' . $htmlname . '" class="viewval_' . $inputType . ($button_only ? ' inactive' : ' active') . '">' . $value . '</span>' . "\n";
  570. $out .= '<span id="editval_' . $htmlname . '" class="editval_' . $inputType . ($button_only ? ' inactive' : ' active') . ' hideobject">' . (!empty($editvalue) ? $editvalue : $value) . '</span>' . "\n";
  571. } else {
  572. $out = $value;
  573. }
  574. return $out;
  575. }
  576. /**
  577. * Show a text and picto with tooltip on text or picto.
  578. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  579. *
  580. * @param string $text Text to show
  581. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  582. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  583. * @param int $direction -1=image is before, 0=no image, 1=image is after
  584. * @param string $img Html code for image (use img_xxx() function to get it)
  585. * @param string $extracss Add a CSS style to td tags
  586. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  587. * @param string $incbefore Include code before the text
  588. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  589. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  590. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  591. * @return string Code html du tooltip (texte+picto)
  592. * @see textwithpicto() Use textwithpicto() instead of textwithtooltip if you can.
  593. */
  594. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  595. {
  596. if ($incbefore) {
  597. $text = $incbefore . $text;
  598. }
  599. if (!$htmltext) {
  600. return $text;
  601. }
  602. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  603. $tag = 'td';
  604. if ($notabs == 2) {
  605. $tag = 'div';
  606. }
  607. if ($notabs == 3) {
  608. $tag = 'span';
  609. }
  610. // Sanitize tooltip
  611. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  612. $extrastyle = '';
  613. if ($direction < 0) {
  614. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  615. $extrastyle = 'padding: 0px; padding-left: 3px;';
  616. }
  617. if ($direction > 0) {
  618. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  619. $extrastyle = 'padding: 0px; padding-right: 3px;';
  620. }
  621. $classfortooltip = 'classfortooltip';
  622. $s = '';
  623. $textfordialog = '';
  624. if ($tooltiptrigger == '') {
  625. $htmltext = str_replace('"', '&quot;', $htmltext);
  626. } else {
  627. $classfortooltip = 'classfortooltiponclick';
  628. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_' . $tooltiptrigger . '" class="classfortooltiponclicktext">' . $htmltext . '</div>';
  629. }
  630. if ($tooltipon == 2 || $tooltipon == 3) {
  631. $paramfortooltipimg = ' class="' . $classfortooltip . ($notabs != 3 ? ' inline-block' : '') . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '"';
  632. if ($tooltiptrigger == '') {
  633. $paramfortooltipimg .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on img tag to store tooltip
  634. } else {
  635. $paramfortooltipimg .= ' dolid="' . $tooltiptrigger . '"';
  636. }
  637. } else {
  638. $paramfortooltipimg = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  639. }
  640. if ($tooltipon == 1 || $tooltipon == 3) {
  641. $paramfortooltiptd = ' class="' . ($tooltipon == 3 ? 'cursorpointer ' : '') . $classfortooltip . ' inline-block' . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '" ';
  642. if ($tooltiptrigger == '') {
  643. $paramfortooltiptd .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on td tag to store tooltip
  644. } else {
  645. $paramfortooltiptd .= ' dolid="' . $tooltiptrigger . '"';
  646. }
  647. } else {
  648. $paramfortooltiptd = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  649. }
  650. if (empty($notabs)) {
  651. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  652. } elseif ($notabs == 2) {
  653. $s .= '<div class="inline-block' . ($forcenowrap ? ' nowrap' : '') . '">';
  654. }
  655. // Define value if value is before
  656. if ($direction < 0) {
  657. $s .= '<' . $tag . $paramfortooltipimg;
  658. if ($tag == 'td') {
  659. $s .= ' class="valigntop" width="14"';
  660. }
  661. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  662. }
  663. // Use another method to help avoid having a space in value in order to use this value with jquery
  664. // Define label
  665. if ((string) $text != '') {
  666. $s .= '<' . $tag . $paramfortooltiptd . '>' . $text . '</' . $tag . '>';
  667. }
  668. // Define value if value is after
  669. if ($direction > 0) {
  670. $s .= '<' . $tag . $paramfortooltipimg;
  671. if ($tag == 'td') {
  672. $s .= ' class="valignmiddle" width="14"';
  673. }
  674. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  675. }
  676. if (empty($notabs)) {
  677. $s .= '</tr></table>';
  678. } elseif ($notabs == 2) {
  679. $s .= '</div>';
  680. }
  681. return $s;
  682. }
  683. /**
  684. * Show a text with a picto and a tooltip on picto
  685. *
  686. * @param string $text Text to show
  687. * @param string $htmltext Content of tooltip
  688. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  689. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  690. * @param string $extracss Add a CSS style to td, div or span tag
  691. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  692. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  693. * @param string $tooltiptrigger ''=Tooltip on hover and hidden on smartphone, 'abconsmartphone'=Tooltip on hover and on click on smartphone, 'abc'=Tooltip on click (abc is a unique key, clickable link is on image or on link if param $type='none' or on both if $type='xxxclickable')
  694. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  695. * @return string HTML code of text, picto, tooltip
  696. */
  697. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  698. {
  699. global $conf, $langs;
  700. //For backwards compatibility
  701. if ($type == '0') {
  702. $type = 'info';
  703. } elseif ($type == '1') {
  704. $type = 'help';
  705. }
  706. // Clean parameters
  707. $tooltiptrigger = preg_replace('/[^a-z0-9]/i', '', $tooltiptrigger);
  708. if (preg_match('/onsmartphone$/', $tooltiptrigger) && empty($conf->dol_no_mouse_hover)) {
  709. $tooltiptrigger = preg_replace('/^.*onsmartphone$/', '', $tooltiptrigger);
  710. }
  711. $alt = '';
  712. if ($tooltiptrigger) {
  713. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  714. }
  715. // If info or help with no javascript, show only text
  716. if (empty($conf->use_javascript_ajax)) {
  717. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  718. return $text;
  719. } else {
  720. $alt = $htmltext;
  721. $htmltext = '';
  722. }
  723. }
  724. // If info or help with smartphone, show only text (tooltip hover can't works)
  725. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  726. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  727. return $text;
  728. }
  729. }
  730. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  731. //if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
  732. //{
  733. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.'</a>';
  734. //}
  735. $img = '';
  736. if ($type == 'info') {
  737. $img = img_help(0, $alt);
  738. } elseif ($type == 'help') {
  739. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  740. } elseif ($type == 'helpclickable') {
  741. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  742. } elseif ($type == 'superadmin') {
  743. $img = img_picto($alt, 'redstar');
  744. } elseif ($type == 'admin') {
  745. $img = img_picto($alt, 'star');
  746. } elseif ($type == 'warning') {
  747. $img = img_warning($alt);
  748. } elseif ($type != 'none') {
  749. $img = img_picto($alt, $type); // $type can be an image path
  750. }
  751. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  752. }
  753. /**
  754. * Generate select HTML to choose massaction
  755. *
  756. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  757. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  758. * @param int $alwaysvisible 1=select button always visible
  759. * @param string $name Name for massaction
  760. * @param string $cssclass CSS class used to check for select
  761. * @return string|void Select list
  762. */
  763. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  764. {
  765. global $conf, $langs, $hookmanager;
  766. $disabled = 0;
  767. $ret = '<div class="centpercent center">';
  768. $ret .= '<select class="flat' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'select valignmiddle alignstart" id="' . $name . '" name="' . $name . '"' . ($disabled ? ' disabled="disabled"' : '') . '>';
  769. // 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.
  770. $parameters = array();
  771. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  772. // check if there is a mass action
  773. if (is_array($arrayofaction) && count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  774. return;
  775. }
  776. if (empty($reshook)) {
  777. $ret .= '<option value="0"' . ($disabled ? ' disabled="disabled"' : '') . '>-- ' . $langs->trans("SelectAction") . ' --</option>';
  778. if (is_array($arrayofaction)) {
  779. foreach ($arrayofaction as $code => $label) {
  780. $ret .= '<option value="' . $code . '"' . ($disabled ? ' disabled="disabled"' : '') . ' data-html="' . dol_escape_htmltag($label) . '">' . $label . '</option>';
  781. }
  782. }
  783. }
  784. $ret .= $hookmanager->resPrint;
  785. $ret .= '</select>';
  786. if (empty($conf->dol_optimize_smallscreen)) {
  787. $ret .= ajax_combobox('.' . $name . 'select');
  788. }
  789. // 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
  790. $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.
  791. $ret .= '<input type="submit" disabled name="confirmmassaction"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display: none"') . ' class="reposition button smallpaddingimp' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'confirmed" value="' . dol_escape_htmltag($langs->trans("Confirm")) . '">';
  792. $ret .= '</div>';
  793. if (!empty($conf->use_javascript_ajax)) {
  794. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  795. <script nonce="' . getNonce() . '">
  796. function initCheckForSelect(mode, name, cssclass) /* mode is 0 during init of page or click all, 1 when we click on 1 checkboxi, "name" refers to the class of the massaction button, "cssclass" to the class of the checkfor select boxes */
  797. {
  798. atleastoneselected=0;
  799. jQuery("."+cssclass).each(function( index ) {
  800. /* console.log( index + ": " + $( this ).text() ); */
  801. if ($(this).is(\':checked\')) atleastoneselected++;
  802. });
  803. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  804. if (atleastoneselected || ' . $alwaysvisible . ')
  805. {
  806. jQuery("."+name).show();
  807. ' . ($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("' . $selected . '").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '') . '
  808. ' . ($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '') . '
  809. }
  810. else
  811. {
  812. jQuery("."+name).hide();
  813. jQuery("."+name+"other").hide();
  814. }
  815. }
  816. jQuery(document).ready(function () {
  817. initCheckForSelect(0, "' . $name . '", "' . $cssclass . '");
  818. jQuery(".' . $cssclass . '").click(function() {
  819. initCheckForSelect(1, "' . $name . '", "' . $cssclass . '");
  820. });
  821. jQuery(".' . $name . 'select").change(function() {
  822. var massaction = $( this ).val();
  823. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  824. if (massaction == "builddoc")
  825. {
  826. urlform = urlform + "#show_files";
  827. }
  828. $( this ).closest("form").attr("action", urlform);
  829. console.log("we select a mass action name=' . $name . ' massaction="+massaction+" - "+urlform);
  830. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  831. if ($(this).val() != \'0\')
  832. {
  833. jQuery(".' . $name . 'confirmed").prop(\'disabled\', false);
  834. jQuery(".' . $name . 'other").hide(); /* To disable if another div was open */
  835. jQuery(".' . $name . '"+massaction).show();
  836. }
  837. else
  838. {
  839. jQuery(".' . $name . 'confirmed").prop(\'disabled\', true);
  840. jQuery(".' . $name . 'other").hide(); /* To disable any div open */
  841. }
  842. });
  843. });
  844. </script>
  845. ';
  846. }
  847. return $ret;
  848. }
  849. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  850. /**
  851. * Return combo list of activated countries, into language of user
  852. *
  853. * @param string $selected Id or Code or Label of preselected country
  854. * @param string $htmlname Name of html select object
  855. * @param string $htmloption More html options on select object
  856. * @param integer $maxlength Max length for labels (0=no limit)
  857. * @param string $morecss More css class
  858. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  859. * @param int|string $showempty Show empty choice
  860. * @param int $disablefavorites 1=Disable favorites,
  861. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  862. * @param array $exclude_country_code Array of country code (iso2) to exclude
  863. * @param int $hideflags Hide flags
  864. * @return string HTML string with select
  865. */
  866. public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array(), $hideflags = 0)
  867. {
  868. // phpcs:enable
  869. global $conf, $langs, $mysoc;
  870. $langs->load("dict");
  871. $out = '';
  872. $countryArray = array();
  873. $favorite = array();
  874. $label = array();
  875. $atleastonefavorite = 0;
  876. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  877. $sql .= " FROM " . $this->db->prefix() . "c_country";
  878. $sql .= " WHERE active > 0";
  879. //$sql.= " ORDER BY code ASC";
  880. dol_syslog(get_class($this) . "::select_country", LOG_DEBUG);
  881. $resql = $this->db->query($sql);
  882. if ($resql) {
  883. $out .= '<select id="select' . $htmlname . '" class="flat maxwidth200onsmartphone selectcountry' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" ' . $htmloption . '>';
  884. $num = $this->db->num_rows($resql);
  885. $i = 0;
  886. if ($num) {
  887. while ($i < $num) {
  888. $obj = $this->db->fetch_object($resql);
  889. $countryArray[$i]['rowid'] = $obj->rowid;
  890. $countryArray[$i]['code_iso'] = $obj->code_iso;
  891. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  892. $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 : ''));
  893. $countryArray[$i]['favorite'] = $obj->favorite;
  894. $countryArray[$i]['eec'] = $obj->eec;
  895. $favorite[$i] = $obj->favorite;
  896. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  897. $i++;
  898. }
  899. if (empty($disablefavorites)) {
  900. $array1_sort_order = SORT_DESC;
  901. $array2_sort_order = SORT_ASC;
  902. array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
  903. } else {
  904. $countryArray = dol_sort_array($countryArray, 'label');
  905. }
  906. if ($showempty) {
  907. if (is_numeric($showempty)) {
  908. $out .= '<option value="">&nbsp;</option>' . "\n";
  909. } else {
  910. $out .= '<option value="-1">' . $langs->trans($showempty) . '</option>' . "\n";
  911. }
  912. }
  913. if ($addspecialentries) { // Add dedicated entries for groups of countries
  914. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  915. $out .= '<option value="special_allnotme"' . ($selected == 'special_allnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  916. $out .= '<option value="special_eec"' . ($selected == 'special_eec' ? ' selected' : '') . '>' . $langs->trans("CountriesInEEC") . '</option>';
  917. if ($mysoc->isInEEC()) {
  918. $out .= '<option value="special_eecnotme"' . ($selected == 'special_eecnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  919. }
  920. $out .= '<option value="special_noteec"' . ($selected == 'special_noteec' ? ' selected' : '') . '>' . $langs->trans("CountriesNotInEEC") . '</option>';
  921. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  922. }
  923. foreach ($countryArray as $row) {
  924. //if (empty($showempty) && empty($row['rowid'])) continue;
  925. if (empty($row['rowid'])) {
  926. continue;
  927. }
  928. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  929. continue; // exclude some countries
  930. }
  931. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  932. $atleastonefavorite++;
  933. }
  934. if (empty($row['favorite']) && $atleastonefavorite) {
  935. $atleastonefavorite = 0;
  936. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  937. }
  938. $labeltoshow = '';
  939. if ($row['label']) {
  940. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  941. } else {
  942. $labeltoshow .= '&nbsp;';
  943. }
  944. if ($row['code_iso']) {
  945. $labeltoshow .= ' <span class="opacitymedium">(' . $row['code_iso'] . ')</span>';
  946. if (empty($hideflags)) {
  947. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  948. $labeltoshow = $tmpflag . ' ' . $labeltoshow;
  949. }
  950. }
  951. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  952. $out .= '<option value="' . ($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']) . '" selected data-html="' . dol_escape_htmltag($labeltoshow) . '" data-eec="' . ((int) $row['eec']) . '">';
  953. } else {
  954. $out .= '<option value="' . ($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']) . '" data-html="' . dol_escape_htmltag($labeltoshow) . '" data-eec="' . ((int) $row['eec']) . '">';
  955. }
  956. $out .= $labeltoshow;
  957. $out .= '</option>' . "\n";
  958. }
  959. }
  960. $out .= '</select>';
  961. } else {
  962. dol_print_error($this->db);
  963. }
  964. // Make select dynamic
  965. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  966. $out .= ajax_combobox('select' . $htmlname, array(), 0, 0, 'resolve');
  967. return $out;
  968. }
  969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  970. /**
  971. * Return select list of incoterms
  972. *
  973. * @param string $selected Id or Code of preselected incoterm
  974. * @param string $location_incoterms Value of input location
  975. * @param string $page Defined the form action
  976. * @param string $htmlname Name of html select object
  977. * @param string $htmloption Options html on select object
  978. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  979. * @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')))
  980. * @param int $disableautocomplete Disable autocomplete
  981. * @return string HTML string with select and input
  982. */
  983. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
  984. {
  985. // phpcs:enable
  986. global $conf, $langs;
  987. $langs->load("dict");
  988. $out = '';
  989. $moreattrib = '';
  990. $incotermArray = array();
  991. $sql = "SELECT rowid, code";
  992. $sql .= " FROM " . $this->db->prefix() . "c_incoterms";
  993. $sql .= " WHERE active > 0";
  994. $sql .= " ORDER BY code ASC";
  995. dol_syslog(get_class($this) . "::select_incoterm", LOG_DEBUG);
  996. $resql = $this->db->query($sql);
  997. if ($resql) {
  998. if ($conf->use_javascript_ajax && !$forcecombo) {
  999. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1000. $out .= ajax_combobox($htmlname, $events);
  1001. }
  1002. if (!empty($page)) {
  1003. $out .= '<form method="post" action="' . $page . '">';
  1004. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  1005. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  1006. }
  1007. $out .= '<select id="' . $htmlname . '" class="flat selectincoterm width75" name="' . $htmlname . '" ' . $htmloption . '>';
  1008. $out .= '<option value="0">&nbsp;</option>';
  1009. $num = $this->db->num_rows($resql);
  1010. $i = 0;
  1011. if ($num) {
  1012. while ($i < $num) {
  1013. $obj = $this->db->fetch_object($resql);
  1014. $incotermArray[$i]['rowid'] = $obj->rowid;
  1015. $incotermArray[$i]['code'] = $obj->code;
  1016. $i++;
  1017. }
  1018. foreach ($incotermArray as $row) {
  1019. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  1020. $out .= '<option value="' . $row['rowid'] . '" selected>';
  1021. } else {
  1022. $out .= '<option value="' . $row['rowid'] . '">';
  1023. }
  1024. if ($row['code']) {
  1025. $out .= $row['code'];
  1026. }
  1027. $out .= '</option>';
  1028. }
  1029. }
  1030. $out .= '</select>';
  1031. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  1032. $out .= ajax_multiautocompleter('location_incoterms', array(), DOL_URL_ROOT . '/core/ajax/locationincoterms.php') . "\n";
  1033. $moreattrib .= ' autocomplete="off"';
  1034. }
  1035. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="' . $location_incoterms . '">' . "\n";
  1036. if (!empty($page)) {
  1037. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="' . $langs->trans("Modify") . '"></form>';
  1038. }
  1039. } else {
  1040. dol_print_error($this->db);
  1041. }
  1042. return $out;
  1043. }
  1044. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1045. /**
  1046. * Return list of types of lines (product or service)
  1047. * Example: 0=product, 1=service, 9=other (for external module)
  1048. *
  1049. * @param string $selected Preselected type
  1050. * @param string $htmlname Name of field in html form
  1051. * @param int $showempty Add an empty field
  1052. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  1053. * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service')
  1054. * @return void
  1055. */
  1056. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  1057. {
  1058. // phpcs:enable
  1059. global $langs;
  1060. // If product & services are enabled or both disabled.
  1061. if ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
  1062. || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
  1063. if (empty($hidetext)) {
  1064. print $langs->trans("Type") . ': ';
  1065. }
  1066. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  1067. if ($showempty) {
  1068. print '<option value="-1"';
  1069. if ($selected == -1) {
  1070. print ' selected';
  1071. }
  1072. print '>&nbsp;</option>';
  1073. }
  1074. print '<option value="0"';
  1075. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1076. print ' selected';
  1077. }
  1078. print '>' . $langs->trans("Product");
  1079. print '<option value="1"';
  1080. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1081. print ' selected';
  1082. }
  1083. print '>' . $langs->trans("Service");
  1084. print '</select>';
  1085. print ajax_combobox('select_' . $htmlname);
  1086. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1087. }
  1088. if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
  1089. print $langs->trans("Service");
  1090. print '<input type="hidden" name="' . $htmlname . '" value="1">';
  1091. }
  1092. if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
  1093. print $langs->trans("Product");
  1094. print '<input type="hidden" name="' . $htmlname . '" value="0">';
  1095. }
  1096. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1097. 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
  1098. }
  1099. }
  1100. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1101. /**
  1102. * Load into cache cache_types_fees, array of types of fees
  1103. *
  1104. * @return int Nb of lines loaded, <0 if KO
  1105. */
  1106. public function load_cache_types_fees()
  1107. {
  1108. // phpcs:enable
  1109. global $langs;
  1110. $num = count($this->cache_types_fees);
  1111. if ($num > 0) {
  1112. return 0; // Cache already loaded
  1113. }
  1114. dol_syslog(__METHOD__, LOG_DEBUG);
  1115. $langs->load("trips");
  1116. $sql = "SELECT c.code, c.label";
  1117. $sql .= " FROM " . $this->db->prefix() . "c_type_fees as c";
  1118. $sql .= " WHERE active > 0";
  1119. $resql = $this->db->query($sql);
  1120. if ($resql) {
  1121. $num = $this->db->num_rows($resql);
  1122. $i = 0;
  1123. while ($i < $num) {
  1124. $obj = $this->db->fetch_object($resql);
  1125. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1126. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1127. $this->cache_types_fees[$obj->code] = $label;
  1128. $i++;
  1129. }
  1130. asort($this->cache_types_fees);
  1131. return $num;
  1132. } else {
  1133. dol_print_error($this->db);
  1134. return -1;
  1135. }
  1136. }
  1137. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1138. /**
  1139. * Return list of types of notes
  1140. *
  1141. * @param string $selected Preselected type
  1142. * @param string $htmlname Name of field in form
  1143. * @param int $showempty Add an empty field
  1144. * @return void
  1145. */
  1146. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1147. {
  1148. // phpcs:enable
  1149. global $user, $langs;
  1150. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  1151. $this->load_cache_types_fees();
  1152. print '<select id="select_' . $htmlname . '" class="flat" name="' . $htmlname . '">';
  1153. if ($showempty) {
  1154. print '<option value="-1"';
  1155. if ($selected == -1) {
  1156. print ' selected';
  1157. }
  1158. print '>&nbsp;</option>';
  1159. }
  1160. foreach ($this->cache_types_fees as $key => $value) {
  1161. print '<option value="' . $key . '"';
  1162. if ($key == $selected) {
  1163. print ' selected';
  1164. }
  1165. print '>';
  1166. print $value;
  1167. print '</option>';
  1168. }
  1169. print '</select>';
  1170. if ($user->admin) {
  1171. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1172. }
  1173. }
  1174. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1175. /**
  1176. * Output html form to select a third party
  1177. *
  1178. * @param string $selected Preselected type
  1179. * @param string $htmlname Name of field in form
  1180. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>()] are allowed here (example: 's.rowid <> x', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  1181. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1182. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1183. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1184. * @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')))
  1185. * @param int $limit Maximum number of elements
  1186. * @param string $morecss Add more css styles to the SELECT component
  1187. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1188. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1189. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1190. * @param array $ajaxoptions Options for ajax_autocompleter
  1191. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1192. * @param array $excludeids Exclude IDs from the select combo
  1193. * @param int $showcode Show code
  1194. * @return string HTML string with select box for thirdparty.
  1195. */
  1196. public function select_company($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $limit = 0, $morecss = 'minwidth100', $moreparam = '', $selected_input_value = '', $hidelabel = 1, $ajaxoptions = array(), $multiple = false, $excludeids = array(), $showcode = 0)
  1197. {
  1198. // phpcs:enable
  1199. global $conf, $user, $langs;
  1200. $out = '';
  1201. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT') && !$forcecombo) {
  1202. if (is_null($ajaxoptions)) {
  1203. $ajaxoptions = array();
  1204. }
  1205. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1206. // No immediate load of all database
  1207. $placeholder = '';
  1208. if ($selected && empty($selected_input_value)) {
  1209. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  1210. $societetmp = new Societe($this->db);
  1211. $societetmp->fetch($selected);
  1212. $selected_input_value = $societetmp->name;
  1213. unset($societetmp);
  1214. }
  1215. // mode 1
  1216. $urloption = 'htmlname=' . urlencode(str_replace('.', '_', $htmlname)) . '&outjson=1&filter=' . urlencode($filter) . (empty($excludeids) ? '' : '&excludeids=' . join(',', $excludeids)) . ($showtype ? '&showtype=' . urlencode($showtype) : '') . ($showcode ? '&showcode=' . urlencode($showcode) : '');
  1217. $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
  1218. if (empty($hidelabel)) {
  1219. print $langs->trans("RefOrLabel") . ' : ';
  1220. } elseif ($hidelabel > 1) {
  1221. $placeholder = $langs->trans("RefOrLabel");
  1222. if ($hidelabel == 2) {
  1223. $out .= img_picto($langs->trans("Search"), 'search');
  1224. }
  1225. }
  1226. $out .= '<input type="text" class="' . $morecss . '" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '') . ' ' . (getDolGlobalString('THIRDPARTY_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  1227. if ($hidelabel == 3) {
  1228. $out .= img_picto($langs->trans("Search"), 'search');
  1229. }
  1230. $out .= ajax_event($htmlname, $events);
  1231. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1232. } else {
  1233. // Immediate load of all database
  1234. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
  1235. }
  1236. return $out;
  1237. }
  1238. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1239. /**
  1240. * Output html form to select a third party.
  1241. * 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.
  1242. *
  1243. * @param string $selected Preselected type
  1244. * @param string $htmlname Name of field in form
  1245. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>] are allowed here, example: 's.rowid <> x'
  1246. * If you need parenthesis, use the Universal Filter Syntax, example: '(s.client:in:1,3)'
  1247. * Do not use a filter coming from input of users.
  1248. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1249. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1250. * @param int $forcecombo Force to use standard HTML select component without beautification
  1251. * @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')))
  1252. * @param string $filterkey Filter on key value
  1253. * @param int $outputmode 0=HTML select string, 1=Array
  1254. * @param int $limit Limit number of answers
  1255. * @param string $morecss Add more css styles to the SELECT component
  1256. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1257. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1258. * @param array $excludeids Exclude IDs from the select combo
  1259. * @param int $showcode Show code in list
  1260. * @return array|string HTML string with
  1261. */
  1262. public function select_thirdparty_list($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $filterkey = '', $outputmode = 0, $limit = 0, $morecss = 'minwidth100', $moreparam = '', $multiple = false, $excludeids = array(), $showcode = 0)
  1263. {
  1264. // phpcs:enable
  1265. global $conf, $user, $langs;
  1266. global $hookmanager;
  1267. $out = '';
  1268. $num = 0;
  1269. $outarray = array();
  1270. if ($selected === '') {
  1271. $selected = array();
  1272. } elseif (!is_array($selected)) {
  1273. $selected = array($selected);
  1274. }
  1275. // Clean $filter that may contains sql conditions so sql code
  1276. if (function_exists('testSqlAndScriptInject')) {
  1277. if (testSqlAndScriptInject($filter, 3) > 0) {
  1278. $filter = '';
  1279. return 'SQLInjectionTryDetected';
  1280. }
  1281. }
  1282. if ($filter != '') { // If a filter was provided
  1283. if (preg_match('/[\(\)]/', $filter)) {
  1284. // If there is one parenthesis inside the criteria, we assume it is an Universal Filter Syntax.
  1285. $errormsg = '';
  1286. $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
  1287. // Redo clean $filter that may contains sql conditions so sql code
  1288. if (function_exists('testSqlAndScriptInject')) {
  1289. if (testSqlAndScriptInject($filter, 3) > 0) {
  1290. $filter = '';
  1291. return 'SQLInjectionTryDetected';
  1292. }
  1293. }
  1294. } else {
  1295. // If not, we do nothing. We already know that there is no parenthesis
  1296. // TODO Disallow this case in a future.
  1297. dol_syslog("Warning, select_thirdparty_list was called with a filter criteria not using the Universal Search Syntax.", LOG_WARNING);
  1298. }
  1299. }
  1300. // We search companies
  1301. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1302. if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
  1303. $sql .= ", s.address, s.zip, s.town";
  1304. $sql .= ", dictp.code as country_code";
  1305. }
  1306. $sql .= " FROM " . $this->db->prefix() . "societe as s";
  1307. if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
  1308. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_country as dictp ON dictp.rowid = s.fk_pays";
  1309. }
  1310. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  1311. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  1312. }
  1313. $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")";
  1314. if (!empty($user->socid)) {
  1315. $sql .= " AND s.rowid = " . ((int) $user->socid);
  1316. }
  1317. if ($filter) {
  1318. // $filter is safe because, if it contains '(' or ')', it has been sanitized by testSqlAndScriptInject() and forgeSQLFromUniversalSearchCriteria()
  1319. // if not, by testSqlAndScriptInject() only.
  1320. $sql .= " AND (" . $filter . ")";
  1321. }
  1322. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  1323. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  1324. }
  1325. if (getDolGlobalString('COMPANY_HIDE_INACTIVE_IN_COMBOBOX')) {
  1326. $sql .= " AND s.status <> 0";
  1327. }
  1328. if (!empty($excludeids)) {
  1329. $sql .= " AND s.rowid NOT IN (" . $this->db->sanitize(join(',', $excludeids)) . ")";
  1330. }
  1331. // Add where from hooks
  1332. $parameters = array();
  1333. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1334. $sql .= $hookmanager->resPrint;
  1335. // Add criteria
  1336. if ($filterkey && $filterkey != '') {
  1337. $sql .= " AND (";
  1338. $prefix = !getDolGlobalString('COMPANY_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1339. // For natural search
  1340. $scrit = explode(' ', $filterkey);
  1341. $i = 0;
  1342. if (count($scrit) > 1) {
  1343. $sql .= "(";
  1344. }
  1345. foreach ($scrit as $crit) {
  1346. if ($i > 0) {
  1347. $sql .= " AND ";
  1348. }
  1349. $sql .= "(s.nom LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  1350. $i++;
  1351. }
  1352. if (count($scrit) > 1) {
  1353. $sql .= ")";
  1354. }
  1355. if (isModEnabled('barcode')) {
  1356. $sql .= " OR s.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1357. }
  1358. $sql .= " OR s.code_client LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.code_fournisseur LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1359. $sql .= " OR s.name_alias LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.tva_intra LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1360. $sql .= ")";
  1361. }
  1362. $sql .= $this->db->order("nom", "ASC");
  1363. $sql .= $this->db->plimit($limit, 0);
  1364. // Build output string
  1365. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1366. $resql = $this->db->query($sql);
  1367. if ($resql) {
  1368. if (!$forcecombo) {
  1369. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1370. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1371. }
  1372. // Construct $out and $outarray
  1373. $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($moreparam ? ' ' . $moreparam : '') . ' name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . '>' . "\n";
  1374. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1375. if (getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT')) {
  1376. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1377. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1378. if ($showempty && !is_numeric($showempty)) {
  1379. $textifempty = $langs->trans($showempty);
  1380. } else {
  1381. $textifempty .= $langs->trans("All");
  1382. }
  1383. }
  1384. if ($showempty) {
  1385. $out .= '<option value="-1" data-html="' . dol_escape_htmltag('<span class="opacitymedium">' . ($textifempty ? $textifempty : '&nbsp;') . '</span>') . '">' . $textifempty . '</option>' . "\n";
  1386. }
  1387. $companytemp = new Societe($this->db);
  1388. $num = $this->db->num_rows($resql);
  1389. $i = 0;
  1390. if ($num) {
  1391. while ($i < $num) {
  1392. $obj = $this->db->fetch_object($resql);
  1393. $label = '';
  1394. if ($showcode || getDolGlobalString('SOCIETE_ADD_REF_IN_LIST')) {
  1395. if (($obj->client) && (!empty($obj->code_client))) {
  1396. $label = $obj->code_client . ' - ';
  1397. }
  1398. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1399. $label .= $obj->code_fournisseur . ' - ';
  1400. }
  1401. $label .= ' ' . $obj->name;
  1402. } else {
  1403. $label = $obj->name;
  1404. }
  1405. if (!empty($obj->name_alias)) {
  1406. $label .= ' (' . $obj->name_alias . ')';
  1407. }
  1408. if (getDolGlobalString('SOCIETE_SHOW_VAT_IN_LIST') && !empty($obj->tva_intra)) {
  1409. $label .= ' - '.$obj->tva_intra;
  1410. }
  1411. $labelhtml = $label;
  1412. if ($showtype) {
  1413. $companytemp->id = $obj->rowid;
  1414. $companytemp->client = $obj->client;
  1415. $companytemp->fournisseur = $obj->fournisseur;
  1416. $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
  1417. if ($tmptype) {
  1418. $labelhtml .= ' ' . $tmptype;
  1419. }
  1420. if ($obj->client || $obj->fournisseur) {
  1421. $label .= ' (';
  1422. }
  1423. if ($obj->client == 1 || $obj->client == 3) {
  1424. $label .= $langs->trans("Customer");
  1425. }
  1426. if ($obj->client == 2 || $obj->client == 3) {
  1427. $label .= ($obj->client == 3 ? ', ' : '') . $langs->trans("Prospect");
  1428. }
  1429. if ($obj->fournisseur) {
  1430. $label .= ($obj->client ? ', ' : '') . $langs->trans("Supplier");
  1431. }
  1432. if ($obj->client || $obj->fournisseur) {
  1433. $label .= ')';
  1434. }
  1435. }
  1436. if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
  1437. $s = ($obj->address ? ' - ' . $obj->address : '') . ($obj->zip ? ' - ' . $obj->zip : '') . ($obj->town ? ' ' . $obj->town : '');
  1438. if (!empty($obj->country_code)) {
  1439. $s .= ', ' . $langs->trans('Country' . $obj->country_code);
  1440. }
  1441. $label .= $s;
  1442. $labelhtml .= $s;
  1443. }
  1444. if (empty($outputmode)) {
  1445. if (in_array($obj->rowid, $selected)) {
  1446. $out .= '<option value="' . $obj->rowid . '" selected data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
  1447. } else {
  1448. $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
  1449. }
  1450. } else {
  1451. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label, 'labelhtml' => $labelhtml));
  1452. }
  1453. $i++;
  1454. if (($i % 10) == 0) {
  1455. $out .= "\n";
  1456. }
  1457. }
  1458. }
  1459. $out .= '</select>' . "\n";
  1460. } else {
  1461. dol_print_error($this->db);
  1462. }
  1463. $this->result = array('nbofthirdparties' => $num);
  1464. if ($outputmode) {
  1465. return $outarray;
  1466. }
  1467. return $out;
  1468. }
  1469. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1470. /**
  1471. * Return HTML combo list of absolute discounts
  1472. *
  1473. * @param string $selected Id remise fixe pre-selectionnee
  1474. * @param string $htmlname Nom champ formulaire
  1475. * @param string $filter Criteres optionnels de filtre
  1476. * @param int $socid Id of thirdparty
  1477. * @param int $maxvalue Max value for lines that can be selected
  1478. * @return int Return number of qualifed lines in list
  1479. */
  1480. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1481. {
  1482. // phpcs:enable
  1483. global $langs, $conf;
  1484. // On recherche les remises
  1485. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1486. $sql .= " re.description, re.fk_facture_source";
  1487. $sql .= " FROM " . $this->db->prefix() . "societe_remise_except as re";
  1488. $sql .= " WHERE re.fk_soc = " . (int) $socid;
  1489. $sql .= " AND re.entity = " . $conf->entity;
  1490. if ($filter) {
  1491. $sql .= " AND " . $filter;
  1492. }
  1493. $sql .= " ORDER BY re.description ASC";
  1494. dol_syslog(get_class($this) . "::select_remises", LOG_DEBUG);
  1495. $resql = $this->db->query($sql);
  1496. if ($resql) {
  1497. print '<select id="select_' . $htmlname . '" class="flat maxwidthonsmartphone" name="' . $htmlname . '">';
  1498. $num = $this->db->num_rows($resql);
  1499. $qualifiedlines = $num;
  1500. $i = 0;
  1501. if ($num) {
  1502. print '<option value="0">&nbsp;</option>';
  1503. while ($i < $num) {
  1504. $obj = $this->db->fetch_object($resql);
  1505. $desc = dol_trunc($obj->description, 40);
  1506. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1507. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1508. }
  1509. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1510. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1511. }
  1512. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1513. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1514. }
  1515. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1516. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1517. }
  1518. $selectstring = '';
  1519. if ($selected > 0 && $selected == $obj->rowid) {
  1520. $selectstring = ' selected';
  1521. }
  1522. $disabled = '';
  1523. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1524. $qualifiedlines--;
  1525. $disabled = ' disabled';
  1526. }
  1527. if (getDolGlobalString('MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST') && !empty($obj->fk_facture_source)) {
  1528. $tmpfac = new Facture($this->db);
  1529. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1530. $desc = $desc . ' - ' . $tmpfac->ref;
  1531. }
  1532. }
  1533. print '<option value="' . $obj->rowid . '"' . $selectstring . $disabled . '>' . $desc . ' (' . price($obj->amount_ht) . ' ' . $langs->trans("HT") . ' - ' . price($obj->amount_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
  1534. $i++;
  1535. }
  1536. }
  1537. print '</select>';
  1538. print ajax_combobox('select_' . $htmlname);
  1539. return $qualifiedlines;
  1540. } else {
  1541. dol_print_error($this->db);
  1542. return -1;
  1543. }
  1544. }
  1545. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1546. /**
  1547. * Return list of all contacts (for a third party or all)
  1548. *
  1549. * @param int $socid Id ot third party or 0 for all
  1550. * @param string $selected Id contact pre-selectionne
  1551. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1552. * @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
  1553. * @param string $exclude List of contacts id to exclude
  1554. * @param string $limitto Disable answers that are not id in this array list
  1555. * @param integer $showfunction Add function into label
  1556. * @param string $morecss Add more class to class style
  1557. * @param integer $showsoc Add company into label
  1558. * @param int $forcecombo Force to use combo box
  1559. * @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')))
  1560. * @param bool $options_only Return options only (for ajax treatment)
  1561. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1562. * @param string $htmlid Html id to use instead of htmlname
  1563. * @return int Return integer <0 if KO, Nb of contact in list if OK
  1564. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1565. */
  1566. public function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
  1567. {
  1568. // phpcs:enable
  1569. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1570. return $this->num;
  1571. }
  1572. /**
  1573. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1574. * This also set the number of contacts found into $this->num
  1575. *
  1576. * @since 9.0 Add afterSelectContactOptions hook
  1577. *
  1578. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1579. * @param array|int $selected Array of ID of pre-selected contact id
  1580. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1581. * @param int|string $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
  1582. * @param string $exclude List of contacts id to exclude
  1583. * @param string $limitto Disable answers that are not id in this array list
  1584. * @param integer $showfunction Add function into label
  1585. * @param string $morecss Add more class to class style
  1586. * @param bool $options_only Return options only (for ajax treatment)
  1587. * @param integer $showsoc Add company into label
  1588. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1589. * @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')))
  1590. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1591. * @param string $htmlid Html id to use instead of htmlname
  1592. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1593. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1594. * @return int|string Return integer <0 if KO, HTML with select string if OK.
  1595. */
  1596. public function selectcontacts($socid, $selected = array(), $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0)
  1597. {
  1598. global $conf, $langs, $hookmanager, $action;
  1599. $langs->load('companies');
  1600. if (empty($htmlid)) {
  1601. $htmlid = $htmlname;
  1602. }
  1603. $num = 0;
  1604. if ($selected === '') {
  1605. $selected = array();
  1606. } elseif (!is_array($selected)) {
  1607. $selected = array($selected);
  1608. }
  1609. $out = '';
  1610. if (!is_object($hookmanager)) {
  1611. include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  1612. $hookmanager = new HookManager($this->db);
  1613. }
  1614. // We search third parties
  1615. $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste, sp.email, sp.phone, sp.phone_perso, sp.phone_mobile, sp.town AS contact_town";
  1616. if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
  1617. $sql .= ", s.nom as company, s.town AS company_town";
  1618. }
  1619. $sql .= " FROM " . $this->db->prefix() . "socpeople as sp";
  1620. if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
  1621. $sql .= " LEFT OUTER JOIN " . $this->db->prefix() . "societe as s ON s.rowid=sp.fk_soc";
  1622. }
  1623. $sql .= " WHERE sp.entity IN (" . getEntity('contact') . ")";
  1624. if ($socid > 0 || $socid == -1) {
  1625. $sql .= " AND sp.fk_soc = " . ((int) $socid);
  1626. }
  1627. if (getDolGlobalString('CONTACT_HIDE_INACTIVE_IN_COMBOBOX')) {
  1628. $sql .= " AND sp.statut <> 0";
  1629. }
  1630. // Add where from hooks
  1631. $parameters = array();
  1632. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1633. $sql .= $hookmanager->resPrint;
  1634. $sql .= " ORDER BY sp.lastname ASC";
  1635. dol_syslog(get_class($this) . "::selectcontacts", LOG_DEBUG);
  1636. $resql = $this->db->query($sql);
  1637. if ($resql) {
  1638. $num = $this->db->num_rows($resql);
  1639. if ($htmlname != 'none' && !$options_only) {
  1640. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlid . '" name="' . $htmlname . (($num || empty($disableifempty)) ? '' : ' disabled') . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . (!empty($moreparam) ? $moreparam : '') . '>';
  1641. }
  1642. if ($showempty && !is_numeric($showempty)) {
  1643. $textforempty = $showempty;
  1644. $out .= '<option class="optiongrey" value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>' . $textforempty . '</option>';
  1645. } else {
  1646. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
  1647. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>&nbsp;</option>';
  1648. }
  1649. if ($showempty == 2) {
  1650. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>-- ' . $langs->trans("Internal") . ' --</option>';
  1651. }
  1652. }
  1653. $i = 0;
  1654. if ($num) {
  1655. include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  1656. $contactstatic = new Contact($this->db);
  1657. while ($i < $num) {
  1658. $obj = $this->db->fetch_object($resql);
  1659. // Set email (or phones) and town extended infos
  1660. $extendedInfos = '';
  1661. if (getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
  1662. $extendedInfos = array();
  1663. $email = trim($obj->email);
  1664. if (!empty($email)) {
  1665. $extendedInfos[] = $email;
  1666. } else {
  1667. $phone = trim($obj->phone);
  1668. $phone_perso = trim($obj->phone_perso);
  1669. $phone_mobile = trim($obj->phone_mobile);
  1670. if (!empty($phone)) {
  1671. $extendedInfos[] = $phone;
  1672. }
  1673. if (!empty($phone_perso)) {
  1674. $extendedInfos[] = $phone_perso;
  1675. }
  1676. if (!empty($phone_mobile)) {
  1677. $extendedInfos[] = $phone_mobile;
  1678. }
  1679. }
  1680. $contact_town = trim($obj->contact_town);
  1681. $company_town = trim($obj->company_town);
  1682. if (!empty($contact_town)) {
  1683. $extendedInfos[] = $contact_town;
  1684. } elseif (!empty($company_town)) {
  1685. $extendedInfos[] = $company_town;
  1686. }
  1687. $extendedInfos = implode(' - ', $extendedInfos);
  1688. if (!empty($extendedInfos)) {
  1689. $extendedInfos = ' - ' . $extendedInfos;
  1690. }
  1691. }
  1692. $contactstatic->id = $obj->rowid;
  1693. $contactstatic->lastname = $obj->lastname;
  1694. $contactstatic->firstname = $obj->firstname;
  1695. if ($obj->statut == 1) {
  1696. if ($htmlname != 'none') {
  1697. $disabled = 0;
  1698. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1699. $disabled = 1;
  1700. }
  1701. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1702. $disabled = 1;
  1703. }
  1704. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1705. $out .= '<option value="' . $obj->rowid . '"';
  1706. if ($disabled) {
  1707. $out .= ' disabled';
  1708. }
  1709. $out .= ' selected>';
  1710. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1711. if ($showfunction && $obj->poste) {
  1712. $out .= ' (' . $obj->poste . ')';
  1713. }
  1714. if (($showsoc > 0) && $obj->company) {
  1715. $out .= ' - (' . $obj->company . ')';
  1716. }
  1717. $out .= '</option>';
  1718. } else {
  1719. $out .= '<option value="' . $obj->rowid . '"';
  1720. if ($disabled) {
  1721. $out .= ' disabled';
  1722. }
  1723. $out .= '>';
  1724. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1725. if ($showfunction && $obj->poste) {
  1726. $out .= ' (' . $obj->poste . ')';
  1727. }
  1728. if (($showsoc > 0) && $obj->company) {
  1729. $out .= ' - (' . $obj->company . ')';
  1730. }
  1731. $out .= '</option>';
  1732. }
  1733. } else {
  1734. if (in_array($obj->rowid, $selected)) {
  1735. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1736. if ($showfunction && $obj->poste) {
  1737. $out .= ' (' . $obj->poste . ')';
  1738. }
  1739. if (($showsoc > 0) && $obj->company) {
  1740. $out .= ' - (' . $obj->company . ')';
  1741. }
  1742. }
  1743. }
  1744. }
  1745. $i++;
  1746. }
  1747. } else {
  1748. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1749. $out .= '<option class="disabled" value="-1"' . (($showempty == 2 || $multiple) ? '' : ' selected') . ' disabled="disabled">';
  1750. $out .= $labeltoshow;
  1751. $out .= '</option>';
  1752. }
  1753. $parameters = array(
  1754. 'socid' => $socid,
  1755. 'htmlname' => $htmlname,
  1756. 'resql' => $resql,
  1757. 'out' => &$out,
  1758. 'showfunction' => $showfunction,
  1759. 'showsoc' => $showsoc,
  1760. );
  1761. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1762. if ($htmlname != 'none' && !$options_only) {
  1763. $out .= '</select>';
  1764. }
  1765. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1766. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1767. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1768. }
  1769. $this->num = $num;
  1770. return $out;
  1771. } else {
  1772. dol_print_error($this->db);
  1773. return -1;
  1774. }
  1775. }
  1776. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1777. /**
  1778. * Return the HTML select list of users
  1779. *
  1780. * @param string $selected Id user preselected
  1781. * @param string $htmlname Field name in form
  1782. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1783. * @param array $exclude Array list of users id to exclude
  1784. * @param int $disabled If select list must be disabled
  1785. * @param array|string $include Array list of users id to include. User '' for all users or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1786. * @param array|int $enableonly Array list of users id to be enabled. All other must be disabled
  1787. * @param string $force_entity '0' or Ids of environment to force
  1788. * @return void
  1789. * @deprecated Use select_dolusers instead
  1790. * @see select_dolusers()
  1791. */
  1792. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0')
  1793. {
  1794. // phpcs:enable
  1795. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1796. }
  1797. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1798. /**
  1799. * Return select list of users
  1800. *
  1801. * @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)
  1802. * @param string $htmlname Field name in form
  1803. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1804. * @param array|null $exclude Array list of users id to exclude
  1805. * @param int $disabled If select list must be disabled
  1806. * @param array|string $include Array list of users id to include. User '' for all users or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1807. * @param array|string $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1808. * @param string $force_entity '0' or list of Ids of environment to force separated by a coma
  1809. * @param int $maxlength Maximum length of string into list (0=no limit)
  1810. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1811. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1812. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1813. * @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.
  1814. * @param string $morecss More css
  1815. * @param int $notdisabled Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1816. * @param int $outputmode 0=HTML select string, 1=Array
  1817. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1818. * @param int $forcecombo Force the component to be a simple combo box without ajax
  1819. * @return array|string HTML select string
  1820. * @see select_dolgroups()
  1821. */
  1822. public function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $notdisabled = 0, $outputmode = 0, $multiple = false, $forcecombo = 0)
  1823. {
  1824. // phpcs:enable
  1825. global $conf, $user, $langs, $hookmanager;
  1826. global $action;
  1827. // If no preselected user defined, we take current user
  1828. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && !getDolGlobalString('SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE')) {
  1829. $selected = $user->id;
  1830. }
  1831. if ($selected === '') {
  1832. $selected = array();
  1833. } elseif (!is_array($selected)) {
  1834. $selected = array($selected);
  1835. }
  1836. $excludeUsers = null;
  1837. $includeUsers = null;
  1838. // Exclude some users
  1839. if (is_array($exclude)) {
  1840. $excludeUsers = implode(",", $exclude);
  1841. }
  1842. // Include some uses
  1843. if (is_array($include)) {
  1844. $includeUsers = implode(",", $include);
  1845. } elseif ($include == 'hierarchy') {
  1846. // Build list includeUsers to have only hierarchy
  1847. $includeUsers = implode(",", $user->getAllChildIds(0));
  1848. } elseif ($include == 'hierarchyme') {
  1849. // Build list includeUsers to have only hierarchy and current user
  1850. $includeUsers = implode(",", $user->getAllChildIds(1));
  1851. }
  1852. $out = '';
  1853. $outarray = array();
  1854. $outarray2 = array();
  1855. // Forge request to select users
  1856. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1857. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1858. $sql .= ", e.label";
  1859. }
  1860. $sql .= " FROM " . $this->db->prefix() . "user as u";
  1861. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1862. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid = u.entity";
  1863. if (!empty($force_entity)) {
  1864. $sql .= " WHERE u.entity IN (0, " . $this->db->sanitize($force_entity) . ")";
  1865. } else {
  1866. $sql .= " WHERE u.entity IS NOT NULL";
  1867. }
  1868. } else {
  1869. if (isModEnabled('multicompany') && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
  1870. $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
  1871. } else {
  1872. $sql .= " WHERE u.entity IN (" . getEntity('user') . ")";
  1873. }
  1874. }
  1875. if (!empty($user->socid)) {
  1876. $sql .= " AND u.fk_soc = " . ((int) $user->socid);
  1877. }
  1878. if (is_array($exclude) && $excludeUsers) {
  1879. $sql .= " AND u.rowid NOT IN (" . $this->db->sanitize($excludeUsers) . ")";
  1880. }
  1881. if ($includeUsers) {
  1882. $sql .= " AND u.rowid IN (" . $this->db->sanitize($includeUsers) . ")";
  1883. }
  1884. if (getDolGlobalString('USER_HIDE_INACTIVE_IN_COMBOBOX') || $notdisabled) {
  1885. $sql .= " AND u.statut <> 0";
  1886. }
  1887. if (!empty($morefilter)) {
  1888. $sql .= " " . $morefilter;
  1889. }
  1890. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1891. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1892. if (!empty($reshook)) {
  1893. $sql .= $hookmanager->resPrint;
  1894. }
  1895. if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1896. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1897. } else {
  1898. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1899. }
  1900. dol_syslog(get_class($this) . "::select_dolusers", LOG_DEBUG);
  1901. $resql = $this->db->query($sql);
  1902. if ($resql) {
  1903. $num = $this->db->num_rows($resql);
  1904. $i = 0;
  1905. if ($num) {
  1906. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1907. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : ' minwidth200') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  1908. if ($show_empty && !$multiple) {
  1909. $textforempty = ' ';
  1910. if (!empty($conf->use_javascript_ajax)) {
  1911. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1912. }
  1913. if (!is_numeric($show_empty)) {
  1914. $textforempty = $show_empty;
  1915. }
  1916. $out .= '<option class="optiongrey" value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ((empty($selected) || in_array(-1, $selected)) ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  1917. }
  1918. if ($show_every) {
  1919. $out .= '<option value="-2"' . ((in_array(-2, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("Everybody") . ' --</option>' . "\n";
  1920. }
  1921. $userstatic = new User($this->db);
  1922. while ($i < $num) {
  1923. $obj = $this->db->fetch_object($resql);
  1924. $userstatic->id = $obj->rowid;
  1925. $userstatic->lastname = $obj->lastname;
  1926. $userstatic->firstname = $obj->firstname;
  1927. $userstatic->photo = $obj->photo;
  1928. $userstatic->statut = $obj->status;
  1929. $userstatic->entity = $obj->entity;
  1930. $userstatic->admin = $obj->admin;
  1931. $disableline = '';
  1932. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1933. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1934. }
  1935. $labeltoshow = '';
  1936. $labeltoshowhtml = '';
  1937. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1938. $fullNameMode = 0;
  1939. if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) {
  1940. $fullNameMode = 1; //Firstname+lastname
  1941. }
  1942. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1943. $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1944. if (empty($obj->firstname) && empty($obj->lastname)) {
  1945. $labeltoshow .= $obj->login;
  1946. $labeltoshowhtml .= $obj->login;
  1947. }
  1948. // Complete name with a more info string like: ' (info1 - info2 - ...)'
  1949. $moreinfo = '';
  1950. $moreinfohtml = '';
  1951. if (getDolGlobalString('MAIN_SHOW_LOGIN')) {
  1952. $moreinfo .= ($moreinfo ? ' - ' : ' (');
  1953. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
  1954. $moreinfo .= $obj->login;
  1955. $moreinfohtml .= $obj->login;
  1956. }
  1957. if ($showstatus >= 0) {
  1958. if ($obj->status == 1 && $showstatus == 1) {
  1959. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Enabled');
  1960. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Enabled');
  1961. }
  1962. if ($obj->status == 0 && $showstatus == 1) {
  1963. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Disabled');
  1964. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Disabled');
  1965. }
  1966. }
  1967. if (isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1 && !empty($user->admin) && empty($user->entity)) {
  1968. if (empty($obj->entity)) {
  1969. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans("AllEntities");
  1970. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans("AllEntities");
  1971. } else {
  1972. if ($obj->entity != $conf->entity) {
  1973. $moreinfo .= ($moreinfo ? ' - ' : ' (') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1974. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1975. }
  1976. }
  1977. }
  1978. $moreinfo .= (!empty($moreinfo) ? ')' : '');
  1979. $moreinfohtml .= (!empty($moreinfohtml) ? ')</span>' : '');
  1980. if (!empty($disableline) && $disableline != '1') {
  1981. // Add text from $enableonlytext parameter
  1982. $moreinfo .= ' - ' . $disableline;
  1983. $moreinfohtml .= ' - ' . $disableline;
  1984. }
  1985. $labeltoshow .= $moreinfo;
  1986. $labeltoshowhtml .= $moreinfohtml;
  1987. $out .= '<option value="' . $obj->rowid . '"';
  1988. if (!empty($disableline)) {
  1989. $out .= ' disabled';
  1990. }
  1991. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1992. $out .= ' selected';
  1993. }
  1994. $out .= ' data-html="';
  1995. $outhtml = $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1) . ' ';
  1996. if ($showstatus >= 0 && $obj->status == 0) {
  1997. $outhtml .= '<strike class="opacitymediumxxx">';
  1998. }
  1999. $outhtml .= $labeltoshowhtml;
  2000. if ($showstatus >= 0 && $obj->status == 0) {
  2001. $outhtml .= '</strike>';
  2002. }
  2003. $out .= dol_escape_htmltag($outhtml);
  2004. $out .= '">';
  2005. $out .= $labeltoshow;
  2006. $out .= '</option>';
  2007. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength) . $moreinfo;
  2008. $outarray2[$userstatic->id] = array(
  2009. 'id'=>$userstatic->id,
  2010. 'label'=>$labeltoshow,
  2011. 'labelhtml'=>$labeltoshowhtml,
  2012. 'color'=>'',
  2013. 'picto'=>''
  2014. );
  2015. $i++;
  2016. }
  2017. } else {
  2018. $out .= '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '" disabled>';
  2019. $out .= '<option value="">' . $langs->trans("None") . '</option>';
  2020. }
  2021. $out .= '</select>';
  2022. if ($num && !$forcecombo) {
  2023. // Enhance with select2
  2024. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2025. $out .= ajax_combobox($htmlname);
  2026. }
  2027. } else {
  2028. dol_print_error($this->db);
  2029. }
  2030. if ($outputmode == 2) {
  2031. return $outarray2;
  2032. } elseif ($outputmode) {
  2033. return $outarray;
  2034. }
  2035. return $out;
  2036. }
  2037. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2038. /**
  2039. * Return select list of users. Selected users are stored into session.
  2040. * List of users are provided into $_SESSION['assignedtouser'].
  2041. *
  2042. * @param string $action Value for $action
  2043. * @param string $htmlname Field name in form
  2044. * @param int $show_empty 0=list without the empty value, 1=add empty value
  2045. * @param array $exclude Array list of users id to exclude
  2046. * @param int $disabled If select list must be disabled
  2047. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  2048. * @param array|int $enableonly Array list of users id to be enabled. All other must be disabled
  2049. * @param string $force_entity '0' or Ids of environment to force
  2050. * @param int $maxlength Maximum length of string into list (0=no limit)
  2051. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  2052. * @param string $morefilter Add more filters into sql request
  2053. * @param int $showproperties Show properties of each attendees
  2054. * @param array $listofuserid Array with properties of each user
  2055. * @param array $listofcontactid Array with properties of each contact
  2056. * @param array $listofotherid Array with properties of each other contact
  2057. * @return string HTML select string
  2058. * @see select_dolgroups()
  2059. */
  2060. public function select_dolusers_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = array(), $enableonly = array(), $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofuserid = array(), $listofcontactid = array(), $listofotherid = array())
  2061. {
  2062. // phpcs:enable
  2063. global $langs;
  2064. $userstatic = new User($this->db);
  2065. $out = '';
  2066. $assignedtouser = array();
  2067. if (!empty($_SESSION['assignedtouser'])) {
  2068. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  2069. }
  2070. $nbassignetouser = count($assignedtouser);
  2071. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  2072. if ($nbassignetouser) {
  2073. $out .= '<ul class="attendees">';
  2074. }
  2075. $i = 0;
  2076. $ownerid = 0;
  2077. foreach ($assignedtouser as $key => $value) {
  2078. if ($value['id'] == $ownerid) {
  2079. continue;
  2080. }
  2081. $out .= '<li>';
  2082. $userstatic->fetch($value['id']);
  2083. $out .= $userstatic->getNomUrl(-1);
  2084. if ($i == 0) {
  2085. $ownerid = $value['id'];
  2086. $out .= ' (' . $langs->trans("Owner") . ')';
  2087. }
  2088. if ($nbassignetouser > 1 && $action != 'view') {
  2089. $out .= ' <input type="image" style="border: 0px;" src="' . img_picto($langs->trans("Remove"), 'delete', '', 0, 1) . '" value="' . $userstatic->id . '" class="removedassigned reposition" id="removedassigned_' . $userstatic->id . '" name="removedassigned_' . $userstatic->id . '">';
  2090. }
  2091. // Show my availability
  2092. if ($showproperties) {
  2093. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  2094. $out .= '<div class="myavailability inline-block">';
  2095. $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;<span class="opacitymedium">' . $langs->trans("Availability") . ':</span> </span><input id="transparency" class="paddingrightonly" ' . ($action == 'view' ? 'disabled' : '') . ' type="checkbox" name="transparency"' . ($listofuserid[$ownerid]['transparency'] ? ' checked' : '') . '><label for="transparency">' . $langs->trans("Busy") . '</label>';
  2096. $out .= '</div>';
  2097. }
  2098. }
  2099. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2100. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2101. $out .= '</li>';
  2102. $i++;
  2103. }
  2104. if ($nbassignetouser) {
  2105. $out .= '</ul>';
  2106. }
  2107. // Method with no ajax
  2108. if ($action != 'view') {
  2109. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  2110. $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
  2111. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  2112. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  2113. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#' . $action . 'assignedtouser").attr("disabled", false); }';
  2114. $out .= ' else { jQuery("#' . $action . 'assignedtouser").attr("disabled", true); }';
  2115. $out .= '});';
  2116. $out .= '})</script>';
  2117. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2118. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="' . $action . 'assignedtouser" name="' . $action . 'assignedtouser" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
  2119. $out .= '<br>';
  2120. }
  2121. return $out;
  2122. }
  2123. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2124. /**
  2125. * Return select list of resources. Selected resources are stored into session.
  2126. * List of resources are provided into $_SESSION['assignedtoresource'].
  2127. *
  2128. * @param string $action Value for $action
  2129. * @param string $htmlname Field name in form
  2130. * @param int $show_empty 0=list without the empty value, 1=add empty value
  2131. * @param array $exclude Array list of users id to exclude
  2132. * @param int $disabled If select list must be disabled
  2133. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  2134. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  2135. * @param string $force_entity '0' or Ids of environment to force
  2136. * @param int $maxlength Maximum length of string into list (0=no limit)
  2137. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  2138. * @param string $morefilter Add more filters into sql request
  2139. * @param int $showproperties Show properties of each attendees
  2140. * @param array $listofresourceid Array with properties of each resource
  2141. * @return string HTML select string
  2142. */
  2143. public function select_dolresources_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = array(), $enableonly = array(), $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofresourceid = array())
  2144. {
  2145. // phpcs:enable
  2146. global $langs;
  2147. require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php';
  2148. require_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php';
  2149. $formresources = new FormResource($this->db);
  2150. $resourcestatic = new Dolresource($this->db);
  2151. $out = '';
  2152. $assignedtoresource = array();
  2153. if (!empty($_SESSION['assignedtoresource'])) {
  2154. $assignedtoresource = json_decode($_SESSION['assignedtoresource'], true);
  2155. }
  2156. $nbassignetoresource = count($assignedtoresource);
  2157. //if ($nbassignetoresource && $action != 'view') $out .= '<br>';
  2158. if ($nbassignetoresource) {
  2159. $out .= '<ul class="attendees">';
  2160. }
  2161. $i = 0;
  2162. foreach ($assignedtoresource as $key => $value) {
  2163. $out .= '<li>';
  2164. $resourcestatic->fetch($value['id']);
  2165. $out .= $resourcestatic->getNomUrl(-1);
  2166. if ($nbassignetoresource > 1 && $action != 'view') {
  2167. $out .= ' <input type="image" style="border: 0px;" src="' . img_picto($langs->trans("Remove"), 'delete', '', 0, 1) . '" value="' . $resourcestatic->id . '" class="removedassigned reposition" id="removedassignedresource_' . $resourcestatic->id . '" name="removedassignedresource_' . $resourcestatic->id . '">';
  2168. }
  2169. // Show my availability
  2170. if ($showproperties) {
  2171. if (is_array($listofresourceid) && count($listofresourceid)) {
  2172. $out .= '<div class="myavailability inline-block">';
  2173. $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;<span class="opacitymedium">' . $langs->trans("Availability") . ':</span> </span><input id="transparencyresource" class="paddingrightonly" ' . ($action == 'view' ? 'disabled' : '') . ' type="checkbox" name="transparency"' . ($listofresourceid[$value['id']]['transparency'] ? ' checked' : '') . '><label for="transparency">' . $langs->trans("Busy") . '</label>';
  2174. $out .= '</div>';
  2175. }
  2176. }
  2177. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2178. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2179. $out .= '</li>';
  2180. $i++;
  2181. }
  2182. if ($nbassignetoresource) {
  2183. $out .= '</ul>';
  2184. }
  2185. // Method with no ajax
  2186. if ($action != 'view') {
  2187. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassignedresource" value="">';
  2188. $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
  2189. $out .= 'jQuery(".removedassignedresource").click(function() { jQuery(".removedassignedresourcehidden").val(jQuery(this).val()); });';
  2190. $out .= 'jQuery(".assignedtoresource").change(function() { console.log(jQuery(".assignedtoresource option:selected").val());';
  2191. $out .= ' if (jQuery(".assignedtoresource option:selected").val() > 0) { jQuery("#' . $action . 'assignedtoresource").attr("disabled", false); }';
  2192. $out .= ' else { jQuery("#' . $action . 'assignedtoresource").attr("disabled", true); }';
  2193. $out .= '});';
  2194. $out .= '})</script>';
  2195. $events = array();
  2196. $out .= img_picto('', 'resource', 'class="pictofixedwidth"');
  2197. $out .= $formresources->select_resource_list('', $htmlname, '', 1, 1, 0, $events, '', 2, null);
  2198. //$out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2199. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="' . $action . 'assignedtoresource" name="' . $action . 'assignedtoresource" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
  2200. $out .= '<br>';
  2201. }
  2202. return $out;
  2203. }
  2204. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2205. /**
  2206. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2207. *
  2208. * @param int $selected Preselected products
  2209. * @param string $htmlname Name of HTML select field (must be unique in page).
  2210. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2211. * @param int $limit Limit on number of returned lines
  2212. * @param int $price_level Level of price to show
  2213. * @param int $status Sell status: -1=No filter on sell status, 0=Products not on sell, 1=Products on sell
  2214. * @param int $finished 2=all, 1=finished, 0=raw material
  2215. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2216. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2217. * @param array $ajaxoptions Options for ajax_autocompleter
  2218. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2219. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2220. * @param int $forcecombo Force to use combo box
  2221. * @param string $morecss Add more css on select
  2222. * @param int $hidepriceinlabel 1=Hide prices in label
  2223. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2224. * 'warehouseopen' = count products from open warehouses,
  2225. * 'warehouseclosed' = count products from closed warehouses,
  2226. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2227. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2228. * @param string $nooutput No print, return the output into a string
  2229. * @param int $status_purchase Purchase status: -1=No filter on purchase status, 0=Products not on purchase, 1=Products on purchase
  2230. * @return void|string
  2231. */
  2232. public function select_produits($selected = 0, $htmlname = 'productid', $filtertype = '', $limit = 0, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = null, $nooutput = 0, $status_purchase = -1)
  2233. {
  2234. // phpcs:enable
  2235. global $langs, $conf;
  2236. $out = '';
  2237. // check parameters
  2238. $price_level = (!empty($price_level) ? $price_level : 0);
  2239. if (is_null($ajaxoptions)) {
  2240. $ajaxoptions = array();
  2241. }
  2242. if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
  2243. if (isModEnabled("product") && !isModEnabled('service')) {
  2244. $filtertype = '0';
  2245. } elseif (!isModEnabled('product') && isModEnabled("service")) {
  2246. $filtertype = '1';
  2247. }
  2248. }
  2249. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
  2250. $placeholder = '';
  2251. if ($selected && empty($selected_input_value)) {
  2252. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2253. $producttmpselect = new Product($this->db);
  2254. $producttmpselect->fetch($selected);
  2255. $selected_input_value = $producttmpselect->ref;
  2256. unset($producttmpselect);
  2257. }
  2258. // handle case where product or service module is disabled + no filter specified
  2259. if ($filtertype == '') {
  2260. if (!isModEnabled('product')) { // when product module is disabled, show services only
  2261. $filtertype = 1;
  2262. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2263. $filtertype = 0;
  2264. }
  2265. }
  2266. // mode=1 means customers products
  2267. $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=1&status=' . $status . '&status_purchase=' . $status_purchase . '&finished=' . $finished . '&hidepriceinlabel=' . $hidepriceinlabel . '&warehousestatus=' . $warehouseStatus;
  2268. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2269. if (isModEnabled('variants') && is_array($selected_combinations)) {
  2270. // Code to automatically insert with javascript the select of attributes under the select of product
  2271. // when a parent of variant has been selected.
  2272. $out .= '
  2273. <!-- script to auto show attributes select tags if a variant was selected -->
  2274. <script nonce="' . getNonce() . '">
  2275. // auto show attributes fields
  2276. selected = ' . json_encode($selected_combinations) . ';
  2277. combvalues = {};
  2278. jQuery(document).ready(function () {
  2279. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2280. if (jQuery(this).val() == \'free\') {
  2281. jQuery(\'div#attributes_box\').empty();
  2282. }
  2283. });
  2284. jQuery("input#' . $htmlname . '").change(function () {
  2285. if (!jQuery(this).val()) {
  2286. jQuery(\'div#attributes_box\').empty();
  2287. return;
  2288. }
  2289. console.log("A change has started. We get variants fields to inject html select");
  2290. jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
  2291. id: jQuery(this).val()
  2292. }, function (data) {
  2293. jQuery(\'div#attributes_box\').empty();
  2294. jQuery.each(data, function (key, val) {
  2295. combvalues[val.id] = val.values;
  2296. var span = jQuery(document.createElement(\'div\')).css({
  2297. \'display\': \'table-row\'
  2298. });
  2299. span.append(
  2300. jQuery(document.createElement(\'div\')).text(val.label).css({
  2301. \'font-weight\': \'bold\',
  2302. \'display\': \'table-cell\'
  2303. })
  2304. );
  2305. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2306. \'margin-left\': \'15px\',
  2307. \'white-space\': \'pre\'
  2308. }).append(
  2309. jQuery(document.createElement(\'option\')).val(\'\')
  2310. );
  2311. jQuery.each(combvalues[val.id], function (key, val) {
  2312. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2313. if (selected[val.fk_product_attribute] == val.id) {
  2314. tag.attr(\'selected\', \'selected\');
  2315. }
  2316. html.append(tag);
  2317. });
  2318. span.append(html);
  2319. jQuery(\'div#attributes_box\').append(span);
  2320. });
  2321. })
  2322. });
  2323. ' . ($selected ? 'jQuery("input#' . $htmlname . '").change();' : '') . '
  2324. });
  2325. </script>
  2326. ';
  2327. }
  2328. if (empty($hidelabel)) {
  2329. $out .= $langs->trans("RefOrLabel") . ' : ';
  2330. } elseif ($hidelabel > 1) {
  2331. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  2332. if ($hidelabel == 2) {
  2333. $out .= img_picto($langs->trans("Search"), 'search');
  2334. }
  2335. }
  2336. $out .= '<input type="text" class="minwidth100' . ($morecss ? ' ' . $morecss : '') . '" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  2337. if ($hidelabel == 3) {
  2338. $out .= img_picto($langs->trans("Search"), 'search');
  2339. }
  2340. } else {
  2341. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2342. }
  2343. if (empty($nooutput)) {
  2344. print $out;
  2345. } else {
  2346. return $out;
  2347. }
  2348. }
  2349. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2350. /**
  2351. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2352. *
  2353. * @param string $selected Preselected BOM id
  2354. * @param string $htmlname Name of HTML select field (must be unique in page).
  2355. * @param int $limit Limit on number of returned lines
  2356. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2357. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2358. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2359. * @param string $morecss Add more css on select
  2360. * @param string $nooutput No print, return the output into a string
  2361. * @param int $forcecombo Force to use combo box
  2362. * @param array $TProducts Add filter on a defined product
  2363. * @return void|string
  2364. */
  2365. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
  2366. {
  2367. // phpcs:enable
  2368. global $conf, $user, $langs, $db;
  2369. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2370. $error = 0;
  2371. $out = '';
  2372. if (!$forcecombo) {
  2373. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2374. $events = array();
  2375. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2376. }
  2377. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2378. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2379. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'bom_bom as b';
  2380. $sql .= ' WHERE b.entity IN (' . getEntity('bom') . ')';
  2381. if (!empty($status)) {
  2382. $sql .= ' AND status = ' . (int) $status;
  2383. }
  2384. if (!empty($type)) {
  2385. $sql .= ' AND bomtype = ' . (int) $type;
  2386. }
  2387. if (!empty($TProducts)) {
  2388. $sql .= ' AND fk_product IN (' . $this->db->sanitize(implode(',', $TProducts)) . ')';
  2389. }
  2390. if (!empty($limit)) {
  2391. $sql .= ' LIMIT ' . (int) $limit;
  2392. }
  2393. $resql = $db->query($sql);
  2394. if ($resql) {
  2395. if ($showempty) {
  2396. $out .= '<option value="-1"';
  2397. if (empty($selected)) {
  2398. $out .= ' selected';
  2399. }
  2400. $out .= '>&nbsp;</option>';
  2401. }
  2402. while ($obj = $db->fetch_object($resql)) {
  2403. $product = new Product($db);
  2404. $res = $product->fetch($obj->fk_product);
  2405. $out .= '<option value="' . $obj->rowid . '"';
  2406. if ($obj->rowid == $selected) {
  2407. $out .= 'selected';
  2408. }
  2409. $out .= '>' . $obj->ref . ' - ' . $product->label . ' - ' . $obj->label . '</option>';
  2410. }
  2411. } else {
  2412. $error++;
  2413. dol_print_error($db);
  2414. }
  2415. $out .= '</select>';
  2416. if (empty($nooutput)) {
  2417. print $out;
  2418. } else {
  2419. return $out;
  2420. }
  2421. }
  2422. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2423. /**
  2424. * Return list of products for a customer.
  2425. * Called by select_produits.
  2426. *
  2427. * @param int $selected Preselected product
  2428. * @param string $htmlname Name of select html
  2429. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2430. * @param int $limit Limit on number of returned lines
  2431. * @param int $price_level Level of price to show
  2432. * @param string $filterkey Filter on product
  2433. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2434. * @param int $finished Filter on finished field: 2=No filter
  2435. * @param int $outputmode 0=HTML select string, 1=Array
  2436. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2437. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2438. * @param int $forcecombo Force to use combo box
  2439. * @param string $morecss Add more css on select
  2440. * @param int $hidepriceinlabel 1=Hide prices in label
  2441. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2442. * 'warehouseopen' = count products from open warehouses,
  2443. * 'warehouseclosed' = count products from closed warehouses,
  2444. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2445. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2446. * @return array|string Array of keys for json
  2447. */
  2448. public function select_produits_list($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $status_purchase = -1)
  2449. {
  2450. // phpcs:enable
  2451. global $langs, $conf;
  2452. global $hookmanager;
  2453. $out = '';
  2454. $outarray = array();
  2455. // Units
  2456. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2457. $langs->load('other');
  2458. }
  2459. $warehouseStatusArray = array();
  2460. if (!empty($warehouseStatus)) {
  2461. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  2462. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2463. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2464. }
  2465. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2466. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2467. }
  2468. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2469. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2470. }
  2471. }
  2472. $selectFields = " p.rowid, p.ref, p.label, p.description, p.barcode, p.fk_country, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.default_vat_code, p.duration, p.fk_price_expression";
  2473. if (count($warehouseStatusArray)) {
  2474. $selectFieldsGrouped = ", sum(" . $this->db->ifsql("e.statut IS NULL", "0", "ps.reel") . ") as stock"; // e.statut is null if there is no record in stock
  2475. } else {
  2476. $selectFieldsGrouped = ", " . $this->db->ifsql("p.stock IS NULL", 0, "p.stock") . " AS stock";
  2477. }
  2478. $sql = "SELECT ";
  2479. // Add select from hooks
  2480. $parameters = array();
  2481. $reshook = $hookmanager->executeHooks('selectProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
  2482. if (empty($reshook)) {
  2483. $sql .= $selectFields.$selectFieldsGrouped.$hookmanager->resPrint;
  2484. } else {
  2485. $sql .= $hookmanager->resPrint;
  2486. }
  2487. if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
  2488. //Product category
  2489. $sql .= ", (SELECT " . $this->db->prefix() . "categorie_product.fk_categorie
  2490. FROM " . $this->db->prefix() . "categorie_product
  2491. WHERE " . $this->db->prefix() . "categorie_product.fk_product=p.rowid
  2492. LIMIT 1
  2493. ) AS categorie_product_id ";
  2494. }
  2495. //Price by customer
  2496. if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES') && !empty($socid)) {
  2497. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2498. $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx, pcp.default_vat_code as custdefault_vat_code, pcp.ref_customer as custref';
  2499. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2500. }
  2501. // Units
  2502. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2503. $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units";
  2504. $selectFields .= ', unit_long, unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units';
  2505. }
  2506. // Multilang : we add translation
  2507. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2508. $sql .= ", pl.label as label_translated";
  2509. $sql .= ", pl.description as description_translated";
  2510. $selectFields .= ", label_translated";
  2511. $selectFields .= ", description_translated";
  2512. }
  2513. // Price by quantity
  2514. if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
  2515. $sql .= ", (SELECT pp.rowid FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid";
  2516. if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
  2517. $sql .= " AND price_level = " . ((int) $price_level);
  2518. }
  2519. $sql .= " ORDER BY date_price";
  2520. $sql .= " DESC LIMIT 1) as price_rowid";
  2521. $sql .= ", (SELECT pp.price_by_qty FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid"; // price_by_qty is 1 if some prices by qty exists in subtable
  2522. if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
  2523. $sql .= " AND price_level = " . ((int) $price_level);
  2524. }
  2525. $sql .= " ORDER BY date_price";
  2526. $sql .= " DESC LIMIT 1) as price_by_qty";
  2527. $selectFields .= ", price_rowid, price_by_qty";
  2528. }
  2529. $sql .= " FROM ".$this->db->prefix()."product as p";
  2530. // Add from (left join) from hooks
  2531. $parameters = array();
  2532. $reshook = $hookmanager->executeHooks('selectProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
  2533. $sql .= $hookmanager->resPrint;
  2534. if (count($warehouseStatusArray)) {
  2535. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as ps on ps.fk_product = p.rowid";
  2536. $sql .= " LEFT JOIN " . $this->db->prefix() . "entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (" . getEntity('stock') . ")";
  2537. $sql .= ' AND e.statut IN (' . $this->db->sanitize($this->db->escape(implode(',', $warehouseStatusArray))) . ')'; // Return line if product is inside the selected stock. If not, an empty line will be returned so we will count 0.
  2538. }
  2539. // include search in supplier ref
  2540. if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_SHOW_MULTIPLE') || getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF') || getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_LABEL')) { // MMI Hack : include search in supplier name
  2541. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2542. }
  2543. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_LABEL)) {
  2544. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as pf ON pfp.fk_soc = pf.rowid";
  2545. }
  2546. //Price by customer
  2547. if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES') && !empty($socid)) {
  2548. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_customer_price as pcp ON pcp.fk_soc=" . ((int) $socid) . " AND pcp.fk_product=p.rowid";
  2549. }
  2550. // Units
  2551. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2552. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  2553. }
  2554. // Multilang : we add translation
  2555. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2556. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_lang as pl ON pl.fk_product = p.rowid ";
  2557. if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && !empty($socid)) {
  2558. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  2559. $soc = new Societe($this->db);
  2560. $result = $soc->fetch($socid);
  2561. if ($result > 0 && !empty($soc->default_lang)) {
  2562. $sql .= " AND pl.lang = '" . $this->db->escape($soc->default_lang) . "'";
  2563. } else {
  2564. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2565. }
  2566. } else {
  2567. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2568. }
  2569. }
  2570. if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD')) {
  2571. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2572. }
  2573. $sql .= ' WHERE p.entity IN (' . getEntity('product') . ')';
  2574. if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD')) {
  2575. $sql .= " AND pac.rowid IS NULL";
  2576. }
  2577. if ($finished == 0) {
  2578. $sql .= " AND p.finished = " . ((int) $finished);
  2579. } elseif ($finished == 1) {
  2580. $sql .= " AND p.finished = ".((int) $finished);
  2581. }
  2582. if ($status >= 0) {
  2583. $sql .= " AND p.tosell = ".((int) $status);
  2584. }
  2585. if ($status_purchase >= 0) {
  2586. $sql .= " AND p.tobuy = " . ((int) $status_purchase);
  2587. }
  2588. // Filter by product type
  2589. if (strval($filtertype) != '') {
  2590. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  2591. } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
  2592. $sql .= " AND p.fk_product_type = 1";
  2593. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2594. $sql .= " AND p.fk_product_type = 0";
  2595. }
  2596. // Add where from hooks
  2597. $parameters = array();
  2598. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2599. $sql .= $hookmanager->resPrint;
  2600. // Add criteria on ref/label
  2601. if ($filterkey != '') {
  2602. $sql .= ' AND (';
  2603. $prefix = !getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2604. // For natural search
  2605. $scrit = explode(' ', $filterkey);
  2606. $i = 0;
  2607. if (count($scrit) > 1) {
  2608. $sql .= "(";
  2609. }
  2610. foreach ($scrit as $crit) {
  2611. if ($i > 0) {
  2612. $sql .= " AND ";
  2613. }
  2614. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2615. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2616. $sql .= " OR pl.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2617. }
  2618. if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES') && !empty($socid)) {
  2619. $sql .= " OR pcp.ref_customer LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2620. }
  2621. if (getDolGlobalString('PRODUCT_AJAX_SEARCH_ON_DESCRIPTION')) {
  2622. $sql .= " OR p.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2623. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2624. $sql .= " OR pl.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2625. }
  2626. }
  2627. if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF')) { // MMI Hack
  2628. $sql .= " OR pfp.ref_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2629. }
  2630. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_LABEL)) {
  2631. $sql .= " OR pf.nom LIKE '".$this->db->escape($prefix.$crit)."%'";
  2632. $sql .= " OR pf.name_alias LIKE '".$this->db->escape($prefix.$crit)."%'";
  2633. }
  2634. $sql .= ")";
  2635. $i++;
  2636. }
  2637. if (count($scrit) > 1) {
  2638. $sql .= ")";
  2639. }
  2640. if (isModEnabled('barcode')) {
  2641. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  2642. }
  2643. $sql .= ')';
  2644. }
  2645. if (count($warehouseStatusArray)) {
  2646. $sql .= " GROUP BY " . $selectFields;
  2647. }
  2648. // Added by MMI Mathieu Moulin iProspective
  2649. // @todo gérer le cas où on affiche plusieurs lignes par produit et on sélectionne => mettre le bon prix d'achat, etc.
  2650. elseif (empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_SHOW_MULTIPLE) && (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF) || !empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_LABEL))) {
  2651. $sql .= " GROUP BY p.rowid";
  2652. }
  2653. //Sort by category
  2654. if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
  2655. $sql .= " ORDER BY categorie_product_id ";
  2656. //ASC OR DESC order
  2657. (getDolGlobalInt('PRODUCT_SORT_BY_CATEGORY') == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2658. } else {
  2659. $sql .= $this->db->order("p.ref");
  2660. }
  2661. $sql .= $this->db->plimit($limit, 0);
  2662. // Build output string
  2663. dol_syslog(get_class($this) . "::select_produits_list search products", LOG_DEBUG);
  2664. $result = $this->db->query($sql);
  2665. if ($result) {
  2666. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2667. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2668. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  2669. $num = $this->db->num_rows($result);
  2670. $events = null;
  2671. if (!$forcecombo) {
  2672. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2673. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2674. }
  2675. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2676. $textifempty = '';
  2677. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2678. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2679. if (getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
  2680. if ($showempty && !is_numeric($showempty)) {
  2681. $textifempty = $langs->trans($showempty);
  2682. } else {
  2683. $textifempty .= $langs->trans("All");
  2684. }
  2685. } else {
  2686. if ($showempty && !is_numeric($showempty)) {
  2687. $textifempty = $langs->trans($showempty);
  2688. }
  2689. }
  2690. if ($showempty) {
  2691. $out .= '<option value="-1" selected>' . ($textifempty ? $textifempty : '&nbsp;') . '</option>';
  2692. }
  2693. $i = 0;
  2694. while ($num && $i < $num) {
  2695. $opt = '';
  2696. $optJson = array();
  2697. $objp = $this->db->fetch_object($result);
  2698. if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1) { // Price by quantity will return many prices for the same product
  2699. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2700. $sql .= " FROM " . $this->db->prefix() . "product_price_by_qty";
  2701. $sql .= " WHERE fk_product_price = " . ((int) $objp->price_rowid);
  2702. $sql .= " ORDER BY quantity ASC";
  2703. dol_syslog(get_class($this) . "::select_produits_list search prices by qty", LOG_DEBUG);
  2704. $result2 = $this->db->query($sql);
  2705. if ($result2) {
  2706. $nb_prices = $this->db->num_rows($result2);
  2707. $j = 0;
  2708. while ($nb_prices && $j < $nb_prices) {
  2709. $objp2 = $this->db->fetch_object($result2);
  2710. $objp->price_by_qty_rowid = $objp2->rowid;
  2711. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2712. $objp->price_by_qty_quantity = $objp2->quantity;
  2713. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2714. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2715. // For backward compatibility
  2716. $objp->quantity = $objp2->quantity;
  2717. $objp->price = $objp2->price;
  2718. $objp->unitprice = $objp2->unitprice;
  2719. $objp->remise_percent = $objp2->remise_percent;
  2720. //$objp->tva_tx is not overwritten by $objp2 value
  2721. //$objp->default_vat_code is not overwritten by $objp2 value
  2722. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2723. $j++;
  2724. // Add new entry
  2725. // "key" value of json key array is used by jQuery automatically as selected value
  2726. // "label" value of json key array is used by jQuery automatically as text for combo box
  2727. $out .= $opt;
  2728. array_push($outarray, $optJson);
  2729. }
  2730. }
  2731. } else {
  2732. if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
  2733. $price_product = new Product($this->db);
  2734. $price_product->fetch($objp->rowid, '', '', 1);
  2735. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2736. $priceparser = new PriceParser($this->db);
  2737. $price_result = $priceparser->parseProduct($price_product);
  2738. if ($price_result >= 0) {
  2739. $objp->price = $price_result;
  2740. $objp->unitprice = $price_result;
  2741. //Calculate the VAT
  2742. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2743. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2744. }
  2745. }
  2746. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2747. // Add new entry
  2748. // "key" value of json key array is used by jQuery automatically as selected value
  2749. // "label" value of json key array is used by jQuery automatically as text for combo box
  2750. $out .= $opt;
  2751. array_push($outarray, $optJson);
  2752. }
  2753. $i++;
  2754. }
  2755. $out .= '</select>';
  2756. $this->db->free($result);
  2757. if (empty($outputmode)) {
  2758. return $out;
  2759. }
  2760. return $outarray;
  2761. } else {
  2762. dol_print_error($this->db);
  2763. }
  2764. return '';
  2765. }
  2766. /**
  2767. * Function to forge the string with OPTIONs of SELECT.
  2768. * This define value for &$opt and &$optJson.
  2769. * This function is called by select_produits_list().
  2770. *
  2771. * @param object $objp Resultset of fetch
  2772. * @param string $opt Option (var used for returned value in string option format)
  2773. * @param array $optJson Option (var used for returned value in json format)
  2774. * @param int $price_level Price level
  2775. * @param string $selected Preselected value
  2776. * @param int $hidepriceinlabel Hide price in label
  2777. * @param string $filterkey Filter key to highlight
  2778. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2779. * @return void
  2780. */
  2781. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2782. {
  2783. global $langs, $conf, $user;
  2784. global $hookmanager;
  2785. $outkey = '';
  2786. $outval = '';
  2787. $outref = '';
  2788. $outlabel = '';
  2789. $outlabel_translated = '';
  2790. $outdesc = '';
  2791. $outdesc_translated = '';
  2792. $outbarcode = '';
  2793. $outorigin = '';
  2794. $outtype = '';
  2795. $outprice_ht = '';
  2796. $outprice_ttc = '';
  2797. $outpricebasetype = '';
  2798. $outtva_tx = '';
  2799. $outdefault_vat_code = '';
  2800. $outqty = 1;
  2801. $outdiscount = 0;
  2802. $maxlengtharticle = (!getDolGlobalString('PRODUCT_MAX_LENGTH_COMBO') ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2803. $label = $objp->label;
  2804. if (!empty($objp->label_translated)) {
  2805. $label = $objp->label_translated;
  2806. }
  2807. if (!empty($filterkey) && $filterkey != '') {
  2808. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  2809. }
  2810. $outkey = $objp->rowid;
  2811. $outref = $objp->ref;
  2812. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2813. $outlabel = $objp->label;
  2814. $outdesc = $objp->description;
  2815. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2816. $outlabel_translated = $objp->label_translated;
  2817. $outdesc_translated = $objp->description_translated;
  2818. }
  2819. $outbarcode = $objp->barcode;
  2820. $outorigin = $objp->fk_country;
  2821. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2822. $outtype = $objp->fk_product_type;
  2823. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2824. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  2825. if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
  2826. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  2827. }
  2828. // Units
  2829. $outvalUnits = '';
  2830. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2831. if (!empty($objp->unit_short)) {
  2832. $outvalUnits .= ' - ' . $objp->unit_short;
  2833. }
  2834. }
  2835. if (getDolGlobalString('PRODUCT_SHOW_DIMENSIONS_IN_COMBO')) {
  2836. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2837. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2838. $outvalUnits .= ' - ' . $unitToShow;
  2839. }
  2840. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2841. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  2842. $outvalUnits .= ' - ' . $unitToShow;
  2843. }
  2844. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2845. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2846. $outvalUnits .= ' - ' . $unitToShow;
  2847. }
  2848. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2849. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2850. $outvalUnits .= ' - ' . $unitToShow;
  2851. }
  2852. }
  2853. if ($outdurationvalue && $outdurationunit) {
  2854. $da = array(
  2855. 'h' => $langs->trans('Hour'),
  2856. 'd' => $langs->trans('Day'),
  2857. 'w' => $langs->trans('Week'),
  2858. 'm' => $langs->trans('Month'),
  2859. 'y' => $langs->trans('Year')
  2860. );
  2861. if (isset($da[$outdurationunit])) {
  2862. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  2863. }
  2864. }
  2865. $opt = '<option value="' . $objp->rowid . '"';
  2866. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2867. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2868. $opt .= ' pbq="' . $objp->price_by_qty_rowid . '" data-pbq="' . $objp->price_by_qty_rowid . '" data-pbqup="' . $objp->price_by_qty_unitprice . '" data-pbqbase="' . $objp->price_by_qty_price_base_type . '" data-pbqqty="' . $objp->price_by_qty_quantity . '" data-pbqpercent="' . $objp->price_by_qty_remise_percent . '"';
  2869. }
  2870. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
  2871. if ($user->hasRight('stock', 'lire')) {
  2872. if ($objp->stock > 0) {
  2873. $opt .= ' class="product_line_stock_ok"';
  2874. } elseif ($objp->stock <= 0) {
  2875. $opt .= ' class="product_line_stock_too_low"';
  2876. }
  2877. }
  2878. }
  2879. if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
  2880. $opt .= ' data-labeltrans="' . $outlabel_translated . '"';
  2881. $opt .= ' data-desctrans="' . dol_escape_htmltag($outdesc_translated) . '"';
  2882. }
  2883. $opt .= '>';
  2884. $opt .= $objp->ref;
  2885. if (!empty($objp->custref)) {
  2886. $opt .= ' (' . $objp->custref . ')';
  2887. }
  2888. if ($outbarcode) {
  2889. $opt .= ' (' . $outbarcode . ')';
  2890. }
  2891. $opt .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2892. if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
  2893. $opt .= ' (' . getCountry($outorigin, 1) . ')';
  2894. }
  2895. $objRef = $objp->ref;
  2896. if (!empty($objp->custref)) {
  2897. $objRef .= ' (' . $objp->custref . ')';
  2898. }
  2899. if (!empty($filterkey) && $filterkey != '') {
  2900. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  2901. }
  2902. $outval .= $objRef;
  2903. if ($outbarcode) {
  2904. $outval .= ' (' . $outbarcode . ')';
  2905. }
  2906. $outval .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2907. if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
  2908. $outval .= ' (' . getCountry($outorigin, 1) . ')';
  2909. }
  2910. // Units
  2911. $opt .= $outvalUnits;
  2912. $outval .= $outvalUnits;
  2913. $found = 0;
  2914. // Multiprice
  2915. // If we need a particular price level (from 1 to n)
  2916. if (empty($hidepriceinlabel) && $price_level >= 1 && (getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'))) {
  2917. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2918. $sql .= " FROM " . $this->db->prefix() . "product_price";
  2919. $sql .= " WHERE fk_product = " . ((int) $objp->rowid);
  2920. $sql .= " AND entity IN (" . getEntity('productprice') . ")";
  2921. $sql .= " AND price_level = " . ((int) $price_level);
  2922. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2923. $sql .= " LIMIT 1";
  2924. dol_syslog(get_class($this) . '::constructProductListOption search price for product ' . $objp->rowid . ' AND level ' . $price_level, LOG_DEBUG);
  2925. $result2 = $this->db->query($sql);
  2926. if ($result2) {
  2927. $objp2 = $this->db->fetch_object($result2);
  2928. if ($objp2) {
  2929. $found = 1;
  2930. if ($objp2->price_base_type == 'HT') {
  2931. $opt .= ' - ' . price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2932. $outval .= ' - ' . price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2933. } else {
  2934. $opt .= ' - ' . price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2935. $outval .= ' - ' . price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2936. }
  2937. $outprice_ht = price($objp2->price);
  2938. $outprice_ttc = price($objp2->price_ttc);
  2939. $outpricebasetype = $objp2->price_base_type;
  2940. if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
  2941. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2942. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2943. } else {
  2944. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2945. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2946. }
  2947. }
  2948. } else {
  2949. dol_print_error($this->db);
  2950. }
  2951. }
  2952. // Price by quantity
  2953. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'))) {
  2954. $found = 1;
  2955. $outqty = $objp->quantity;
  2956. $outdiscount = $objp->remise_percent;
  2957. if ($objp->quantity == 1) {
  2958. $opt .= ' - ' . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/";
  2959. $outval .= ' - ' . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/";
  2960. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2961. $outval .= $langs->transnoentities("Unit");
  2962. } else {
  2963. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2964. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2965. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2966. $outval .= $langs->transnoentities("Units");
  2967. }
  2968. $outprice_ht = price($objp->unitprice);
  2969. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2970. $outpricebasetype = $objp->price_base_type;
  2971. $outtva_tx = $objp->tva_tx; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
  2972. $outdefault_vat_code = $objp->default_vat_code; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
  2973. }
  2974. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2975. $opt .= " (" . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2976. $outval .= " (" . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2977. }
  2978. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2979. $opt .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2980. $outval .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2981. }
  2982. // Price by customer
  2983. if (empty($hidepriceinlabel) && getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
  2984. if (!empty($objp->idprodcustprice)) {
  2985. $found = 1;
  2986. if ($objp->custprice_base_type == 'HT') {
  2987. $opt .= ' - ' . price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2988. $outval .= ' - ' . price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2989. } else {
  2990. $opt .= ' - ' . price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2991. $outval .= ' - ' . price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2992. }
  2993. $outprice_ht = price($objp->custprice);
  2994. $outprice_ttc = price($objp->custprice_ttc);
  2995. $outpricebasetype = $objp->custprice_base_type;
  2996. $outtva_tx = $objp->custtva_tx;
  2997. $outdefault_vat_code = $objp->custdefault_vat_code;
  2998. }
  2999. }
  3000. // If level no defined or multiprice not found, we used the default price
  3001. if (empty($hidepriceinlabel) && !$found) {
  3002. if ($objp->price_base_type == 'HT') {
  3003. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  3004. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  3005. } else {
  3006. $opt .= ' - ' . price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  3007. $outval .= ' - ' . price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  3008. }
  3009. $outprice_ht = price($objp->price);
  3010. $outprice_ttc = price($objp->price_ttc);
  3011. $outpricebasetype = $objp->price_base_type;
  3012. $outtva_tx = $objp->tva_tx;
  3013. $outdefault_vat_code = $objp->default_vat_code;
  3014. }
  3015. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
  3016. if ($user->hasRight('stock', 'lire')) {
  3017. $opt .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
  3018. if ($objp->stock > 0) {
  3019. $outval .= ' - <span class="product_line_stock_ok">';
  3020. } elseif ($objp->stock <= 0) {
  3021. $outval .= ' - <span class="product_line_stock_too_low">';
  3022. }
  3023. $outval .= $langs->transnoentities("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  3024. $outval .= '</span>';
  3025. if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
  3026. $langs->load("stocks");
  3027. $tmpproduct = new Product($this->db);
  3028. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3029. $tmpproduct->load_virtual_stock();
  3030. $virtualstock = $tmpproduct->stock_theorique;
  3031. $opt .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  3032. $outval .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  3033. if ($virtualstock > 0) {
  3034. $outval .= '<span class="product_line_stock_ok">';
  3035. } elseif ($virtualstock <= 0) {
  3036. $outval .= '<span class="product_line_stock_too_low">';
  3037. }
  3038. $outval .= $virtualstock;
  3039. $outval .= '</span>';
  3040. unset($tmpproduct);
  3041. }
  3042. }
  3043. }
  3044. $parameters = array('objp'=>$objp);
  3045. $reshook = $hookmanager->executeHooks('constructProductListOption', $parameters); // Note that $action and $object may have been modified by hook
  3046. if (empty($reshook)) {
  3047. $opt .= $hookmanager->resPrint;
  3048. } else {
  3049. $opt = $hookmanager->resPrint;
  3050. }
  3051. $opt .= "</option>\n";
  3052. $optJson = array(
  3053. 'key' => $outkey,
  3054. 'value' => $outref,
  3055. 'label' => $outval,
  3056. 'label2' => $outlabel,
  3057. 'desc' => $outdesc,
  3058. 'type' => $outtype,
  3059. 'price_ht' => price2num($outprice_ht),
  3060. 'price_ttc' => price2num($outprice_ttc),
  3061. 'price_ht_locale' => price(price2num($outprice_ht)),
  3062. 'price_ttc_locale' => price(price2num($outprice_ttc)),
  3063. 'pricebasetype' => $outpricebasetype,
  3064. 'tva_tx' => $outtva_tx,
  3065. 'default_vat_code' => $outdefault_vat_code,
  3066. 'qty' => $outqty,
  3067. 'discount' => $outdiscount,
  3068. 'duration_value' => $outdurationvalue,
  3069. 'duration_unit' => $outdurationunit,
  3070. 'pbq' => $outpbq,
  3071. 'labeltrans' => $outlabel_translated,
  3072. 'desctrans' => $outdesc_translated,
  3073. 'ref_customer' => $outrefcust
  3074. );
  3075. }
  3076. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3077. /**
  3078. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  3079. *
  3080. * @param int $socid Id third party
  3081. * @param string $selected Preselected product
  3082. * @param string $htmlname Name of HTML Select
  3083. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  3084. * @param string $filtre For a SQL filter
  3085. * @param array $ajaxoptions Options for ajax_autocompleter
  3086. * @param int $hidelabel Hide label (0=no, 1=yes)
  3087. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  3088. * @param string $morecss More CSS
  3089. * @param string $placeholder Placeholder
  3090. * @return void
  3091. */
  3092. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  3093. {
  3094. // phpcs:enable
  3095. global $langs, $conf;
  3096. global $price_level, $status, $finished;
  3097. if (!isset($status)) {
  3098. $status = 1;
  3099. }
  3100. $selected_input_value = '';
  3101. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
  3102. if ($selected > 0) {
  3103. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  3104. $producttmpselect = new Product($this->db);
  3105. $producttmpselect->fetch($selected);
  3106. $selected_input_value = $producttmpselect->ref;
  3107. unset($producttmpselect);
  3108. }
  3109. // mode=2 means suppliers products
  3110. $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=2&status=' . $status . '&finished=' . $finished . '&alsoproductwithnosupplierprice=' . $alsoproductwithnosupplierprice;
  3111. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  3112. print($hidelabel ? '' : $langs->trans("RefOrLabel") . ' : ') . '<input type="text" class="minwidth300" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . $placeholder . '"' : '') . '>';
  3113. } else {
  3114. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  3115. }
  3116. }
  3117. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3118. /**
  3119. * Return list of suppliers products
  3120. *
  3121. * @param int $socid Id of supplier thirdparty (0 = no filter)
  3122. * @param string $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  3123. * @param string $htmlname Name of HTML select
  3124. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  3125. * @param string $filtre Generic filter. Data must not come from user input.
  3126. * @param string $filterkey Filter of produdts
  3127. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  3128. * @param int $outputmode 0=HTML select string, 1=Array
  3129. * @param int $limit Limit of line number
  3130. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  3131. * @param string $morecss Add more CSS
  3132. * @param int $showstockinlist Show stock information (slower).
  3133. * @param string $placeholder Placeholder
  3134. * @return array|string Array of keys for json or HTML component
  3135. */
  3136. public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '', $showstockinlist = 0, $placeholder = '')
  3137. {
  3138. // phpcs:enable
  3139. global $langs, $conf, $user;
  3140. global $hookmanager;
  3141. $out = '';
  3142. $outarray = array();
  3143. $maxlengtharticle = (!getDolGlobalString('PRODUCT_MAX_LENGTH_COMBO') ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  3144. $langs->load('stocks');
  3145. // Units
  3146. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3147. $langs->load('other');
  3148. }
  3149. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock, p.tva_tx as tva_tx_sale, p.default_vat_code as default_vat_code_sale,";
  3150. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice";
  3151. $sql .= ", pfp.multicurrency_code, pfp.multicurrency_unitprice";
  3152. $sql .= ", pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name";
  3153. $sql .= ", pfp.supplier_reputation";
  3154. // if we use supplier description of the products
  3155. if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
  3156. $sql .= ", pfp.desc_fourn as description";
  3157. } else {
  3158. $sql .= ", p.description";
  3159. }
  3160. // Units
  3161. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3162. $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units";
  3163. }
  3164. if (isModEnabled('barcode')) {
  3165. $sql .= ", pfp.barcode";
  3166. }
  3167. $sql .= " FROM " . $this->db->prefix() . "product as p";
  3168. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (" . getEntity('product') . ") )";
  3169. if ($socid > 0) {
  3170. $sql .= " AND pfp.fk_soc = " . ((int) $socid);
  3171. }
  3172. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  3173. // Units
  3174. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3175. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  3176. }
  3177. $sql .= " WHERE p.entity IN (" . getEntity('product') . ")";
  3178. if ($statut != -1) {
  3179. $sql .= " AND p.tobuy = " . ((int) $statut);
  3180. }
  3181. if (strval($filtertype) != '') {
  3182. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  3183. }
  3184. if (!empty($filtre)) {
  3185. $sql .= " " . $filtre;
  3186. }
  3187. // Add where from hooks
  3188. $parameters = array();
  3189. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  3190. $sql .= $hookmanager->resPrint;
  3191. // Add criteria on ref/label
  3192. if ($filterkey != '') {
  3193. $sql .= ' AND (';
  3194. $prefix = !getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  3195. // For natural search
  3196. $scrit = explode(' ', $filterkey);
  3197. $i = 0;
  3198. if (count($scrit) > 1) {
  3199. $sql .= "(";
  3200. }
  3201. foreach ($scrit as $crit) {
  3202. if ($i > 0) {
  3203. $sql .= " AND ";
  3204. }
  3205. $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) . "%'";
  3206. if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
  3207. $sql .= " OR pfp.desc_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  3208. }
  3209. $sql .= ")";
  3210. $i++;
  3211. }
  3212. if (count($scrit) > 1) {
  3213. $sql .= ")";
  3214. }
  3215. if (isModEnabled('barcode')) {
  3216. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3217. $sql .= " OR pfp.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3218. }
  3219. $sql .= ')';
  3220. }
  3221. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  3222. $sql .= $this->db->plimit($limit, 0);
  3223. // Build output string
  3224. dol_syslog(get_class($this) . "::select_produits_fournisseurs_list", LOG_DEBUG);
  3225. $result = $this->db->query($sql);
  3226. if ($result) {
  3227. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3228. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  3229. $num = $this->db->num_rows($result);
  3230. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  3231. $out .= '<select class="flat ' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '">';
  3232. if (!$selected) {
  3233. $out .= '<option value="-1" selected>' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3234. } else {
  3235. $out .= '<option value="-1">' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3236. }
  3237. $i = 0;
  3238. while ($i < $num) {
  3239. $objp = $this->db->fetch_object($result);
  3240. if (is_null($objp->idprodfournprice)) {
  3241. // There is no supplier price found, we will use the vat rate for sale
  3242. $objp->tva_tx = $objp->tva_tx_sale;
  3243. $objp->default_vat_code = $objp->default_vat_code_sale;
  3244. }
  3245. $outkey = $objp->idprodfournprice; // id in table of price
  3246. if (!$outkey && $alsoproductwithnosupplierprice) {
  3247. $outkey = 'idprod_' . $objp->rowid; // id of product
  3248. }
  3249. $outref = $objp->ref;
  3250. $outbarcode = $objp->barcode;
  3251. $outqty = 1;
  3252. $outdiscount = 0;
  3253. $outtype = $objp->fk_product_type;
  3254. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3255. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  3256. // Units
  3257. $outvalUnits = '';
  3258. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3259. if (!empty($objp->unit_short)) {
  3260. $outvalUnits .= ' - ' . $objp->unit_short;
  3261. }
  3262. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3263. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3264. $outvalUnits .= ' - ' . $unitToShow;
  3265. }
  3266. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3267. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  3268. $outvalUnits .= ' - ' . $unitToShow;
  3269. }
  3270. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3271. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3272. $outvalUnits .= ' - ' . $unitToShow;
  3273. }
  3274. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3275. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3276. $outvalUnits .= ' - ' . $unitToShow;
  3277. }
  3278. if ($outdurationvalue && $outdurationunit) {
  3279. $da = array(
  3280. 'h' => $langs->trans('Hour'),
  3281. 'd' => $langs->trans('Day'),
  3282. 'w' => $langs->trans('Week'),
  3283. 'm' => $langs->trans('Month'),
  3284. 'y' => $langs->trans('Year')
  3285. );
  3286. if (isset($da[$outdurationunit])) {
  3287. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  3288. }
  3289. }
  3290. }
  3291. $objRef = $objp->ref;
  3292. if ($filterkey && $filterkey != '') {
  3293. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  3294. }
  3295. $objRefFourn = $objp->ref_fourn;
  3296. if ($filterkey && $filterkey != '') {
  3297. $objRefFourn = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3298. }
  3299. $label = $objp->label;
  3300. if ($filterkey && $filterkey != '') {
  3301. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  3302. }
  3303. switch ($objp->fk_product_type) {
  3304. case Product::TYPE_PRODUCT:
  3305. $picto = 'product';
  3306. break;
  3307. case Product::TYPE_SERVICE:
  3308. $picto = 'service';
  3309. break;
  3310. default:
  3311. $picto = '';
  3312. break;
  3313. }
  3314. if (empty($picto)) {
  3315. $optlabel = '';
  3316. } else {
  3317. $optlabel = img_object('', $picto, 'class="paddingright classfortooltip"', 0, 0, 1);
  3318. }
  3319. $optlabel .= $objp->ref;
  3320. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3321. $optlabel .= ' <span class="opacitymedium">(' . $objp->ref_fourn . ')</span>';
  3322. }
  3323. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3324. $optlabel .= ' (' . $outbarcode . ')';
  3325. }
  3326. $optlabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3327. $outvallabel = $objRef;
  3328. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3329. $outvallabel .= ' (' . $objRefFourn . ')';
  3330. }
  3331. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3332. $outvallabel .= ' (' . $outbarcode . ')';
  3333. }
  3334. $outvallabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3335. // Units
  3336. $optlabel .= $outvalUnits;
  3337. $outvallabel .= $outvalUnits;
  3338. if (!empty($objp->idprodfournprice)) {
  3339. $outqty = $objp->quantity;
  3340. $outdiscount = $objp->remise_percent;
  3341. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3342. $prod_supplier = new ProductFournisseur($this->db);
  3343. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3344. $prod_supplier->id = $objp->fk_product;
  3345. $prod_supplier->fourn_qty = $objp->quantity;
  3346. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3347. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3348. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3349. $priceparser = new PriceParser($this->db);
  3350. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3351. if ($price_result >= 0) {
  3352. $objp->fprice = $price_result;
  3353. if ($objp->quantity >= 1) {
  3354. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3355. }
  3356. }
  3357. }
  3358. if ($objp->quantity == 1) {
  3359. $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3360. $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/";
  3361. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3362. $outvallabel .= $langs->transnoentities("Unit");
  3363. } else {
  3364. $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  3365. $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  3366. $optlabel .= ' ' . $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3367. $outvallabel .= ' ' . $langs->transnoentities("Units");
  3368. }
  3369. if ($objp->quantity > 1) {
  3370. $optlabel .= " (" . price($objp->unitprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  3371. $outvallabel .= " (" . price($objp->unitprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  3372. }
  3373. if ($objp->remise_percent >= 1) {
  3374. $optlabel .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3375. $outvallabel .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3376. }
  3377. if ($objp->duration) {
  3378. $optlabel .= " - " . $objp->duration;
  3379. $outvallabel .= " - " . $objp->duration;
  3380. }
  3381. if (!$socid) {
  3382. $optlabel .= " - " . dol_trunc($objp->name, 8);
  3383. $outvallabel .= " - " . dol_trunc($objp->name, 8);
  3384. }
  3385. if ($objp->supplier_reputation) {
  3386. //TODO dictionary
  3387. $reputations = array('' => $langs->trans('Standard'), 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
  3388. $optlabel .= " - " . $reputations[$objp->supplier_reputation];
  3389. $outvallabel .= " - " . $reputations[$objp->supplier_reputation];
  3390. }
  3391. } else {
  3392. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3393. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3394. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3395. } else { // No supplier price defined for product, even on other suppliers
  3396. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3397. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3398. }
  3399. }
  3400. if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
  3401. $novirtualstock = ($showstockinlist == 2);
  3402. if ($user->hasRight('stock', 'lire')) {
  3403. $outvallabel .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  3404. if ($objp->stock > 0) {
  3405. $optlabel .= ' - <span class="product_line_stock_ok">';
  3406. } elseif ($objp->stock <= 0) {
  3407. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3408. }
  3409. $optlabel .= $langs->transnoentities("Stock") . ':' . price(price2num($objp->stock, 'MS'));
  3410. $optlabel .= '</span>';
  3411. if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
  3412. $langs->load("stocks");
  3413. $tmpproduct = new Product($this->db);
  3414. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3415. $tmpproduct->load_virtual_stock();
  3416. $virtualstock = $tmpproduct->stock_theorique;
  3417. $outvallabel .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  3418. $optlabel .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  3419. if ($virtualstock > 0) {
  3420. $optlabel .= '<span class="product_line_stock_ok">';
  3421. } elseif ($virtualstock <= 0) {
  3422. $optlabel .= '<span class="product_line_stock_too_low">';
  3423. }
  3424. $optlabel .= $virtualstock;
  3425. $optlabel .= '</span>';
  3426. unset($tmpproduct);
  3427. }
  3428. }
  3429. }
  3430. $optstart = '<option value="' . $outkey . '"';
  3431. if ($selected && $selected == $objp->idprodfournprice) {
  3432. $optstart .= ' selected';
  3433. }
  3434. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3435. $optstart .= ' disabled';
  3436. }
  3437. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3438. $optstart .= ' data-product-id="' . dol_escape_htmltag($objp->rowid) . '"';
  3439. $optstart .= ' data-price-id="' . dol_escape_htmltag($objp->idprodfournprice) . '"';
  3440. $optstart .= ' data-qty="' . dol_escape_htmltag($objp->quantity) . '"';
  3441. $optstart .= ' data-up="' . dol_escape_htmltag(price2num($objp->unitprice)) . '"';
  3442. $optstart .= ' data-up-locale="' . dol_escape_htmltag(price($objp->unitprice)) . '"';
  3443. $optstart .= ' data-discount="' . dol_escape_htmltag($outdiscount) . '"';
  3444. $optstart .= ' data-tvatx="' . dol_escape_htmltag(price2num($objp->tva_tx)) . '"';
  3445. $optstart .= ' data-tvatx-formated="' . dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)) . '"';
  3446. $optstart .= ' data-default-vat-code="' . dol_escape_htmltag($objp->default_vat_code) . '"';
  3447. $optstart .= ' data-supplier-ref="' . dol_escape_htmltag($objp->ref_fourn) . '"';
  3448. if (isModEnabled('multicurrency')) {
  3449. $optstart .= ' data-multicurrency-code="' . dol_escape_htmltag($objp->multicurrency_code) . '"';
  3450. $optstart .= ' data-multicurrency-up="' . dol_escape_htmltag($objp->multicurrency_unitprice) . '"';
  3451. }
  3452. }
  3453. $optstart .= ' data-description="' . dol_escape_htmltag($objp->description, 0, 1) . '"';
  3454. $outarrayentry = array(
  3455. 'key' => $outkey,
  3456. 'value' => $outref,
  3457. 'label' => $outvallabel,
  3458. 'qty' => $outqty,
  3459. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3460. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3461. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3462. 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
  3463. 'tva_tx' => price2num($objp->tva_tx),
  3464. 'default_vat_code' => $objp->default_vat_code,
  3465. 'discount' => $outdiscount,
  3466. 'type' => $outtype,
  3467. 'duration_value' => $outdurationvalue,
  3468. 'duration_unit' => $outdurationunit,
  3469. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3470. 'description' => $objp->description
  3471. );
  3472. if (isModEnabled('multicurrency')) {
  3473. $outarrayentry['multicurrency_code'] = $objp->multicurrency_code;
  3474. $outarrayentry['multicurrency_unitprice'] = price2num($objp->multicurrency_unitprice, 'MU');
  3475. }
  3476. $parameters = array(
  3477. 'objp' => &$objp,
  3478. 'optstart' => &$optstart,
  3479. 'optlabel' => &$optlabel,
  3480. 'outvallabel' => &$outvallabel,
  3481. 'outarrayentry' => &$outarrayentry
  3482. );
  3483. $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
  3484. // Add new entry
  3485. // "key" value of json key array is used by jQuery automatically as selected value. Example: 'type' = product or service, 'price_ht' = unit price without tax
  3486. // "label" value of json key array is used by jQuery automatically as text for combo box
  3487. $out .= $optstart . ' data-html="' . dol_escape_htmltag($optlabel) . '">' . $optlabel . "</option>\n";
  3488. $outarraypush = array(
  3489. 'key' => $outkey,
  3490. 'value' => $outref,
  3491. 'label' => $outvallabel,
  3492. 'qty' => $outqty,
  3493. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3494. 'price_qty_ht_locale' => price($objp->fprice),
  3495. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3496. 'price_unit_ht_locale' => price($objp->unitprice),
  3497. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3498. 'tva_tx_formated' => price($objp->tva_tx),
  3499. 'tva_tx' => price2num($objp->tva_tx),
  3500. 'default_vat_code' => $objp->default_vat_code,
  3501. 'discount' => $outdiscount,
  3502. 'type' => $outtype,
  3503. 'duration_value' => $outdurationvalue,
  3504. 'duration_unit' => $outdurationunit,
  3505. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3506. 'description' => $objp->description
  3507. );
  3508. if (isModEnabled('multicurrency')) {
  3509. $outarraypush['multicurrency_code'] = $objp->multicurrency_code;
  3510. $outarraypush['multicurrency_unitprice'] = price2num($objp->multicurrency_unitprice, 'MU');
  3511. }
  3512. array_push($outarray, $outarraypush);
  3513. // Example of var_dump $outarray
  3514. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3515. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3516. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3517. //}
  3518. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3519. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3520. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3521. $i++;
  3522. }
  3523. $out .= '</select>';
  3524. $this->db->free($result);
  3525. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  3526. $out .= ajax_combobox($htmlname);
  3527. } else {
  3528. dol_print_error($this->db);
  3529. }
  3530. if (empty($outputmode)) {
  3531. return $out;
  3532. }
  3533. return $outarray;
  3534. }
  3535. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3536. /**
  3537. * Return list of suppliers prices for a product
  3538. *
  3539. * @param int $productid Id of product
  3540. * @param string $htmlname Name of HTML field
  3541. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3542. * @return string
  3543. */
  3544. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = 0)
  3545. {
  3546. // phpcs:enable
  3547. global $langs, $conf;
  3548. $langs->load('stocks');
  3549. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3550. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3551. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3552. $sql .= " FROM " . $this->db->prefix() . "product as p";
  3553. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3554. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  3555. $sql .= " WHERE pfp.entity IN (" . getEntity('productsupplierprice') . ")";
  3556. $sql .= " AND p.tobuy = 1";
  3557. $sql .= " AND s.fournisseur = 1";
  3558. $sql .= " AND p.rowid = " . ((int) $productid);
  3559. if (!getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED')) {
  3560. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3561. } else {
  3562. $sql .= " ORDER BY pfp.unitprice ASC";
  3563. }
  3564. dol_syslog(get_class($this) . "::select_product_fourn_price", LOG_DEBUG);
  3565. $result = $this->db->query($sql);
  3566. if ($result) {
  3567. $num = $this->db->num_rows($result);
  3568. $form = '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3569. if (!$num) {
  3570. $form .= '<option value="0">-- ' . $langs->trans("NoSupplierPriceDefinedForThisProduct") . ' --</option>';
  3571. } else {
  3572. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3573. $form .= '<option value="0">&nbsp;</option>';
  3574. $i = 0;
  3575. while ($i < $num) {
  3576. $objp = $this->db->fetch_object($result);
  3577. $opt = '<option value="' . $objp->idprodfournprice . '"';
  3578. //if there is only one supplier, preselect it
  3579. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED'))) {
  3580. $opt .= ' selected';
  3581. }
  3582. $opt .= '>' . $objp->name . ' - ' . $objp->ref_fourn . ' - ';
  3583. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3584. $prod_supplier = new ProductFournisseur($this->db);
  3585. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3586. $prod_supplier->id = $productid;
  3587. $prod_supplier->fourn_qty = $objp->quantity;
  3588. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3589. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3590. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3591. $priceparser = new PriceParser($this->db);
  3592. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3593. if ($price_result >= 0) {
  3594. $objp->fprice = $price_result;
  3595. if ($objp->quantity >= 1) {
  3596. $objp->unitprice = $objp->fprice / $objp->quantity;
  3597. }
  3598. }
  3599. }
  3600. if ($objp->quantity == 1) {
  3601. $opt .= price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3602. }
  3603. $opt .= $objp->quantity . ' ';
  3604. if ($objp->quantity == 1) {
  3605. $opt .= $langs->trans("Unit");
  3606. } else {
  3607. $opt .= $langs->trans("Units");
  3608. }
  3609. if ($objp->quantity > 1) {
  3610. $opt .= " - ";
  3611. $opt .= price($objp->unitprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit");
  3612. }
  3613. if ($objp->duration) {
  3614. $opt .= " - " . $objp->duration;
  3615. }
  3616. $opt .= "</option>\n";
  3617. $form .= $opt;
  3618. $i++;
  3619. }
  3620. }
  3621. $form .= '</select>';
  3622. $this->db->free($result);
  3623. return $form;
  3624. } else {
  3625. dol_print_error($this->db);
  3626. return '';
  3627. }
  3628. }
  3629. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3630. /**
  3631. * Load into cache list of payment terms
  3632. *
  3633. * @return int Nb of lines loaded, <0 if KO
  3634. */
  3635. public function load_cache_conditions_paiements()
  3636. {
  3637. // phpcs:enable
  3638. global $langs;
  3639. $num = count($this->cache_conditions_paiements);
  3640. if ($num > 0) {
  3641. return 0; // Cache already loaded
  3642. }
  3643. dol_syslog(__METHOD__, LOG_DEBUG);
  3644. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3645. $sql .= " FROM " . $this->db->prefix() . 'c_payment_term';
  3646. $sql .= " WHERE entity IN (" . getEntity('c_payment_term') . ")";
  3647. $sql .= " AND active > 0";
  3648. $sql .= " ORDER BY sortorder";
  3649. $resql = $this->db->query($sql);
  3650. if ($resql) {
  3651. $num = $this->db->num_rows($resql);
  3652. $i = 0;
  3653. while ($i < $num) {
  3654. $obj = $this->db->fetch_object($resql);
  3655. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3656. $label = ($langs->trans("PaymentConditionShort" . $obj->code) != "PaymentConditionShort" . $obj->code ? $langs->trans("PaymentConditionShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3657. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3658. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3659. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3660. $i++;
  3661. }
  3662. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3663. return $num;
  3664. } else {
  3665. dol_print_error($this->db);
  3666. return -1;
  3667. }
  3668. }
  3669. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3670. /**
  3671. * Load int a cache property th elist of possible delivery delays.
  3672. *
  3673. * @return int Nb of lines loaded, <0 if KO
  3674. */
  3675. public function load_cache_availability()
  3676. {
  3677. // phpcs:enable
  3678. global $langs;
  3679. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3680. if ($num > 0) {
  3681. return 0; // Cache already loaded
  3682. }
  3683. dol_syslog(__METHOD__, LOG_DEBUG);
  3684. $langs->load('propal');
  3685. $sql = "SELECT rowid, code, label, position";
  3686. $sql .= " FROM " . $this->db->prefix() . 'c_availability';
  3687. $sql .= " WHERE active > 0";
  3688. $resql = $this->db->query($sql);
  3689. if ($resql) {
  3690. $num = $this->db->num_rows($resql);
  3691. $i = 0;
  3692. while ($i < $num) {
  3693. $obj = $this->db->fetch_object($resql);
  3694. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3695. $label = ($langs->trans("AvailabilityType" . $obj->code) != "AvailabilityType" . $obj->code ? $langs->trans("AvailabilityType" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3696. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3697. $this->cache_availability[$obj->rowid]['label'] = $label;
  3698. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3699. $i++;
  3700. }
  3701. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3702. return $num;
  3703. } else {
  3704. dol_print_error($this->db);
  3705. return -1;
  3706. }
  3707. }
  3708. /**
  3709. * Retourne la liste des types de delais de livraison possibles
  3710. *
  3711. * @param string $selected Id du type de delais pre-selectionne
  3712. * @param string $htmlname Nom de la zone select
  3713. * @param string $filtertype To add a filter
  3714. * @param int $addempty Add empty entry
  3715. * @param string $morecss More CSS
  3716. * @return void
  3717. */
  3718. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3719. {
  3720. global $langs, $user;
  3721. $this->load_cache_availability();
  3722. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3723. print '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3724. if ($addempty) {
  3725. print '<option value="0">&nbsp;</option>';
  3726. }
  3727. foreach ($this->cache_availability as $id => $arrayavailability) {
  3728. if ($selected == $id) {
  3729. print '<option value="' . $id . '" selected>';
  3730. } else {
  3731. print '<option value="' . $id . '">';
  3732. }
  3733. print dol_escape_htmltag($arrayavailability['label']);
  3734. print '</option>';
  3735. }
  3736. print '</select>';
  3737. if ($user->admin) {
  3738. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3739. }
  3740. print ajax_combobox($htmlname);
  3741. }
  3742. /**
  3743. * Load into cache cache_demand_reason, array of input reasons
  3744. *
  3745. * @return int Nb of lines loaded, <0 if KO
  3746. */
  3747. public function loadCacheInputReason()
  3748. {
  3749. global $langs;
  3750. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3751. if ($num > 0) {
  3752. return 0; // Cache already loaded
  3753. }
  3754. $sql = "SELECT rowid, code, label";
  3755. $sql .= " FROM " . $this->db->prefix() . 'c_input_reason';
  3756. $sql .= " WHERE active > 0";
  3757. $resql = $this->db->query($sql);
  3758. if ($resql) {
  3759. $num = $this->db->num_rows($resql);
  3760. $i = 0;
  3761. $tmparray = array();
  3762. while ($i < $num) {
  3763. $obj = $this->db->fetch_object($resql);
  3764. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3765. $label = ($obj->label != '-' ? $obj->label : '');
  3766. if ($langs->trans("DemandReasonType" . $obj->code) != "DemandReasonType" . $obj->code) {
  3767. $label = $langs->trans("DemandReasonType" . $obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3768. }
  3769. if ($langs->trans($obj->code) != $obj->code) {
  3770. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3771. }
  3772. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3773. $tmparray[$obj->rowid]['code'] = $obj->code;
  3774. $tmparray[$obj->rowid]['label'] = $label;
  3775. $i++;
  3776. }
  3777. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3778. unset($tmparray);
  3779. return $num;
  3780. } else {
  3781. dol_print_error($this->db);
  3782. return -1;
  3783. }
  3784. }
  3785. /**
  3786. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3787. * List found into table c_input_reason loaded by loadCacheInputReason
  3788. *
  3789. * @param string $selected Id or code of type origin to select by default
  3790. * @param string $htmlname Nom de la zone select
  3791. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3792. * @param int $addempty Add an empty entry
  3793. * @param string $morecss Add more css to the HTML select component
  3794. * @param int $notooltip Do not show the tooltip for admin
  3795. * @return void
  3796. */
  3797. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3798. {
  3799. global $langs, $user;
  3800. $this->loadCacheInputReason();
  3801. print '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3802. if ($addempty) {
  3803. print '<option value="0"' . (empty($selected) ? ' selected' : '') . '>&nbsp;</option>';
  3804. }
  3805. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3806. if ($arraydemandreason['code'] == $exclude) {
  3807. continue;
  3808. }
  3809. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3810. print '<option value="' . $arraydemandreason['id'] . '" selected>';
  3811. } else {
  3812. print '<option value="' . $arraydemandreason['id'] . '">';
  3813. }
  3814. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3815. print $langs->trans($label);
  3816. print '</option>';
  3817. }
  3818. print '</select>';
  3819. if ($user->admin && empty($notooltip)) {
  3820. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3821. }
  3822. print ajax_combobox('select_' . $htmlname);
  3823. }
  3824. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3825. /**
  3826. * Charge dans cache la liste des types de paiements possibles
  3827. *
  3828. * @return int Nb of lines loaded, <0 if KO
  3829. */
  3830. public function load_cache_types_paiements()
  3831. {
  3832. // phpcs:enable
  3833. global $langs;
  3834. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3835. if ($num > 0) {
  3836. return $num; // Cache already loaded
  3837. }
  3838. dol_syslog(__METHOD__, LOG_DEBUG);
  3839. $this->cache_types_paiements = array();
  3840. $sql = "SELECT id, code, libelle as label, type, active";
  3841. $sql .= " FROM " . $this->db->prefix() . "c_paiement";
  3842. $sql .= " WHERE entity IN (" . getEntity('c_paiement') . ")";
  3843. $resql = $this->db->query($sql);
  3844. if ($resql) {
  3845. $num = $this->db->num_rows($resql);
  3846. $i = 0;
  3847. while ($i < $num) {
  3848. $obj = $this->db->fetch_object($resql);
  3849. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3850. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3851. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3852. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3853. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3854. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3855. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3856. $i++;
  3857. }
  3858. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3859. return $num;
  3860. } else {
  3861. dol_print_error($this->db);
  3862. return -1;
  3863. }
  3864. }
  3865. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3866. /**
  3867. * print list of payment modes.
  3868. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can be used to set default value but scope is all application, probably not what you want.
  3869. * See instead to force the default value by the caller.
  3870. *
  3871. * @param int $selected Id of payment term to preselect by default
  3872. * @param string $htmlname Nom de la zone select
  3873. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3874. * @param int $addempty Add an empty entry
  3875. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3876. * @param string $morecss Add more CSS on select tag
  3877. * @param int $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3878. * 0 : use default deposit percentage from entry
  3879. * > 0 : force deposit percentage (for example, from company object)
  3880. * @return void
  3881. * @deprecated
  3882. */
  3883. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3884. {
  3885. // phpcs:enable
  3886. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
  3887. }
  3888. /**
  3889. * Return list of payment modes.
  3890. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can be used to set default value but scope is all application, probably not what you want.
  3891. * See instead to force the default value by the caller.
  3892. *
  3893. * @param int $selected Id of payment term to preselect by default
  3894. * @param string $htmlname Nom de la zone select
  3895. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3896. * @param int $addempty Add an empty entry
  3897. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3898. * @param string $morecss Add more CSS on select tag
  3899. * @param int $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3900. * 0 : use default deposit percentage from entry
  3901. * > 0 : force deposit percentage (for example, from company object)
  3902. * @return string String for the HTML select component
  3903. */
  3904. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3905. {
  3906. global $langs, $user, $conf;
  3907. $out = '';
  3908. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3909. $this->load_cache_conditions_paiements();
  3910. // Set default value if not already set by caller
  3911. if (empty($selected) && getDolGlobalString('MAIN_DEFAULT_PAYMENT_TERM_ID')) {
  3912. dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TERM_ID", LOG_NOTICE);
  3913. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3914. }
  3915. $out .= '<select id="' . $htmlname . '" class="flat selectpaymentterms' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3916. if ($addempty) {
  3917. $out .= '<option value="0">&nbsp;</option>';
  3918. }
  3919. $selectedDepositPercent = null;
  3920. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3921. if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
  3922. continue;
  3923. }
  3924. if ($selected == $id) {
  3925. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3926. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3927. } else {
  3928. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3929. }
  3930. $label = $arrayconditions['label'];
  3931. if (!empty($arrayconditions['deposit_percent'])) {
  3932. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3933. }
  3934. $out .= $label;
  3935. $out .= '</option>';
  3936. }
  3937. $out .= '</select>';
  3938. if ($user->admin && empty($noinfoadmin)) {
  3939. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3940. }
  3941. $out .= ajax_combobox($htmlname);
  3942. if ($deposit_percent >= 0) {
  3943. $out .= ' <span id="' . $htmlname . '_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3944. $out .= $langs->trans('DepositPercent') . ' : ';
  3945. $out .= '<input id="' . $htmlname . '_deposit_percent" name="' . $htmlname . '_deposit_percent" class="maxwidth50" value="' . $deposit_percent . '" />';
  3946. $out .= '</span>';
  3947. $out .= '
  3948. <script nonce="' . getNonce() . '">
  3949. $(document).ready(function () {
  3950. $("#' . $htmlname . '").change(function () {
  3951. let $selected = $(this).find("option:selected");
  3952. let depositPercent = $selected.attr("data-deposit_percent");
  3953. if (depositPercent.length > 0) {
  3954. $("#' . $htmlname . '_deposit_percent_container").show().find("#' . $htmlname . '_deposit_percent").val(depositPercent);
  3955. } else {
  3956. $("#' . $htmlname . '_deposit_percent_container").hide();
  3957. }
  3958. return true;
  3959. });
  3960. });
  3961. </script>';
  3962. }
  3963. return $out;
  3964. }
  3965. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3966. /**
  3967. * Return list of payment methods
  3968. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3969. *
  3970. * @param string $selected Id or code or preselected payment mode
  3971. * @param string $htmlname Name of select field
  3972. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3973. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3974. * @param int $empty 1=can be empty, 0 otherwise
  3975. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3976. * @param int $maxlength Max length of label
  3977. * @param int $active Active or not, -1 = all
  3978. * @param string $morecss Add more CSS on select tag
  3979. * @param int $nooutput 1=Return string, do not send to output
  3980. * @return string|void String for the HTML select component
  3981. */
  3982. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3983. {
  3984. // phpcs:enable
  3985. global $langs, $user, $conf;
  3986. $out = '';
  3987. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
  3988. $filterarray = array();
  3989. if ($filtertype == 'CRDT') {
  3990. $filterarray = array(0, 2, 3);
  3991. } elseif ($filtertype == 'DBIT') {
  3992. $filterarray = array(1, 2, 3);
  3993. } elseif ($filtertype != '' && $filtertype != '-1') {
  3994. $filterarray = explode(',', $filtertype);
  3995. }
  3996. $this->load_cache_types_paiements();
  3997. // Set default value if not already set by caller
  3998. if (empty($selected) && getDolGlobalString('MAIN_DEFAULT_PAYMENT_TYPE_ID')) {
  3999. dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TYPE_ID", LOG_NOTICE);
  4000. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  4001. }
  4002. $out .= '<select id="select' . $htmlname . '" class="flat selectpaymenttypes' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  4003. if ($empty) {
  4004. $out .= '<option value="">&nbsp;</option>';
  4005. }
  4006. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  4007. // If not good status
  4008. if ($active >= 0 && $arraytypes['active'] != $active) {
  4009. continue;
  4010. }
  4011. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  4012. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  4013. continue;
  4014. }
  4015. // We discard empty line if showempty is on because an empty line has already been output.
  4016. if ($empty && empty($arraytypes['code'])) {
  4017. continue;
  4018. }
  4019. if ($format == 0) {
  4020. $out .= '<option value="' . $id . '"';
  4021. } elseif ($format == 1) {
  4022. $out .= '<option value="' . $arraytypes['code'] . '"';
  4023. } elseif ($format == 2) {
  4024. $out .= '<option value="' . $arraytypes['code'] . '"';
  4025. } elseif ($format == 3) {
  4026. $out .= '<option value="' . $id . '"';
  4027. }
  4028. // Print attribute selected or not
  4029. if ($format == 1 || $format == 2) {
  4030. if ($selected == $arraytypes['code']) {
  4031. $out .= ' selected';
  4032. }
  4033. } else {
  4034. if ($selected == $id) {
  4035. $out .= ' selected';
  4036. }
  4037. }
  4038. $out .= '>';
  4039. $value = '';
  4040. if ($format == 0) {
  4041. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4042. } elseif ($format == 1) {
  4043. $value = $arraytypes['code'];
  4044. } elseif ($format == 2) {
  4045. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4046. } elseif ($format == 3) {
  4047. $value = $arraytypes['code'];
  4048. }
  4049. $out .= $value ? $value : '&nbsp;';
  4050. $out .= '</option>';
  4051. }
  4052. $out .= '</select>';
  4053. if ($user->admin && !$noadmininfo) {
  4054. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4055. }
  4056. $out .= ajax_combobox('select' . $htmlname);
  4057. if (empty($nooutput)) {
  4058. print $out;
  4059. } else {
  4060. return $out;
  4061. }
  4062. }
  4063. /**
  4064. * Selection HT or TTC
  4065. *
  4066. * @param string $selected Id pre-selectionne
  4067. * @param string $htmlname Nom de la zone select
  4068. * @param int $addjscombo Add js combo
  4069. * @return string Code of HTML select to chose tax or not
  4070. */
  4071. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  4072. {
  4073. global $langs;
  4074. $return = '<select class="flat maxwidth100" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  4075. $options = array(
  4076. 'HT' => $langs->trans("HT"),
  4077. 'TTC' => $langs->trans("TTC")
  4078. );
  4079. foreach ($options as $id => $value) {
  4080. if ($selected == $id) {
  4081. $return .= '<option value="' . $id . '" selected>' . $value;
  4082. } else {
  4083. $return .= '<option value="' . $id . '">' . $value;
  4084. }
  4085. $return .= '</option>';
  4086. }
  4087. $return .= '</select>';
  4088. if ($addjscombo) {
  4089. $return .= ajax_combobox('select_' . $htmlname);
  4090. }
  4091. return $return;
  4092. }
  4093. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4094. /**
  4095. * Load in cache list of transport mode
  4096. *
  4097. * @return int Nb of lines loaded, <0 if KO
  4098. */
  4099. public function load_cache_transport_mode()
  4100. {
  4101. // phpcs:enable
  4102. global $langs;
  4103. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  4104. if ($num > 0) {
  4105. return $num; // Cache already loaded
  4106. }
  4107. dol_syslog(__METHOD__, LOG_DEBUG);
  4108. $this->cache_transport_mode = array();
  4109. $sql = "SELECT rowid, code, label, active";
  4110. $sql .= " FROM " . $this->db->prefix() . "c_transport_mode";
  4111. $sql .= " WHERE entity IN (" . getEntity('c_transport_mode') . ")";
  4112. $resql = $this->db->query($sql);
  4113. if ($resql) {
  4114. $num = $this->db->num_rows($resql);
  4115. $i = 0;
  4116. while ($i < $num) {
  4117. $obj = $this->db->fetch_object($resql);
  4118. // If traduction exist, we use it else we take the default label
  4119. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  4120. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  4121. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  4122. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  4123. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  4124. $i++;
  4125. }
  4126. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  4127. return $num;
  4128. } else {
  4129. dol_print_error($this->db);
  4130. return -1;
  4131. }
  4132. }
  4133. /**
  4134. * Return list of transport mode for intracomm report
  4135. *
  4136. * @param string $selected Id of the transport mode pre-selected
  4137. * @param string $htmlname Name of the select field
  4138. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  4139. * @param int $empty 1=can be empty, 0 else
  4140. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  4141. * @param int $maxlength Max length of label
  4142. * @param int $active Active or not, -1 = all
  4143. * @param string $morecss Add more CSS on select tag
  4144. * @return void
  4145. */
  4146. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  4147. {
  4148. global $langs, $user;
  4149. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $format, LOG_DEBUG);
  4150. $this->load_cache_transport_mode();
  4151. print '<select id="select' . $htmlname . '" class="flat selectmodetransport' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  4152. if ($empty) {
  4153. print '<option value="">&nbsp;</option>';
  4154. }
  4155. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  4156. // If not good status
  4157. if ($active >= 0 && $arraytypes['active'] != $active) {
  4158. continue;
  4159. }
  4160. // We discard empty line if showempty is on because an empty line has already been output.
  4161. if ($empty && empty($arraytypes['code'])) {
  4162. continue;
  4163. }
  4164. if ($format == 0) {
  4165. print '<option value="' . $id . '"';
  4166. } elseif ($format == 1) {
  4167. print '<option value="' . $arraytypes['code'] . '"';
  4168. } elseif ($format == 2) {
  4169. print '<option value="' . $arraytypes['code'] . '"';
  4170. } elseif ($format == 3) {
  4171. print '<option value="' . $id . '"';
  4172. }
  4173. // If text is selected, we compare with code, else with id
  4174. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  4175. print ' selected';
  4176. } elseif ($selected == $id) {
  4177. print ' selected';
  4178. }
  4179. print '>';
  4180. $value = '';
  4181. if ($format == 0) {
  4182. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4183. } elseif ($format == 1) {
  4184. $value = $arraytypes['code'];
  4185. } elseif ($format == 2) {
  4186. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4187. } elseif ($format == 3) {
  4188. $value = $arraytypes['code'];
  4189. }
  4190. print $value ? $value : '&nbsp;';
  4191. print '</option>';
  4192. }
  4193. print '</select>';
  4194. if ($user->admin && !$noadmininfo) {
  4195. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4196. }
  4197. }
  4198. /**
  4199. * Return a HTML select list of shipping mode
  4200. *
  4201. * @param string $selected Id shipping mode pre-selected
  4202. * @param string $htmlname Name of select zone
  4203. * @param string $filtre To filter list. This parameter must not come from input of users
  4204. * @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.
  4205. * @param string $moreattrib To add more attribute on select
  4206. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  4207. * @param string $morecss More CSS
  4208. * @return void
  4209. */
  4210. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  4211. {
  4212. global $langs, $user;
  4213. $langs->load("admin");
  4214. $langs->load("deliveries");
  4215. $sql = "SELECT rowid, code, libelle as label";
  4216. $sql .= " FROM " . $this->db->prefix() . "c_shipment_mode";
  4217. $sql .= " WHERE active > 0";
  4218. if ($filtre) {
  4219. $sql .= " AND " . $filtre;
  4220. }
  4221. $sql .= " ORDER BY libelle ASC";
  4222. dol_syslog(get_class($this) . "::selectShippingMode", LOG_DEBUG);
  4223. $result = $this->db->query($sql);
  4224. if ($result) {
  4225. $num = $this->db->num_rows($result);
  4226. $i = 0;
  4227. if ($num) {
  4228. print '<select id="select' . $htmlname . '" class="flat selectshippingmethod' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4229. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4230. print '<option value="-1">&nbsp;</option>';
  4231. }
  4232. while ($i < $num) {
  4233. $obj = $this->db->fetch_object($result);
  4234. if ($selected == $obj->rowid) {
  4235. print '<option value="' . $obj->rowid . '" selected>';
  4236. } else {
  4237. print '<option value="' . $obj->rowid . '">';
  4238. }
  4239. print ($langs->trans("SendingMethod" . strtoupper($obj->code)) != "SendingMethod" . strtoupper($obj->code)) ? $langs->trans("SendingMethod" . strtoupper($obj->code)) : $obj->label;
  4240. print '</option>';
  4241. $i++;
  4242. }
  4243. print "</select>";
  4244. if ($user->admin && empty($noinfoadmin)) {
  4245. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4246. }
  4247. print ajax_combobox('select' . $htmlname);
  4248. } else {
  4249. print $langs->trans("NoShippingMethodDefined");
  4250. }
  4251. } else {
  4252. dol_print_error($this->db);
  4253. }
  4254. }
  4255. /**
  4256. * Display form to select shipping mode
  4257. *
  4258. * @param string $page Page
  4259. * @param string $selected Id of shipping mode
  4260. * @param string $htmlname Name of select html field
  4261. * @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.
  4262. * @return void
  4263. */
  4264. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  4265. {
  4266. global $langs;
  4267. $langs->load("deliveries");
  4268. if ($htmlname != "none") {
  4269. print '<form method="POST" action="' . $page . '">';
  4270. print '<input type="hidden" name="action" value="setshippingmethod">';
  4271. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4272. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  4273. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  4274. print '</form>';
  4275. } else {
  4276. if ($selected) {
  4277. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  4278. print $langs->trans("SendingMethod" . strtoupper($code));
  4279. } else {
  4280. print "&nbsp;";
  4281. }
  4282. }
  4283. }
  4284. /**
  4285. * Creates HTML last in cycle situation invoices selector
  4286. *
  4287. * @param string $selected Preselected ID
  4288. * @param int $socid Company ID
  4289. *
  4290. * @return string HTML select
  4291. */
  4292. public function selectSituationInvoices($selected = '', $socid = 0)
  4293. {
  4294. global $langs;
  4295. $langs->load('bills');
  4296. $opt = '<option value="" selected></option>';
  4297. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4298. $sql .= ' FROM ' . $this->db->prefix() . 'facture';
  4299. $sql .= ' WHERE entity IN (' . getEntity('invoice') . ')';
  4300. $sql .= ' AND situation_counter >= 1';
  4301. $sql .= ' AND fk_soc = ' . (int) $socid;
  4302. $sql .= ' AND type <> 2';
  4303. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4304. $resql = $this->db->query($sql);
  4305. if ($resql && $this->db->num_rows($resql) > 0) {
  4306. // Last seen cycle
  4307. $ref = 0;
  4308. while ($obj = $this->db->fetch_object($resql)) {
  4309. //Same cycle ?
  4310. if ($obj->situation_cycle_ref != $ref) {
  4311. // Just seen this cycle
  4312. $ref = $obj->situation_cycle_ref;
  4313. //not final ?
  4314. if ($obj->situation_final != 1) {
  4315. //Not prov?
  4316. if (substr($obj->ref, 1, 4) != 'PROV') {
  4317. if ($selected == $obj->rowid) {
  4318. $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
  4319. } else {
  4320. $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
  4321. }
  4322. }
  4323. }
  4324. }
  4325. }
  4326. } else {
  4327. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  4328. }
  4329. if ($opt == '<option value ="" selected></option>') {
  4330. $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
  4331. }
  4332. return $opt;
  4333. }
  4334. /**
  4335. * Creates HTML units selector (code => label)
  4336. *
  4337. * @param string $selected Preselected Unit ID
  4338. * @param string $htmlname Select name
  4339. * @param int $showempty Add a nempty line
  4340. * @param string $unit_type Restrict to one given unit type
  4341. * @return string HTML select
  4342. */
  4343. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4344. {
  4345. global $langs;
  4346. $langs->load('products');
  4347. $return = '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
  4348. $sql = "SELECT rowid, label, code FROM " . $this->db->prefix() . "c_units";
  4349. $sql .= ' WHERE active > 0';
  4350. if (!empty($unit_type)) {
  4351. $sql .= " AND unit_type = '" . $this->db->escape($unit_type) . "'";
  4352. }
  4353. $sql .= " ORDER BY sortorder";
  4354. $resql = $this->db->query($sql);
  4355. if ($resql && $this->db->num_rows($resql) > 0) {
  4356. if ($showempty) {
  4357. $return .= '<option value="none"></option>';
  4358. }
  4359. while ($res = $this->db->fetch_object($resql)) {
  4360. $unitLabel = $res->label;
  4361. if (!empty($langs->tab_translate['unit' . $res->code])) { // check if Translation is available before
  4362. $unitLabel = $langs->trans('unit' . $res->code) != $res->label ? $langs->trans('unit' . $res->code) : $res->label;
  4363. }
  4364. if ($selected == $res->rowid) {
  4365. $return .= '<option value="' . $res->rowid . '" selected>' . $unitLabel . '</option>';
  4366. } else {
  4367. $return .= '<option value="' . $res->rowid . '">' . $unitLabel . '</option>';
  4368. }
  4369. }
  4370. $return .= '</select>';
  4371. }
  4372. return $return;
  4373. }
  4374. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4375. /**
  4376. * Return a HTML select list of bank accounts
  4377. *
  4378. * @param string $selected Id account pre-selected
  4379. * @param string $htmlname Name of select zone
  4380. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4381. * @param string $filtre To filter list. This parameter must not come from input of users
  4382. * @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.
  4383. * @param string $moreattrib To add more attribute on select
  4384. * @param int $showcurrency Show currency in label
  4385. * @param string $morecss More CSS
  4386. * @param int $nooutput 1=Return string, do not send to output
  4387. * @return int Return integer <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4388. */
  4389. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4390. {
  4391. // phpcs:enable
  4392. global $langs, $conf;
  4393. $out = '';
  4394. $langs->load("admin");
  4395. $num = 0;
  4396. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4397. $sql .= " FROM " . $this->db->prefix() . "bank_account";
  4398. $sql .= " WHERE entity IN (" . getEntity('bank_account') . ")";
  4399. if ($status != 2) {
  4400. $sql .= " AND clos = " . (int) $status;
  4401. }
  4402. if ($filtre) {
  4403. $sql .= " AND " . $filtre;
  4404. }
  4405. $sql .= " ORDER BY label";
  4406. dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
  4407. $result = $this->db->query($sql);
  4408. if ($result) {
  4409. $num = $this->db->num_rows($result);
  4410. $i = 0;
  4411. if ($num) {
  4412. $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4413. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4414. $out .= '<option value="-1">&nbsp;</option>';
  4415. }
  4416. while ($i < $num) {
  4417. $obj = $this->db->fetch_object($result);
  4418. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4419. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" selected>';
  4420. } else {
  4421. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '">';
  4422. }
  4423. $out .= trim($obj->label);
  4424. if ($showcurrency) {
  4425. $out .= ' (' . $obj->currency_code . ')';
  4426. }
  4427. if ($status == 2 && $obj->status == 1) {
  4428. $out .= ' (' . $langs->trans("Closed") . ')';
  4429. }
  4430. $out .= '</option>';
  4431. $i++;
  4432. }
  4433. $out .= "</select>";
  4434. $out .= ajax_combobox('select' . $htmlname);
  4435. } else {
  4436. if ($status == 0) {
  4437. $out .= '<span class="opacitymedium">' . $langs->trans("NoActiveBankAccountDefined") . '</span>';
  4438. } else {
  4439. $out .= '<span class="opacitymedium">' . $langs->trans("NoBankAccountFound") . '</span>';
  4440. }
  4441. }
  4442. } else {
  4443. dol_print_error($this->db);
  4444. }
  4445. // Output or return
  4446. if (empty($nooutput)) {
  4447. print $out;
  4448. } else {
  4449. return $out;
  4450. }
  4451. return $num;
  4452. }
  4453. /**
  4454. * Return a HTML select list of establishment
  4455. *
  4456. * @param string $selected Id establishment pre-selected
  4457. * @param string $htmlname Name of select zone
  4458. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4459. * @param string $filtre To filter list. This parameter must not come from input of users
  4460. * @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.
  4461. * @param string $moreattrib To add more attribute on select
  4462. * @return int Return integer <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4463. */
  4464. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4465. {
  4466. global $langs, $conf;
  4467. $langs->load("admin");
  4468. $num = 0;
  4469. $sql = "SELECT rowid, name, fk_country, status, entity";
  4470. $sql .= " FROM " . $this->db->prefix() . "establishment";
  4471. $sql .= " WHERE 1=1";
  4472. if ($status != 2) {
  4473. $sql .= " AND status = " . (int) $status;
  4474. }
  4475. if ($filtre) {
  4476. $sql .= " AND " . $filtre;
  4477. }
  4478. $sql .= " ORDER BY name";
  4479. dol_syslog(get_class($this) . "::select_establishment", LOG_DEBUG);
  4480. $result = $this->db->query($sql);
  4481. if ($result) {
  4482. $num = $this->db->num_rows($result);
  4483. $i = 0;
  4484. if ($num) {
  4485. print '<select id="select' . $htmlname . '" class="flat selectestablishment" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4486. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4487. print '<option value="-1">&nbsp;</option>';
  4488. }
  4489. while ($i < $num) {
  4490. $obj = $this->db->fetch_object($result);
  4491. if ($selected == $obj->rowid) {
  4492. print '<option value="' . $obj->rowid . '" selected>';
  4493. } else {
  4494. print '<option value="' . $obj->rowid . '">';
  4495. }
  4496. print trim($obj->name);
  4497. if ($status == 2 && $obj->status == 1) {
  4498. print ' (' . $langs->trans("Closed") . ')';
  4499. }
  4500. print '</option>';
  4501. $i++;
  4502. }
  4503. print "</select>";
  4504. } else {
  4505. if ($status == 0) {
  4506. print '<span class="opacitymedium">' . $langs->trans("NoActiveEstablishmentDefined") . '</span>';
  4507. } else {
  4508. print '<span class="opacitymedium">' . $langs->trans("NoEstablishmentFound") . '</span>';
  4509. }
  4510. }
  4511. return $num;
  4512. } else {
  4513. dol_print_error($this->db);
  4514. return -1;
  4515. }
  4516. }
  4517. /**
  4518. * Display form to select bank account
  4519. *
  4520. * @param string $page Page
  4521. * @param string $selected Id of bank account
  4522. * @param string $htmlname Name of select html field
  4523. * @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.
  4524. * @return void
  4525. */
  4526. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4527. {
  4528. global $langs;
  4529. if ($htmlname != "none") {
  4530. print '<form method="POST" action="' . $page . '">';
  4531. print '<input type="hidden" name="action" value="setbankaccount">';
  4532. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4533. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4534. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4535. if ($nbaccountfound > 0) {
  4536. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  4537. }
  4538. print '</form>';
  4539. } else {
  4540. $langs->load('banks');
  4541. if ($selected) {
  4542. require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
  4543. $bankstatic = new Account($this->db);
  4544. $result = $bankstatic->fetch($selected);
  4545. if ($result) {
  4546. print $bankstatic->getNomUrl(1);
  4547. }
  4548. } else {
  4549. print "&nbsp;";
  4550. }
  4551. }
  4552. }
  4553. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4554. /**
  4555. * Return list of categories having choosed type
  4556. *
  4557. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4558. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4559. * @param string $htmlname HTML field name
  4560. * @param int $maxlength Maximum length for labels
  4561. * @param int|string|array $markafterid Keep only or removed all categories including the leaf $markafterid in category tree (exclude) or Keep only of category is inside the leaf starting with this id.
  4562. * $markafterid can be an :
  4563. * - int (id of category)
  4564. * - string (categories ids seprated by comma)
  4565. * - array (list of categories ids)
  4566. * @param int $outputmode 0=HTML select string, 1=Array with full label only, 2=Array extended, 3=Array with full picto + label
  4567. * @param int $include [=0] Removed or 1=Keep only
  4568. * @param string $morecss More CSS
  4569. * @return string|array String list or Array of categories
  4570. * @see select_categories()
  4571. */
  4572. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4573. {
  4574. // phpcs:enable
  4575. global $conf, $langs;
  4576. $langs->load("categories");
  4577. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  4578. // For backward compatibility
  4579. if (is_numeric($type)) {
  4580. dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4581. }
  4582. if ($type === Categorie::TYPE_BANK_LINE) {
  4583. // TODO Move this into common category feature
  4584. $cate_arbo = array();
  4585. $sql = "SELECT c.label, c.rowid";
  4586. $sql .= " FROM " . $this->db->prefix() . "bank_categ as c";
  4587. $sql .= " WHERE entity = " . $conf->entity;
  4588. $sql .= " ORDER BY c.label";
  4589. $result = $this->db->query($sql);
  4590. if ($result) {
  4591. $num = $this->db->num_rows($result);
  4592. $i = 0;
  4593. while ($i < $num) {
  4594. $objp = $this->db->fetch_object($result);
  4595. if ($objp) {
  4596. $cate_arbo[$objp->rowid] = array('id' => $objp->rowid, 'fulllabel' => $objp->label, 'color' => '', 'picto' => 'category');
  4597. }
  4598. $i++;
  4599. }
  4600. $this->db->free($result);
  4601. } else {
  4602. dol_print_error($this->db);
  4603. }
  4604. } else {
  4605. $cat = new Categorie($this->db);
  4606. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4607. }
  4608. $outarray = array();
  4609. $outarrayrichhtml = array();
  4610. $output = '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  4611. if (is_array($cate_arbo)) {
  4612. if (!count($cate_arbo)) {
  4613. $output .= '<option value="-1" disabled>' . $langs->trans("NoCategoriesDefined") . '</option>';
  4614. } else {
  4615. $output .= '<option value="-1">&nbsp;</option>';
  4616. foreach ($cate_arbo as $key => $value) {
  4617. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4618. $add = 'selected ';
  4619. } else {
  4620. $add = '';
  4621. }
  4622. $labeltoshow = img_picto('', 'category', 'class="pictofixedwidth" style="color: #' . $cate_arbo[$key]['color'] . '"');
  4623. $labeltoshow .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
  4624. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4625. $outarrayrichhtml[$cate_arbo[$key]['id']] = $labeltoshow;
  4626. $output .= '<option ' . $add . 'value="' . $cate_arbo[$key]['id'] . '"';
  4627. $output .= ' data-html="' . dol_escape_htmltag($labeltoshow) . '"';
  4628. $output .= '>';
  4629. $output .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
  4630. $output .= '</option>';
  4631. }
  4632. }
  4633. }
  4634. $output .= '</select>';
  4635. $output .= "\n";
  4636. if ($outputmode == 2) {
  4637. return $cate_arbo;
  4638. } elseif ($outputmode == 1) {
  4639. return $outarray;
  4640. } elseif ($outputmode == 3) {
  4641. return $outarrayrichhtml;
  4642. }
  4643. return $output;
  4644. }
  4645. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4646. /**
  4647. * Show a confirmation HTML form or AJAX popup
  4648. *
  4649. * @param string $page Url of page to call if confirmation is OK
  4650. * @param string $title Title
  4651. * @param string $question Question
  4652. * @param string $action Action
  4653. * @param array $formquestion An array with forms complementary inputs
  4654. * @param string $selectedchoice "" or "no" or "yes"
  4655. * @param int|string $useajax 0=No, 1=Yes use Ajax to show the popup, 2=Yes and also submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4656. * @param int $height Force height of box
  4657. * @param int $width Force width of box
  4658. * @return void
  4659. * @deprecated
  4660. * @see formconfirm()
  4661. */
  4662. public function form_confirm($page, $title, $question, $action, $formquestion = array(), $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4663. {
  4664. // phpcs:enable
  4665. dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4666. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4667. }
  4668. /**
  4669. * Show a confirmation HTML form or AJAX popup.
  4670. * Easiest way to use this is with useajax=1.
  4671. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4672. * just after calling this method. For example:
  4673. * print '<script nonce="'.getNonce().'" type="text/javascript">'."\n";
  4674. * print 'jQuery(document).ready(function() {'."\n";
  4675. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4676. * print '});'."\n";
  4677. * print '</script>'."\n";
  4678. *
  4679. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4680. * @param string $title Title
  4681. * @param string $question Question
  4682. * @param string $action Action
  4683. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...'))
  4684. * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'datetime', 'select', 'multiselect', 'morecss',
  4685. * 'other', 'onecolumn' or 'hidden'...
  4686. * @param int|string $selectedchoice '' or 'no', or 'yes' or '1', 1, '0' or 0
  4687. * @param int|string $useajax 0=No, 1=Yes use Ajax to show the popup, 2=Yes and also submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4688. * @param int|string $height Force height of box (0 = auto)
  4689. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4690. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4691. * @param string $labelbuttonyes Label for Yes
  4692. * @param string $labelbuttonno Label for No
  4693. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4694. */
  4695. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
  4696. {
  4697. global $langs, $conf;
  4698. $more = '<!-- formconfirm - before call, page=' . dol_escape_htmltag($page) . ' -->';
  4699. $formconfirm = '';
  4700. $inputok = array();
  4701. $inputko = array();
  4702. // Clean parameters
  4703. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4704. if ($conf->browser->layout == 'phone') {
  4705. $width = '95%';
  4706. }
  4707. // Set height automatically if not defined
  4708. if (empty($height)) {
  4709. $height = 220;
  4710. if (is_array($formquestion) && count($formquestion) > 2) {
  4711. $height += ((count($formquestion) - 2) * 24);
  4712. }
  4713. }
  4714. if (is_array($formquestion) && !empty($formquestion)) {
  4715. // First add hidden fields and value
  4716. foreach ($formquestion as $key => $input) {
  4717. if (is_array($input) && !empty($input)) {
  4718. if ($input['type'] == 'hidden') {
  4719. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4720. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4721. $more .= '<input type="hidden" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '" value="' . dol_escape_htmltag($input['value']) . '" class="' . $morecss . '"' . $moreattr . '>' . "\n";
  4722. }
  4723. }
  4724. }
  4725. // Now add questions
  4726. $moreonecolumn = '';
  4727. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">' . "\n";
  4728. foreach ($formquestion as $key => $input) {
  4729. if (is_array($input) && !empty($input)) {
  4730. $size = (!empty($input['size']) ? ' size="' . $input['size'] . '"' : ''); // deprecated. Use morecss instead.
  4731. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4732. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4733. if ($input['type'] == 'text') {
  4734. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div><div class="tagtd"><input type="text" class="flat' . $morecss . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $size . ' value="' . (empty($input['value']) ? '' : $input['value']) . '"' . $moreattr . ' /></div></div>' . "\n";
  4735. } elseif ($input['type'] == 'password') {
  4736. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div><div class="tagtd"><input type="password" class="flat' . $morecss . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $size . ' value="' . (empty($input['value']) ? '' : $input['value']) . '"' . $moreattr . ' /></div></div>' . "\n";
  4737. } elseif ($input['type'] == 'textarea') {
  4738. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4739. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4740. $more .= $input['value'];
  4741. $more .= '</textarea>';
  4742. $more .= '</div></div>'."\n";*/
  4743. $moreonecolumn .= '<div class="margintoponly">';
  4744. $moreonecolumn .= $input['label'] . '<br>';
  4745. $moreonecolumn .= '<textarea name="' . dol_escape_htmltag($input['name']) . '" id="' . dol_escape_htmltag($input['name']) . '" class="' . $morecss . '"' . $moreattr . '>';
  4746. $moreonecolumn .= $input['value'];
  4747. $moreonecolumn .= '</textarea>';
  4748. $moreonecolumn .= '</div>';
  4749. } elseif (in_array($input['type'], ['select', 'multiselect'])) {
  4750. if (empty($morecss)) {
  4751. $morecss = 'minwidth100';
  4752. }
  4753. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4754. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4755. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4756. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4757. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4758. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4759. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4760. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">';
  4761. if (!empty($input['label'])) {
  4762. $more .= $input['label'] . '</div><div class="tagtd left">';
  4763. }
  4764. if ($input['type'] == 'select') {
  4765. $more .= $this->selectarray($input['name'], $input['values'], isset($input['default']) ? $input['default'] : '-1', $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4766. } else {
  4767. $more .= $this->multiselectarray($input['name'], $input['values'], is_array($input['default']) ? $input['default'] : [$input['default']], $key_in_label, $value_as_key, $morecss, $translate, $maxlen, $moreattr);
  4768. }
  4769. $more .= '</div></div>' . "\n";
  4770. } elseif ($input['type'] == 'checkbox') {
  4771. $more .= '<div class="tagtr">';
  4772. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '"><label for="' . dol_escape_htmltag($input['name']) . '">' . $input['label'] . '</label></div><div class="tagtd">';
  4773. $more .= '<input type="checkbox" class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $moreattr;
  4774. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4775. $more .= ' checked';
  4776. }
  4777. if (is_bool($input['value']) && $input['value']) {
  4778. $more .= ' checked';
  4779. }
  4780. if (isset($input['disabled'])) {
  4781. $more .= ' disabled';
  4782. }
  4783. $more .= ' /></div>';
  4784. $more .= '</div>' . "\n";
  4785. } elseif ($input['type'] == 'radio') {
  4786. $i = 0;
  4787. foreach ($input['values'] as $selkey => $selval) {
  4788. $more .= '<div class="tagtr">';
  4789. if (isset($input['label'])) {
  4790. if ($i == 0) {
  4791. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? ' tdtop' : (' tdtop ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4792. } else {
  4793. $more .= '<div clas="tagtd' . (empty($input['tdclass']) ? '' : (' "' . $input['tdclass'])) . '">&nbsp;</div>';
  4794. }
  4795. }
  4796. $more .= '<div class="tagtd' . ($i == 0 ? ' tdtop' : '') . '"><input type="radio" class="flat' . $morecss . '" id="' . dol_escape_htmltag($input['name'] . $selkey) . '" name="' . dol_escape_htmltag($input['name']) . '" value="' . $selkey . '"' . $moreattr;
  4797. if (!empty($input['disabled'])) {
  4798. $more .= ' disabled';
  4799. }
  4800. if (isset($input['default']) && $input['default'] === $selkey) {
  4801. $more .= ' checked="checked"';
  4802. }
  4803. $more .= ' /> ';
  4804. $more .= '<label for="' . dol_escape_htmltag($input['name'] . $selkey) . '" class="valignmiddle">' . $selval . '</label>';
  4805. $more .= '</div></div>' . "\n";
  4806. $i++;
  4807. }
  4808. } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
  4809. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4810. $more .= '<div class="tagtd">';
  4811. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4812. $h = $m = 0;
  4813. if ($input['type'] == 'datetime') {
  4814. $h = isset($input['hours']) ? $input['hours'] : 1;
  4815. $m = isset($input['minutes']) ? $input['minutes'] : 1;
  4816. }
  4817. $more .= $this->selectDate($input['value'], $input['name'], $h, $m, 0, '', 1, $addnowlink);
  4818. $more .= '</div></div>'."\n";
  4819. $formquestion[] = array('name'=>$input['name'].'day');
  4820. $formquestion[] = array('name'=>$input['name'].'month');
  4821. $formquestion[] = array('name'=>$input['name'].'year');
  4822. $formquestion[] = array('name'=>$input['name'].'hour');
  4823. $formquestion[] = array('name'=>$input['name'].'min');
  4824. } elseif ($input['type'] == 'other') { // can be 1 column or 2 depending if label is set or not
  4825. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4826. if (!empty($input['label'])) {
  4827. $more .= $input['label'] . '</div><div class="tagtd">';
  4828. }
  4829. $more .= $input['value'];
  4830. $more .= '</div></div>' . "\n";
  4831. } elseif ($input['type'] == 'onecolumn') {
  4832. $moreonecolumn .= '<div class="margintoponly">';
  4833. $moreonecolumn .= $input['value'];
  4834. $moreonecolumn .= '</div>' . "\n";
  4835. } elseif ($input['type'] == 'hidden') {
  4836. // Do nothing more, already added by a previous loop
  4837. } elseif ($input['type'] == 'separator') {
  4838. $more .= '<br>';
  4839. } else {
  4840. $more .= 'Error type ' . $input['type'] . ' for the confirm box is not a supported type';
  4841. }
  4842. }
  4843. }
  4844. $more .= '</div>' . "\n";
  4845. $more .= $moreonecolumn;
  4846. }
  4847. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4848. // 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
  4849. // See page product/card.php for example
  4850. if (!empty($conf->dol_use_jmobile)) {
  4851. $useajax = 0;
  4852. }
  4853. if (empty($conf->use_javascript_ajax)) {
  4854. $useajax = 0;
  4855. }
  4856. if ($useajax) {
  4857. $autoOpen = true;
  4858. $dialogconfirm = 'dialog-confirm';
  4859. $button = '';
  4860. if (!is_numeric($useajax)) {
  4861. $button = $useajax;
  4862. $useajax = 1;
  4863. $autoOpen = false;
  4864. $dialogconfirm .= '-' . $button;
  4865. }
  4866. $pageyes = $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=yes';
  4867. $pageno = ($useajax == 2 ? $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=no' : '');
  4868. // Add input fields into list of fields to read during submit (inputok and inputko)
  4869. if (is_array($formquestion)) {
  4870. foreach ($formquestion as $key => $input) {
  4871. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4872. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4873. if (is_array($input) && isset($input['name'])) {
  4874. if (strpos($input['name'], ',') > 0) {
  4875. $inputok = array_merge($inputok, explode(',', $input['name']));
  4876. } else {
  4877. array_push($inputok, $input['name']);
  4878. }
  4879. }
  4880. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4881. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4882. array_push($inputko, $input['name']);
  4883. }
  4884. }
  4885. }
  4886. // Show JQuery confirm box.
  4887. $formconfirm .= '<div id="' . $dialogconfirm . '" title="' . dol_escape_htmltag($title) . '" style="display: none;">';
  4888. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4889. $formconfirm .= '<div class="confirmtext">' . $formquestion['text'] . '</div>' . "\n";
  4890. }
  4891. if (!empty($more)) {
  4892. $formconfirm .= '<div class="confirmquestions">' . $more . '</div>' . "\n";
  4893. }
  4894. $formconfirm .= ($question ? '<div class="confirmmessage">' . img_help('', '') . ' ' . $question . '</div>' : '');
  4895. $formconfirm .= '</div>' . "\n";
  4896. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=" . $page . " -->\n";
  4897. $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
  4898. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4899. $formconfirm .= 'jQuery(document).ready(function() {
  4900. $(function() {
  4901. $( "#' . $dialogconfirm . '" ).dialog(
  4902. {
  4903. autoOpen: ' . ($autoOpen ? "true" : "false") . ',';
  4904. if ($newselectedchoice == 'no') {
  4905. $formconfirm .= '
  4906. open: function() {
  4907. $(this).parent().find("button.ui-button:eq(2)").focus();
  4908. },';
  4909. }
  4910. $jsforcursor = '';
  4911. if ($useajax == 1) {
  4912. $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor' . "\n";
  4913. $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");' . "\n";
  4914. }
  4915. $postconfirmas = 'GET';
  4916. $formconfirm .= '
  4917. resizable: false,
  4918. height: "' . $height . '",
  4919. width: "' . $width . '",
  4920. modal: true,
  4921. closeOnEscape: false,
  4922. buttons: {
  4923. "' . dol_escape_js($langs->transnoentities($labelbuttonyes)) . '": function() {
  4924. var options = "token=' . urlencode(newToken()) . '";
  4925. var inputok = ' . json_encode($inputok) . '; /* List of fields into form */
  4926. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4927. var pageyes = "' . dol_escape_js(!empty($pageyes) ? $pageyes : '') . '";
  4928. if (inputok.length > 0) {
  4929. $.each(inputok, function(i, inputname) {
  4930. var more = "";
  4931. var inputvalue;
  4932. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4933. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4934. } else {
  4935. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4936. inputvalue = $("#" + inputname + more).val();
  4937. }
  4938. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4939. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4940. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4941. });
  4942. }
  4943. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
  4944. if (pageyes.length > 0) {';
  4945. if ($postconfirmas == 'GET') {
  4946. $formconfirm .= 'location.href = urljump;';
  4947. } else {
  4948. $formconfirm .= $jsforcursor;
  4949. $formconfirm .= 'var post = $.post(
  4950. pageyes,
  4951. options,
  4952. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4953. );';
  4954. }
  4955. $formconfirm .= '
  4956. console.log("after post ok");
  4957. }
  4958. $(this).dialog("close");
  4959. },
  4960. "' . dol_escape_js($langs->transnoentities($labelbuttonno)) . '": function() {
  4961. var options = "token=' . urlencode(newToken()) . '";
  4962. var inputko = ' . json_encode($inputko) . '; /* List of fields into form */
  4963. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4964. var pageno="' . dol_escape_js(!empty($pageno) ? $pageno : '') . '";
  4965. if (inputko.length > 0) {
  4966. $.each(inputko, function(i, inputname) {
  4967. var more = "";
  4968. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4969. var inputvalue = $("#" + inputname + more).val();
  4970. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4971. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4972. });
  4973. }
  4974. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
  4975. //alert(urljump);
  4976. if (pageno.length > 0) {';
  4977. if ($postconfirmas == 'GET') {
  4978. $formconfirm .= 'location.href = urljump;';
  4979. } else {
  4980. $formconfirm .= $jsforcursor;
  4981. $formconfirm .= 'var post = $.post(
  4982. pageno,
  4983. options,
  4984. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4985. );';
  4986. }
  4987. $formconfirm .= '
  4988. console.log("after post ko");
  4989. }
  4990. $(this).dialog("close");
  4991. }
  4992. }
  4993. }
  4994. );
  4995. var button = "' . $button . '";
  4996. if (button.length > 0) {
  4997. $( "#" + button ).click(function() {
  4998. $("#' . $dialogconfirm . '").dialog("open");
  4999. });
  5000. }
  5001. });
  5002. });
  5003. </script>';
  5004. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  5005. } else {
  5006. $formconfirm .= "\n<!-- begin formconfirm page=" . dol_escape_htmltag($page) . " -->\n";
  5007. if (empty($disableformtag)) {
  5008. $formconfirm .= '<form method="POST" action="' . $page . '" class="notoptoleftroright">' . "\n";
  5009. }
  5010. $formconfirm .= '<input type="hidden" name="action" value="' . $action . '">' . "\n";
  5011. $formconfirm .= '<input type="hidden" name="token" value="' . newToken() . '">' . "\n";
  5012. $formconfirm .= '<table class="valid centpercent">' . "\n";
  5013. // Line title
  5014. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  5015. $formconfirm .= img_picto('', 'pictoconfirm') . ' ' . $title;
  5016. $formconfirm .= '</td></tr>' . "\n";
  5017. // Line text
  5018. if (is_array($formquestion) && !empty($formquestion['text'])) {
  5019. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . $formquestion['text'] . '</td></tr>' . "\n";
  5020. }
  5021. // Line form fields
  5022. if ($more) {
  5023. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . "\n";
  5024. $formconfirm .= $more;
  5025. $formconfirm .= '</td></tr>' . "\n";
  5026. }
  5027. // Line with question
  5028. $formconfirm .= '<tr class="valid">';
  5029. $formconfirm .= '<td class="valid">' . $question . '</td>';
  5030. $formconfirm .= '<td class="valid center">';
  5031. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
  5032. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="' . $langs->trans("Validate") . '">';
  5033. $formconfirm .= '</td>';
  5034. $formconfirm .= '</tr>' . "\n";
  5035. $formconfirm .= '</table>' . "\n";
  5036. if (empty($disableformtag)) {
  5037. $formconfirm .= "</form>\n";
  5038. }
  5039. $formconfirm .= '<br>';
  5040. if (!empty($conf->use_javascript_ajax)) {
  5041. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  5042. $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
  5043. $formconfirm .= '
  5044. $(document).ready(function () {
  5045. $(".confirmvalidatebutton").on("click", function() {
  5046. console.log("We click on button confirmvalidatebutton");
  5047. $(this).attr("disabled", "disabled");
  5048. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  5049. //console.log($(this).closest("form"));
  5050. $(this).closest("form").submit();
  5051. });
  5052. });
  5053. ';
  5054. $formconfirm .= '</script>' . "\n";
  5055. }
  5056. $formconfirm .= "<!-- end formconfirm -->\n";
  5057. }
  5058. return $formconfirm;
  5059. }
  5060. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5061. /**
  5062. * Show a form to select a project
  5063. *
  5064. * @param int $page Page
  5065. * @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)
  5066. * @param string $selected Id pre-selected project
  5067. * @param string $htmlname Name of select field
  5068. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  5069. * @param int $maxlength Max length
  5070. * @param int $forcefocus Force focus on field (works with javascript only)
  5071. * @param int $nooutput No print is done. String is returned.
  5072. * @param string $textifnoproject Text to show if no project
  5073. * @param string $morecss More CSS
  5074. * @return string Return html content
  5075. */
  5076. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '')
  5077. {
  5078. // phpcs:enable
  5079. global $langs;
  5080. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  5081. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  5082. $out = '';
  5083. $formproject = new FormProjets($this->db);
  5084. $langs->load("project");
  5085. if ($htmlname != "none") {
  5086. $out .= '<form method="post" action="' . $page . '">';
  5087. $out .= '<input type="hidden" name="action" value="classin">';
  5088. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5089. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
  5090. $out .= '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5091. $out .= '</form>';
  5092. } else {
  5093. $out .= '<span class="project_head_block">';
  5094. if ($selected) {
  5095. $projet = new Project($this->db);
  5096. $projet->fetch($selected);
  5097. $out .= $projet->getNomUrl(0, '', 1);
  5098. } else {
  5099. $out .= '<span class="opacitymedium">' . $textifnoproject . '</span>';
  5100. }
  5101. $out .= '</span>';
  5102. }
  5103. if (empty($nooutput)) {
  5104. print $out;
  5105. return '';
  5106. }
  5107. return $out;
  5108. }
  5109. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5110. /**
  5111. * Show a form to select payment conditions
  5112. *
  5113. * @param int $page Page
  5114. * @param string $selected Id condition pre-selectionne
  5115. * @param string $htmlname Name of select html field
  5116. * @param int $addempty Add empty entry
  5117. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5118. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  5119. * @param int $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  5120. * 0 : use default deposit percentage from entry
  5121. * > 0 : force deposit percentage (for example, from company object)
  5122. * @param int $nooutput No print is done. String is returned.
  5123. * @return string HTML output or ''
  5124. */
  5125. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
  5126. {
  5127. // phpcs:enable
  5128. global $langs;
  5129. $out = '';
  5130. if ($htmlname != "none") {
  5131. $out .= '<form method="POST" action="' . $page . '">';
  5132. $out .= '<input type="hidden" name="action" value="setconditions">';
  5133. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5134. if ($type) {
  5135. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5136. }
  5137. $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  5138. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5139. $out .= '</form>';
  5140. } else {
  5141. if ($selected) {
  5142. $this->load_cache_conditions_paiements();
  5143. if (isset($this->cache_conditions_paiements[$selected])) {
  5144. $label = $this->cache_conditions_paiements[$selected]['label'];
  5145. if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  5146. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  5147. }
  5148. $out .= $label;
  5149. } else {
  5150. $langs->load('errors');
  5151. $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions');
  5152. }
  5153. } else {
  5154. $out .= '&nbsp;';
  5155. }
  5156. }
  5157. if (empty($nooutput)) {
  5158. print $out;
  5159. return '';
  5160. }
  5161. return $out;
  5162. }
  5163. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5164. /**
  5165. * Show a form to select a delivery delay
  5166. *
  5167. * @param int $page Page
  5168. * @param string $selected Id condition pre-selectionne
  5169. * @param string $htmlname Name of select html field
  5170. * @param int $addempty Add an empty entry
  5171. * @return void
  5172. */
  5173. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  5174. {
  5175. // phpcs:enable
  5176. global $langs;
  5177. if ($htmlname != "none") {
  5178. print '<form method="post" action="' . $page . '">';
  5179. print '<input type="hidden" name="action" value="setavailability">';
  5180. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5181. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  5182. print '<input type="submit" name="modify" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5183. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="' . $langs->trans("Cancel") . '">';
  5184. print '</form>';
  5185. } else {
  5186. if ($selected) {
  5187. $this->load_cache_availability();
  5188. print $this->cache_availability[$selected]['label'];
  5189. } else {
  5190. print "&nbsp;";
  5191. }
  5192. }
  5193. }
  5194. /**
  5195. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  5196. * List found into table c_input_reason loaded by loadCacheInputReason
  5197. *
  5198. * @param string $page Page
  5199. * @param string $selected Id condition pre-selectionne
  5200. * @param string $htmlname Name of select html field
  5201. * @param int $addempty Add empty entry
  5202. * @return void
  5203. */
  5204. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  5205. {
  5206. global $langs;
  5207. if ($htmlname != "none") {
  5208. print '<form method="post" action="' . $page . '">';
  5209. print '<input type="hidden" name="action" value="setdemandreason">';
  5210. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5211. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  5212. print '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5213. print '</form>';
  5214. } else {
  5215. if ($selected) {
  5216. $this->loadCacheInputReason();
  5217. foreach ($this->cache_demand_reason as $key => $val) {
  5218. if ($val['id'] == $selected) {
  5219. print $val['label'];
  5220. break;
  5221. }
  5222. }
  5223. } else {
  5224. print "&nbsp;";
  5225. }
  5226. }
  5227. }
  5228. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5229. /**
  5230. * Show a form + html select a date
  5231. *
  5232. * @param string $page Page
  5233. * @param string $selected Date preselected
  5234. * @param string $htmlname Html name of date input fields or 'none'
  5235. * @param int $displayhour Display hour selector
  5236. * @param int $displaymin Display minutes selector
  5237. * @param int $nooutput 1=No print output, return string
  5238. * @param string $type 'direct-debit' or 'bank-transfer'
  5239. * @return string
  5240. * @see selectDate()
  5241. */
  5242. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  5243. {
  5244. // phpcs:enable
  5245. global $langs;
  5246. $ret = '';
  5247. if ($htmlname != "none") {
  5248. $ret .= '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5249. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5250. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5251. if ($type) {
  5252. $ret .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5253. }
  5254. $ret .= '<table class="nobordernopadding">';
  5255. $ret .= '<tr><td>';
  5256. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form' . $htmlname, 1, 0);
  5257. $ret .= '</td>';
  5258. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5259. $ret .= '</tr></table></form>';
  5260. } else {
  5261. if ($displayhour) {
  5262. $ret .= dol_print_date($selected, 'dayhour');
  5263. } else {
  5264. $ret .= dol_print_date($selected, 'day');
  5265. }
  5266. }
  5267. if (empty($nooutput)) {
  5268. print $ret;
  5269. }
  5270. return $ret;
  5271. }
  5272. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5273. /**
  5274. * Show a select form to choose a user
  5275. *
  5276. * @param string $page Page
  5277. * @param string $selected Id of user preselected
  5278. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  5279. * @param array $exclude List of users id to exclude
  5280. * @param array $include List of users id to include
  5281. * @return void
  5282. */
  5283. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = array(), $include = array())
  5284. {
  5285. // phpcs:enable
  5286. global $langs;
  5287. if ($htmlname != "none") {
  5288. print '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5289. print '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5290. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5291. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  5292. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5293. print '</form>';
  5294. } else {
  5295. if ($selected) {
  5296. require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
  5297. $theuser = new User($this->db);
  5298. $theuser->fetch($selected);
  5299. print $theuser->getNomUrl(1);
  5300. } else {
  5301. print "&nbsp;";
  5302. }
  5303. }
  5304. }
  5305. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5306. /**
  5307. * Show form with payment mode
  5308. *
  5309. * @param string $page Page
  5310. * @param string $selected Id mode pre-selectionne
  5311. * @param string $htmlname Name of select html field
  5312. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  5313. * @param int $active Active or not, -1 = all
  5314. * @param int $addempty 1=Add empty entry
  5315. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5316. * @param int $nooutput 1=Return string, no output
  5317. * @return string HTML output or ''
  5318. */
  5319. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
  5320. {
  5321. // phpcs:enable
  5322. global $langs;
  5323. $out = '';
  5324. if ($htmlname != "none") {
  5325. $out .= '<form method="POST" action="' . $page . '">';
  5326. $out .= '<input type="hidden" name="action" value="setmode">';
  5327. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5328. if ($type) {
  5329. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5330. }
  5331. $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  5332. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5333. $out .= '</form>';
  5334. } else {
  5335. if ($selected) {
  5336. $this->load_cache_types_paiements();
  5337. $out .= $this->cache_types_paiements[$selected]['label'];
  5338. } else {
  5339. $out .= "&nbsp;";
  5340. }
  5341. }
  5342. if ($nooutput) {
  5343. return $out;
  5344. } else {
  5345. print $out;
  5346. }
  5347. return '';
  5348. }
  5349. /**
  5350. * Show form with transport mode
  5351. *
  5352. * @param string $page Page
  5353. * @param string $selected Id mode pre-select
  5354. * @param string $htmlname Name of select html field
  5355. * @param int $active Active or not, -1 = all
  5356. * @param int $addempty 1=Add empty entry
  5357. * @return void
  5358. */
  5359. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5360. {
  5361. global $langs;
  5362. if ($htmlname != "none") {
  5363. print '<form method="POST" action="' . $page . '">';
  5364. print '<input type="hidden" name="action" value="settransportmode">';
  5365. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5366. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5367. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5368. print '</form>';
  5369. } else {
  5370. if ($selected) {
  5371. $this->load_cache_transport_mode();
  5372. print $this->cache_transport_mode[$selected]['label'];
  5373. } else {
  5374. print "&nbsp;";
  5375. }
  5376. }
  5377. }
  5378. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5379. /**
  5380. * Show form with multicurrency code
  5381. *
  5382. * @param string $page Page
  5383. * @param string $selected code pre-selectionne
  5384. * @param string $htmlname Name of select html field
  5385. * @return void
  5386. */
  5387. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5388. {
  5389. // phpcs:enable
  5390. global $langs;
  5391. if ($htmlname != "none") {
  5392. print '<form method="POST" action="' . $page . '">';
  5393. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5394. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5395. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5396. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5397. print '</form>';
  5398. } else {
  5399. dol_include_once('/core/lib/company.lib.php');
  5400. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5401. }
  5402. }
  5403. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5404. /**
  5405. * Show form with multicurrency rate
  5406. *
  5407. * @param string $page Page
  5408. * @param double $rate Current rate
  5409. * @param string $htmlname Name of select html field
  5410. * @param string $currency Currency code to explain the rate
  5411. * @return void
  5412. */
  5413. public function form_multicurrency_rate($page, $rate = 0.0, $htmlname = 'multicurrency_tx', $currency = '')
  5414. {
  5415. // phpcs:enable
  5416. global $langs, $mysoc, $conf;
  5417. if ($htmlname != "none") {
  5418. print '<form method="POST" action="' . $page . '">';
  5419. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5420. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5421. print '<input type="text" class="maxwidth100" name="' . $htmlname . '" value="' . (!empty($rate) ? price(price2num($rate, 'CU')) : 1) . '" /> ';
  5422. print '<select name="calculation_mode">';
  5423. print '<option value="1">Change ' . $langs->trans("PriceUHT") . ' of lines</option>';
  5424. print '<option value="2">Change ' . $langs->trans("PriceUHTCurrency") . ' of lines</option>';
  5425. print '</select> ';
  5426. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5427. print '</form>';
  5428. } else {
  5429. if (!empty($rate)) {
  5430. print price($rate, 1, $langs, 0, 0);
  5431. if ($currency && $rate != 1) {
  5432. print ' &nbsp; (' . price($rate, 1, $langs, 0, 0) . ' ' . $currency . ' = 1 ' . $conf->currency . ')';
  5433. }
  5434. } else {
  5435. print 1;
  5436. }
  5437. }
  5438. }
  5439. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5440. /**
  5441. * Show a select box with available absolute discounts
  5442. *
  5443. * @param string $page Page URL where form is shown
  5444. * @param int $selected Value pre-selected
  5445. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5446. * @param int $socid Third party id
  5447. * @param float $amount Total amount available
  5448. * @param string $filter SQL filter on discounts
  5449. * @param int $maxvalue Max value for lines that can be selected
  5450. * @param string $more More string to add
  5451. * @param int $hidelist 1=Hide list
  5452. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5453. * @return void
  5454. */
  5455. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5456. {
  5457. // phpcs:enable
  5458. global $conf, $langs;
  5459. if ($htmlname != "none") {
  5460. print '<form method="post" action="' . $page . '">';
  5461. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5462. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5463. print '<div class="inline-block">';
  5464. if (!empty($discount_type)) {
  5465. if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
  5466. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5467. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5468. } else {
  5469. $translationKey = 'HasCreditNoteFromSupplier';
  5470. }
  5471. } else {
  5472. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5473. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5474. } else {
  5475. $translationKey = 'HasCreditNoteFromSupplier';
  5476. }
  5477. }
  5478. } else {
  5479. if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
  5480. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5481. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5482. } else {
  5483. $translationKey = 'CompanyHasCreditNote';
  5484. }
  5485. } else {
  5486. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5487. $translationKey = 'CompanyHasAbsoluteDiscount';
  5488. } else {
  5489. $translationKey = 'CompanyHasCreditNote';
  5490. }
  5491. }
  5492. }
  5493. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5494. if (empty($hidelist)) {
  5495. print ' ';
  5496. }
  5497. print '</div>';
  5498. if (empty($hidelist)) {
  5499. print '<div class="inline-block" style="padding-right: 10px">';
  5500. $newfilter = 'discount_type=' . intval($discount_type);
  5501. if (!empty($discount_type)) {
  5502. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5503. } else {
  5504. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5505. }
  5506. if ($filter) {
  5507. $newfilter .= ' AND (' . $filter . ')';
  5508. }
  5509. // output the combo of discounts
  5510. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5511. if ($nbqualifiedlines > 0) {
  5512. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("UseLine")) . '"';
  5513. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5514. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5515. }
  5516. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5517. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5518. }
  5519. print '>';
  5520. }
  5521. print '</div>';
  5522. }
  5523. if ($more) {
  5524. print '<div class="inline-block">';
  5525. print $more;
  5526. print '</div>';
  5527. }
  5528. print '</form>';
  5529. } else {
  5530. if ($selected) {
  5531. print $selected;
  5532. } else {
  5533. print "0";
  5534. }
  5535. }
  5536. }
  5537. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5538. /**
  5539. * Show forms to select a contact
  5540. *
  5541. * @param string $page Page
  5542. * @param Societe $societe Filter on third party
  5543. * @param string $selected Id contact pre-selectionne
  5544. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5545. * @return void
  5546. */
  5547. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5548. {
  5549. // phpcs:enable
  5550. global $langs, $conf;
  5551. if ($htmlname != "none") {
  5552. print '<form method="post" action="' . $page . '">';
  5553. print '<input type="hidden" name="action" value="set_contact">';
  5554. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5555. print '<table class="nobordernopadding">';
  5556. print '<tr><td>';
  5557. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5558. $num = $this->num;
  5559. if ($num == 0) {
  5560. $addcontact = (getDolGlobalString('SOCIETE_ADDRESSES_MANAGEMENT') ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5561. print '<a href="' . DOL_URL_ROOT . '/contact/card.php?socid=' . $societe->id . '&amp;action=create&amp;backtoreferer=1">' . $addcontact . '</a>';
  5562. }
  5563. print '</td>';
  5564. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5565. print '</tr></table></form>';
  5566. } else {
  5567. if ($selected) {
  5568. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  5569. $contact = new Contact($this->db);
  5570. $contact->fetch($selected);
  5571. print $contact->getFullName($langs);
  5572. } else {
  5573. print "&nbsp;";
  5574. }
  5575. }
  5576. }
  5577. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5578. /**
  5579. * Output html select to select thirdparty
  5580. *
  5581. * @param string $page Page
  5582. * @param string $selected Id preselected
  5583. * @param string $htmlname Name of HTML select
  5584. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>()] are allowed here (example: 's.rowid <> x', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  5585. * @param int $showempty Add an empty field
  5586. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5587. * @param int $forcecombo Force to use combo box
  5588. * @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')))
  5589. * @param int $nooutput No print output. Return it only.
  5590. * @param array $excludeids Exclude IDs from the select combo
  5591. * @param string $textifnothirdparty Text to show if no thirdparty
  5592. * @return string HTML output or ''
  5593. */
  5594. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
  5595. {
  5596. // phpcs:enable
  5597. global $langs;
  5598. $out = '';
  5599. if ($htmlname != "none") {
  5600. $out .= '<form method="post" action="' . $page . '">';
  5601. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5602. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5603. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5604. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5605. $out .= '</form>';
  5606. } else {
  5607. if ($selected) {
  5608. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  5609. $soc = new Societe($this->db);
  5610. $soc->fetch($selected);
  5611. $out .= $soc->getNomUrl(0, '');
  5612. } else {
  5613. $out .= '<span class="opacitymedium">' . $textifnothirdparty . '</span>';
  5614. }
  5615. }
  5616. if ($nooutput) {
  5617. return $out;
  5618. } else {
  5619. print $out;
  5620. }
  5621. return '';
  5622. }
  5623. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5624. /**
  5625. * Retourne la liste des devises, dans la langue de l'utilisateur
  5626. *
  5627. * @param string $selected preselected currency code
  5628. * @param string $htmlname name of HTML select list
  5629. * @deprecated
  5630. * @return void
  5631. */
  5632. public function select_currency($selected = '', $htmlname = 'currency_id')
  5633. {
  5634. // phpcs:enable
  5635. print $this->selectCurrency($selected, $htmlname);
  5636. }
  5637. /**
  5638. * Retourne la liste des devises, dans la langue de l'utilisateur
  5639. *
  5640. * @param string $selected preselected currency code
  5641. * @param string $htmlname name of HTML select list
  5642. * @param int $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5643. * @param string $useempty '1'=Allow empty value
  5644. * @return string
  5645. */
  5646. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
  5647. {
  5648. global $conf, $langs, $user;
  5649. $langs->loadCacheCurrencies('');
  5650. $out = '';
  5651. if ($selected == 'euro' || $selected == 'euros') {
  5652. $selected = 'EUR'; // Pour compatibilite
  5653. }
  5654. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="' . $htmlname . '" id="' . $htmlname . '">';
  5655. if ($useempty) {
  5656. $out .= '<option value="-1" selected></option>';
  5657. }
  5658. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5659. $labeltoshow = $currency['label'];
  5660. if ($mode == 1) {
  5661. $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso . ')</span>';
  5662. } else {
  5663. $labeltoshow .= ' <span class="opacitymedium">(' . $langs->getCurrencySymbol($code_iso) . ')</span>';
  5664. }
  5665. if ($selected && $selected == $code_iso) {
  5666. $out .= '<option value="' . $code_iso . '" selected data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5667. } else {
  5668. $out .= '<option value="' . $code_iso . '" data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5669. }
  5670. $out .= $labeltoshow;
  5671. $out .= '</option>';
  5672. }
  5673. $out .= '</select>';
  5674. if ($user->admin) {
  5675. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5676. }
  5677. // Make select dynamic
  5678. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5679. $out .= ajax_combobox($htmlname);
  5680. return $out;
  5681. }
  5682. /**
  5683. * Return array of currencies in user language
  5684. *
  5685. * @param string $selected Preselected currency code
  5686. * @param string $htmlname Name of HTML select list
  5687. * @param integer $useempty 1=Add empty line
  5688. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5689. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available.
  5690. * true = we are in currency_rate update , we don't want to see conf->currency in select
  5691. * @param string $morecss More css
  5692. * @return string
  5693. */
  5694. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
  5695. {
  5696. global $conf, $langs;
  5697. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5698. $TCurrency = array();
  5699. $sql = "SELECT code FROM " . $this->db->prefix() . "multicurrency";
  5700. $sql .= " WHERE entity IN ('" . getEntity('mutlicurrency') . "')";
  5701. if ($filter) {
  5702. $sql .= " AND " . $filter;
  5703. }
  5704. $resql = $this->db->query($sql);
  5705. if ($resql) {
  5706. while ($obj = $this->db->fetch_object($resql)) {
  5707. $TCurrency[$obj->code] = $obj->code;
  5708. }
  5709. }
  5710. $out = '';
  5711. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  5712. if ($useempty) {
  5713. $out .= '<option value="">&nbsp;</option>';
  5714. }
  5715. // If company current currency not in table, we add it into list. Should always be available.
  5716. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5717. $TCurrency[$conf->currency] = $conf->currency;
  5718. }
  5719. if (count($TCurrency) > 0) {
  5720. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5721. if (isset($TCurrency[$code_iso])) {
  5722. if (!empty($selected) && $selected == $code_iso) {
  5723. $out .= '<option value="' . $code_iso . '" selected="selected">';
  5724. } else {
  5725. $out .= '<option value="' . $code_iso . '">';
  5726. }
  5727. $out .= $currency['label'];
  5728. $out .= ' (' . $langs->getCurrencySymbol($code_iso) . ')';
  5729. $out .= '</option>';
  5730. }
  5731. }
  5732. }
  5733. $out .= '</select>';
  5734. // Make select dynamic
  5735. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5736. $out .= ajax_combobox($htmlname);
  5737. return $out;
  5738. }
  5739. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5740. /**
  5741. * Load into the cache vat rates of a country
  5742. *
  5743. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5744. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5745. */
  5746. public function load_cache_vatrates($country_code)
  5747. {
  5748. // phpcs:enable
  5749. global $langs, $user;
  5750. $num = count($this->cache_vatrates);
  5751. if ($num > 0) {
  5752. return $num; // Cache already loaded
  5753. }
  5754. dol_syslog(__METHOD__, LOG_DEBUG);
  5755. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5756. $sql .= " FROM " . $this->db->prefix() . "c_tva as t, " . $this->db->prefix() . "c_country as c";
  5757. $sql .= " WHERE t.fk_pays = c.rowid";
  5758. $sql .= " AND t.active > 0";
  5759. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  5760. $sql .= " AND c.code IN (" . $this->db->sanitize($country_code, 1) . ")";
  5761. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5762. $resql = $this->db->query($sql);
  5763. if ($resql) {
  5764. $num = $this->db->num_rows($resql);
  5765. if ($num) {
  5766. for ($i = 0; $i < $num; $i++) {
  5767. $obj = $this->db->fetch_object($resql);
  5768. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5769. $this->cache_vatrates[$i]['code'] = $obj->code;
  5770. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5771. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5772. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5773. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5774. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5775. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5776. $this->cache_vatrates[$i]['label'] = $obj->taux . '%' . ($obj->code ? ' (' . $obj->code . ')' : ''); // Label must contains only 0-9 , . % or *
  5777. $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
  5778. $positiverates = '';
  5779. if ($obj->taux) {
  5780. $positiverates .= ($positiverates ? '/' : '') . $obj->taux;
  5781. }
  5782. if ($obj->localtax1) {
  5783. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax1;
  5784. }
  5785. if ($obj->localtax2) {
  5786. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax2;
  5787. }
  5788. if (empty($positiverates)) {
  5789. $positiverates = '0';
  5790. }
  5791. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates . ($obj->code ? ' (' . $obj->code . ')' : ''); // Must never be used as key, only label
  5792. }
  5793. return $num;
  5794. } else {
  5795. $this->error = '<span class="error">';
  5796. $this->error .= $langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code);
  5797. $reg = array();
  5798. if (!empty($user) && $user->admin && preg_match('/\'(..)\'/', $country_code, $reg)) {
  5799. $langs->load("errors");
  5800. $new_country_code = $reg[1];
  5801. $country_id = dol_getIdFromCode($this->db, $new_country_code, 'c_pays', 'code', 'rowid');
  5802. $this->error .= '<br>'.$langs->trans("ErrorFixThisHere", DOL_URL_ROOT.'/admin/dict.php?id=10'.($country_id > 0 ? '&countryidforinsert='.$country_id : ''));
  5803. }
  5804. $this->error .= '</span>';
  5805. return -1;
  5806. }
  5807. } else {
  5808. $this->error = '<span class="error">' . $this->db->error() . '</span>';
  5809. return -2;
  5810. }
  5811. }
  5812. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5813. /**
  5814. * Output an HTML select vat rate.
  5815. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5816. *
  5817. * @param string $htmlname Name of HTML select field
  5818. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5819. * @param Societe $societe_vendeuse Thirdparty seller
  5820. * @param Societe $societe_acheteuse Thirdparty buyer
  5821. * @param int $idprod Id product. O if unknown of NA.
  5822. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5823. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5824. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5825. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5826. * 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.
  5827. * Si vendeur et acheteur dans Communauté européenne et acheteur=particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5828. * Si vendeur et acheteur dans Communauté européenne et acheteur=entreprise alors TVA par défaut=0. Fin de règle.
  5829. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5830. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5831. * @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
  5832. * @return string
  5833. */
  5834. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = null, $societe_acheteuse = null, $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5835. {
  5836. // phpcs:enable
  5837. global $langs, $conf, $mysoc;
  5838. $langs->load('errors');
  5839. $return = '';
  5840. // Define defaultnpr, defaultttx and defaultcode
  5841. $defaultnpr = ($info_bits & 0x01);
  5842. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5843. $defaulttx = str_replace('*', '', $selectedrate);
  5844. $defaultcode = '';
  5845. $reg = array();
  5846. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5847. $defaultcode = $reg[1];
  5848. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5849. }
  5850. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5851. // Check parameters
  5852. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5853. if ($societe_vendeuse->id == $mysoc->id) {
  5854. $return .= '<span class="error">' . $langs->trans("ErrorYourCountryIsNotDefined") . '</span>';
  5855. } else {
  5856. $return .= '<span class="error">' . $langs->trans("ErrorSupplierCountryIsNotDefined") . '</span>';
  5857. }
  5858. return $return;
  5859. }
  5860. //var_dump($societe_acheteuse);
  5861. //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";
  5862. //exit;
  5863. // Define list of countries to use to search VAT rates to show
  5864. // First we defined code_country to use to find list
  5865. if (is_object($societe_vendeuse)) {
  5866. $code_country = "'" . $societe_vendeuse->country_code . "'";
  5867. } else {
  5868. $code_country = "'" . $mysoc->country_code . "'"; // Pour compatibilite ascendente
  5869. }
  5870. if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) { // If option to have vat for end customer for services is on
  5871. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  5872. // If SERVICE_ARE_ECOMMERCE_200238EC=1 combo list vat rate of purchaser and seller countries
  5873. // If SERVICE_ARE_ECOMMERCE_200238EC=2 combo list only the vat rate of the purchaser country
  5874. $selectVatComboMode = getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC');
  5875. if (isInEEC($societe_vendeuse) && isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()) {
  5876. // We also add the buyer country code
  5877. if (is_numeric($type)) {
  5878. if ($type == 1) { // We know product is a service
  5879. switch ($selectVatComboMode) {
  5880. case '1':
  5881. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5882. break;
  5883. case '2':
  5884. $code_country = "'" . $societe_acheteuse->country_code . "'";
  5885. break;
  5886. }
  5887. }
  5888. } elseif (!$idprod) { // We don't know type of product
  5889. switch ($selectVatComboMode) {
  5890. case '1':
  5891. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5892. break;
  5893. case '2':
  5894. $code_country = "'" . $societe_acheteuse->country_code . "'";
  5895. break;
  5896. }
  5897. } else {
  5898. $prodstatic = new Product($this->db);
  5899. $prodstatic->fetch($idprod);
  5900. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5901. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5902. }
  5903. }
  5904. }
  5905. }
  5906. // Now we get list
  5907. $num = $this->load_cache_vatrates($code_country); // If no vat at all defined for this country, return -1 with message into this->error
  5908. if ($num > 0) {
  5909. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5910. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5911. $tmpthirdparty = new Societe($this->db);
  5912. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5913. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5914. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5915. $defaultcode = $reg[1];
  5916. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5917. }
  5918. if (empty($defaulttx)) {
  5919. $defaultnpr = 0;
  5920. }
  5921. }
  5922. // If we fails to find a default vat rate, we take the last one in list
  5923. // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
  5924. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5925. if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
  5926. // We take the last one found in list
  5927. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5928. } else {
  5929. // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
  5930. $defaulttx = '';
  5931. if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
  5932. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5933. }
  5934. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5935. $defaultcode = $reg[1];
  5936. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5937. }
  5938. }
  5939. }
  5940. // Disabled if seller is not subject to VAT
  5941. $disabled = false;
  5942. $title = '';
  5943. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5944. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5945. // of using supplier invoices (this is a very bad idea !)
  5946. if (!getDolGlobalString('EXPENSEREPORT_OVERRIDE_VAT')) {
  5947. $title = ' title="' . dol_escape_htmltag($langs->trans('VATIsNotUsed')) . '"';
  5948. $disabled = true;
  5949. }
  5950. }
  5951. if (!$options_only) {
  5952. $return .= '<select class="flat minwidth50imp maxwidth100" id="' . $htmlname . '" name="' . $htmlname . '"' . ($disabled ? ' disabled' : '') . $title . '>';
  5953. }
  5954. $selectedfound = false;
  5955. foreach ($this->cache_vatrates as $rate) {
  5956. // Keep only 0 if seller is not subject to VAT
  5957. if ($disabled && $rate['txtva'] != 0) {
  5958. continue;
  5959. }
  5960. // Define key to use into select list
  5961. $key = $rate['txtva'];
  5962. $key .= $rate['nprtva'] ? '*' : '';
  5963. if ($mode > 0 && $rate['code']) {
  5964. $key .= ' (' . $rate['code'] . ')';
  5965. }
  5966. if ($mode < 0) {
  5967. $key = $rate['rowid'];
  5968. }
  5969. $return .= '<option value="' . $key . '"';
  5970. if (!$selectedfound) {
  5971. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5972. if ($defaultcode == $rate['code']) {
  5973. $return .= ' selected';
  5974. $selectedfound = true;
  5975. }
  5976. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5977. $return .= ' selected';
  5978. $selectedfound = true;
  5979. }
  5980. }
  5981. $return .= '>';
  5982. // Show label of VAT
  5983. if ($mysoc->country_code == 'IN' || getDolGlobalString('MAIN_VAT_LABEL_IS_POSITIVE_RATES')) {
  5984. // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
  5985. $return .= $rate['labelpositiverates'];
  5986. } else {
  5987. // Simple label
  5988. $return .= vatrate($rate['label']);
  5989. }
  5990. //$return.=($rate['code']?' '.$rate['code']:'');
  5991. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5992. $return .= '</option>';
  5993. }
  5994. if (!$options_only) {
  5995. $return .= '</select>';
  5996. //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
  5997. }
  5998. } else {
  5999. $return .= $this->error;
  6000. }
  6001. $this->num = $num;
  6002. return $return;
  6003. }
  6004. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6005. /**
  6006. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  6007. * Fields are preselected with :
  6008. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  6009. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  6010. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  6011. *
  6012. * @param integer|string $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).
  6013. * @param string $prefix Prefix for fields name
  6014. * @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
  6015. * @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
  6016. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  6017. * @param string $form_name Not used
  6018. * @param int $d 1=Show days, month, years
  6019. * @param int $addnowlink Add a link "Now"
  6020. * @param int $nooutput Do not output html string but return it
  6021. * @param int $disabled Disable input fields
  6022. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  6023. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  6024. * @param int|string $adddateof Add a link "Date of invoice" using the following date.
  6025. * @return string '' or HTML component string if nooutput is 1
  6026. * @deprecated
  6027. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  6028. */
  6029. public function select_date($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $nooutput = 0, $disabled = 0, $fullday = 0, $addplusone = '', $adddateof = '')
  6030. {
  6031. // phpcs:enable
  6032. dol_syslog(__METHOD__ . ': using select_date is deprecated. Use selectDate instead.', LOG_WARNING);
  6033. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  6034. if (!empty($nooutput)) {
  6035. return $retstring;
  6036. }
  6037. print $retstring;
  6038. return '';
  6039. }
  6040. /**
  6041. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  6042. * Fields are preselected with :
  6043. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  6044. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  6045. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  6046. *
  6047. * @param integer|string $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).
  6048. * @param integer|string $set_time_end Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  6049. * @param string $prefix Prefix for fields name
  6050. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  6051. * @param int $forcenewline Force new line between the 2 dates.
  6052. * @return string Html for selectDate
  6053. * @see form_date(), select_month(), select_year(), select_dayofweek()
  6054. */
  6055. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  6056. {
  6057. global $langs;
  6058. $ret = $this->selectDate($set_time, $prefix . '_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  6059. if ($forcenewline) {
  6060. $ret .= '<br>';
  6061. }
  6062. $ret .= $this->selectDate($set_time_end, $prefix . '_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  6063. return $ret;
  6064. }
  6065. /**
  6066. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  6067. * Fields are preselected with :
  6068. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  6069. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  6070. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  6071. *
  6072. * @param integer|string $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).
  6073. * @param string $prefix Prefix for fields name
  6074. * @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
  6075. * @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
  6076. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  6077. * @param string $form_name Not used
  6078. * @param int $d 1=Show days, month, years
  6079. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  6080. * @param int $disabled Disable input fields
  6081. * @param int|string $fullday When a checkbox with id #fullday is checked, hours are set with 00:00 (if value if 'fulldaystart') or 23:59 (if value is 'fulldayend')
  6082. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  6083. * @param int|string|array $adddateof Add a link "Date of ..." using the following date. Must be array(array('adddateof'=>..., 'labeladddateof'=>...))
  6084. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  6085. * @param int $stepminutes Specify step for minutes between 1 and 30
  6086. * @param string $labeladddateof Label to use for the $adddateof parameter. Deprecated. Used only when $adddateof is not an array.
  6087. * @param string $placeholder Placeholder
  6088. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  6089. * @return string Html for selectDate
  6090. * @see form_date(), select_month(), select_year(), select_dayofweek()
  6091. */
  6092. public function selectDate($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '', $openinghours = '', $stepminutes = 1, $labeladddateof = '', $placeholder = '', $gm = 'auto')
  6093. {
  6094. global $conf, $langs;
  6095. if ($gm === 'auto') {
  6096. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  6097. }
  6098. $retstring = '';
  6099. if ($prefix == '') {
  6100. $prefix = 're';
  6101. }
  6102. if ($h == '') {
  6103. $h = 0;
  6104. }
  6105. if ($m == '') {
  6106. $m = 0;
  6107. }
  6108. $emptydate = 0;
  6109. $emptyhours = 0;
  6110. if ($stepminutes <= 0 || $stepminutes > 30) {
  6111. $stepminutes = 1;
  6112. }
  6113. if ($empty == 1) {
  6114. $emptydate = 1;
  6115. $emptyhours = 1;
  6116. }
  6117. if ($empty == 2) {
  6118. $emptydate = 0;
  6119. $emptyhours = 1;
  6120. }
  6121. $orig_set_time = $set_time;
  6122. if ($set_time === '' && $emptydate == 0) {
  6123. include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  6124. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  6125. $set_time = dol_now($gm);
  6126. } else {
  6127. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  6128. }
  6129. }
  6130. // Analysis of the pre-selection date
  6131. $reg = array();
  6132. $shour = '';
  6133. $smin = '';
  6134. $ssec = '';
  6135. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  6136. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  6137. $syear = (!empty($reg[1]) ? $reg[1] : '');
  6138. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  6139. $sday = (!empty($reg[3]) ? $reg[3] : '');
  6140. $shour = (!empty($reg[4]) ? $reg[4] : '');
  6141. $smin = (!empty($reg[5]) ? $reg[5] : '');
  6142. } elseif (strval($set_time) != '' && $set_time != -1) {
  6143. // set_time est un timestamps (0 possible)
  6144. $syear = dol_print_date($set_time, "%Y", $gm);
  6145. $smonth = dol_print_date($set_time, "%m", $gm);
  6146. $sday = dol_print_date($set_time, "%d", $gm);
  6147. if ($orig_set_time != '') {
  6148. $shour = dol_print_date($set_time, "%H", $gm);
  6149. $smin = dol_print_date($set_time, "%M", $gm);
  6150. $ssec = dol_print_date($set_time, "%S", $gm);
  6151. }
  6152. } else {
  6153. // Date est '' ou vaut -1
  6154. $syear = '';
  6155. $smonth = '';
  6156. $sday = '';
  6157. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  6158. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  6159. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  6160. }
  6161. if ($h == 3) {
  6162. $shour = '';
  6163. }
  6164. if ($m == 3) {
  6165. $smin = '';
  6166. }
  6167. $nowgmt = dol_now('gmt');
  6168. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  6169. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  6170. $usecalendar = 'combo';
  6171. if (!empty($conf->use_javascript_ajax) && (!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') != "none")) {
  6172. $usecalendar = ((!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  6173. }
  6174. if ($d) {
  6175. // Show date with popup
  6176. if ($usecalendar != 'combo') {
  6177. $formated_date = '';
  6178. //print "e".$set_time." t ".$conf->format_date_short;
  6179. if (strval($set_time) != '' && $set_time != -1) {
  6180. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  6181. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6182. }
  6183. // Calendrier popup version eldy
  6184. if ($usecalendar == "eldy") {
  6185. // Input area to enter date manually
  6186. $retstring .= '<input id="' . $prefix . '" name="' . $prefix . '" type="text" class="maxwidthdate" maxlength="11" value="' . $formated_date . '"';
  6187. $retstring .= ($disabled ? ' disabled' : '');
  6188. $retstring .= ' onChange="dpChangeDay(\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6189. $retstring .= '>';
  6190. // Icon calendar
  6191. $retstringbuttom = '';
  6192. if (!$disabled) {
  6193. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons"';
  6194. $base = DOL_URL_ROOT . '/core/';
  6195. $retstringbuttom .= ' onClick="showDP(\'' . $base . '\',\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\',\'' . $langs->defaultlang . '\');"';
  6196. $retstringbuttom .= '>' . img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"') . '</button>';
  6197. } else {
  6198. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  6199. }
  6200. $retstring = $retstringbuttom . $retstring;
  6201. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  6202. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  6203. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  6204. } elseif ($usecalendar == 'jquery') {
  6205. if (!$disabled) {
  6206. // Output javascript for datepicker
  6207. $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (date('Y') - 100));
  6208. $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (date('Y') + 100));
  6209. $retstring .= '<script nonce="' . getNonce() . '" type="text/javascript">';
  6210. $retstring .= "$(function(){ $('#" . $prefix . "').datepicker({
  6211. dateFormat: '" . $langs->trans("FormatDateShortJQueryInput") . "',
  6212. autoclose: true,
  6213. todayHighlight: true,
  6214. yearRange: '" . $minYear . ":" . $maxYear . "',";
  6215. if (!empty($conf->dol_use_jmobile)) {
  6216. $retstring .= "
  6217. beforeShow: function (input, datePicker) {
  6218. input.disabled = true;
  6219. },
  6220. onClose: function (dateText, datePicker) {
  6221. this.disabled = false;
  6222. },
  6223. ";
  6224. }
  6225. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  6226. if (!getDolGlobalString('MAIN_POPUP_CALENDAR_ON_FOCUS')) {
  6227. $retstring .= "
  6228. showOn: 'button', /* both has problem with autocompletion */
  6229. buttonImage: '" . DOL_URL_ROOT . "/theme/" . dol_escape_js($conf->theme) . "/img/object_calendarday.png',
  6230. buttonImageOnly: true";
  6231. }
  6232. $retstring .= "
  6233. }) });";
  6234. $retstring .= "</script>";
  6235. }
  6236. // Zone de saisie manuelle de la date
  6237. $retstring .= '<div class="nowraponall inline-block divfordateinput">';
  6238. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  6239. $retstring .= ($disabled ? ' disabled' : '');
  6240. $retstring .= ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '');
  6241. $retstring .= ' onChange="dpChangeDay(\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($langs->trans("FormatDateShortJavaInput")) . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6242. $retstring .= '>';
  6243. // Icone calendrier
  6244. if (!$disabled) {
  6245. /* Not required. Managed by option buttonImage of jquery
  6246. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  6247. $retstring.='<script nonce="'.getNonce().'" type="text/javascript">';
  6248. $retstring.="jQuery(document).ready(function() {";
  6249. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  6250. $retstring.=" jQuery('#".$prefix."').focus();";
  6251. $retstring.=' });';
  6252. $retstring.='});';
  6253. $retstring.="</script>";*/
  6254. } else {
  6255. $retstringbutton = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  6256. $retsring = $retstringbutton . $retstring;
  6257. }
  6258. $retstring .= '</div>';
  6259. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  6260. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  6261. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  6262. } else {
  6263. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  6264. }
  6265. } else {
  6266. // Show date with combo selects
  6267. // Day
  6268. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50imp" id="' . $prefix . 'day" name="' . $prefix . 'day">';
  6269. if ($emptydate || $set_time == -1) {
  6270. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6271. }
  6272. for ($day = 1; $day <= 31; $day++) {
  6273. $retstring .= '<option value="' . $day . '"' . ($day == $sday ? ' selected' : '') . '>' . $day . '</option>';
  6274. }
  6275. $retstring .= "</select>";
  6276. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'month" name="' . $prefix . 'month">';
  6277. if ($emptydate || $set_time == -1) {
  6278. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6279. }
  6280. // Month
  6281. for ($month = 1; $month <= 12; $month++) {
  6282. $retstring .= '<option value="' . $month . '"' . ($month == $smonth ? ' selected' : '') . '>';
  6283. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  6284. $retstring .= "</option>";
  6285. }
  6286. $retstring .= "</select>";
  6287. // Year
  6288. if ($emptydate || $set_time == -1) {
  6289. $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 . '">';
  6290. } else {
  6291. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'year" name="' . $prefix . 'year">';
  6292. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  6293. $retstring .= '<option value="' . $year . '"' . ($year == $syear ? ' selected' : '') . '>' . $year . '</option>';
  6294. }
  6295. $retstring .= "</select>\n";
  6296. }
  6297. }
  6298. }
  6299. if ($d && $h) {
  6300. $retstring .= ($h == 2 ? '<br>' : ' ');
  6301. $retstring .= '<span class="nowraponall">';
  6302. }
  6303. if ($h) {
  6304. $hourstart = 0;
  6305. $hourend = 24;
  6306. if ($openinghours != '') {
  6307. $openinghours = explode(',', $openinghours);
  6308. $hourstart = $openinghours[0];
  6309. $hourend = $openinghours[1];
  6310. if ($hourend < $hourstart) {
  6311. $hourend = $hourstart;
  6312. }
  6313. }
  6314. // Show hour
  6315. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'hour' : '') . '" id="' . $prefix . 'hour" name="' . $prefix . 'hour">';
  6316. if ($emptyhours) {
  6317. $retstring .= '<option value="-1">&nbsp;</option>';
  6318. }
  6319. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  6320. if (strlen($hour) < 2) {
  6321. $hour = "0" . $hour;
  6322. }
  6323. $retstring .= '<option value="' . $hour . '"' . (($hour == $shour) ? ' selected' : '') . '>' . $hour;
  6324. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  6325. $retstring .= '</option>';
  6326. }
  6327. $retstring .= '</select>';
  6328. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  6329. if ($m) {
  6330. $retstring .= ":";
  6331. }
  6332. }
  6333. if ($m) {
  6334. // Show minutes
  6335. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'min' : '') . '" id="' . $prefix . 'min" name="' . $prefix . 'min">';
  6336. if ($emptyhours) {
  6337. $retstring .= '<option value="-1">&nbsp;</option>';
  6338. }
  6339. for ($min = 0; $min < 60; $min += $stepminutes) {
  6340. if (strlen($min) < 2) {
  6341. $min = "0" . $min;
  6342. }
  6343. $retstring .= '<option value="' . $min . '"' . (($min == $smin) ? ' selected' : '') . '>' . $min . (empty($conf->dol_optimize_smallscreen) ? '' : '') . '</option>';
  6344. }
  6345. $retstring .= '</select>';
  6346. $retstring .= '<input type="hidden" name="' . $prefix . 'sec" value="' . $ssec . '">';
  6347. }
  6348. if ($d && $h) {
  6349. $retstring .= '</span>';
  6350. }
  6351. // Add a "Now" link
  6352. if (!empty($conf->use_javascript_ajax) && $addnowlink) {
  6353. // Script which will be inserted in the onClick of the "Now" link
  6354. $reset_scripts = "";
  6355. if ($addnowlink == 2) { // local computer time
  6356. // pad add leading 0 on numbers
  6357. $reset_scripts .= "Number.prototype.pad = function(size) {
  6358. var s = String(this);
  6359. while (s.length < (size || 2)) {s = '0' + s;}
  6360. return s;
  6361. };
  6362. var d = new Date();";
  6363. }
  6364. // Generate the date part, depending on the use or not of the javascript calendar
  6365. if ($addnowlink == 1) { // server time expressed in user time setup
  6366. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6367. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6368. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6369. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6370. } elseif ($addnowlink == 2) {
  6371. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  6372. * This break application for foreign languages.
  6373. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  6374. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  6375. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  6376. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  6377. */
  6378. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6379. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6380. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6381. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6382. }
  6383. /*if ($usecalendar == "eldy")
  6384. {
  6385. $base=DOL_URL_ROOT.'/core/';
  6386. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  6387. }
  6388. else
  6389. {
  6390. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  6391. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  6392. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  6393. }*/
  6394. // Update the hour part
  6395. if ($h) {
  6396. if ($fullday) {
  6397. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6398. }
  6399. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  6400. if ($addnowlink == 1) {
  6401. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6402. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6403. } elseif ($addnowlink == 2) {
  6404. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(d.getHours().pad());';
  6405. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6406. }
  6407. if ($fullday) {
  6408. $reset_scripts .= ' } ';
  6409. }
  6410. }
  6411. // Update the minute part
  6412. if ($m) {
  6413. if ($fullday) {
  6414. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6415. }
  6416. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6417. if ($addnowlink == 1) {
  6418. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6419. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6420. } elseif ($addnowlink == 2) {
  6421. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(d.getMinutes().pad());';
  6422. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6423. }
  6424. if ($fullday) {
  6425. $reset_scripts .= ' } ';
  6426. }
  6427. }
  6428. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6429. if ($reset_scripts && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  6430. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonNow" type="button" name="_useless" value="now" onClick="' . $reset_scripts . '">';
  6431. $retstring .= $langs->trans("Now");
  6432. $retstring .= '</button> ';
  6433. }
  6434. }
  6435. // Add a "Plus one hour" link
  6436. if ($conf->use_javascript_ajax && $addplusone) {
  6437. // Script which will be inserted in the onClick of the "Add plusone" link
  6438. $reset_scripts = "";
  6439. // Generate the date part, depending on the use or not of the javascript calendar
  6440. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel') . '\');';
  6441. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6442. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6443. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6444. // Update the hour part
  6445. if ($h) {
  6446. if ($fullday) {
  6447. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6448. }
  6449. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6450. if ($fullday) {
  6451. $reset_scripts .= ' } ';
  6452. }
  6453. }
  6454. // Update the minute part
  6455. if ($m) {
  6456. if ($fullday) {
  6457. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6458. }
  6459. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6460. if ($fullday) {
  6461. $reset_scripts .= ' } ';
  6462. }
  6463. }
  6464. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6465. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6466. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="' . $reset_scripts . '">';
  6467. $retstring .= $langs->trans("DateStartPlusOne");
  6468. $retstring .= '</button> ';
  6469. }
  6470. }
  6471. // Add a link to set data
  6472. if ($conf->use_javascript_ajax && !empty($adddateof)) {
  6473. if (!is_array($adddateof)) {
  6474. $arrayofdateof = array(array('adddateof'=>$adddateof, 'labeladddateof'=>$labeladddateof));
  6475. } else {
  6476. $arrayofdateof = $adddateof;
  6477. }
  6478. foreach ($arrayofdateof as $valuedateof) {
  6479. $tmpadddateof = empty($valuedateof['adddateof']) ? 0 : $valuedateof['adddateof'];
  6480. $tmplabeladddateof = empty($valuedateof['labeladddateof']) ? '' : $valuedateof['labeladddateof'];
  6481. $tmparray = dol_getdate($tmpadddateof);
  6482. if (empty($tmplabeladddateof)) {
  6483. $tmplabeladddateof = $langs->trans("DateInvoice");
  6484. }
  6485. $reset_scripts = 'console.log(\'Click on now link\'); ';
  6486. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($tmpadddateof, 'dayinputnoreduce').'\');';
  6487. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.$tmparray['mday'].'\');';
  6488. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.$tmparray['mon'].'\');';
  6489. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.$tmparray['year'].'\');';
  6490. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="'.$reset_scripts.'">'.$tmplabeladddateof.'</button>';
  6491. }
  6492. }
  6493. return $retstring;
  6494. }
  6495. /**
  6496. * selectTypeDuration
  6497. *
  6498. * @param string $prefix Prefix
  6499. * @param string $selected Selected duration type
  6500. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6501. * @return string HTML select string
  6502. */
  6503. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6504. {
  6505. global $langs;
  6506. $TDurationTypes = array(
  6507. 'y' => $langs->trans('Years'),
  6508. 'm' => $langs->trans('Month'),
  6509. 'w' => $langs->trans('Weeks'),
  6510. 'd' => $langs->trans('Days'),
  6511. 'h' => $langs->trans('Hours'),
  6512. 'i' => $langs->trans('Minutes')
  6513. );
  6514. // Removed undesired duration types
  6515. foreach ($excludetypes as $value) {
  6516. unset($TDurationTypes[$value]);
  6517. }
  6518. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_' . $prefix . 'type_duration" name="' . $prefix . 'type_duration">';
  6519. foreach ($TDurationTypes as $key => $typeduration) {
  6520. $retstring .= '<option value="' . $key . '"';
  6521. if ($key == $selected) {
  6522. $retstring .= " selected";
  6523. }
  6524. $retstring .= ">" . $typeduration . "</option>";
  6525. }
  6526. $retstring .= "</select>";
  6527. $retstring .= ajax_combobox('select_' . $prefix . 'type_duration');
  6528. return $retstring;
  6529. }
  6530. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6531. /**
  6532. * Function to show a form to select a duration on a page
  6533. *
  6534. * @param string $prefix Prefix for input fields
  6535. * @param int|string $iSecond Default preselected duration (number of seconds or '')
  6536. * @param int $disabled Disable the combo box
  6537. * @param string $typehour If 'select' then input hour and input min is a combo,
  6538. * If 'text' input hour is in text and input min is a text,
  6539. * If 'textselect' input hour is in text and input min is a combo
  6540. * @param integer $minunderhours If 1, show minutes selection under the hours
  6541. * @param int $nooutput Do not output html string but return it
  6542. * @return string HTML component
  6543. */
  6544. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6545. {
  6546. // phpcs:enable
  6547. global $langs;
  6548. $retstring = '<span class="nowraponall">';
  6549. $hourSelected = '';
  6550. $minSelected = '';
  6551. // Hours
  6552. if ($iSecond != '') {
  6553. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  6554. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6555. $minSelected = convertSecondToTime($iSecond, 'min');
  6556. }
  6557. if ($typehour == 'select') {
  6558. $retstring .= '<select class="flat" id="select_' . $prefix . 'hour" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . '>';
  6559. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6560. $retstring .= '<option value="' . $hour . '"';
  6561. if (is_numeric($hourSelected) && $hourSelected == $hour) {
  6562. $retstring .= " selected";
  6563. }
  6564. $retstring .= ">" . $hour . "</option>";
  6565. }
  6566. $retstring .= "</select>";
  6567. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6568. $retstring .= '<input placeholder="' . $langs->trans('HourShort') . '" type="number" min="0" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputhour right" value="' . (($hourSelected != '') ? ((int) $hourSelected) : '') . '">';
  6569. } else {
  6570. return 'BadValueForParameterTypeHour';
  6571. }
  6572. if ($typehour != 'text') {
  6573. $retstring .= ' ' . $langs->trans('HourShort');
  6574. } else {
  6575. $retstring .= '<span class="">:</span>';
  6576. }
  6577. // Minutes
  6578. if ($minunderhours) {
  6579. $retstring .= '<br>';
  6580. } else {
  6581. if ($typehour != 'text') {
  6582. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6583. }
  6584. }
  6585. if ($typehour == 'select' || $typehour == 'textselect') {
  6586. $retstring .= '<select class="flat" id="select_' . $prefix . 'min" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . '>';
  6587. for ($min = 0; $min <= 55; $min = $min + 5) {
  6588. $retstring .= '<option value="' . $min . '"';
  6589. if (is_numeric($minSelected) && $minSelected == $min) {
  6590. $retstring .= ' selected';
  6591. }
  6592. $retstring .= '>' . $min . '</option>';
  6593. }
  6594. $retstring .= "</select>";
  6595. } elseif ($typehour == 'text') {
  6596. $retstring .= '<input placeholder="' . $langs->trans('MinuteShort') . '" type="number" min="0" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputminute right" value="' . (($minSelected != '') ? ((int) $minSelected) : '') . '">';
  6597. }
  6598. if ($typehour != 'text') {
  6599. $retstring .= ' ' . $langs->trans('MinuteShort');
  6600. }
  6601. $retstring .= "</span>";
  6602. if (!empty($nooutput)) {
  6603. return $retstring;
  6604. }
  6605. print $retstring;
  6606. return '';
  6607. }
  6608. /**
  6609. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6610. *
  6611. * @param string $selected Preselected tickets
  6612. * @param string $htmlname Name of HTML select field (must be unique in page).
  6613. * @param string $filtertype To add a filter
  6614. * @param int $limit Limit on number of returned lines
  6615. * @param int $status Ticket status
  6616. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6617. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6618. * @param array $ajaxoptions Options for ajax_autocompleter
  6619. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6620. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6621. * @param int $forcecombo Force to use combo box
  6622. * @param string $morecss Add more css on select
  6623. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6624. * @param int $nooutput No print, return the output into a string
  6625. * @return string
  6626. */
  6627. public function selectTickets($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6628. {
  6629. global $langs, $conf;
  6630. $out = '';
  6631. // check parameters
  6632. if (is_null($ajaxoptions)) {
  6633. $ajaxoptions = array();
  6634. }
  6635. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
  6636. $placeholder = '';
  6637. if ($selected && empty($selected_input_value)) {
  6638. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6639. $tickettmpselect = new Ticket($this->db);
  6640. $tickettmpselect->fetch($selected);
  6641. $selected_input_value = $tickettmpselect->ref;
  6642. unset($tickettmpselect);
  6643. }
  6644. $urloption = '';
  6645. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6646. if (empty($hidelabel)) {
  6647. $out .= $langs->trans("RefOrLabel") . ' : ';
  6648. } elseif ($hidelabel > 1) {
  6649. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6650. if ($hidelabel == 2) {
  6651. $out .= img_picto($langs->trans("Search"), 'search');
  6652. }
  6653. }
  6654. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  6655. if ($hidelabel == 3) {
  6656. $out .= img_picto($langs->trans("Search"), 'search');
  6657. }
  6658. } else {
  6659. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6660. }
  6661. if (empty($nooutput)) {
  6662. print $out;
  6663. } else {
  6664. return $out;
  6665. }
  6666. return '';
  6667. }
  6668. /**
  6669. * Return list of tickets.
  6670. * Called by selectTickets.
  6671. *
  6672. * @param string $selected Preselected ticket
  6673. * @param string $htmlname Name of select html
  6674. * @param string $filtertype Filter on ticket type
  6675. * @param int $limit Limit on number of returned lines
  6676. * @param string $filterkey Filter on ticket ref or subject
  6677. * @param int $status Ticket status
  6678. * @param int $outputmode 0=HTML select string, 1=Array
  6679. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6680. * @param int $forcecombo Force to use combo box
  6681. * @param string $morecss Add more css on select
  6682. * @return array|string Array of keys for json or HTML component
  6683. */
  6684. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6685. {
  6686. global $langs, $conf;
  6687. $out = '';
  6688. $outarray = array();
  6689. $selectFields = " p.rowid, p.ref, p.message";
  6690. $sql = "SELECT ";
  6691. $sql .= $selectFields;
  6692. $sql .= " FROM " . $this->db->prefix() . "ticket as p";
  6693. $sql .= ' WHERE p.entity IN (' . getEntity('ticket') . ')';
  6694. // Add criteria on ref/label
  6695. if ($filterkey != '') {
  6696. $sql .= ' AND (';
  6697. $prefix = !getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6698. // For natural search
  6699. $scrit = explode(' ', $filterkey);
  6700. $i = 0;
  6701. if (count($scrit) > 1) {
  6702. $sql .= "(";
  6703. }
  6704. foreach ($scrit as $crit) {
  6705. if ($i > 0) {
  6706. $sql .= " AND ";
  6707. }
  6708. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.subject LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6709. $sql .= ")";
  6710. $i++;
  6711. }
  6712. if (count($scrit) > 1) {
  6713. $sql .= ")";
  6714. }
  6715. $sql .= ')';
  6716. }
  6717. $sql .= $this->db->plimit($limit, 0);
  6718. // Build output string
  6719. dol_syslog(get_class($this) . "::selectTicketsList search tickets", LOG_DEBUG);
  6720. $result = $this->db->query($sql);
  6721. if ($result) {
  6722. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6723. require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php';
  6724. $num = $this->db->num_rows($result);
  6725. $events = null;
  6726. if (!$forcecombo) {
  6727. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6728. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6729. }
  6730. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6731. $textifempty = '';
  6732. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6733. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6734. if (getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
  6735. if ($showempty && !is_numeric($showempty)) {
  6736. $textifempty = $langs->trans($showempty);
  6737. } else {
  6738. $textifempty .= $langs->trans("All");
  6739. }
  6740. } else {
  6741. if ($showempty && !is_numeric($showempty)) {
  6742. $textifempty = $langs->trans($showempty);
  6743. }
  6744. }
  6745. if ($showempty) {
  6746. $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6747. }
  6748. $i = 0;
  6749. while ($num && $i < $num) {
  6750. $opt = '';
  6751. $optJson = array();
  6752. $objp = $this->db->fetch_object($result);
  6753. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6754. // Add new entry
  6755. // "key" value of json key array is used by jQuery automatically as selected value
  6756. // "label" value of json key array is used by jQuery automatically as text for combo box
  6757. $out .= $opt;
  6758. array_push($outarray, $optJson);
  6759. $i++;
  6760. }
  6761. $out .= '</select>';
  6762. $this->db->free($result);
  6763. if (empty($outputmode)) {
  6764. return $out;
  6765. }
  6766. return $outarray;
  6767. } else {
  6768. dol_print_error($this->db);
  6769. }
  6770. return array();
  6771. }
  6772. /**
  6773. * constructTicketListOption.
  6774. * This define value for &$opt and &$optJson.
  6775. *
  6776. * @param object $objp Result set of fetch
  6777. * @param string $opt Option (var used for returned value in string option format)
  6778. * @param array $optJson Option (var used for returned value in json format)
  6779. * @param string $selected Preselected value
  6780. * @param string $filterkey Filter key to highlight
  6781. * @return void
  6782. */
  6783. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6784. {
  6785. $outkey = '';
  6786. $outref = '';
  6787. $outtype = '';
  6788. $outkey = $objp->rowid;
  6789. $outref = $objp->ref;
  6790. $outtype = $objp->fk_product_type;
  6791. $opt = '<option value="' . $objp->rowid . '"';
  6792. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6793. $opt .= '>';
  6794. $opt .= $objp->ref;
  6795. $objRef = $objp->ref;
  6796. if (!empty($filterkey) && $filterkey != '') {
  6797. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6798. }
  6799. $opt .= "</option>\n";
  6800. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6801. }
  6802. /**
  6803. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6804. *
  6805. * @param string $selected Preselected tickets
  6806. * @param string $htmlname Name of HTML select field (must be unique in page).
  6807. * @param string $filtertype To add a filter
  6808. * @param int $limit Limit on number of returned lines
  6809. * @param int $status Ticket status
  6810. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6811. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6812. * @param array $ajaxoptions Options for ajax_autocompleter
  6813. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6814. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6815. * @param int $forcecombo Force to use combo box
  6816. * @param string $morecss Add more css on select
  6817. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6818. * @param int $nooutput No print, return the output into a string
  6819. * @return string
  6820. */
  6821. public function selectProjects($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6822. {
  6823. global $langs, $conf;
  6824. $out = '';
  6825. // check parameters
  6826. if (is_null($ajaxoptions)) {
  6827. $ajaxoptions = array();
  6828. }
  6829. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
  6830. $placeholder = '';
  6831. if ($selected && empty($selected_input_value)) {
  6832. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6833. $projecttmpselect = new Project($this->db);
  6834. $projecttmpselect->fetch($selected);
  6835. $selected_input_value = $projecttmpselect->ref;
  6836. unset($projecttmpselect);
  6837. }
  6838. $urloption = '';
  6839. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6840. if (empty($hidelabel)) {
  6841. $out .= $langs->trans("RefOrLabel") . ' : ';
  6842. } elseif ($hidelabel > 1) {
  6843. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6844. if ($hidelabel == 2) {
  6845. $out .= img_picto($langs->trans("Search"), 'search');
  6846. }
  6847. }
  6848. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  6849. if ($hidelabel == 3) {
  6850. $out .= img_picto($langs->trans("Search"), 'search');
  6851. }
  6852. } else {
  6853. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6854. }
  6855. if (empty($nooutput)) {
  6856. print $out;
  6857. } else {
  6858. return $out;
  6859. }
  6860. return '';
  6861. }
  6862. /**
  6863. * Return list of projects.
  6864. * Called by selectProjects.
  6865. *
  6866. * @param string $selected Preselected project
  6867. * @param string $htmlname Name of select html
  6868. * @param string $filtertype Filter on project type
  6869. * @param int $limit Limit on number of returned lines
  6870. * @param string $filterkey Filter on project ref or subject
  6871. * @param int $status Ticket status
  6872. * @param int $outputmode 0=HTML select string, 1=Array
  6873. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6874. * @param int $forcecombo Force to use combo box
  6875. * @param string $morecss Add more css on select
  6876. * @return array|string Array of keys for json or HTML component
  6877. */
  6878. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6879. {
  6880. global $langs, $conf;
  6881. $out = '';
  6882. $outarray = array();
  6883. $selectFields = " p.rowid, p.ref";
  6884. $sql = "SELECT ";
  6885. $sql .= $selectFields;
  6886. $sql .= " FROM " . $this->db->prefix() . "projet as p";
  6887. $sql .= ' WHERE p.entity IN (' . getEntity('project') . ')';
  6888. // Add criteria on ref/label
  6889. if ($filterkey != '') {
  6890. $sql .= ' AND (';
  6891. $prefix = !getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6892. // For natural search
  6893. $scrit = explode(' ', $filterkey);
  6894. $i = 0;
  6895. if (count($scrit) > 1) {
  6896. $sql .= "(";
  6897. }
  6898. foreach ($scrit as $crit) {
  6899. if ($i > 0) {
  6900. $sql .= " AND ";
  6901. }
  6902. $sql .= "p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6903. $sql .= "";
  6904. $i++;
  6905. }
  6906. if (count($scrit) > 1) {
  6907. $sql .= ")";
  6908. }
  6909. $sql .= ')';
  6910. }
  6911. $sql .= $this->db->plimit($limit, 0);
  6912. // Build output string
  6913. dol_syslog(get_class($this) . "::selectProjectsList search projects", LOG_DEBUG);
  6914. $result = $this->db->query($sql);
  6915. if ($result) {
  6916. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6917. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  6918. $num = $this->db->num_rows($result);
  6919. $events = null;
  6920. if (!$forcecombo) {
  6921. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6922. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6923. }
  6924. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6925. $textifempty = '';
  6926. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6927. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6928. if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
  6929. if ($showempty && !is_numeric($showempty)) {
  6930. $textifempty = $langs->trans($showempty);
  6931. } else {
  6932. $textifempty .= $langs->trans("All");
  6933. }
  6934. } else {
  6935. if ($showempty && !is_numeric($showempty)) {
  6936. $textifempty = $langs->trans($showempty);
  6937. }
  6938. }
  6939. if ($showempty) {
  6940. $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6941. }
  6942. $i = 0;
  6943. while ($num && $i < $num) {
  6944. $opt = '';
  6945. $optJson = array();
  6946. $objp = $this->db->fetch_object($result);
  6947. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6948. // Add new entry
  6949. // "key" value of json key array is used by jQuery automatically as selected value
  6950. // "label" value of json key array is used by jQuery automatically as text for combo box
  6951. $out .= $opt;
  6952. array_push($outarray, $optJson);
  6953. $i++;
  6954. }
  6955. $out .= '</select>';
  6956. $this->db->free($result);
  6957. if (empty($outputmode)) {
  6958. return $out;
  6959. }
  6960. return $outarray;
  6961. } else {
  6962. dol_print_error($this->db);
  6963. }
  6964. return array();
  6965. }
  6966. /**
  6967. * constructProjectListOption.
  6968. * This define value for &$opt and &$optJson.
  6969. *
  6970. * @param object $objp Result set of fetch
  6971. * @param string $opt Option (var used for returned value in string option format)
  6972. * @param array $optJson Option (var used for returned value in json format)
  6973. * @param string $selected Preselected value
  6974. * @param string $filterkey Filter key to highlight
  6975. * @return void
  6976. */
  6977. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6978. {
  6979. $outkey = '';
  6980. $outref = '';
  6981. $outtype = '';
  6982. $label = $objp->label;
  6983. $outkey = $objp->rowid;
  6984. $outref = $objp->ref;
  6985. $outlabel = $objp->label;
  6986. $outtype = $objp->fk_product_type;
  6987. $opt = '<option value="' . $objp->rowid . '"';
  6988. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6989. $opt .= '>';
  6990. $opt .= $objp->ref;
  6991. $objRef = $objp->ref;
  6992. if (!empty($filterkey) && $filterkey != '') {
  6993. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6994. }
  6995. $opt .= "</option>\n";
  6996. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6997. }
  6998. /**
  6999. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  7000. *
  7001. * @param string $selected Preselected tickets
  7002. * @param string $htmlname Name of HTML select field (must be unique in page).
  7003. * @param string $filtertype To add a filter
  7004. * @param int $limit Limit on number of returned lines
  7005. * @param int $status Ticket status
  7006. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  7007. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  7008. * @param array $ajaxoptions Options for ajax_autocompleter
  7009. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  7010. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  7011. * @param int $forcecombo Force to use combo box
  7012. * @param string $morecss Add more css on select
  7013. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  7014. * @param int $nooutput No print, return the output into a string
  7015. * @return string
  7016. */
  7017. public function selectMembers($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  7018. {
  7019. global $langs, $conf;
  7020. $out = '';
  7021. // check parameters
  7022. if (is_null($ajaxoptions)) {
  7023. $ajaxoptions = array();
  7024. }
  7025. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
  7026. $placeholder = '';
  7027. $urloption = '';
  7028. if ($selected && empty($selected_input_value)) {
  7029. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  7030. $adherenttmpselect = new Adherent($this->db);
  7031. $adherenttmpselect->fetch($selected);
  7032. $selected_input_value = $adherenttmpselect->ref;
  7033. unset($adherenttmpselect);
  7034. }
  7035. $urloption = '';
  7036. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  7037. if (empty($hidelabel)) {
  7038. $out .= $langs->trans("RefOrLabel") . ' : ';
  7039. } elseif ($hidelabel > 1) {
  7040. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  7041. if ($hidelabel == 2) {
  7042. $out .= img_picto($langs->trans("Search"), 'search');
  7043. }
  7044. }
  7045. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  7046. if ($hidelabel == 3) {
  7047. $out .= img_picto($langs->trans("Search"), 'search');
  7048. }
  7049. } else {
  7050. $filterkey = '';
  7051. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  7052. }
  7053. if (empty($nooutput)) {
  7054. print $out;
  7055. } else {
  7056. return $out;
  7057. }
  7058. return '';
  7059. }
  7060. /**
  7061. * Return list of adherents.
  7062. * Called by selectMembers.
  7063. *
  7064. * @param string $selected Preselected adherent
  7065. * @param string $htmlname Name of select html
  7066. * @param string $filtertype Filter on adherent type
  7067. * @param int $limit Limit on number of returned lines
  7068. * @param string $filterkey Filter on member status
  7069. * @param int $status Member status
  7070. * @param int $outputmode 0=HTML select string, 1=Array
  7071. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  7072. * @param int $forcecombo Force to use combo box
  7073. * @param string $morecss Add more css on select
  7074. * @return array|string Array of keys for json or HTML string component
  7075. */
  7076. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  7077. {
  7078. global $langs, $conf;
  7079. $out = '';
  7080. $outarray = array();
  7081. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname, p.fk_adherent_type";
  7082. $sql = "SELECT ";
  7083. $sql .= $selectFields;
  7084. $sql .= " FROM " . $this->db->prefix() . "adherent as p";
  7085. $sql .= ' WHERE p.entity IN (' . getEntity('adherent') . ')';
  7086. // Add criteria on ref/label
  7087. if ($filterkey != '') {
  7088. $sql .= ' AND (';
  7089. $prefix = !getDolGlobalString('MEMBER_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  7090. // For natural search
  7091. $scrit = explode(' ', $filterkey);
  7092. $i = 0;
  7093. if (count($scrit) > 1) {
  7094. $sql .= "(";
  7095. }
  7096. foreach ($scrit as $crit) {
  7097. if ($i > 0) {
  7098. $sql .= " AND ";
  7099. }
  7100. $sql .= "(p.firstname LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  7101. $sql .= " OR p.lastname LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  7102. $i++;
  7103. }
  7104. if (count($scrit) > 1) {
  7105. $sql .= ")";
  7106. }
  7107. $sql .= ')';
  7108. }
  7109. if ($status != -1) {
  7110. $sql .= ' AND statut = ' . ((int) $status);
  7111. }
  7112. $sql .= $this->db->plimit($limit, 0);
  7113. // Build output string
  7114. dol_syslog(get_class($this) . "::selectMembersList search adherents", LOG_DEBUG);
  7115. $result = $this->db->query($sql);
  7116. if ($result) {
  7117. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  7118. require_once DOL_DOCUMENT_ROOT . '/core/lib/member.lib.php';
  7119. $num = $this->db->num_rows($result);
  7120. $events = null;
  7121. if (!$forcecombo) {
  7122. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7123. $out .= ajax_combobox($htmlname, $events, getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT') ? $conf->global->PROJECT_USE_SEARCH_TO_SELECT : '');
  7124. }
  7125. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  7126. $textifempty = '';
  7127. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  7128. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7129. if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
  7130. if ($showempty && !is_numeric($showempty)) {
  7131. $textifempty = $langs->trans($showempty);
  7132. } else {
  7133. $textifempty .= $langs->trans("All");
  7134. }
  7135. } else {
  7136. if ($showempty && !is_numeric($showempty)) {
  7137. $textifempty = $langs->trans($showempty);
  7138. }
  7139. }
  7140. if ($showempty) {
  7141. $out .= '<option value="-1" selected>' . $textifempty . '</option>';
  7142. }
  7143. $i = 0;
  7144. while ($num && $i < $num) {
  7145. $opt = '';
  7146. $optJson = array();
  7147. $objp = $this->db->fetch_object($result);
  7148. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  7149. // Add new entry
  7150. // "key" value of json key array is used by jQuery automatically as selected value
  7151. // "label" value of json key array is used by jQuery automatically as text for combo box
  7152. $out .= $opt;
  7153. array_push($outarray, $optJson);
  7154. $i++;
  7155. }
  7156. $out .= '</select>';
  7157. $this->db->free($result);
  7158. if (empty($outputmode)) {
  7159. return $out;
  7160. }
  7161. return $outarray;
  7162. } else {
  7163. dol_print_error($this->db);
  7164. }
  7165. return array();
  7166. }
  7167. /**
  7168. * constructMemberListOption.
  7169. * This define value for &$opt and &$optJson.
  7170. *
  7171. * @param object $objp Result set of fetch
  7172. * @param string $opt Option (var used for returned value in string option format)
  7173. * @param array $optJson Option (var used for returned value in json format)
  7174. * @param string $selected Preselected value
  7175. * @param string $filterkey Filter key to highlight
  7176. * @return void
  7177. */
  7178. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  7179. {
  7180. $outkey = '';
  7181. $outlabel = '';
  7182. $outtype = '';
  7183. $outkey = $objp->rowid;
  7184. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  7185. $outtype = $objp->fk_adherent_type;
  7186. $opt = '<option value="' . $objp->rowid . '"';
  7187. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  7188. $opt .= '>';
  7189. if (!empty($filterkey) && $filterkey != '') {
  7190. $outlabel = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $outlabel, 1);
  7191. }
  7192. $opt .= $outlabel;
  7193. $opt .= "</option>\n";
  7194. $optJson = array('key' => $outkey, 'value' => $outlabel, 'type' => $outtype);
  7195. }
  7196. /**
  7197. * Generic method to select a component from a combo list.
  7198. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  7199. * This is the generic method that will replace all specific existing methods.
  7200. *
  7201. * @param string $objectdesc 'ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'. For hard coded custom needs. Try to prefer method using $objectfield instead of $objectdesc.
  7202. * @param string $htmlname Name of HTML select component
  7203. * @param int $preSelectedValue Preselected value (ID of element)
  7204. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  7205. * @param string $searchkey Search criteria
  7206. * @param string $placeholder Place holder
  7207. * @param string $morecss More CSS
  7208. * @param string $moreparams More params provided to ajax call
  7209. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7210. * @param int $disabled 1=Html component is disabled
  7211. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  7212. * @param string $objectfield Object:Field that contains the definition (in table $fields or $extrafields). Example: 'Object:xxx' or 'Module_Object:xxx' or 'Object:options_xxx' or 'Module_Object:options_xxx'
  7213. * @return string Return HTML string
  7214. * @see selectForFormsList(), select_thirdparty_list()
  7215. */
  7216. public function selectForForms($objectdesc, $htmlname, $preSelectedValue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '', $objectfield = '')
  7217. {
  7218. global $conf, $extrafields, $user;
  7219. //var_dump($objectdesc); debug_print_backtrace();
  7220. $objectdescorig = $objectdesc;
  7221. $objecttmp = null;
  7222. $InfoFieldList = array();
  7223. if ($objectfield) { // We must retreive the objectdesc from the field or extrafield
  7224. // Example: $objectfield = 'product:options_package'
  7225. $tmparray = explode(':', $objectfield);
  7226. // Load object according to $id and $element
  7227. $objectforfieldstmp = fetchObjectByElement(0, strtolower($tmparray[0]));
  7228. if (is_object($objectforfieldstmp)) {
  7229. $objectdesc = '';
  7230. $reg = array();
  7231. if (preg_match('/^options_(.*)$/', $tmparray[1], $reg)) {
  7232. // For a property in extrafields
  7233. $key = $reg[1];
  7234. // fetch optionals attributes and labels
  7235. $extrafields->fetch_name_optionals_label($objectforfieldstmp->table_element);
  7236. if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key]) && $extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key] == 'link') {
  7237. if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options'])) {
  7238. $tmpextrafields = array_keys($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options']);
  7239. $objectdesc = $tmpextrafields[0];
  7240. }
  7241. }
  7242. } else {
  7243. // For a property in ->fields
  7244. if (array_key_exists($tmparray[1], $objectforfieldstmp->fields)) {
  7245. $objectdesc = $objectforfieldstmp->fields[$tmparray[1]]['type'];
  7246. $objectdesc = preg_replace('/^integer[^:]*:/', '', $objectdesc);
  7247. }
  7248. }
  7249. }
  7250. }
  7251. if ($objectdesc) {
  7252. // Example of value for $objectdesc:
  7253. // Bom:bom/class/bom.class.php:0:t.status=1
  7254. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  7255. // Bom:bom/class/bom.class.php:0:(t.status:=:1) OR (t.field2:=:2):ref
  7256. $InfoFieldList = explode(":", $objectdesc, 4);
  7257. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  7258. $reg = array();
  7259. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  7260. $InfoFieldList[4] = $reg[1]; // take the sort field
  7261. }
  7262. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  7263. $classname = $InfoFieldList[0];
  7264. $classpath = empty($InfoFieldList[1]) ? '' : $InfoFieldList[1];
  7265. //$addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  7266. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  7267. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  7268. // Load object according to $id and $element
  7269. $objecttmp = fetchObjectByElement(0, strtolower($InfoFieldList[0]));
  7270. // Fallback to another solution to get $objecttmp
  7271. if (empty($objecttmp) && !empty($classpath)) {
  7272. dol_include_once($classpath);
  7273. if ($classname && class_exists($classname)) {
  7274. $objecttmp = new $classname($this->db);
  7275. }
  7276. }
  7277. }
  7278. // Make some replacement in $filter. May not be used if we used the ajax mode with $objectfield. In such a case
  7279. // we propagate the $objectfield and not the filter and replacement is done by the ajax/selectobject.php component.
  7280. $sharedentities = getEntity($objecttmp->element);
  7281. $filter = str_replace(
  7282. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  7283. array($conf->entity, $sharedentities, $user->id),
  7284. $filter
  7285. );
  7286. if (!is_object($objecttmp)) {
  7287. dol_syslog('selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.$objectfield.', objectdesc='.$objectdesc, LOG_WARNING);
  7288. return 'selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.$objectfield.', objectdesc='.$objectdesc;
  7289. }
  7290. //var_dump($filter);
  7291. $prefixforautocompletemode = $objecttmp->element;
  7292. if ($prefixforautocompletemode == 'societe') {
  7293. $prefixforautocompletemode = 'company';
  7294. }
  7295. if ($prefixforautocompletemode == 'product') {
  7296. $prefixforautocompletemode = 'produit';
  7297. }
  7298. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7299. dol_syslog(get_class($this) . "::selectForForms filter=" . $filter, LOG_DEBUG);
  7300. // Generate the combo HTML component
  7301. $out = '';
  7302. if (!empty($conf->use_javascript_ajax) && getDolGlobalString($confkeyforautocompletemode) && !$forcecombo) {
  7303. // No immediate load of all database
  7304. $placeholder = '';
  7305. if ($preSelectedValue && empty($selected_input_value)) {
  7306. $objecttmp->fetch($preSelectedValue);
  7307. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  7308. $oldValueForShowOnCombobox = 0;
  7309. foreach ($objecttmp->fields as $fieldK => $fielV) {
  7310. if (!array_key_exists('showoncombobox', $fielV) || !$fielV['showoncombobox'] || empty($objecttmp->$fieldK)) continue;
  7311. if (!$oldValueForShowOnCombobox) {
  7312. $selected_input_value = '';
  7313. }
  7314. $selected_input_value .= $oldValueForShowOnCombobox ? ' - ' : '';
  7315. $selected_input_value .= $objecttmp->$fieldK;
  7316. $oldValueForShowOnCombobox = empty($fielV['showoncombobox']) ? 0 : $fielV['showoncombobox'];
  7317. }
  7318. }
  7319. // Set url and param to call to get json of the search results
  7320. $urlforajaxcall = DOL_URL_ROOT . '/core/ajax/selectobject.php';
  7321. $urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1&objectdesc=' . urlencode($objectdescorig) . '&objectfield='.urlencode($objectfield) . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
  7322. // Activate the auto complete using ajax call.
  7323. $out .= ajax_autocompleter($preSelectedValue, $htmlname, $urlforajaxcall, $urloption, getDolGlobalString($confkeyforautocompletemode), 0);
  7324. $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
  7325. $out .= '<input type="text" class="' . $morecss . '"' . ($disabled ? ' disabled="disabled"' : '') . ' name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '') . ' />';
  7326. } else {
  7327. // Immediate load of table record.
  7328. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preSelectedValue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
  7329. }
  7330. return $out;
  7331. }
  7332. /**
  7333. * Output html form to select an object.
  7334. * Note, this function is called by selectForForms or by ajax selectobject.php
  7335. *
  7336. * @param Object $objecttmp Object to know the table to scan for combo.
  7337. * @param string $htmlname Name of HTML select component
  7338. * @param int $preselectedvalue Preselected value (ID of element)
  7339. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  7340. * @param string $searchkey Search value
  7341. * @param string $placeholder Place holder
  7342. * @param string $morecss More CSS
  7343. * @param string $moreparams More params provided to ajax call
  7344. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7345. * @param int $outputmode 0=HTML select string, 1=Array
  7346. * @param int $disabled 1=Html component is disabled
  7347. * @param string $sortfield Sort field
  7348. * @param string $filter Add more filter (Universal Search Filter)
  7349. * @return string|array Return HTML string
  7350. * @see selectForForms()
  7351. */
  7352. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '')
  7353. {
  7354. global $langs, $user, $hookmanager;
  7355. //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
  7356. $prefixforautocompletemode = $objecttmp->element;
  7357. if ($prefixforautocompletemode == 'societe') {
  7358. $prefixforautocompletemode = 'company';
  7359. }
  7360. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7361. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  7362. $tmpfieldstoshow = '';
  7363. foreach ($objecttmp->fields as $key => $val) {
  7364. if (!dol_eval($val['enabled'], 1, 1, '1')) {
  7365. continue;
  7366. }
  7367. if (!empty($val['showoncombobox'])) {
  7368. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '') . 't.' . $key;
  7369. }
  7370. }
  7371. if ($tmpfieldstoshow) {
  7372. $fieldstoshow = $tmpfieldstoshow;
  7373. }
  7374. } else {
  7375. // For backward compatibility
  7376. $objecttmp->fields['ref'] = array('type' => 'varchar(30)', 'label' => 'Ref', 'showoncombobox' => 1);
  7377. }
  7378. if (empty($fieldstoshow)) {
  7379. if (isset($objecttmp->fields['ref'])) {
  7380. $fieldstoshow = 't.ref';
  7381. } else {
  7382. $langs->load("errors");
  7383. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  7384. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  7385. }
  7386. }
  7387. $out = '';
  7388. $outarray = array();
  7389. $tmparray = array();
  7390. $num = 0;
  7391. // Search data
  7392. $sql = "SELECT t.rowid, " . $fieldstoshow . " FROM " . $this->db->prefix() . $objecttmp->table_element . " as t";
  7393. if (!empty($objecttmp->isextrafieldmanaged)) {
  7394. $sql .= " LEFT JOIN " . $this->db->prefix() . $objecttmp->table_element . "_extrafields as e ON t.rowid=e.fk_object";
  7395. }
  7396. if (isset($objecttmp->ismultientitymanaged)) {
  7397. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7398. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  7399. $sql .= " INNER JOIN " . $this->db->prefix() . $tmparray[1] . " as parenttable ON parenttable.rowid = t." . $tmparray[0];
  7400. }
  7401. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7402. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  7403. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  7404. }
  7405. }
  7406. }
  7407. // Add where from hooks
  7408. $parameters = array(
  7409. 'object' => $objecttmp,
  7410. 'htmlname' => $htmlname,
  7411. 'filter' => $filter,
  7412. 'searchkey' => $searchkey
  7413. );
  7414. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  7415. if (!empty($hookmanager->resPrint)) {
  7416. $sql .= $hookmanager->resPrint;
  7417. } else {
  7418. $sql .= " WHERE 1=1";
  7419. if (isset($objecttmp->ismultientitymanaged)) {
  7420. if ($objecttmp->ismultientitymanaged == 1) {
  7421. $sql .= " AND t.entity IN (" . getEntity($objecttmp->table_element) . ")";
  7422. }
  7423. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7424. $sql .= " AND parenttable.entity = t." . $tmparray[0];
  7425. }
  7426. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  7427. if ($objecttmp->element == 'societe') {
  7428. $sql .= " AND t.rowid = " . ((int) $user->socid);
  7429. } else {
  7430. $sql .= " AND t.fk_soc = " . ((int) $user->socid);
  7431. }
  7432. }
  7433. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7434. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  7435. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  7436. }
  7437. }
  7438. }
  7439. if ($searchkey != '') {
  7440. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  7441. }
  7442. if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  7443. $errormessage = '';
  7444. $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
  7445. if ($errormessage) {
  7446. return 'Error forging a SQL request from an universal criteria: ' . $errormessage;
  7447. }
  7448. }
  7449. }
  7450. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  7451. //$sql.=$this->db->plimit($limit, 0);
  7452. //print $sql;
  7453. // Build output string
  7454. $resql = $this->db->query($sql);
  7455. if ($resql) {
  7456. // Construct $out and $outarray
  7457. $out .= '<select id="' . $htmlname . '" class="flat minwidth100' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ($moreparams ? ' ' . $moreparams : '') . ' name="' . $htmlname . '">' . "\n";
  7458. // 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
  7459. $textifempty = '&nbsp;';
  7460. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7461. if (getDolGlobalInt($confkeyforautocompletemode)) {
  7462. if ($showempty && !is_numeric($showempty)) {
  7463. $textifempty = $langs->trans($showempty);
  7464. } else {
  7465. $textifempty .= $langs->trans("All");
  7466. }
  7467. }
  7468. if ($showempty) {
  7469. $out .= '<option value="-1">' . $textifempty . '</option>' . "\n";
  7470. }
  7471. $num = $this->db->num_rows($resql);
  7472. $i = 0;
  7473. if ($num) {
  7474. while ($i < $num) {
  7475. $obj = $this->db->fetch_object($resql);
  7476. $label = '';
  7477. $labelhtml = '';
  7478. $tmparray = explode(',', $fieldstoshow);
  7479. $oldvalueforshowoncombobox = 0;
  7480. foreach ($tmparray as $key => $val) {
  7481. $val = preg_replace('/t\./', '', $val);
  7482. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7483. $labelhtml .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7484. $label .= $obj->$val;
  7485. $labelhtml .= $obj->$val;
  7486. $oldvalueforshowoncombobox = empty($objecttmp->fields[$val]['showoncombobox']) ? 0 : $objecttmp->fields[$val]['showoncombobox'];
  7487. }
  7488. if (empty($outputmode)) {
  7489. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  7490. $out .= '<option value="' . $obj->rowid . '" selected data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
  7491. } else {
  7492. $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
  7493. }
  7494. } else {
  7495. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label));
  7496. }
  7497. $i++;
  7498. if (($i % 10) == 0) {
  7499. $out .= "\n";
  7500. }
  7501. }
  7502. }
  7503. $out .= '</select>' . "\n";
  7504. if (!$forcecombo) {
  7505. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7506. $out .= ajax_combobox($htmlname, null, getDolGlobalInt($confkeyforautocompletemode, 0));
  7507. }
  7508. } else {
  7509. dol_print_error($this->db);
  7510. }
  7511. $this->result = array('nbofelement' => $num);
  7512. if ($outputmode) {
  7513. return $outarray;
  7514. }
  7515. return $out;
  7516. }
  7517. /**
  7518. * Return a HTML select string, built from an array of key+value.
  7519. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  7520. *
  7521. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  7522. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7523. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7524. * @param int|string $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (If 1: key is -1 and value is '' or '&nbsp;', If placeholder string: key is -1 and value is the string), <0 to add an empty value with key that is this value.
  7525. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7526. * @param int $value_as_key 1 to use value as key
  7527. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7528. * @param int $translate 1=Translate and encode value
  7529. * @param int $maxlen Length maximum for labels
  7530. * @param int $disabled Html select box is disabled
  7531. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7532. * @param string $morecss Add more class to css styles
  7533. * @param int $addjscombo Add js combo
  7534. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7535. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7536. * @param int $nohtmlescape No html escaping.
  7537. * @return string HTML select string.
  7538. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7539. */
  7540. public static function selectarray($htmlname, $array, $id = '', $show_empty = 0, $key_in_label = 0, $value_as_key = 0, $moreparam = '', $translate = 0, $maxlen = 0, $disabled = 0, $sort = '', $morecss = 'minwidth75', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  7541. {
  7542. global $conf, $langs;
  7543. // Do we want a multiselect ?
  7544. //$jsbeautify = 0;
  7545. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7546. $jsbeautify = 1;
  7547. if ($value_as_key) {
  7548. $array = array_combine($array, $array);
  7549. }
  7550. $out = '';
  7551. if ($addjscombo < 0) {
  7552. if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  7553. $addjscombo = 1;
  7554. } else {
  7555. $addjscombo = 0;
  7556. }
  7557. }
  7558. $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
  7559. $out .= '<select id="' . preg_replace('/^\./', '', $idname) . '" ' . ($disabled ? 'disabled="disabled" ' : '') . 'class="flat ' . (preg_replace('/^\./', '', $htmlname)) . ($morecss ? ' ' . $morecss : '') . ' selectformat"';
  7560. $out .= ' name="' . preg_replace('/^\./', '', $htmlname) . '" ' . ($moreparam ? $moreparam : '');
  7561. $out .= '>'."\n";
  7562. if ($show_empty) {
  7563. $textforempty = ' ';
  7564. if (!empty($conf->use_javascript_ajax)) {
  7565. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7566. }
  7567. if (!is_numeric($show_empty)) {
  7568. $textforempty = $show_empty;
  7569. }
  7570. $out .= '<option class="optiongrey" ' . ($moreparamonempty ? $moreparamonempty . ' ' : '') . 'value="' . (((int) $show_empty) < 0 ? $show_empty : -1) . '"' . ($id == $show_empty ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  7571. }
  7572. if (is_array($array)) {
  7573. // Translate
  7574. if ($translate) {
  7575. foreach ($array as $key => $value) {
  7576. if (!is_array($value)) {
  7577. $array[$key] = $langs->trans($value);
  7578. } else {
  7579. $array[$key]['label'] = $langs->trans($value['label']);
  7580. }
  7581. }
  7582. }
  7583. // Sort
  7584. if ($sort == 'ASC') {
  7585. asort($array);
  7586. } elseif ($sort == 'DESC') {
  7587. arsort($array);
  7588. }
  7589. foreach ($array as $key => $tmpvalue) {
  7590. if (is_array($tmpvalue)) {
  7591. $value = $tmpvalue['label'];
  7592. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7593. $style = empty($tmpvalue['css']) ? '' : ' class="' . $tmpvalue['css'] . '"';
  7594. } else {
  7595. $value = $tmpvalue;
  7596. $disabled = '';
  7597. $style = '';
  7598. }
  7599. if (!empty($disablebademail)) {
  7600. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7601. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7602. $disabled = ' disabled';
  7603. $style = ' class="warning"';
  7604. }
  7605. }
  7606. if ($key_in_label) {
  7607. if (empty($nohtmlescape)) {
  7608. $selectOptionValue = dol_escape_htmltag($key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value));
  7609. } else {
  7610. $selectOptionValue = $key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value);
  7611. }
  7612. } else {
  7613. if (empty($nohtmlescape)) {
  7614. $selectOptionValue = dol_escape_htmltag($maxlen ? dol_trunc($value, $maxlen) : $value);
  7615. } else {
  7616. $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
  7617. }
  7618. if ($value == '' || $value == '-') {
  7619. $selectOptionValue = '&nbsp;';
  7620. }
  7621. }
  7622. $out .= '<option value="' . $key . '"';
  7623. $out .= $style . $disabled;
  7624. if (is_array($id)) {
  7625. if (in_array($key, $id) && !$disabled) {
  7626. $out .= ' selected'; // To preselect a value
  7627. }
  7628. } else {
  7629. $id = (string) $id; // if $id = 0, then $id = '0'
  7630. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7631. $out .= ' selected'; // To preselect a value
  7632. }
  7633. }
  7634. if ($nohtmlescape) {
  7635. $out .= ' data-html="' . dol_escape_htmltag($selectOptionValue) . '"';
  7636. }
  7637. if (is_array($tmpvalue)) {
  7638. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7639. if (preg_match('/^data-/', $keyforvalue)) {
  7640. $out .= ' '.$keyforvalue.'="'.dol_escape_htmltag($valueforvalue).'"';
  7641. }
  7642. }
  7643. }
  7644. $out .= '>';
  7645. $out .= $selectOptionValue;
  7646. $out .= "</option>\n";
  7647. }
  7648. }
  7649. $out .= "</select>";
  7650. // Add code for jquery to use multiselect
  7651. if ($addjscombo && $jsbeautify) {
  7652. // Enhance with select2
  7653. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7654. $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', (((int) $show_empty) < 0 ? (string) $show_empty : '-1'), $morecss);
  7655. }
  7656. return $out;
  7657. }
  7658. /**
  7659. * 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.
  7660. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7661. *
  7662. * @param string $htmlname Name of html select area
  7663. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7664. * @param string $id Preselected key
  7665. * @param string $moreparam Add more parameters onto the select tag
  7666. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7667. * @param int $disabled Html select box is disabled
  7668. * @param int $minimumInputLength Minimum Input Length
  7669. * @param string $morecss Add more class to css styles
  7670. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7671. * @param string $placeholder String to use as placeholder
  7672. * @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)
  7673. * @return string HTML select string
  7674. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7675. */
  7676. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7677. {
  7678. global $conf, $langs;
  7679. global $delayedhtmlcontent; // Will be used later outside of this function
  7680. // TODO Use an internal dolibarr component instead of select2
  7681. if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7682. return '';
  7683. }
  7684. $out = '<select type="text" class="' . $htmlname . ($morecss ? ' ' . $morecss : '') . '" ' . ($moreparam ? $moreparam . ' ' : '') . 'name="' . $htmlname . '"></select>';
  7685. $outdelayed = '';
  7686. if (!empty($conf->use_javascript_ajax)) {
  7687. $tmpplugin = 'select2';
  7688. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7689. <script nonce="' . getNonce() . '">
  7690. $(document).ready(function () {
  7691. ' . ($callurlonselect ? 'var saveRemoteData = [];' : '') . '
  7692. $(".' . $htmlname . '").select2({
  7693. ajax: {
  7694. dir: "ltr",
  7695. url: "' . $url . '",
  7696. dataType: \'json\',
  7697. delay: 250,
  7698. data: function (params) {
  7699. return {
  7700. q: params.term, // search term
  7701. page: params.page
  7702. }
  7703. },
  7704. processResults: function (data) {
  7705. // parse the results into the format expected by Select2.
  7706. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7707. //console.log(data);
  7708. saveRemoteData = data;
  7709. /* format json result for select2 */
  7710. result = []
  7711. $.each( data, function( key, value ) {
  7712. result.push({id: key, text: value.text});
  7713. });
  7714. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7715. //console.log(result);
  7716. return {results: result, more: false}
  7717. },
  7718. cache: true
  7719. },
  7720. language: select2arrayoflanguage,
  7721. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7722. placeholder: "' . dol_escape_js($placeholder) . '",
  7723. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7724. minimumInputLength: ' . ((int) $minimumInputLength) . ',
  7725. formatResult: function (result, container, query, escapeMarkup) {
  7726. return escapeMarkup(result.text);
  7727. },
  7728. });
  7729. ' . ($callurlonselect ? '
  7730. /* Code to execute a GET when we select a value */
  7731. $(".' . $htmlname . '").change(function() {
  7732. var selected = $(".' . $htmlname . '").val();
  7733. console.log("We select in selectArrayAjax the entry "+selected)
  7734. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7735. $.each( saveRemoteData, function( key, value ) {
  7736. if (key == selected)
  7737. {
  7738. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7739. location.assign(value.url);
  7740. }
  7741. });
  7742. });' : '') . '
  7743. });
  7744. </script>';
  7745. }
  7746. if ($acceptdelayedhtml) {
  7747. $delayedhtmlcontent .= $outdelayed;
  7748. } else {
  7749. $out .= $outdelayed;
  7750. }
  7751. return $out;
  7752. }
  7753. /**
  7754. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7755. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7756. *
  7757. * @param string $htmlname Name of html select area
  7758. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7759. * @param string $id Preselected key
  7760. * @param string $moreparam Add more parameters onto the select tag
  7761. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7762. * @param int $disabled Html select box is disabled
  7763. * @param int $minimumInputLength Minimum Input Length
  7764. * @param string $morecss Add more class to css styles
  7765. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7766. * @param string $placeholder String to use as placeholder
  7767. * @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)
  7768. * @param string $textfortitle Text to show on title.
  7769. * @return string HTML select string
  7770. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7771. */
  7772. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0, $textfortitle = '')
  7773. {
  7774. global $conf, $langs;
  7775. global $delayedhtmlcontent; // Will be used later outside of this function
  7776. // TODO Use an internal dolibarr component instead of select2
  7777. if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7778. return '';
  7779. }
  7780. $out = '<select type="text"'.($textfortitle ? ' title="'.dol_escape_htmltag($textfortitle).'"' : '').' id="'.$htmlname.'" class="'.$htmlname.($morecss ? ' ' . $morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.'"><option></option></select>';
  7781. $formattedarrayresult = array();
  7782. foreach ($array as $key => $value) {
  7783. $o = new stdClass();
  7784. $o->id = $key;
  7785. $o->text = $value['text'];
  7786. $o->url = $value['url'];
  7787. $formattedarrayresult[] = $o;
  7788. }
  7789. $outdelayed = '';
  7790. if (!empty($conf->use_javascript_ajax)) {
  7791. $tmpplugin = 'select2';
  7792. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7793. <script nonce="' . getNonce() . '">
  7794. $(document).ready(function () {
  7795. var data = ' . json_encode($formattedarrayresult) . ';
  7796. ' . ($callurlonselect ? 'var saveRemoteData = ' . json_encode($array) . ';' : '') . '
  7797. $(".' . $htmlname . '").select2({
  7798. data: data,
  7799. language: select2arrayoflanguage,
  7800. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7801. placeholder: "' . dol_escape_js($placeholder) . '",
  7802. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7803. minimumInputLength: ' . $minimumInputLength . ',
  7804. formatResult: function (result, container, query, escapeMarkup) {
  7805. return escapeMarkup(result.text);
  7806. },
  7807. matcher: function (params, data) {
  7808. if(! data.id) return null;';
  7809. if ($callurlonselect) {
  7810. // We forge the url with 'sall='
  7811. $outdelayed .= '
  7812. var urlBase = data.url;
  7813. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7814. /* console.log("params.term="+params.term); */
  7815. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7816. saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7817. }
  7818. if (!$disableFiltering) {
  7819. $outdelayed .= '
  7820. if(data.text.match(new RegExp(params.term))) {
  7821. return data;
  7822. }
  7823. return null;';
  7824. } else {
  7825. $outdelayed .= '
  7826. return data;';
  7827. }
  7828. $outdelayed .= '
  7829. }
  7830. });
  7831. ' . ($callurlonselect ? '
  7832. /* Code to execute a GET when we select a value */
  7833. $(".' . $htmlname . '").change(function() {
  7834. var selected = $(".' . $htmlname . '").val();
  7835. console.log("We select "+selected)
  7836. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7837. $.each( saveRemoteData, function( key, value ) {
  7838. if (key == selected)
  7839. {
  7840. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7841. location.assign(value.url);
  7842. }
  7843. });
  7844. });' : '') . '
  7845. });
  7846. </script>';
  7847. }
  7848. if ($acceptdelayedhtml) {
  7849. $delayedhtmlcontent .= $outdelayed;
  7850. } else {
  7851. $out .= $outdelayed;
  7852. }
  7853. return $out;
  7854. }
  7855. /**
  7856. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7857. *
  7858. * @param string $htmlname Name of select
  7859. * @param array $array Array(key=>value) or Array(key=>array('id'=>key, 'label'=>value, 'color'=> , 'picto'=> , 'labelhtml'=> ))
  7860. * @param array $selected Array of keys preselected
  7861. * @param int $key_in_label 1 to show key like in "[key] value"
  7862. * @param int $value_as_key 1 to use value as key
  7863. * @param string $morecss Add more css style
  7864. * @param int $translate Translate and encode value
  7865. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7866. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7867. * @param string $elemtype Type of element we show ('category', ...). Will execute a formating function on it. To use in readonly mode if js component support HTML formatting.
  7868. * @param string $placeholder String to use as placeholder
  7869. * @param int $addjscombo Add js combo
  7870. * @return string HTML multiselect string
  7871. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7872. */
  7873. public static function multiselectarray($htmlname, $array, $selected = array(), $key_in_label = 0, $value_as_key = 0, $morecss = '', $translate = 0, $width = 0, $moreattrib = '', $elemtype = '', $placeholder = '', $addjscombo = -1)
  7874. {
  7875. global $conf, $langs;
  7876. $out = '';
  7877. if ($addjscombo < 0) {
  7878. if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  7879. $addjscombo = 1;
  7880. } else {
  7881. $addjscombo = 0;
  7882. }
  7883. }
  7884. $useenhancedmultiselect = 0;
  7885. if (!empty($conf->use_javascript_ajax) && (getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT'))) {
  7886. if ($addjscombo) {
  7887. $useenhancedmultiselect = 1; // Use the js multiselect in one line. Possible only if $addjscombo not 0.
  7888. }
  7889. }
  7890. // We need a hidden field because when using the multiselect, if we unselect all, there is no
  7891. // variable submitted at all, so no way to make a difference between variable not submited and variable
  7892. // submited to nothing.
  7893. $out .= '<input type="hidden" name="'.$htmlname.'_multiselect" value="1">';
  7894. // Output select component
  7895. $out .= '<select id="' . $htmlname . '" class="multiselect' . ($useenhancedmultiselect ? ' multiselectononeline' : '') . ($morecss ? ' ' . $morecss : '') . '" multiple name="' . $htmlname . '[]"' . ($moreattrib ? ' ' . $moreattrib : '') . ($width ? ' style="width: ' . (preg_match('/%/', $width) ? $width : $width . 'px') . '"' : '') . '>' . "\n";
  7896. if (is_array($array) && !empty($array)) {
  7897. if ($value_as_key) {
  7898. $array = array_combine($array, $array);
  7899. }
  7900. if (!empty($array)) {
  7901. foreach ($array as $key => $value) {
  7902. $tmpkey = $key;
  7903. $tmpvalue = $value;
  7904. $tmpcolor = '';
  7905. $tmppicto = '';
  7906. $tmplabelhtml = '';
  7907. if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
  7908. $tmpkey = $value['id'];
  7909. $tmpvalue = empty($value['label']) ? '' : $value['label'];
  7910. $tmpcolor = empty($value['color']) ? '' : $value['color'];
  7911. $tmppicto = empty($value['picto']) ? '' : $value['picto'];
  7912. $tmplabelhtml = empty($value['labelhtml']) ? '' : $value['labelhtml'];
  7913. }
  7914. $newval = ($translate ? $langs->trans($tmpvalue) : $tmpvalue);
  7915. $newval = ($key_in_label ? $tmpkey . ' - ' . $newval : $newval);
  7916. $out .= '<option value="' . $tmpkey . '"';
  7917. if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
  7918. $out .= ' selected';
  7919. }
  7920. if (!empty($tmplabelhtml)) {
  7921. $out .= ' data-html="' . dol_escape_htmltag($tmplabelhtml, 0, 0, '', 0, 1) . '"';
  7922. } else {
  7923. $tmplabelhtml = ($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #' . $tmpcolor . '"') : '') . $newval;
  7924. $out .= ' data-html="' . dol_escape_htmltag($tmplabelhtml, 0, 0, '', 0, 1) . '"';
  7925. }
  7926. $out .= '>';
  7927. $out .= dol_htmlentitiesbr($newval);
  7928. $out .= '</option>' . "\n";
  7929. }
  7930. }
  7931. }
  7932. $out .= '</select>' . "\n";
  7933. // Add code for jquery to use multiselect
  7934. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7935. $out .= "\n" . '<!-- JS CODE TO ENABLE select for id ' . $htmlname . ', addjscombo=' . $addjscombo . ' -->';
  7936. $out .= "\n" . '<script nonce="' . getNonce() . '">' . "\n";
  7937. if ($addjscombo == 1) {
  7938. $tmpplugin = !getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') ? constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7939. $out .= 'function formatResult(record, container) {' . "\n";
  7940. // If property html set, we decode html entities and use this.
  7941. // Note that HTML content must have been sanitized from js with dol_escape_htmltag(xxx, 0, 0, '', 0, 1) when building the select option.
  7942. $out .= ' if ($(record.element).attr("data-html") != undefined) { return htmlEntityDecodeJs($(record.element).attr("data-html")); }'."\n";
  7943. $out .= ' return record.text;';
  7944. $out .= '}' . "\n";
  7945. $out .= 'function formatSelection(record) {' . "\n";
  7946. if ($elemtype == 'category') {
  7947. $out .= 'return \'<span><img src="' . DOL_URL_ROOT . '/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7948. } else {
  7949. $out .= 'return record.text;';
  7950. }
  7951. $out .= '}' . "\n";
  7952. $out .= '$(document).ready(function () {
  7953. $(\'#' . $htmlname . '\').' . $tmpplugin . '({';
  7954. if ($placeholder) {
  7955. $out .= '
  7956. placeholder: {
  7957. id: \'-1\',
  7958. text: \'' . dol_escape_js($placeholder) . '\'
  7959. },';
  7960. }
  7961. $out .= ' dir: \'ltr\',
  7962. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag (ko with multiselect) */
  7963. dropdownCssClass: \'' . $morecss . '\', /* Line to add class on the new <span class="select2-selection...> tag (ok with multiselect) */
  7964. // Specify format function for dropdown item
  7965. formatResult: formatResult,
  7966. templateResult: formatResult, /* For 4.0 */
  7967. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7968. // Specify format function for selected item
  7969. formatSelection: formatSelection,
  7970. templateSelection: formatSelection /* For 4.0 */
  7971. });
  7972. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7973. the size only if component is not hidden by default on load */
  7974. $(\'#' . $htmlname . ' + .select2\').addClass(\'' . $morecss . '\');
  7975. });' . "\n";
  7976. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7977. // Add other js lib
  7978. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7979. // ...
  7980. $out .= 'console.log(\'addjscombo=2 for htmlname=' . $htmlname . '\');';
  7981. $out .= '$(document).ready(function () {
  7982. $(\'#' . $htmlname . '\').multiSelect({
  7983. containerHTML: \'<div class="multi-select-container">\',
  7984. menuHTML: \'<div class="multi-select-menu">\',
  7985. buttonHTML: \'<span class="multi-select-button ' . $morecss . '">\',
  7986. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7987. activeClass: \'multi-select-container--open\',
  7988. noneText: \'' . $placeholder . '\'
  7989. });
  7990. })';
  7991. }
  7992. $out .= '</script>';
  7993. }
  7994. return $out;
  7995. }
  7996. /**
  7997. * Show a multiselect dropbox from an array. If a saved selection of fields exists for user (into $user->conf->MAIN_SELECTEDFIELDS_contextofpage), we use this one instead of default.
  7998. *
  7999. * @param string $htmlname Name of HTML field
  8000. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  8001. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  8002. * @param string $pos Position colon on liste value 'left' or '' (meaning 'right').
  8003. * @return string HTML multiselect string
  8004. * @see selectarray()
  8005. */
  8006. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  8007. {
  8008. global $conf, $langs, $user, $extrafields;
  8009. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  8010. return '';
  8011. }
  8012. if (empty($array)) {
  8013. return '';
  8014. }
  8015. $tmpvar = "MAIN_SELECTEDFIELDS_" . $varpage; // To get list of saved selected fields to show
  8016. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  8017. $tmparray = explode(',', $user->conf->$tmpvar);
  8018. foreach ($array as $key => $val) {
  8019. //var_dump($key);
  8020. //var_dump($tmparray);
  8021. if (in_array($key, $tmparray)) {
  8022. $array[$key]['checked'] = 1;
  8023. } else {
  8024. $array[$key]['checked'] = 0;
  8025. }
  8026. }
  8027. } else { // There is no list of fields already customized for user
  8028. foreach ($array as $key => $val) {
  8029. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  8030. $array[$key]['checked'] = 0;
  8031. }
  8032. }
  8033. }
  8034. $listoffieldsforselection = '';
  8035. $listcheckedstring = '';
  8036. foreach ($array as $key => $val) {
  8037. // var_dump($val);
  8038. // var_dump(array_key_exists('enabled', $val));
  8039. // var_dump(!$val['enabled']);
  8040. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  8041. unset($array[$key]); // We don't want this field
  8042. continue;
  8043. }
  8044. if (!empty($val['type']) && $val['type'] == 'separate') {
  8045. // Field remains in array but we don't add it into $listoffieldsforselection
  8046. //$listoffieldsforselection .= '<li>-----</li>';
  8047. continue;
  8048. }
  8049. if ($val['label']) {
  8050. if (!empty($val['langfile']) && is_object($langs)) {
  8051. $langs->load($val['langfile']);
  8052. }
  8053. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  8054. $listoffieldsforselection .= '<li><input type="checkbox" id="checkbox' . $key . '" value="' . $key . '"' . ((empty($val['checked']) || $val['checked'] == '-1') ? '' : ' checked="checked"') . '/><label for="checkbox' . $key . '">' . dol_escape_htmltag($langs->trans($val['label'])) . '</label></li>';
  8055. $listcheckedstring .= (empty($val['checked']) ? '' : $key . ',');
  8056. }
  8057. }
  8058. $out = '<!-- Component multiSelectArrayWithCheckbox ' . $htmlname . ' -->
  8059. <dl class="dropdown">
  8060. <dt>
  8061. <a href="#' . $htmlname . '">
  8062. ' . img_picto('', 'list') . '
  8063. </a>
  8064. <input type="hidden" class="' . $htmlname . '" name="' . $htmlname . '" value="' . $listcheckedstring . '">
  8065. </dt>
  8066. <dd class="dropdowndd">
  8067. <div class="multiselectcheckbox'.$htmlname.'">
  8068. <ul class="'.$htmlname.($pos == '1' ? 'left' : '').'">
  8069. <li><input class="inputsearch_dropdownselectedfields width90p minwidth200imp" style="width:90%;" type="text" placeholder="'.$langs->trans('Search').'"></li>
  8070. '.$listoffieldsforselection.'
  8071. </ul>
  8072. </div>
  8073. </dd>
  8074. </dl>
  8075. <script nonce="' . getNonce() . '" type="text/javascript">
  8076. jQuery(document).ready(function () {
  8077. $(\'.multiselectcheckbox' . $htmlname . ' input[type="checkbox"]\').on(\'click\', function () {
  8078. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  8079. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  8080. var title = $(this).val() + ",";
  8081. if ($(this).is(\':checked\')) {
  8082. $(\'.' . $htmlname . '\').val(title + $(\'.' . $htmlname . '\').val());
  8083. }
  8084. else {
  8085. $(\'.' . $htmlname . '\').val( $(\'.' . $htmlname . '\').val().replace(title, \'\') )
  8086. }
  8087. // Now, we submit page
  8088. //$(this).parents(\'form:first\').submit();
  8089. });
  8090. $("input.inputsearch_dropdownselectedfields").on("keyup", function() {
  8091. var value = $(this).val().toLowerCase();
  8092. $(\'.multiselectcheckbox'.$htmlname.' li > label\').filter(function() {
  8093. $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
  8094. });
  8095. });
  8096. });
  8097. </script>
  8098. ';
  8099. return $out;
  8100. }
  8101. /**
  8102. * Render list of categories linked to object with id $id and type $type
  8103. *
  8104. * @param int $id Id of object
  8105. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  8106. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  8107. * @param int $nolink 1=Do not add html links
  8108. * @return string String with categories
  8109. */
  8110. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  8111. {
  8112. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  8113. $cat = new Categorie($this->db);
  8114. $categories = $cat->containing($id, $type);
  8115. if ($rendermode == 1) {
  8116. $toprint = array();
  8117. foreach ($categories as $c) {
  8118. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  8119. foreach ($ways as $way) {
  8120. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '</li>';
  8121. }
  8122. }
  8123. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  8124. }
  8125. if ($rendermode == 0) {
  8126. $arrayselected = array();
  8127. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  8128. foreach ($categories as $c) {
  8129. $arrayselected[] = $c->id;
  8130. }
  8131. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  8132. }
  8133. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  8134. }
  8135. /**
  8136. * Show linked object block.
  8137. *
  8138. * @param CommonObject $object Object we want to show links to
  8139. * @param string $morehtmlright More html to show on right of title
  8140. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  8141. * @param string $title Title
  8142. * @return int Return integer <0 if KO, >=0 if OK
  8143. */
  8144. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = array(), $title = 'RelatedObjects')
  8145. {
  8146. global $conf, $langs, $hookmanager;
  8147. global $bc, $action;
  8148. $object->fetchObjectLinked();
  8149. // Bypass the default method
  8150. $hookmanager->initHooks(array('commonobject'));
  8151. $parameters = array(
  8152. 'morehtmlright' => $morehtmlright,
  8153. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  8154. );
  8155. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  8156. $nbofdifferenttypes = count($object->linkedObjects);
  8157. if (empty($reshook)) {
  8158. print '<!-- showLinkedObjectBlock -->';
  8159. print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  8160. print '<div class="div-table-responsive-no-min">';
  8161. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="' . $object->element . '" data-elementid="' . $object->id . '" >';
  8162. print '<tr class="liste_titre">';
  8163. print '<td>' . $langs->trans("Type") . '</td>';
  8164. print '<td>' . $langs->trans("Ref") . '</td>';
  8165. print '<td class="center"></td>';
  8166. print '<td class="center">' . $langs->trans("Date") . '</td>';
  8167. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  8168. print '<td class="right">' . $langs->trans("Status") . '</td>';
  8169. print '<td></td>';
  8170. print '</tr>';
  8171. $nboftypesoutput = 0;
  8172. foreach ($object->linkedObjects as $objecttype => $objects) {
  8173. $tplpath = $element = $subelement = $objecttype;
  8174. // to display inport button on tpl
  8175. $showImportButton = false;
  8176. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  8177. $showImportButton = true;
  8178. }
  8179. $regs = array();
  8180. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  8181. $element = $regs[1];
  8182. $subelement = $regs[2];
  8183. $tplpath = $element . '/' . $subelement;
  8184. }
  8185. $tplname = 'linkedobjectblock';
  8186. // To work with non standard path
  8187. if ($objecttype == 'facture') {
  8188. $tplpath = 'compta/' . $element;
  8189. if (!isModEnabled('facture')) {
  8190. continue; // Do not show if module disabled
  8191. }
  8192. } elseif ($objecttype == 'facturerec') {
  8193. $tplpath = 'compta/facture';
  8194. $tplname = 'linkedobjectblockForRec';
  8195. if (!isModEnabled('facture')) {
  8196. continue; // Do not show if module disabled
  8197. }
  8198. } elseif ($objecttype == 'propal') {
  8199. $tplpath = 'comm/' . $element;
  8200. if (!isModEnabled('propal')) {
  8201. continue; // Do not show if module disabled
  8202. }
  8203. } elseif ($objecttype == 'supplier_proposal') {
  8204. if (!isModEnabled('supplier_proposal')) {
  8205. continue; // Do not show if module disabled
  8206. }
  8207. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
  8208. $tplpath = 'expedition';
  8209. if (!isModEnabled('expedition')) {
  8210. continue; // Do not show if module disabled
  8211. }
  8212. } elseif ($objecttype == 'reception') {
  8213. $tplpath = 'reception';
  8214. if (!isModEnabled('reception')) {
  8215. continue; // Do not show if module disabled
  8216. }
  8217. } elseif ($objecttype == 'delivery') {
  8218. $tplpath = 'delivery';
  8219. if (!isModEnabled('expedition')) {
  8220. continue; // Do not show if module disabled
  8221. }
  8222. } elseif ($objecttype == 'ficheinter') {
  8223. $tplpath = 'fichinter';
  8224. if (!isModEnabled('ficheinter')) {
  8225. continue; // Do not show if module disabled
  8226. }
  8227. } elseif ($objecttype == 'invoice_supplier') {
  8228. $tplpath = 'fourn/facture';
  8229. } elseif ($objecttype == 'order_supplier') {
  8230. $tplpath = 'fourn/commande';
  8231. } elseif ($objecttype == 'expensereport') {
  8232. $tplpath = 'expensereport';
  8233. } elseif ($objecttype == 'subscription') {
  8234. $tplpath = 'adherents';
  8235. } elseif ($objecttype == 'conferenceorbooth') {
  8236. $tplpath = 'eventorganization';
  8237. } elseif ($objecttype == 'conferenceorboothattendee') {
  8238. $tplpath = 'eventorganization';
  8239. } elseif ($objecttype == 'mo') {
  8240. $tplpath = 'mrp';
  8241. if (!isModEnabled('mrp')) {
  8242. continue; // Do not show if module disabled
  8243. }
  8244. }
  8245. global $linkedObjectBlock;
  8246. $linkedObjectBlock = $objects;
  8247. // Output template part (modules that overwrite templates must declare this into descriptor)
  8248. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/' . $tplpath . '/tpl'));
  8249. foreach ($dirtpls as $reldir) {
  8250. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  8251. global $noMoreLinkedObjectBlockAfter;
  8252. $noMoreLinkedObjectBlockAfter = 1;
  8253. }
  8254. $res = @include dol_buildpath($reldir . '/' . $tplname . '.tpl.php');
  8255. if ($res) {
  8256. $nboftypesoutput++;
  8257. break;
  8258. }
  8259. }
  8260. }
  8261. if (!$nboftypesoutput) {
  8262. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">' . $langs->trans("None") . '</span></td></tr>';
  8263. }
  8264. print '</table>';
  8265. if (!empty($compatibleImportElementsList)) {
  8266. $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
  8267. }
  8268. print '</div>';
  8269. }
  8270. return $nbofdifferenttypes;
  8271. }
  8272. /**
  8273. * Show block with links to link to other objects.
  8274. *
  8275. * @param CommonObject $object Object we want to show links to
  8276. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  8277. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  8278. * @return string HTML block
  8279. */
  8280. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  8281. {
  8282. global $conf, $langs, $hookmanager;
  8283. global $action;
  8284. $linktoelem = '';
  8285. $linktoelemlist = '';
  8286. $listofidcompanytoscan = '';
  8287. if (!is_object($object->thirdparty)) {
  8288. $object->fetch_thirdparty();
  8289. }
  8290. $possiblelinks = array();
  8291. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  8292. $listofidcompanytoscan = $object->thirdparty->id;
  8293. if (($object->thirdparty->parent > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PARENT_IN_LINKTO')) {
  8294. $listofidcompanytoscan .= ',' . $object->thirdparty->parent;
  8295. }
  8296. if (($object->fk_project > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO')) {
  8297. include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  8298. $tmpproject = new Project($this->db);
  8299. $tmpproject->fetch($object->fk_project);
  8300. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  8301. $listofidcompanytoscan .= ',' . $tmpproject->socid;
  8302. }
  8303. unset($tmpproject);
  8304. }
  8305. $possiblelinks = array(
  8306. 'propal' => array(
  8307. 'enabled' => isModEnabled('propal'),
  8308. 'perms' => 1,
  8309. 'label' => 'LinkToProposal',
  8310. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('propal') . ')'),
  8311. 'shipping' => array(
  8312. 'enabled' => isModEnabled('expedition'),
  8313. 'perms' => 1,
  8314. 'label' => 'LinkToExpedition',
  8315. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "expedition as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('shipping') . ')'),
  8316. 'order' => array(
  8317. 'enabled' => isModEnabled('commande'),
  8318. 'perms' => 1,
  8319. 'label' => 'LinkToOrder',
  8320. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('commande') . ')'),
  8321. 'invoice' => array(
  8322. 'enabled' => isModEnabled('facture'),
  8323. 'perms' => 1,
  8324. 'label' => 'LinkToInvoice',
  8325. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('invoice') . ')'),
  8326. 'invoice_template' => array(
  8327. 'enabled' => isModEnabled('facture'),
  8328. 'perms' => 1,
  8329. 'label' => 'LinkToTemplateInvoice',
  8330. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('invoice') . ')'),
  8331. 'contrat' => array(
  8332. 'enabled' => isModEnabled('contrat'),
  8333. 'perms' => 1,
  8334. 'label' => 'LinkToContract',
  8335. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_customer as ref_client, t.ref_supplier, SUM(td.total_ht) as total_ht
  8336. FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "contrat as t, " . $this->db->prefix() . "contratdet as td WHERE t.fk_soc = s.rowid AND td.fk_contrat = t.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('contract') . ') GROUP BY s.rowid, s.nom, s.client, t.rowid, t.ref, t.ref_customer, t.ref_supplier'
  8337. ),
  8338. 'fichinter' => array(
  8339. 'enabled' => isModEnabled('ficheinter'),
  8340. 'perms' => 1,
  8341. 'label' => 'LinkToIntervention',
  8342. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('intervention') . ')'),
  8343. 'supplier_proposal' => array(
  8344. 'enabled' => isModEnabled('supplier_proposal'),
  8345. 'perms' => 1,
  8346. 'label' => 'LinkToSupplierProposal',
  8347. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('supplier_proposal') . ')'),
  8348. 'order_supplier' => array(
  8349. 'enabled' => isModEnabled("supplier_order"),
  8350. 'perms' => 1,
  8351. 'label' => 'LinkToSupplierOrder',
  8352. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('commande_fournisseur') . ')'),
  8353. 'invoice_supplier' => array(
  8354. 'enabled' => isModEnabled("supplier_invoice"),
  8355. 'perms' => 1, 'label' => 'LinkToSupplierInvoice',
  8356. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('facture_fourn') . ')'),
  8357. 'ticket' => array(
  8358. 'enabled' => isModEnabled('ticket'),
  8359. 'perms' => 1,
  8360. 'label' => 'LinkToTicket',
  8361. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('ticket') . ')'),
  8362. 'mo' => array(
  8363. 'enabled' => isModEnabled('mrp'),
  8364. 'perms' => 1,
  8365. 'label' => 'LinkToMo',
  8366. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM " . $this->db->prefix() . "societe as s INNER JOIN " . $this->db->prefix() . "mrp_mo as t ON t.fk_soc = s.rowid WHERE t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('mo') . ')')
  8367. );
  8368. }
  8369. if ($object->table_element == 'commande_fournisseur') {
  8370. $possiblelinks['mo']['sql'] = "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM ".$this->db->prefix()."societe as s INNER JOIN ".$this->db->prefix().'mrp_mo as t ON t.fk_soc = s.rowid WHERE t.entity IN ('.getEntity('mo').')';
  8371. } elseif ($object->table_element == 'mrp_mo') {
  8372. $possiblelinks['order_supplier']['sql'] = "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix().'commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.entity IN ('.getEntity('commande_fournisseur').')';
  8373. }
  8374. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  8375. // Can complete the possiblelink array
  8376. $hookmanager->initHooks(array('commonobject'));
  8377. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  8378. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  8379. }
  8380. if (empty($reshook)) {
  8381. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8382. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  8383. }
  8384. } elseif ($reshook > 0) {
  8385. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8386. $possiblelinks = $hookmanager->resArray;
  8387. }
  8388. }
  8389. foreach ($possiblelinks as $key => $possiblelink) {
  8390. $num = 0;
  8391. if (empty($possiblelink['enabled'])) {
  8392. continue;
  8393. }
  8394. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  8395. print '<div id="' . $key . 'list"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display:none"') . '>';
  8396. if (getDolGlobalString('MAIN_LINK_BY_REF_IN_LINKTO')) {
  8397. print '<br>'."\n";
  8398. print '<!-- form to add a link from anywhere -->'."\n";
  8399. print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  8400. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8401. print '<input type="hidden" name="action" value="addlinkbyref">';
  8402. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8403. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8404. print '<table class="noborder">';
  8405. print '<tr>';
  8406. //print '<td>' . $langs->trans("Ref") . '</td>';
  8407. print '<td class="center"><input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Ref")).'" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;';
  8408. print '<input type="submit" class="button small valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;';
  8409. print '<input type="submit" class="button small" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  8410. print '</tr>';
  8411. print '</table>';
  8412. print '</form>';
  8413. }
  8414. $sql = $possiblelink['sql'];
  8415. $resqllist = $this->db->query($sql);
  8416. if ($resqllist) {
  8417. $num = $this->db->num_rows($resqllist);
  8418. $i = 0;
  8419. print '<br>';
  8420. print '<!-- form to add a link from object to same thirdparty -->'."\n";
  8421. print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinked' . $key . '">';
  8422. print '<input type="hidden" name="action" value="addlink">';
  8423. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8424. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8425. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8426. print '<table class="noborder">';
  8427. print '<tr class="liste_titre">';
  8428. print '<td class="nowrap"></td>';
  8429. print '<td class="center">' . $langs->trans("Ref") . '</td>';
  8430. print '<td class="left">' . $langs->trans("RefCustomer") . '</td>';
  8431. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  8432. print '<td class="left">' . $langs->trans("Company") . '</td>';
  8433. print '</tr>';
  8434. while ($i < $num) {
  8435. $objp = $this->db->fetch_object($resqllist);
  8436. print '<tr class="oddeven">';
  8437. print '<td class="left">';
  8438. print '<input type="radio" name="idtolinkto" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
  8439. print '</td>';
  8440. print '<td class="center"><label for="' . $key . '_' . $objp->rowid . '">' . $objp->ref . '</label></td>';
  8441. print '<td>' . (!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')) . '</td>';
  8442. print '<td class="right">';
  8443. if ($possiblelink['label'] == 'LinkToContract') {
  8444. $form = new Form($this->db);
  8445. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")) . ' ';
  8446. }
  8447. print '<span class="amount">' . (isset($objp->total_ht) ? price($objp->total_ht) : '') . '</span>';
  8448. print '</td>';
  8449. print '<td>' . $objp->name . '</td>';
  8450. print '</tr>';
  8451. $i++;
  8452. }
  8453. print '</table>';
  8454. print '<div class="center">';
  8455. if ($num) {
  8456. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly small" value="' . $langs->trans('ToLink') . '">';
  8457. }
  8458. if (empty($conf->use_javascript_ajax)) {
  8459. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly small" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
  8460. } else {
  8461. print '<input type="submit" onclick="jQuery(\'#' . $key . 'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly small" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
  8462. }
  8463. print '</form>';
  8464. $this->db->free($resqllist);
  8465. } else {
  8466. dol_print_error($this->db);
  8467. }
  8468. print '</div>';
  8469. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  8470. if ($num > 0 || getDolGlobalString('MAIN_LINK_BY_REF_IN_LINKTO')) {
  8471. $linktoelemlist .= '<li><a href="#linkto' . $key . '" class="linkto dropdowncloseonclick" rel="' . $key . '">' . $langs->trans($possiblelink['label']) . ' (' . $num . ')</a></li>';
  8472. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  8473. } else {
  8474. $linktoelemlist .= '<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
  8475. }
  8476. }
  8477. }
  8478. if ($linktoelemlist) {
  8479. $linktoelem = '
  8480. <dl class="dropdown" id="linktoobjectname">
  8481. ';
  8482. if (!empty($conf->use_javascript_ajax)) {
  8483. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>' . $langs->trans("LinkTo") . '...</a></dt>';
  8484. }
  8485. $linktoelem .= '<dd>
  8486. <div class="multiselectlinkto">
  8487. <ul class="ulselectedfields">' . $linktoelemlist . '
  8488. </ul>
  8489. </div>
  8490. </dd>
  8491. </dl>';
  8492. } else {
  8493. $linktoelem = '';
  8494. }
  8495. if (!empty($conf->use_javascript_ajax)) {
  8496. print '<!-- Add js to show linkto box -->
  8497. <script nonce="' . getNonce() . '">
  8498. jQuery(document).ready(function() {
  8499. jQuery(".linkto").click(function() {
  8500. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  8501. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  8502. });
  8503. });
  8504. </script>
  8505. ';
  8506. }
  8507. return $linktoelem;
  8508. }
  8509. /**
  8510. * Return an html string with a select combo box to choose yes or no
  8511. *
  8512. * @param string $htmlname Name of html select field
  8513. * @param string $value Pre-selected value
  8514. * @param int $option 0 return yes/no, 1 return 1/0
  8515. * @param bool $disabled true or false
  8516. * @param int $useempty 1=Add empty line
  8517. * @param int $addjscombo 1=Add js beautifier on combo box
  8518. * @param string $morecss More CSS
  8519. * @param string $labelyes Label for Yes
  8520. * @param string $labelno Label for No
  8521. * @return string See option
  8522. */
  8523. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '', $labelyes = 'Yes', $labelno = 'No')
  8524. {
  8525. global $langs;
  8526. $yes = "yes";
  8527. $no = "no";
  8528. if ($option) {
  8529. $yes = "1";
  8530. $no = "0";
  8531. }
  8532. $disabled = ($disabled ? ' disabled' : '');
  8533. $resultyesno = '<select class="flat width75' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '"' . $disabled . '>' . "\n";
  8534. if ($useempty) {
  8535. $resultyesno .= '<option value="-1"' . (($value < 0) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  8536. }
  8537. if (("$value" == 'yes') || ($value == 1)) {
  8538. $resultyesno .= '<option value="' . $yes . '" selected>' . $langs->trans($labelyes) . '</option>' . "\n";
  8539. $resultyesno .= '<option value="' . $no . '">' . $langs->trans($labelno) . '</option>' . "\n";
  8540. } else {
  8541. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  8542. $resultyesno .= '<option value="' . $yes . '">' . $langs->trans($labelyes) . '</option>' . "\n";
  8543. $resultyesno .= '<option value="' . $no . '"' . $selected . '>' . $langs->trans($labelno) . '</option>' . "\n";
  8544. }
  8545. $resultyesno .= '</select>' . "\n";
  8546. if ($addjscombo) {
  8547. $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
  8548. }
  8549. return $resultyesno;
  8550. }
  8551. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8552. /**
  8553. * Return list of export templates
  8554. *
  8555. * @param string $selected Id modele pre-selectionne
  8556. * @param string $htmlname Name of HTML select
  8557. * @param string $type Type of searched templates
  8558. * @param int $useempty Affiche valeur vide dans liste
  8559. * @return void
  8560. */
  8561. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  8562. {
  8563. // phpcs:enable
  8564. $sql = "SELECT rowid, label";
  8565. $sql .= " FROM " . $this->db->prefix() . "export_model";
  8566. $sql .= " WHERE type = '" . $this->db->escape($type) . "'";
  8567. $sql .= " ORDER BY rowid";
  8568. $result = $this->db->query($sql);
  8569. if ($result) {
  8570. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  8571. if ($useempty) {
  8572. print '<option value="-1">&nbsp;</option>';
  8573. }
  8574. $num = $this->db->num_rows($result);
  8575. $i = 0;
  8576. while ($i < $num) {
  8577. $obj = $this->db->fetch_object($result);
  8578. if ($selected == $obj->rowid) {
  8579. print '<option value="' . $obj->rowid . '" selected>';
  8580. } else {
  8581. print '<option value="' . $obj->rowid . '">';
  8582. }
  8583. print $obj->label;
  8584. print '</option>';
  8585. $i++;
  8586. }
  8587. print "</select>";
  8588. } else {
  8589. dol_print_error($this->db);
  8590. }
  8591. }
  8592. /**
  8593. * Return a HTML area with the reference of object and a navigation bar for a business object
  8594. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  8595. *
  8596. * @param object $object Object to show.
  8597. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  8598. * @param string $morehtml More html content to output just before the nav bar.
  8599. * @param int $shownav Show Condition (navigation is shown if value is 1).
  8600. * @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.
  8601. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  8602. * @param string $morehtmlref More html to show after ref.
  8603. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  8604. * @param int $nodbprefix Do not include DB prefix to forge table name.
  8605. * @param string $morehtmlleft More html code to show before ref.
  8606. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  8607. * @param string $morehtmlright More html code to show after ref.
  8608. * @return string Portion HTML with ref + navigation buttons
  8609. */
  8610. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  8611. {
  8612. global $conf, $langs, $hookmanager, $extralanguages;
  8613. $ret = '';
  8614. if (empty($fieldid)) {
  8615. $fieldid = 'rowid';
  8616. }
  8617. if (empty($fieldref)) {
  8618. $fieldref = 'ref';
  8619. }
  8620. // Preparing gender's display if there is one
  8621. $addgendertxt = '';
  8622. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8623. $addgendertxt = ' ';
  8624. switch ($object->gender) {
  8625. case 'man':
  8626. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8627. break;
  8628. case 'woman':
  8629. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8630. break;
  8631. case 'other':
  8632. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8633. break;
  8634. }
  8635. }
  8636. // Add where from hooks
  8637. if (is_object($hookmanager)) {
  8638. $parameters = array('showrefnav' => true);
  8639. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8640. $object->next_prev_filter .= $hookmanager->resPrint;
  8641. }
  8642. $previous_ref = $next_ref = '';
  8643. if ($shownav) {
  8644. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8645. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8646. $navurl = $_SERVER["PHP_SELF"];
  8647. // Special case for project/task page
  8648. if ($paramid == 'project_ref') {
  8649. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8650. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8651. $paramid = 'ref';
  8652. }
  8653. }
  8654. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8655. // accesskey is for Mac: CTRL + key for all browsers
  8656. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8657. if ($conf->browser->name == 'chrome') {
  8658. $stringforfirstkey .= ' ALT +';
  8659. } elseif ($conf->browser->name == 'firefox') {
  8660. $stringforfirstkey .= ' ALT + SHIFT +';
  8661. } else {
  8662. $stringforfirstkey .= ' CTL +';
  8663. }
  8664. $previous_ref = $object->ref_previous ? '<a accesskey="p" title="' . $stringforfirstkey . ' p" class="classfortooltip" href="' . $navurl . '?' . $paramid . '=' . urlencode($object->ref_previous) . $moreparam . '"><i class="fa fa-chevron-left"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
  8665. $next_ref = $object->ref_next ? '<a accesskey="n" title="' . $stringforfirstkey . ' n" class="classfortooltip" href="' . $navurl . '?' . $paramid . '=' . urlencode($object->ref_next) . $moreparam . '"><i class="fa fa-chevron-right"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
  8666. }
  8667. //print "xx".$previous_ref."x".$next_ref;
  8668. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8669. // Right part of banner
  8670. if ($morehtmlright) {
  8671. $ret .= '<div class="inline-block floatleft">' . $morehtmlright . '</div>';
  8672. }
  8673. if ($previous_ref || $next_ref || $morehtml) {
  8674. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8675. }
  8676. if ($morehtml) {
  8677. $ret .= '<li class="noborder litext' . (($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '') . '">' . $morehtml . '</li>';
  8678. }
  8679. if ($shownav && ($previous_ref || $next_ref)) {
  8680. $ret .= '<li class="pagination">' . $previous_ref . '</li>';
  8681. $ret .= '<li class="pagination">' . $next_ref . '</li>';
  8682. }
  8683. if ($previous_ref || $next_ref || $morehtml) {
  8684. $ret .= '</ul></div>';
  8685. }
  8686. // Status
  8687. $parameters = array('morehtmlstatus' => $morehtmlstatus);
  8688. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8689. if (empty($reshook)) {
  8690. $morehtmlstatus .= $hookmanager->resPrint;
  8691. } else {
  8692. $morehtmlstatus = $hookmanager->resPrint;
  8693. }
  8694. if ($morehtmlstatus) {
  8695. $ret .= '<div class="statusref">' . $morehtmlstatus . '</div>';
  8696. }
  8697. $parameters = array();
  8698. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8699. if (empty($reshook)) {
  8700. $morehtmlref .= $hookmanager->resPrint;
  8701. } elseif ($reshook > 0) {
  8702. $morehtmlref = $hookmanager->resPrint;
  8703. }
  8704. // Left part of banner
  8705. if ($morehtmlleft) {
  8706. if ($conf->browser->layout == 'phone') {
  8707. $ret .= '<!-- morehtmlleft --><div class="floatleft">' . $morehtmlleft . '</div>';
  8708. } else {
  8709. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">' . $morehtmlleft . '</div>';
  8710. }
  8711. }
  8712. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8713. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid' . (($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '') . '">';
  8714. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8715. if ($object->element == 'societe') {
  8716. $ret .= dol_htmlentities($object->name);
  8717. // List of extra languages
  8718. $arrayoflangcode = array();
  8719. if (getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE')) {
  8720. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8721. }
  8722. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8723. if (!is_object($extralanguages)) {
  8724. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  8725. $extralanguages = new ExtraLanguages($this->db);
  8726. }
  8727. $extralanguages->fetch_name_extralanguages('societe');
  8728. if (!empty($extralanguages->attributes['societe']['name'])) {
  8729. $object->fetchValuesForExtraLanguages();
  8730. $htmltext = '';
  8731. // If there is extra languages
  8732. foreach ($arrayoflangcode as $extralangcode) {
  8733. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8734. if ($object->array_languages['name'][$extralangcode]) {
  8735. $htmltext .= $object->array_languages['name'][$extralangcode];
  8736. } else {
  8737. $htmltext .= '<span class="opacitymedium">' . $langs->trans("SwitchInEditModeToAddTranslation") . '</span>';
  8738. }
  8739. }
  8740. $ret .= '<!-- Show translations of name -->' . "\n";
  8741. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8742. }
  8743. }
  8744. } elseif ($object->element == 'member') {
  8745. $ret .= $object->ref . '<br>';
  8746. $fullname = $object->getFullName($langs);
  8747. if ($object->morphy == 'mor' && $object->societe) {
  8748. $ret .= dol_htmlentities($object->societe) . ((!empty($fullname) && $object->societe != $fullname) ? ' (' . dol_htmlentities($fullname) . $addgendertxt . ')' : '');
  8749. } else {
  8750. $ret .= dol_htmlentities($fullname) . $addgendertxt . ((!empty($object->societe) && $object->societe != $fullname) ? ' (' . dol_htmlentities($object->societe) . ')' : '');
  8751. }
  8752. } elseif (in_array($object->element, array('contact', 'user'))) {
  8753. $ret .= dol_htmlentities($object->getFullName($langs)) . $addgendertxt;
  8754. } elseif ($object->element == 'usergroup') {
  8755. $ret .= dol_htmlentities($object->name);
  8756. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8757. $ret .= $object->ref . '<br>' . $object->label;
  8758. } elseif (in_array($object->element, array('adherent_type'))) {
  8759. $ret .= $object->label;
  8760. } elseif ($object->element == 'ecm_directories') {
  8761. $ret .= '';
  8762. } elseif ($fieldref != 'none') {
  8763. $ret .= dol_htmlentities(!empty($object->$fieldref) ? $object->$fieldref : "");
  8764. }
  8765. if ($morehtmlref) {
  8766. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8767. if (substr($morehtmlref, 0, 4) != '<div') {
  8768. $ret .= ' ';
  8769. }
  8770. $ret .= $morehtmlref;
  8771. }
  8772. $ret .= '</div>';
  8773. $ret .= '</div><!-- End banner content -->';
  8774. return $ret;
  8775. }
  8776. /**
  8777. * Return HTML code to output a barcode
  8778. *
  8779. * @param Object $object Object containing data to retrieve file name
  8780. * @param int $width Width of photo
  8781. * @param string $morecss More CSS on img of barcode
  8782. * @return string HTML code to output barcode
  8783. */
  8784. public function showbarcode(&$object, $width = 100, $morecss = '')
  8785. {
  8786. global $conf;
  8787. //Check if barcode is filled in the card
  8788. if (empty($object->barcode)) {
  8789. return '';
  8790. }
  8791. // Complete object if not complete
  8792. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8793. $result = $object->fetch_barcode();
  8794. //Check if fetch_barcode() failed
  8795. if ($result < 1) {
  8796. return '<!-- ErrorFetchBarcode -->';
  8797. }
  8798. }
  8799. // Barcode image
  8800. $url = DOL_URL_ROOT . '/viewimage.php?modulepart=barcode&generator=' . urlencode($object->barcode_type_coder) . '&code=' . urlencode($object->barcode) . '&encoding=' . urlencode($object->barcode_type_code);
  8801. $out = '<!-- url barcode = ' . $url . ' -->';
  8802. $out .= '<img src="' . $url . '"' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
  8803. return $out;
  8804. }
  8805. /**
  8806. * Return HTML code to output a photo
  8807. *
  8808. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8809. * @param object $object Object containing data to retrieve file name
  8810. * @param int $width Width of photo
  8811. * @param int $height Height of photo (auto if 0)
  8812. * @param int $caneditfield Add edit fields
  8813. * @param string $cssclass CSS name to use on img for photo
  8814. * @param string $imagesize 'mini', 'small' or '' (original)
  8815. * @param int $addlinktofullsize Add link to fullsize image
  8816. * @param int $cache 1=Accept to use image in cache
  8817. * @param string $forcecapture '', 'user' or 'environment'. Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if ''.
  8818. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8819. * @return string HTML code to output photo
  8820. */
  8821. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8822. {
  8823. global $conf, $langs;
  8824. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  8825. $id = (empty($object->id) ? $object->rowid : $object->id);
  8826. $ret = '';
  8827. $dir = '';
  8828. $file = '';
  8829. $originalfile = '';
  8830. $altfile = '';
  8831. $email = '';
  8832. $capture = '';
  8833. if ($modulepart == 'societe') {
  8834. $dir = $conf->societe->multidir_output[$entity];
  8835. if (!empty($object->logo)) {
  8836. if (dolIsAllowedForPreview($object->logo)) {
  8837. if ((string) $imagesize == 'mini') {
  8838. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8839. } elseif ((string) $imagesize == 'small') {
  8840. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_small');
  8841. } else {
  8842. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8843. }
  8844. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8845. }
  8846. }
  8847. $email = $object->email;
  8848. } elseif ($modulepart == 'contact') {
  8849. $dir = $conf->societe->multidir_output[$entity] . '/contact';
  8850. if (!empty($object->photo)) {
  8851. if (dolIsAllowedForPreview($object->photo)) {
  8852. if ((string) $imagesize == 'mini') {
  8853. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8854. } elseif ((string) $imagesize == 'small') {
  8855. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8856. } else {
  8857. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8858. }
  8859. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8860. }
  8861. }
  8862. $email = $object->email;
  8863. $capture = 'user';
  8864. } elseif ($modulepart == 'userphoto') {
  8865. $dir = $conf->user->dir_output;
  8866. if (!empty($object->photo)) {
  8867. if (dolIsAllowedForPreview($object->photo)) {
  8868. if ((string) $imagesize == 'mini') {
  8869. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8870. } elseif ((string) $imagesize == 'small') {
  8871. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8872. } else {
  8873. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8874. }
  8875. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8876. }
  8877. }
  8878. if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
  8879. $altfile = $object->id . ".jpg"; // For backward compatibility
  8880. }
  8881. $email = $object->email;
  8882. $capture = 'user';
  8883. } elseif ($modulepart == 'memberphoto') {
  8884. $dir = $conf->adherent->dir_output;
  8885. if (!empty($object->photo)) {
  8886. if (dolIsAllowedForPreview($object->photo)) {
  8887. if ((string) $imagesize == 'mini') {
  8888. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8889. } elseif ((string) $imagesize == 'small') {
  8890. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8891. } else {
  8892. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8893. }
  8894. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8895. }
  8896. }
  8897. if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
  8898. $altfile = $object->id . ".jpg"; // For backward compatibility
  8899. }
  8900. $email = $object->email;
  8901. $capture = 'user';
  8902. } else {
  8903. // Generic case to show photos
  8904. $dir = $conf->$modulepart->dir_output;
  8905. if (!empty($object->photo)) {
  8906. if (dolIsAllowedForPreview($object->photo)) {
  8907. if ((string) $imagesize == 'mini') {
  8908. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8909. } elseif ((string) $imagesize == 'small') {
  8910. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8911. } else {
  8912. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8913. }
  8914. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8915. }
  8916. }
  8917. if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
  8918. $altfile = $object->id . ".jpg"; // For backward compatibility
  8919. }
  8920. $email = $object->email;
  8921. }
  8922. if ($forcecapture) {
  8923. $capture = $forcecapture;
  8924. }
  8925. if ($dir) {
  8926. if ($file && file_exists($dir . "/" . $file)) {
  8927. if ($addlinktofullsize) {
  8928. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8929. if ($urladvanced) {
  8930. $ret .= '<a href="' . $urladvanced . '">';
  8931. } else {
  8932. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8933. }
  8934. }
  8935. $ret .= '<img alt="Photo" class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . ' photologo' . (preg_replace('/[^a-z]/i', '_', $file)) . '" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($file) . '&cache=' . $cache . '">';
  8936. if ($addlinktofullsize) {
  8937. $ret .= '</a>';
  8938. }
  8939. } elseif ($altfile && file_exists($dir . "/" . $altfile)) {
  8940. if ($addlinktofullsize) {
  8941. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8942. if ($urladvanced) {
  8943. $ret .= '<a href="' . $urladvanced . '">';
  8944. } else {
  8945. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8946. }
  8947. }
  8948. $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 . '">';
  8949. if ($addlinktofullsize) {
  8950. $ret .= '</a>';
  8951. }
  8952. } else {
  8953. $nophoto = '/public/theme/common/nophoto.png';
  8954. $defaultimg = 'identicon'; // For gravatar
  8955. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8956. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && !empty($object->morphy) && strpos($object->morphy, 'mor')) !== false) {
  8957. $nophoto = 'company';
  8958. } else {
  8959. $nophoto = '/public/theme/common/user_anonymous.png';
  8960. if (!empty($object->gender) && $object->gender == 'man') {
  8961. $nophoto = '/public/theme/common/user_man.png';
  8962. }
  8963. if (!empty($object->gender) && $object->gender == 'woman') {
  8964. $nophoto = '/public/theme/common/user_woman.png';
  8965. }
  8966. }
  8967. }
  8968. if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
  8969. // see https://gravatar.com/site/implement/images/php/
  8970. $ret .= '<!-- Put link to gravatar -->';
  8971. $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" title="' . $email . ' Gravatar avatar" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="https://www.gravatar.com/avatar/' . dol_hash(strtolower(trim($email)), 'sha256', 1) . '?s=' . $width . '&d=' . $defaultimg . '">'; // gravatar need md5 hash
  8972. } else {
  8973. if ($nophoto == 'company') {
  8974. $ret .= '<div class="divforspanimg photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . '>' . img_picto('', 'company') . '</div>';
  8975. $ret .= '<div class="difforspanimgright"></div>';
  8976. } else {
  8977. $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . $nophoto . '">';
  8978. }
  8979. }
  8980. }
  8981. if ($caneditfield) {
  8982. if ($object->photo) {
  8983. $ret .= "<br>\n";
  8984. }
  8985. $ret .= '<table class="nobordernopadding centpercent">';
  8986. if ($object->photo) {
  8987. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">' . $langs->trans("Delete") . '</label><br><br></td></tr>';
  8988. }
  8989. $ret .= '<tr><td class="tdoverflow">';
  8990. $maxfilesizearray = getMaxFileSizeArray();
  8991. $maxmin = $maxfilesizearray['maxmin'];
  8992. if ($maxmin > 0) {
  8993. $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">'; // MAX_FILE_SIZE must precede the field type=file
  8994. }
  8995. $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"' . ($capture ? ' capture="' . $capture . '"' : '') . '>';
  8996. $ret .= '</td></tr>';
  8997. $ret .= '</table>';
  8998. }
  8999. }
  9000. return $ret;
  9001. }
  9002. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  9003. /**
  9004. * Return select list of groups
  9005. *
  9006. * @param string|object $selected Id group or group preselected
  9007. * @param string $htmlname Field name in form
  9008. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  9009. * @param string|array $exclude Array list of groups id to exclude
  9010. * @param int $disabled If select list must be disabled
  9011. * @param string|array $include Array list of groups id to include
  9012. * @param array $enableonly Array list of groups id to be enabled. All other must be disabled
  9013. * @param string $force_entity '0' or Ids of environment to force
  9014. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  9015. * @param string $morecss More css to add to html component
  9016. * @return string
  9017. * @see select_dolusers()
  9018. */
  9019. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0', $multiple = false, $morecss = '')
  9020. {
  9021. // phpcs:enable
  9022. global $conf, $user, $langs;
  9023. // Permettre l'exclusion de groupes
  9024. $excludeGroups = null;
  9025. if (is_array($exclude)) {
  9026. $excludeGroups = implode(",", $exclude);
  9027. }
  9028. // Permettre l'inclusion de groupes
  9029. $includeGroups = null;
  9030. if (is_array($include)) {
  9031. $includeGroups = implode(",", $include);
  9032. }
  9033. if (!is_array($selected)) {
  9034. $selected = array($selected);
  9035. }
  9036. $out = '';
  9037. // On recherche les groupes
  9038. $sql = "SELECT ug.rowid, ug.nom as name";
  9039. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  9040. $sql .= ", e.label";
  9041. }
  9042. $sql .= " FROM " . $this->db->prefix() . "usergroup as ug ";
  9043. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  9044. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid=ug.entity";
  9045. if ($force_entity) {
  9046. $sql .= " WHERE ug.entity IN (0, " . $force_entity . ")";
  9047. } else {
  9048. $sql .= " WHERE ug.entity IS NOT NULL";
  9049. }
  9050. } else {
  9051. $sql .= " WHERE ug.entity IN (0, " . $conf->entity . ")";
  9052. }
  9053. if (is_array($exclude) && $excludeGroups) {
  9054. $sql .= " AND ug.rowid NOT IN (" . $this->db->sanitize($excludeGroups) . ")";
  9055. }
  9056. if (is_array($include) && $includeGroups) {
  9057. $sql .= " AND ug.rowid IN (" . $this->db->sanitize($includeGroups) . ")";
  9058. }
  9059. $sql .= " ORDER BY ug.nom ASC";
  9060. dol_syslog(get_class($this) . "::select_dolgroups", LOG_DEBUG);
  9061. $resql = $this->db->query($sql);
  9062. if ($resql) {
  9063. // Enhance with select2
  9064. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9065. $out .= '<select class="flat minwidth200' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  9066. $num = $this->db->num_rows($resql);
  9067. $i = 0;
  9068. if ($num) {
  9069. if ($show_empty && !$multiple) {
  9070. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  9071. }
  9072. while ($i < $num) {
  9073. $obj = $this->db->fetch_object($resql);
  9074. $disableline = 0;
  9075. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  9076. $disableline = 1;
  9077. }
  9078. $label = $obj->name;
  9079. $labelhtml = $obj->name;
  9080. if (isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1) {
  9081. $label .= " (" . $obj->label . ")";
  9082. $labelhtml .= ' <span class="opacitymedium">(' . $obj->label . ')</span>';
  9083. }
  9084. $out .= '<option value="' . $obj->rowid . '"';
  9085. if ($disableline) {
  9086. $out .= ' disabled';
  9087. }
  9088. if ((isset($selected[0]) && is_object($selected[0]) && $selected[0]->id == $obj->rowid) || ((!isset($selected[0]) || !is_object($selected[0])) && !empty($selected) && in_array($obj->rowid, $selected))) {
  9089. $out .= ' selected';
  9090. }
  9091. $out .= ' data-html="'.dol_escape_htmltag($labelhtml).'"';
  9092. $out .= '>';
  9093. $out .= $label;
  9094. $out .= '</option>';
  9095. $i++;
  9096. }
  9097. } else {
  9098. if ($show_empty) {
  9099. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '></option>' . "\n";
  9100. }
  9101. $out .= '<option value="" disabled>' . $langs->trans("NoUserGroupDefined") . '</option>';
  9102. }
  9103. $out .= '</select>';
  9104. $out .= ajax_combobox($htmlname);
  9105. } else {
  9106. dol_print_error($this->db);
  9107. }
  9108. return $out;
  9109. }
  9110. /**
  9111. * Return HTML to show the search and clear seach button
  9112. *
  9113. * @param string $pos Position of colon on the list. Value 'left' or 'right'
  9114. * @return string
  9115. */
  9116. public function showFilterButtons($pos = '')
  9117. {
  9118. $out = '<div class="nowraponall">';
  9119. if ($pos == 'left') {
  9120. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fas fa-search"></span></button>';
  9121. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fas fa-times"></span></button>';
  9122. } else {
  9123. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fas fa-search"></span></button>';
  9124. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fas fa-times"></span></button>';
  9125. }
  9126. $out .= '</div>';
  9127. return $out;
  9128. }
  9129. /**
  9130. * Return HTML to show the search and clear search button
  9131. *
  9132. * @param string $cssclass CSS class
  9133. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  9134. * @param string $massactionname Mass action button name that will launch an action on the selected items
  9135. * @return string
  9136. */
  9137. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  9138. {
  9139. global $conf;
  9140. $out = '';
  9141. if (!empty($conf->use_javascript_ajax)) {
  9142. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="' . $cssclass . 's" name="' . $cssclass . 's" class="checkallactions"></div>';
  9143. }
  9144. $out .= '<script nonce="' . getNonce() . '">
  9145. $(document).ready(function() {
  9146. $("#' . $cssclass . 's").click(function() {
  9147. if($(this).is(\':checked\')){
  9148. console.log("We check all ' . $cssclass . ' and trigger the change method");
  9149. $(".' . $cssclass . '").prop(\'checked\', true).trigger(\'change\');
  9150. }
  9151. else
  9152. {
  9153. console.log("We uncheck all");
  9154. $(".' . $cssclass . '").prop(\'checked\', false).trigger(\'change\');
  9155. }' . "\n";
  9156. if ($calljsfunction) {
  9157. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "' . $massactionname . '", "' . $cssclass . '"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  9158. }
  9159. $out .= ' });
  9160. $(".' . $cssclass . '").change(function() {
  9161. $(this).closest("tr").toggleClass("highlight", this.checked);
  9162. });
  9163. });
  9164. </script>';
  9165. return $out;
  9166. }
  9167. /**
  9168. * Return HTML to show the search and clear seach button
  9169. *
  9170. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  9171. * @param string $cssclass CSS class
  9172. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  9173. * @param string $massactionname Mass action name
  9174. * @return string
  9175. */
  9176. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  9177. {
  9178. $out = $this->showFilterButtons();
  9179. if ($addcheckuncheckall) {
  9180. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  9181. }
  9182. return $out;
  9183. }
  9184. /**
  9185. * Return HTML to show the select of expense categories
  9186. *
  9187. * @param string $selected preselected category
  9188. * @param string $htmlname name of HTML select list
  9189. * @param integer $useempty 1=Add empty line
  9190. * @param array $excludeid id to exclude
  9191. * @param string $target htmlname of target select to bind event
  9192. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  9193. * @param array $params param to give
  9194. * @param int $info_admin Show the tooltip help picto to setup list
  9195. * @return string
  9196. */
  9197. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  9198. {
  9199. global $langs, $user;
  9200. $out = '';
  9201. $sql = "SELECT rowid, label FROM " . $this->db->prefix() . "c_exp_tax_cat WHERE active = 1";
  9202. $sql .= " AND entity IN (0," . getEntity('exp_tax_cat') . ")";
  9203. if (!empty($excludeid)) {
  9204. $sql .= " AND rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeid)) . ")";
  9205. }
  9206. $sql .= " ORDER BY label";
  9207. $resql = $this->db->query($sql);
  9208. if ($resql) {
  9209. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp maxwidth200">';
  9210. if ($useempty) {
  9211. $out .= '<option value="0">&nbsp;</option>';
  9212. }
  9213. while ($obj = $this->db->fetch_object($resql)) {
  9214. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . $langs->trans($obj->label) . '</option>';
  9215. }
  9216. $out .= '</select>';
  9217. $out .= ajax_combobox('select_' . $htmlname);
  9218. if (!empty($htmlname) && $user->admin && $info_admin) {
  9219. $out .= ' ' . info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  9220. }
  9221. if (!empty($target)) {
  9222. $sql = "SELECT c.id FROM " . $this->db->prefix() . "c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  9223. $resql = $this->db->query($sql);
  9224. if ($resql) {
  9225. if ($this->db->num_rows($resql) > 0) {
  9226. $obj = $this->db->fetch_object($resql);
  9227. $out .= '<script nonce="' . getNonce() . '">
  9228. $(function() {
  9229. $("select[name=' . $target . ']").on("change", function() {
  9230. var current_val = $(this).val();
  9231. if (current_val == ' . $obj->id . ') {';
  9232. if (!empty($default_selected) || !empty($selected)) {
  9233. $out .= '$("select[name=' . $htmlname . ']").val("' . ($default_selected > 0 ? $default_selected : $selected) . '");';
  9234. }
  9235. $out .= '
  9236. $("select[name=' . $htmlname . ']").change();
  9237. }
  9238. });
  9239. $("select[name=' . $htmlname . ']").change(function() {
  9240. if ($("select[name=' . $target . ']").val() == ' . $obj->id . ') {
  9241. // get price of kilometer to fill the unit price
  9242. $.ajax({
  9243. method: "POST",
  9244. dataType: "json",
  9245. data: { fk_c_exp_tax_cat: $(this).val(), token: \'' . currentToken() . '\' },
  9246. url: "' . (DOL_URL_ROOT . '/expensereport/ajax/ajaxik.php?' . join('&', $params)) . '",
  9247. }).done(function( data, textStatus, jqXHR ) {
  9248. console.log(data);
  9249. if (typeof data.up != "undefined") {
  9250. $("input[name=value_unit]").val(data.up);
  9251. $("select[name=' . $htmlname . ']").attr("title", data.title);
  9252. } else {
  9253. $("input[name=value_unit]").val("");
  9254. $("select[name=' . $htmlname . ']").attr("title", "");
  9255. }
  9256. });
  9257. }
  9258. });
  9259. });
  9260. </script>';
  9261. }
  9262. }
  9263. }
  9264. } else {
  9265. dol_print_error($this->db);
  9266. }
  9267. return $out;
  9268. }
  9269. /**
  9270. * Return HTML to show the select ranges of expense range
  9271. *
  9272. * @param string $selected preselected category
  9273. * @param string $htmlname name of HTML select list
  9274. * @param integer $useempty 1=Add empty line
  9275. * @return string
  9276. */
  9277. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  9278. {
  9279. global $conf, $langs;
  9280. $out = '';
  9281. $sql = "SELECT rowid, range_ik FROM " . $this->db->prefix() . "c_exp_tax_range";
  9282. $sql .= " WHERE entity = " . $conf->entity . " AND active = 1";
  9283. $resql = $this->db->query($sql);
  9284. if ($resql) {
  9285. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  9286. if ($useempty) {
  9287. $out .= '<option value="0"></option>';
  9288. }
  9289. while ($obj = $this->db->fetch_object($resql)) {
  9290. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . price($obj->range_ik, 0, $langs, 1, 0) . '</option>';
  9291. }
  9292. $out .= '</select>';
  9293. } else {
  9294. dol_print_error($this->db);
  9295. }
  9296. return $out;
  9297. }
  9298. /**
  9299. * Return HTML to show a select of expense
  9300. *
  9301. * @param string $selected preselected category
  9302. * @param string $htmlname name of HTML select list
  9303. * @param integer $useempty 1=Add empty choice
  9304. * @param integer $allchoice 1=Add all choice
  9305. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  9306. * @return string
  9307. */
  9308. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  9309. {
  9310. global $langs;
  9311. $out = '';
  9312. $sql = "SELECT id, code, label";
  9313. $sql .= " FROM ".$this->db->prefix()."c_type_fees";
  9314. $sql .= " WHERE active = 1";
  9315. $resql = $this->db->query($sql);
  9316. if ($resql) {
  9317. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  9318. if ($useempty) {
  9319. $out .= '<option value="0"></option>';
  9320. }
  9321. if ($allchoice) {
  9322. $out .= '<option value="-1">' . $langs->trans('AllExpenseReport') . '</option>';
  9323. }
  9324. $field = 'code';
  9325. if ($useid) {
  9326. $field = 'id';
  9327. }
  9328. while ($obj = $this->db->fetch_object($resql)) {
  9329. $key = $langs->trans($obj->code);
  9330. $out .= '<option ' . ($selected == $obj->{$field} ? 'selected="selected"' : '') . ' value="' . $obj->{$field} . '">' . ($key != $obj->code ? $key : $obj->label) . '</option>';
  9331. }
  9332. $out .= '</select>';
  9333. $out .= ajax_combobox('select_'.$htmlname);
  9334. } else {
  9335. dol_print_error($this->db);
  9336. }
  9337. return $out;
  9338. }
  9339. /**
  9340. * Output a combo list with invoices qualified for a third party
  9341. *
  9342. * @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)
  9343. * @param string $selected Id invoice preselected
  9344. * @param string $htmlname Name of HTML select
  9345. * @param int $maxlength Maximum length of label
  9346. * @param int $option_only Return only html options lines without the select tag
  9347. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9348. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  9349. * @param int $forcefocus Force focus on field (works with javascript only)
  9350. * @param int $disabled Disabled
  9351. * @param string $morecss More css added to the select component
  9352. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  9353. * @param string $showproject 'all' = Show project info, ''=Hide project info
  9354. * @param User $usertofilter User object to use for filtering
  9355. * @return string HTML Select Invoice
  9356. */
  9357. public function selectInvoice($socid = -1, $selected = '', $htmlname = 'invoiceid', $maxlength = 24, $option_only = 0, $show_empty = '1', $discard_closed = 0, $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500', $projectsListId = '', $showproject = 'all', $usertofilter = null)
  9358. {
  9359. global $user, $conf, $langs;
  9360. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  9361. if (is_null($usertofilter)) {
  9362. $usertofilter = $user;
  9363. }
  9364. $out = '';
  9365. $hideunselectables = false;
  9366. if (getDolGlobalString('PROJECT_HIDE_UNSELECTABLES')) {
  9367. $hideunselectables = true;
  9368. }
  9369. if (empty($projectsListId)) {
  9370. if (!$usertofilter->hasRight('projet', 'all', 'lire')) {
  9371. $projectstatic = new Project($this->db);
  9372. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  9373. }
  9374. }
  9375. // Search all projects
  9376. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  9377. p.title, p.fk_soc, p.fk_statut, p.public,";
  9378. $sql .= ' s.nom as name';
  9379. $sql .= ' FROM ' . $this->db->prefix() . 'projet as p';
  9380. $sql .= ' LEFT JOIN ' . $this->db->prefix() . 'societe as s ON s.rowid = p.fk_soc,';
  9381. $sql .= ' ' . $this->db->prefix() . 'facture as f';
  9382. $sql .= " WHERE p.entity IN (" . getEntity('project') . ")";
  9383. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  9384. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  9385. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  9386. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  9387. $sql .= " ORDER BY p.ref, f.ref ASC";
  9388. $resql = $this->db->query($sql);
  9389. if ($resql) {
  9390. // Use select2 selector
  9391. if (!empty($conf->use_javascript_ajax)) {
  9392. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9393. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9394. $out .= $comboenhancement;
  9395. $morecss = 'minwidth200imp maxwidth500';
  9396. }
  9397. if (empty($option_only)) {
  9398. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9399. }
  9400. if (!empty($show_empty)) {
  9401. $out .= '<option value="0" class="optiongrey">';
  9402. if (!is_numeric($show_empty)) {
  9403. $out .= $show_empty;
  9404. } else {
  9405. $out .= '&nbsp;';
  9406. }
  9407. $out .= '</option>';
  9408. }
  9409. $num = $this->db->num_rows($resql);
  9410. $i = 0;
  9411. if ($num) {
  9412. while ($i < $num) {
  9413. $obj = $this->db->fetch_object($resql);
  9414. // If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
  9415. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && !$usertofilter->hasRight('societe', 'lire')) {
  9416. // Do nothing
  9417. } else {
  9418. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  9419. $i++;
  9420. continue;
  9421. }
  9422. $labeltoshow = '';
  9423. if ($showproject == 'all') {
  9424. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  9425. if ($obj->name) {
  9426. $labeltoshow .= ' - ' . $obj->name; // Soc name
  9427. }
  9428. $disabled = 0;
  9429. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  9430. $disabled = 1;
  9431. $labeltoshow .= ' - ' . $langs->trans("Draft");
  9432. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  9433. if ($discard_closed == 2) {
  9434. $disabled = 1;
  9435. }
  9436. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9437. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  9438. $disabled = 1;
  9439. $labeltoshow .= ' - ' . $langs->trans("LinkedToAnotherCompany");
  9440. }
  9441. }
  9442. if (!empty($selected) && $selected == $obj->rowid) {
  9443. $out .= '<option value="' . $obj->rowid . '" selected';
  9444. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9445. $out .= '>' . $labeltoshow . '</option>';
  9446. } else {
  9447. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  9448. $resultat = '';
  9449. } else {
  9450. $resultat = '<option value="' . $obj->rowid . '"';
  9451. if ($disabled) {
  9452. $resultat .= ' disabled';
  9453. }
  9454. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  9455. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  9456. $resultat .= '>';
  9457. $resultat .= $labeltoshow;
  9458. $resultat .= '</option>';
  9459. }
  9460. $out .= $resultat;
  9461. }
  9462. }
  9463. $i++;
  9464. }
  9465. }
  9466. if (empty($option_only)) {
  9467. $out .= '</select>';
  9468. }
  9469. $this->db->free($resql);
  9470. return $out;
  9471. } else {
  9472. dol_print_error($this->db);
  9473. return '';
  9474. }
  9475. }
  9476. /**
  9477. * Output a combo list with invoices qualified for a third party
  9478. *
  9479. * @param string $selected Id invoice preselected
  9480. * @param string $htmlname Name of HTML select
  9481. * @param int $maxlength Maximum length of label
  9482. * @param int $option_only Return only html options lines without the select tag
  9483. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9484. * @param int $forcefocus Force focus on field (works with javascript only)
  9485. * @param int $disabled Disabled
  9486. * @param string $morecss More css added to the select component
  9487. * @return int Nbr of project if OK, <0 if KO
  9488. */
  9489. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  9490. {
  9491. global $conf, $langs;
  9492. $out = '';
  9493. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  9494. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  9495. //$sql.= ', el.fk_source';
  9496. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  9497. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  9498. $sql .= " ORDER BY f.titre ASC";
  9499. $resql = $this->db->query($sql);
  9500. if ($resql) {
  9501. // Use select2 selector
  9502. if (!empty($conf->use_javascript_ajax)) {
  9503. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9504. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9505. $out .= $comboenhancement;
  9506. $morecss = 'minwidth200imp maxwidth500';
  9507. }
  9508. if (empty($option_only)) {
  9509. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9510. }
  9511. if (!empty($show_empty)) {
  9512. $out .= '<option value="0" class="optiongrey">';
  9513. if (!is_numeric($show_empty)) {
  9514. $out .= $show_empty;
  9515. } else {
  9516. $out .= '&nbsp;';
  9517. }
  9518. $out .= '</option>';
  9519. }
  9520. $num = $this->db->num_rows($resql);
  9521. if ($num) {
  9522. while ($obj = $this->db->fetch_object($resql)) {
  9523. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  9524. $disabled = 0;
  9525. if (!empty($obj->suspended)) {
  9526. $disabled = 1;
  9527. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9528. }
  9529. if (!empty($selected) && $selected == $obj->rowid) {
  9530. $out .= '<option value="' . $obj->rowid . '" selected';
  9531. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9532. $out .= '>' . $labeltoshow . '</option>';
  9533. } else {
  9534. if ($disabled && ($selected != $obj->rowid)) {
  9535. $resultat = '';
  9536. } else {
  9537. $resultat = '<option value="' . $obj->rowid . '"';
  9538. if ($disabled) {
  9539. $resultat .= ' disabled';
  9540. }
  9541. $resultat .= '>';
  9542. $resultat .= $labeltoshow;
  9543. $resultat .= '</option>';
  9544. }
  9545. $out .= $resultat;
  9546. }
  9547. }
  9548. }
  9549. if (empty($option_only)) {
  9550. $out .= '</select>';
  9551. }
  9552. print $out;
  9553. $this->db->free($resql);
  9554. return $num;
  9555. } else {
  9556. $this->errors[] = $this->db->lasterror;
  9557. return -1;
  9558. }
  9559. }
  9560. /**
  9561. * Output the component to make advanced search criteries
  9562. *
  9563. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  9564. * @param array $search_component_params Array of selected search criterias
  9565. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  9566. * @param string $search_component_params_hidden String with $search_component_params criterias
  9567. * @return string HTML component for advanced search
  9568. */
  9569. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  9570. {
  9571. global $langs;
  9572. if ($search_component_params_hidden != '' && !preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  9573. $search_component_params_hidden = '(' . $search_component_params_hidden . ')';
  9574. }
  9575. $ret = '';
  9576. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  9577. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  9578. $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="' . dol_escape_htmltag($langs->trans("Filters")) . '" id="idsubimgproductdistribution"></span>';
  9579. $ret .= '</a>';
  9580. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  9581. // Show select fields as tags.
  9582. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  9583. if ($search_component_params_hidden) {
  9584. // Split the criteria on each AND
  9585. //var_dump($search_component_params_hidden);
  9586. $nbofchars = dol_strlen($search_component_params_hidden);
  9587. $arrayofandtags = array();
  9588. $i = 0;
  9589. $s = '';
  9590. $countparenthesis = 0;
  9591. while ($i < $nbofchars) {
  9592. $char = dol_substr($search_component_params_hidden, $i, 1);
  9593. if ($char == '(') {
  9594. $countparenthesis++;
  9595. } elseif ($char == ')') {
  9596. $countparenthesis--;
  9597. }
  9598. if ($countparenthesis == 0) {
  9599. $char2 = dol_substr($search_component_params_hidden, $i+1, 1);
  9600. $char3 = dol_substr($search_component_params_hidden, $i+2, 1);
  9601. if ($char == 'A' && $char2 == 'N' && $char3 == 'D') {
  9602. // We found a AND
  9603. $arrayofandtags[] = trim($s);
  9604. $s = '';
  9605. $i+=2;
  9606. } else {
  9607. $s .= $char;
  9608. }
  9609. } else {
  9610. $s .= $char;
  9611. }
  9612. $i++;
  9613. }
  9614. if ($s) {
  9615. $arrayofandtags[] = trim($s);
  9616. }
  9617. // Show each AND part
  9618. foreach ($arrayofandtags as $tmpkey => $tmpval) {
  9619. $errormessage = '';
  9620. $searchtags = forgeSQLFromUniversalSearchCriteria($tmpval, $errormessage, 1, 1);
  9621. if ($errormessage) {
  9622. $this->error = 'ERROR in parsing search string: '.$errormessage;
  9623. }
  9624. // Remove first and last parenthesis but only if first is the opening and last the closing of the same group
  9625. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  9626. $searchtags = removeGlobalParenthesis($searchtags);
  9627. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch" data-ufilterid="'.($tmpkey+1).'" data-ufilter="'.dol_escape_htmltag($tmpval).'">';
  9628. $ret .= '<span class="tagsearchdelete select2-selection__choice__remove" data-ufilterid="'.($tmpkey+1).'">x</span> ';
  9629. $ret .= dol_escape_htmltag($searchtags);
  9630. $ret .= '</span>';
  9631. }
  9632. }
  9633. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  9634. //$ret .= search_component_params
  9635. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  9636. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  9637. $show_search_component_params_hidden = 1;
  9638. if ($show_search_component_params_hidden) {
  9639. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  9640. }
  9641. $ret .= "<!-- We store the full Universal Search String into this field. For example: (t.ref:like:'SO-%') AND ((t.ref:like:'CO-%') OR (t.ref:like:'AA%')) -->";
  9642. $ret .= '<input type="hidden" name="search_component_params_hidden" value="' . dol_escape_htmltag($search_component_params_hidden) . '">';
  9643. // $ret .= "<!-- sql= ".forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage)." -->";
  9644. // For compatibility with forms that show themself the search criteria in addition of this component, we output these fields
  9645. foreach ($arrayofcriterias as $criterias) {
  9646. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  9647. if (in_array('search_' . $criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  9648. continue;
  9649. }
  9650. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  9651. continue;
  9652. }
  9653. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  9654. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_start">';
  9655. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startyear">';
  9656. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startmonth">';
  9657. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startday">';
  9658. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_end">';
  9659. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endyear">';
  9660. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endmonth">';
  9661. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endday">';
  9662. } else {
  9663. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '">';
  9664. }
  9665. }
  9666. }
  9667. $ret .= '</div>';
  9668. $ret .= "<!-- Field to enter a generic filter string: t.ref:like:'SO-%', t.date_creation:<:'20160101', t.date_creation:<:'2016-01-01 12:30:00', t.nature:is:NULL, t.field2:isnot:NULL -->\n";
  9669. $ret .= '<input type="text" placeholder="' . $langs->trans("Search") . '" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9670. $ret .= '</div>';
  9671. $ret .= '</div>';
  9672. $ret .= '<script>
  9673. jQuery(".tagsearchdelete").click(function() {
  9674. var filterid = $(this).parents().data("ufilterid");
  9675. console.log("We click to delete a criteria nb "+filterid);
  9676. // TODO Update the search_component_params_hidden with all data-ufilter except the one delete and post page
  9677. });
  9678. </script>
  9679. ';
  9680. return $ret;
  9681. }
  9682. /**
  9683. * selectModelMail
  9684. *
  9685. * @param string $prefix Prefix
  9686. * @param string $modelType Model type
  9687. * @param int $default 1=Show also Default mail template
  9688. * @param int $addjscombo Add js combobox
  9689. * @return string HTML select string
  9690. */
  9691. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9692. {
  9693. global $langs, $user;
  9694. $retstring = '';
  9695. $TModels = array();
  9696. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  9697. $formmail = new FormMail($this->db);
  9698. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9699. if ($default) {
  9700. $TModels[0] = $langs->trans('DefaultMailModel');
  9701. }
  9702. if ($result > 0) {
  9703. foreach ($formmail->lines_model as $model) {
  9704. $TModels[$model->id] = $model->label;
  9705. }
  9706. }
  9707. $retstring .= '<select class="flat" id="select_' . $prefix . 'model_mail" name="' . $prefix . 'model_mail">';
  9708. foreach ($TModels as $id_model => $label_model) {
  9709. $retstring .= '<option value="' . $id_model . '"';
  9710. $retstring .= ">" . $label_model . "</option>";
  9711. }
  9712. $retstring .= "</select>";
  9713. if ($addjscombo) {
  9714. $retstring .= ajax_combobox('select_' . $prefix . 'model_mail');
  9715. }
  9716. return $retstring;
  9717. }
  9718. /**
  9719. * Output the buttons to submit a creation/edit form
  9720. *
  9721. * @param string $save_label Alternative label for save button
  9722. * @param string $cancel_label Alternative label for cancel button
  9723. * @param array $morebuttons Add additional buttons between save and cancel
  9724. * @param bool $withoutdiv Option to remove enclosing centered div
  9725. * @param string $morecss More CSS
  9726. * @param string $dol_openinpopup If the button are shown in a context of a page shown inside a popup, we put here the string name of popup.
  9727. * @return string Html code with the buttons
  9728. */
  9729. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = false, $morecss = '', $dol_openinpopup = '')
  9730. {
  9731. global $langs;
  9732. $buttons = array();
  9733. $save = array(
  9734. 'name' => 'save',
  9735. 'label_key' => $save_label,
  9736. );
  9737. if ($save_label == 'Create' || $save_label == 'Add') {
  9738. $save['name'] = 'add';
  9739. } elseif ($save_label == 'Modify') {
  9740. $save['name'] = 'edit';
  9741. }
  9742. $cancel = array(
  9743. 'name' => 'cancel',
  9744. 'label_key' => 'Cancel',
  9745. );
  9746. !empty($save_label) ? $buttons[] = $save : '';
  9747. if (!empty($morebuttons)) {
  9748. $buttons[] = $morebuttons;
  9749. }
  9750. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9751. $retstring = $withoutdiv ? '' : '<div class="center">';
  9752. foreach ($buttons as $button) {
  9753. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9754. $retstring .= '<input type="submit" class="button button-' . $button['name'] . ($morecss ? ' ' . $morecss : '') . ' ' . $addclass . '" name="' . $button['name'] . '" value="' . dol_escape_htmltag($langs->trans($button['label_key'])) . '">';
  9755. }
  9756. $retstring .= $withoutdiv ? '' : '</div>';
  9757. if ($dol_openinpopup) {
  9758. $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . $dol_openinpopup . ' context, so we enable the close of dialog on cancel -->' . "\n";
  9759. $retstring .= '<script nonce="' . getNonce() . '">';
  9760. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9761. e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . $dol_openinpopup . '\');
  9762. window.parent.jQuery(\'#idfordialog' . $dol_openinpopup . '\').dialog(\'close\');
  9763. });';
  9764. $retstring .= '</script>';
  9765. }
  9766. return $retstring;
  9767. }
  9768. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  9769. /**
  9770. * Load into cache list of invoice subtypes
  9771. *
  9772. * @return int Nb of lines loaded, <0 if KO
  9773. */
  9774. public function load_cache_invoice_subtype()
  9775. {
  9776. // phpcs:enable
  9777. global $langs;
  9778. $num = count($this->cache_invoice_subtype);
  9779. if ($num > 0) {
  9780. return 0; // Cache already loaded
  9781. }
  9782. dol_syslog(__METHOD__, LOG_DEBUG);
  9783. $sql = "SELECT rowid, code, label as label";
  9784. $sql .= " FROM " . MAIN_DB_PREFIX . 'c_invoice_subtype';
  9785. $sql .= " WHERE active = 1";
  9786. $resql = $this->db->query($sql);
  9787. if ($resql) {
  9788. $num = $this->db->num_rows($resql);
  9789. $i = 0;
  9790. while ($i < $num) {
  9791. $obj = $this->db->fetch_object($resql);
  9792. // If translation exists, we use it, otherwise we take the default wording
  9793. $label = ($langs->trans("InvoiceSubtype" . $obj->rowid) != "InvoiceSubtype" . $obj->rowid) ? $langs->trans("InvoiceSubtype" . $obj->rowid) : (($obj->label != '-') ? $obj->label : '');
  9794. $this->cache_invoice_subtype[$obj->rowid]['rowid'] = $obj->rowid;
  9795. $this->cache_invoice_subtype[$obj->rowid]['code'] = $obj->code;
  9796. $this->cache_invoice_subtype[$obj->rowid]['label'] = $label;
  9797. $i++;
  9798. }
  9799. $this->cache_invoice_subtype = dol_sort_array($this->cache_invoice_subtype, 'code', 'asc', 0, 0, 1);
  9800. return $num;
  9801. } else {
  9802. dol_print_error($this->db);
  9803. return -1;
  9804. }
  9805. }
  9806. /**
  9807. * Return list of invoice subtypes.
  9808. *
  9809. * @param int $selected Id of invoice subtype to preselect by default
  9810. * @param string $htmlname Select field name
  9811. * @param int $addempty Add an empty entry
  9812. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  9813. * @param string $morecss Add more CSS on select tag
  9814. * @return string String for the HTML select component
  9815. */
  9816. public function getSelectInvoiceSubtype($selected = 0, $htmlname = 'subtypeid', $addempty = 0, $noinfoadmin = 0, $morecss = '')
  9817. {
  9818. global $langs, $user;
  9819. $out = '';
  9820. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  9821. $this->load_cache_invoice_subtype();
  9822. $out .= '<select id="' . $htmlname . '" class="flat selectsubtype' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  9823. if ($addempty) {
  9824. $out .= '<option value="0">&nbsp;</option>';
  9825. }
  9826. foreach ($this->cache_invoice_subtype as $rowid => $subtype) {
  9827. $label = $subtype['label'];
  9828. $out .= '<option value="' . $subtype['rowid'] . '"';
  9829. if ($selected == $subtype['rowid']) {
  9830. $out .= ' selected="selected"';
  9831. }
  9832. $out .= '>';
  9833. $out .= $label;
  9834. $out .= '</option>';
  9835. }
  9836. $out .= '</select>';
  9837. if ($user->admin && empty($noinfoadmin)) {
  9838. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  9839. }
  9840. $out .= ajax_combobox($htmlname);
  9841. return $out;
  9842. }
  9843. }