html.form.class.php 414 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962
  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-2020 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. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. */
  38. /**
  39. * \file htdocs/core/class/html.form.class.php
  40. * \ingroup core
  41. * \brief File of class with all html predefined components
  42. */
  43. /**
  44. * Class to manage generation of HTML components
  45. * Only common components must be here.
  46. *
  47. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  48. */
  49. class Form
  50. {
  51. /**
  52. * @var DoliDB Database handler.
  53. */
  54. public $db;
  55. /**
  56. * @var string Error code (or message)
  57. */
  58. public $error = '';
  59. /**
  60. * @var string[] Array of error strings
  61. */
  62. public $errors = array();
  63. public $num;
  64. // Cache arrays
  65. public $cache_types_paiements = array();
  66. public $cache_conditions_paiements = array();
  67. public $cache_transport_mode = array();
  68. public $cache_availability = array();
  69. public $cache_demand_reason = array();
  70. public $cache_types_fees = array();
  71. public $cache_vatrates = array();
  72. /**
  73. * Constructor
  74. *
  75. * @param DoliDB $db Database handler
  76. */
  77. public function __construct($db)
  78. {
  79. $this->db = $db;
  80. }
  81. /**
  82. * Output key field for an editable field
  83. *
  84. * @param string $text Text of label or key to translate
  85. * @param string $htmlname Name of select field ('edit' prefix will be added)
  86. * @param string $preselected Value to show/edit (not used in this function)
  87. * @param object $object Object
  88. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  89. * @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), 'checkbox:ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  90. * @param string $moreparam More param to add on a href URL.
  91. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  92. * @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 ' '
  93. * @param string $paramid Key of parameter for id ('id', 'socid')
  94. * @param string $help Tooltip help
  95. * @return string HTML edit field
  96. */
  97. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  98. {
  99. global $conf, $langs;
  100. $ret = '';
  101. // TODO change for compatibility
  102. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
  103. if (!empty($perm)) {
  104. $tmp = explode(':', $typeofdata);
  105. $ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  106. if ($fieldrequired) {
  107. $ret .= '<span class="fieldrequired">';
  108. }
  109. if ($help) {
  110. $ret .= $this->textwithpicto($langs->trans($text), $help);
  111. } else {
  112. $ret .= $langs->trans($text);
  113. }
  114. if ($fieldrequired) {
  115. $ret .= '</span>';
  116. }
  117. $ret .= '</div>'."\n";
  118. } else {
  119. if ($fieldrequired) {
  120. $ret .= '<span class="fieldrequired">';
  121. }
  122. if ($help) {
  123. $ret .= $this->textwithpicto($langs->trans($text), $help);
  124. } else {
  125. $ret .= $langs->trans($text);
  126. }
  127. if ($fieldrequired) {
  128. $ret .= '</span>';
  129. }
  130. }
  131. } else {
  132. if (empty($notabletag) && $perm) {
  133. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  134. }
  135. if ($fieldrequired) {
  136. $ret .= '<span class="fieldrequired">';
  137. }
  138. if ($help) {
  139. $ret .= $this->textwithpicto($langs->trans($text), $help);
  140. } else {
  141. $ret .= $langs->trans($text);
  142. }
  143. if ($fieldrequired) {
  144. $ret .= '</span>';
  145. }
  146. if (!empty($notabletag)) {
  147. $ret .= ' ';
  148. }
  149. if (empty($notabletag) && $perm) {
  150. $ret .= '</td>';
  151. }
  152. if (empty($notabletag) && $perm) {
  153. $ret .= '<td class="right">';
  154. }
  155. if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  156. $ret .= '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&token='.newToken().'&'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  157. }
  158. if (!empty($notabletag) && $notabletag == 1) {
  159. $ret .= ' : ';
  160. }
  161. if (!empty($notabletag) && $notabletag == 3) {
  162. $ret .= ' ';
  163. }
  164. if (empty($notabletag) && $perm) {
  165. $ret .= '</td>';
  166. }
  167. if (empty($notabletag) && $perm) {
  168. $ret .= '</tr></table>';
  169. }
  170. }
  171. return $ret;
  172. }
  173. /**
  174. * Output value of a field for an editable field
  175. *
  176. * @param string $text Text of label (not used in this function)
  177. * @param string $htmlname Name of select field
  178. * @param string $value Value to show/edit
  179. * @param object $object Object
  180. * @param boolean $perm Permission to allow button to edit parameter
  181. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select;xkey:xval,ykey:yval,...')
  182. * @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). Use '' to use same than $value
  183. * @param object $extObject External object
  184. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  185. * @param string $moreparam More param to add on the form action href URL
  186. * @param int $notabletag Do no output table tags
  187. * @param string $formatfunc Call a specific function to output field in view mode (For example: 'dol_print_email')
  188. * @param string $paramid Key of parameter for id ('id', 'socid')
  189. * @param string $gm 'auto' or 'tzuser' or 'tzserver' (when $typeofdata is a date)
  190. * @return string HTML edit field
  191. */
  192. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id', $gm = 'auto')
  193. {
  194. global $conf, $langs;
  195. $ret = '';
  196. // Check parameters
  197. if (empty($typeofdata)) {
  198. return 'ErrorBadParameter';
  199. }
  200. // When option to edit inline is activated
  201. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  202. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  203. } else {
  204. $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
  205. if ($editmode) {
  206. $ret .= "\n";
  207. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  208. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  209. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  210. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  211. if (empty($notabletag)) {
  212. $ret .= '<table class="nobordernopadding centpercent">';
  213. }
  214. if (empty($notabletag)) {
  215. $ret .= '<tr><td>';
  216. }
  217. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) {
  218. $tmp = explode(':', $typeofdata);
  219. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  220. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  221. $tmp = explode(':', $typeofdata);
  222. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  223. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ? price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  224. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  225. $tmp = explode(':', $typeofdata);
  226. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  227. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  228. $tmp = explode(':', $typeofdata);
  229. $cols = $tmp[2];
  230. $morealt = '';
  231. if (preg_match('/%/', $cols)) {
  232. $morealt = ' style="width: '.$cols.'"';
  233. $cols = '';
  234. }
  235. $valuetoshow = ($editvalue ? $editvalue : $value);
  236. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  237. // textarea convert automatically entities chars into simple chars.
  238. // 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.
  239. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  240. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  241. $ret .= '</textarea>';
  242. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  243. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  244. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  245. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  246. } elseif (preg_match('/^select;/', $typeofdata)) {
  247. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  248. $arraylist = array();
  249. foreach ($arraydata as $val) {
  250. $tmp = explode(':', $val);
  251. $tmpkey = str_replace('|', ':', $tmp[0]);
  252. $arraylist[$tmpkey] = $tmp[1];
  253. }
  254. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  255. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  256. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  257. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  258. $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), ($tmp[2] ? $tmp[2] : ''), ($tmp[3] ? $tmp[3] : '100'), ($tmp[1] ? $tmp[1] : 'dolibarr_notes'), 'In', ($tmp[5] ? $tmp[5] : 0), (isset($tmp[8]) ? ($tmp[8] ?true:false) : true), true, ($tmp[6] ? $tmp[6] : '20'), ($tmp[7] ? $tmp[7] : '100'));
  259. $ret .= $doleditor->Create(1);
  260. }
  261. if (empty($notabletag)) {
  262. $ret .= '</td>';
  263. }
  264. if (empty($notabletag)) {
  265. $ret .= '<td class="left">';
  266. }
  267. //else $ret.='<div class="clearboth"></div>';
  268. $ret .= '<input type="submit" class="smallpaddingimp button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  269. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  270. $ret .= '<br>'."\n";
  271. }
  272. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  273. if (empty($notabletag)) {
  274. $ret .= '</td>';
  275. }
  276. if (empty($notabletag)) {
  277. $ret .= '</tr></table>'."\n";
  278. }
  279. $ret .= '</form>'."\n";
  280. } else {
  281. if (preg_match('/^(email)/', $typeofdata)) {
  282. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  283. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  284. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  285. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  286. $tmp = explode(':', $typeofdata);
  287. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  288. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  289. $ret .= dol_htmlentitiesbr($value);
  290. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  291. $ret .= dol_string_onlythesehtmltags($value);
  292. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  293. $ret .= dol_string_onlythesehtmltags($value);
  294. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  295. $ret .= '<span class="valuedate">'.dol_print_date($value, 'day', $gm).'</span>';
  296. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  297. $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour', $gm).'</span>';
  298. } elseif (preg_match('/^select;/', $typeofdata)) {
  299. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  300. $arraylist = array();
  301. foreach ($arraydata as $val) {
  302. $tmp = explode(':', $val);
  303. $arraylist[$tmp[0]] = $tmp[1];
  304. }
  305. $ret .= $arraylist[$value];
  306. if ($htmlname == 'fk_product_type') {
  307. if ($value == 0) {
  308. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  309. } else {
  310. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  311. }
  312. }
  313. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  314. $tmpcontent = dol_htmlentitiesbr($value);
  315. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  316. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  317. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  318. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  319. }
  320. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  321. // clean data from some dangerous html
  322. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  323. } else {
  324. $ret .= dol_escape_htmltag($value);
  325. }
  326. if ($formatfunc && method_exists($object, $formatfunc)) {
  327. $ret = $object->$formatfunc($ret);
  328. }
  329. }
  330. }
  331. return $ret;
  332. }
  333. /**
  334. * Output edit in place form
  335. *
  336. * @param string $fieldname Name of the field
  337. * @param object $object Object
  338. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  339. * @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]'...)
  340. * @param string $check Same coe than $check parameter of GETPOST()
  341. * @param string $morecss More CSS
  342. * @return string HTML code for the edit of alternative language
  343. */
  344. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  345. {
  346. global $conf, $langs, $extralanguages;
  347. $result = '';
  348. // List of extra languages
  349. $arrayoflangcode = array();
  350. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  351. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  352. }
  353. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  354. if (!is_object($extralanguages)) {
  355. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  356. $extralanguages = new ExtraLanguages($this->db);
  357. }
  358. $extralanguages->fetch_name_extralanguages('societe');
  359. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  360. return ''; // No extralang field to show
  361. }
  362. $result .= '<!-- Widget for translation -->'."\n";
  363. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  364. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  365. $result .= $s;
  366. $result .= '</div>';
  367. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  368. $resultforextrlang = '';
  369. foreach ($arrayoflangcode as $langcode) {
  370. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  371. if (empty($valuetoshow)) {
  372. $object->fetchValuesForExtraLanguages();
  373. //var_dump($object->array_languages);
  374. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  375. }
  376. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  377. $resultforextrlang .= $s;
  378. // TODO Use the showInputField() method of ExtraLanguages object
  379. if ($typeofdata == 'textarea') {
  380. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  381. $resultforextrlang .= $valuetoshow;
  382. $resultforextrlang .= '</textarea>';
  383. } else {
  384. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  385. }
  386. }
  387. $result .= $resultforextrlang;
  388. $result .= '</div>';
  389. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  390. }
  391. return $result;
  392. }
  393. /**
  394. * Output edit in place form
  395. *
  396. * @param object $object Object
  397. * @param string $value Value to show/edit
  398. * @param string $htmlname DIV ID (field name)
  399. * @param int $condition Condition to edit
  400. * @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')
  401. * @param string $editvalue When in edit mode, use this value as $value instead of value
  402. * @param object $extObject External object
  403. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  404. * @return string HTML edit in place
  405. */
  406. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  407. {
  408. global $conf;
  409. $out = '';
  410. // Check parameters
  411. if (preg_match('/^text/', $inputType)) {
  412. $value = dol_nl2br($value);
  413. } elseif (preg_match('/^numeric/', $inputType)) {
  414. $value = price($value);
  415. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  416. $value = dol_print_date($value, 'day');
  417. }
  418. if ($condition) {
  419. $element = false;
  420. $table_element = false;
  421. $fk_element = false;
  422. $loadmethod = false;
  423. $savemethod = false;
  424. $ext_element = false;
  425. $button_only = false;
  426. $inputOption = '';
  427. if (is_object($object)) {
  428. $element = $object->element;
  429. $table_element = $object->table_element;
  430. $fk_element = $object->id;
  431. }
  432. if (is_object($extObject)) {
  433. $ext_element = $extObject->element;
  434. }
  435. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  436. $tmp = explode(':', $inputType);
  437. $inputType = $tmp[0];
  438. if (!empty($tmp[1])) {
  439. $inputOption = $tmp[1];
  440. }
  441. if (!empty($tmp[2])) {
  442. $savemethod = $tmp[2];
  443. }
  444. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  445. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  446. $tmp = explode(':', $inputType);
  447. $inputType = $tmp[0];
  448. if (!empty($tmp[1])) {
  449. $inputOption = $tmp[1];
  450. }
  451. if (!empty($tmp[2])) {
  452. $savemethod = $tmp[2];
  453. }
  454. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  455. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  456. $tmp = explode(':', $inputType);
  457. $inputType = $tmp[0];
  458. $loadmethod = $tmp[1];
  459. if (!empty($tmp[2])) {
  460. $savemethod = $tmp[2];
  461. }
  462. if (!empty($tmp[3])) {
  463. $button_only = true;
  464. }
  465. } elseif (preg_match('/^textarea/', $inputType)) {
  466. $tmp = explode(':', $inputType);
  467. $inputType = $tmp[0];
  468. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  469. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  470. } elseif (preg_match('/^ckeditor/', $inputType)) {
  471. $tmp = explode(':', $inputType);
  472. $inputType = $tmp[0];
  473. $toolbar = $tmp[1];
  474. if (!empty($tmp[2])) {
  475. $width = $tmp[2];
  476. }
  477. if (!empty($tmp[3])) {
  478. $heigth = $tmp[3];
  479. }
  480. if (!empty($tmp[4])) {
  481. $savemethod = $tmp[4];
  482. }
  483. if (!empty($conf->fckeditor->enabled)) {
  484. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  485. } else {
  486. $inputType = 'textarea';
  487. }
  488. }
  489. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  490. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  491. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  492. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  493. if (!empty($savemethod)) {
  494. $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  495. }
  496. if (!empty($ext_element)) {
  497. $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  498. }
  499. if (!empty($custommsg)) {
  500. if (is_array($custommsg)) {
  501. if (!empty($custommsg['success'])) {
  502. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  503. }
  504. if (!empty($custommsg['error'])) {
  505. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  506. }
  507. } else {
  508. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  509. }
  510. }
  511. if ($inputType == 'textarea') {
  512. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  513. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  514. }
  515. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  516. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  517. } else {
  518. $out = $value;
  519. }
  520. return $out;
  521. }
  522. /**
  523. * Show a text and picto with tooltip on text or picto.
  524. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  525. *
  526. * @param string $text Text to show
  527. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  528. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  529. * @param int $direction -1=image is before, 0=no image, 1=image is after
  530. * @param string $img Html code for image (use img_xxx() function to get it)
  531. * @param string $extracss Add a CSS style to td tags
  532. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  533. * @param string $incbefore Include code before the text
  534. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  535. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  536. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  537. * @return string Code html du tooltip (texte+picto)
  538. * @see textwithpicto() Use thisfunction if you can.
  539. */
  540. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  541. {
  542. if ($incbefore) {
  543. $text = $incbefore.$text;
  544. }
  545. if (!$htmltext) {
  546. return $text;
  547. }
  548. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  549. $tag = 'td';
  550. if ($notabs == 2) {
  551. $tag = 'div';
  552. }
  553. if ($notabs == 3) {
  554. $tag = 'span';
  555. }
  556. // Sanitize tooltip
  557. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  558. $extrastyle = '';
  559. if ($direction < 0) {
  560. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  561. $extrastyle = 'padding: 0px; padding-left: 3px !important;';
  562. }
  563. if ($direction > 0) {
  564. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  565. $extrastyle = 'padding: 0px; padding-right: 3px !important;';
  566. }
  567. $classfortooltip = 'classfortooltip';
  568. $s = '';
  569. $textfordialog = '';
  570. if ($tooltiptrigger == '') {
  571. $htmltext = str_replace('"', '&quot;', $htmltext);
  572. } else {
  573. $classfortooltip = 'classfortooltiponclick';
  574. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  575. }
  576. if ($tooltipon == 2 || $tooltipon == 3) {
  577. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  578. if ($tooltiptrigger == '') {
  579. $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  580. } else {
  581. $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  582. }
  583. } else {
  584. $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  585. }
  586. if ($tooltipon == 1 || $tooltipon == 3) {
  587. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  588. if ($tooltiptrigger == '') {
  589. $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  590. } else {
  591. $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  592. }
  593. } else {
  594. $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  595. }
  596. if (empty($notabs)) {
  597. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  598. } elseif ($notabs == 2) {
  599. $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  600. }
  601. // Define value if value is before
  602. if ($direction < 0) {
  603. $s .= '<'.$tag.$paramfortooltipimg;
  604. if ($tag == 'td') {
  605. $s .= ' class=valigntop" width="14"';
  606. }
  607. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  608. }
  609. // Use another method to help avoid having a space in value in order to use this value with jquery
  610. // Define label
  611. if ((string) $text != '') {
  612. $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  613. }
  614. // Define value if value is after
  615. if ($direction > 0) {
  616. $s .= '<'.$tag.$paramfortooltipimg;
  617. if ($tag == 'td') {
  618. $s .= ' class="valignmiddle" width="14"';
  619. }
  620. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  621. }
  622. if (empty($notabs)) {
  623. $s .= '</tr></table>';
  624. } elseif ($notabs == 2) {
  625. $s .= '</div>';
  626. }
  627. return $s;
  628. }
  629. /**
  630. * Show a text with a picto and a tooltip on picto
  631. *
  632. * @param string $text Text to show
  633. * @param string $htmltext Content of tooltip
  634. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  635. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  636. * @param string $extracss Add a CSS style to td, div or span tag
  637. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  638. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  639. * @param string $tooltiptrigger ''=Tooltip on hover, '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')
  640. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  641. * @return string HTML code of text, picto, tooltip
  642. */
  643. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  644. {
  645. global $conf, $langs;
  646. $alt = '';
  647. if ($tooltiptrigger) {
  648. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  649. }
  650. //For backwards compatibility
  651. if ($type == '0') {
  652. $type = 'info';
  653. } elseif ($type == '1') {
  654. $type = 'help';
  655. }
  656. // If info or help with no javascript, show only text
  657. if (empty($conf->use_javascript_ajax)) {
  658. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  659. return $text;
  660. } else {
  661. $alt = $htmltext;
  662. $htmltext = '';
  663. }
  664. }
  665. // If info or help with smartphone, show only text (tooltip hover can't works)
  666. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  667. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  668. return $text;
  669. }
  670. }
  671. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  672. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  673. //{
  674. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  675. //}
  676. $img = '';
  677. if ($type == 'info') {
  678. $img = img_help(0, $alt);
  679. } elseif ($type == 'help') {
  680. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  681. } elseif ($type == 'helpclickable') {
  682. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  683. } elseif ($type == 'superadmin') {
  684. $img = img_picto($alt, 'redstar');
  685. } elseif ($type == 'admin') {
  686. $img = img_picto($alt, 'star');
  687. } elseif ($type == 'warning') {
  688. $img = img_warning($alt);
  689. } elseif ($type != 'none') {
  690. $img = img_picto($alt, $type); // $type can be an image path
  691. }
  692. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  693. }
  694. /**
  695. * Generate select HTML to choose massaction
  696. *
  697. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  698. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  699. * @param int $alwaysvisible 1=select button always visible
  700. * @param string $name Name for massaction
  701. * @param string $cssclass CSS class used to check for select
  702. * @return string|void Select list
  703. */
  704. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  705. {
  706. global $conf, $langs, $hookmanager;
  707. $disabled = 0;
  708. $ret = '<div class="centpercent center">';
  709. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  710. // 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.
  711. $parameters = array();
  712. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  713. // check if there is a mass action
  714. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  715. return;
  716. }
  717. if (empty($reshook)) {
  718. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  719. foreach ($arrayofaction as $code => $label) {
  720. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  721. }
  722. }
  723. $ret .= $hookmanager->resPrint;
  724. $ret .= '</select>';
  725. if (empty($conf->dol_optimize_smallscreen)) {
  726. $ret .= ajax_combobox('.'.$name.'select');
  727. }
  728. // 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
  729. $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.
  730. $ret .= '<input type="submit" disabled name="confirmmassaction"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display: none"').' class="button smallpaddingimp'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'confirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  731. $ret .= '</div>';
  732. if (!empty($conf->use_javascript_ajax)) {
  733. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  734. <script>
  735. 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 */
  736. {
  737. atleastoneselected=0;
  738. jQuery("."+cssclass).each(function( index ) {
  739. /* console.log( index + ": " + $( this ).text() ); */
  740. if ($(this).is(\':checked\')) atleastoneselected++;
  741. });
  742. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  743. if (atleastoneselected || '.$alwaysvisible.')
  744. {
  745. jQuery("."+name).show();
  746. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  747. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  748. }
  749. else
  750. {
  751. jQuery("."+name).hide();
  752. jQuery("."+name+"other").hide();
  753. }
  754. }
  755. jQuery(document).ready(function () {
  756. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  757. jQuery(".' . $cssclass.'").click(function() {
  758. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  759. });
  760. jQuery(".' . $name.'select").change(function() {
  761. var massaction = $( this ).val();
  762. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  763. if (massaction == "builddoc")
  764. {
  765. urlform = urlform + "#show_files";
  766. }
  767. $( this ).closest("form").attr("action", urlform);
  768. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  769. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  770. if ($(this).val() != \'0\')
  771. {
  772. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  773. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  774. jQuery(".' . $name.'"+massaction).show();
  775. }
  776. else
  777. {
  778. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  779. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  780. }
  781. });
  782. });
  783. </script>
  784. ';
  785. }
  786. return $ret;
  787. }
  788. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  789. /**
  790. * Return combo list of activated countries, into language of user
  791. *
  792. * @param string $selected Id or Code or Label of preselected country
  793. * @param string $htmlname Name of html select object
  794. * @param string $htmloption More html options on select object
  795. * @param integer $maxlength Max length for labels (0=no limit)
  796. * @param string $morecss More css class
  797. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  798. * @param int $showempty Show empty choice
  799. * @param int $disablefavorites 1=Disable favorites,
  800. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  801. * @param array $exclude_country_code Array of country code (iso2) to exclude
  802. * @param int $hideflags Hide flags
  803. * @return string HTML string with select
  804. */
  805. 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)
  806. {
  807. // phpcs:enable
  808. global $conf, $langs, $mysoc;
  809. $langs->load("dict");
  810. $out = '';
  811. $countryArray = array();
  812. $favorite = array();
  813. $label = array();
  814. $atleastonefavorite = 0;
  815. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  816. $sql .= " FROM ".$this->db->prefix()."c_country";
  817. $sql .= " WHERE active > 0";
  818. //$sql.= " ORDER BY code ASC";
  819. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  820. $resql = $this->db->query($sql);
  821. if ($resql) {
  822. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  823. $num = $this->db->num_rows($resql);
  824. $i = 0;
  825. if ($num) {
  826. while ($i < $num) {
  827. $obj = $this->db->fetch_object($resql);
  828. $countryArray[$i]['rowid'] = $obj->rowid;
  829. $countryArray[$i]['code_iso'] = $obj->code_iso;
  830. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  831. $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 : ''));
  832. $countryArray[$i]['favorite'] = $obj->favorite;
  833. $countryArray[$i]['eec'] = $obj->eec;
  834. $favorite[$i] = $obj->favorite;
  835. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  836. $i++;
  837. }
  838. if (empty($disablefavorites)) {
  839. array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  840. } else {
  841. $countryArray = dol_sort_array($countryArray, 'label');
  842. }
  843. if ($showempty) {
  844. $out .= '<option value="">&nbsp;</option>'."\n";
  845. }
  846. if ($addspecialentries) { // Add dedicated entries for groups of countries
  847. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  848. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  849. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  850. if ($mysoc->isInEEC()) {
  851. $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  852. }
  853. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  854. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  855. }
  856. foreach ($countryArray as $row) {
  857. //if (empty($showempty) && empty($row['rowid'])) continue;
  858. if (empty($row['rowid'])) {
  859. continue;
  860. }
  861. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  862. continue; // exclude some countries
  863. }
  864. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  865. $atleastonefavorite++;
  866. }
  867. if (empty($row['favorite']) && $atleastonefavorite) {
  868. $atleastonefavorite = 0;
  869. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  870. }
  871. $labeltoshow = '';
  872. if ($row['label']) {
  873. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  874. } else {
  875. $labeltoshow .= '&nbsp;';
  876. }
  877. if ($row['code_iso']) {
  878. $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
  879. if (empty($hideflags)) {
  880. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  881. $labeltoshow = $tmpflag.' '.$labeltoshow;
  882. }
  883. }
  884. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  885. $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']).'">';
  886. } else {
  887. $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']).'">';
  888. }
  889. $out .= $labeltoshow;
  890. $out .= '</option>'."\n";
  891. }
  892. }
  893. $out .= '</select>';
  894. } else {
  895. dol_print_error($this->db);
  896. }
  897. // Make select dynamic
  898. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  899. $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
  900. return $out;
  901. }
  902. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  903. /**
  904. * Return select list of incoterms
  905. *
  906. * @param string $selected Id or Code of preselected incoterm
  907. * @param string $location_incoterms Value of input location
  908. * @param string $page Defined the form action
  909. * @param string $htmlname Name of html select object
  910. * @param string $htmloption Options html on select object
  911. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  912. * @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')))
  913. * @return string HTML string with select and input
  914. */
  915. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
  916. {
  917. // phpcs:enable
  918. global $conf, $langs;
  919. $langs->load("dict");
  920. $out = '';
  921. $moreattrib = '';
  922. $incotermArray = array();
  923. $sql = "SELECT rowid, code";
  924. $sql .= " FROM ".$this->db->prefix()."c_incoterms";
  925. $sql .= " WHERE active > 0";
  926. $sql .= " ORDER BY code ASC";
  927. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  928. $resql = $this->db->query($sql);
  929. if ($resql) {
  930. if ($conf->use_javascript_ajax && !$forcecombo) {
  931. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  932. $out .= ajax_combobox($htmlname, $events);
  933. }
  934. if (!empty($page)) {
  935. $out .= '<form method="post" action="'.$page.'">';
  936. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  937. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  938. }
  939. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm width75" name="'.$htmlname.'" '.$htmloption.'>';
  940. $out .= '<option value="0">&nbsp;</option>';
  941. $num = $this->db->num_rows($resql);
  942. $i = 0;
  943. if ($num) {
  944. $foundselected = false;
  945. while ($i < $num) {
  946. $obj = $this->db->fetch_object($resql);
  947. $incotermArray[$i]['rowid'] = $obj->rowid;
  948. $incotermArray[$i]['code'] = $obj->code;
  949. $i++;
  950. }
  951. foreach ($incotermArray as $row) {
  952. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  953. $out .= '<option value="'.$row['rowid'].'" selected>';
  954. } else {
  955. $out .= '<option value="'.$row['rowid'].'">';
  956. }
  957. if ($row['code']) {
  958. $out .= $row['code'];
  959. }
  960. $out .= '</option>';
  961. }
  962. }
  963. $out .= '</select>';
  964. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  965. $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT.'/core/ajax/locationincoterms.php')."\n";
  966. $moreattrib .= ' autocomplete="off"';
  967. }
  968. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="'.$location_incoterms.'">'."\n";
  969. if (!empty($page)) {
  970. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="'.$langs->trans("Modify").'"></form>';
  971. }
  972. } else {
  973. dol_print_error($this->db);
  974. }
  975. return $out;
  976. }
  977. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  978. /**
  979. * Return list of types of lines (product or service)
  980. * Example: 0=product, 1=service, 9=other (for external module)
  981. *
  982. * @param string $selected Preselected type
  983. * @param string $htmlname Name of field in html form
  984. * @param int $showempty Add an empty field
  985. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  986. * @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')
  987. * @return void
  988. */
  989. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  990. {
  991. // phpcs:enable
  992. global $langs, $conf;
  993. // If product & services are enabled or both disabled.
  994. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  995. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled))) {
  996. if (empty($hidetext)) {
  997. print $langs->trans("Type").': ';
  998. }
  999. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  1000. if ($showempty) {
  1001. print '<option value="-1"';
  1002. if ($selected == -1) {
  1003. print ' selected';
  1004. }
  1005. print '>&nbsp;</option>';
  1006. }
  1007. print '<option value="0"';
  1008. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1009. print ' selected';
  1010. }
  1011. print '>'.$langs->trans("Product");
  1012. print '<option value="1"';
  1013. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1014. print ' selected';
  1015. }
  1016. print '>'.$langs->trans("Service");
  1017. print '</select>';
  1018. print ajax_combobox('select_'.$htmlname);
  1019. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1020. }
  1021. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3) {
  1022. print $langs->trans("Service");
  1023. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  1024. }
  1025. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2) {
  1026. print $langs->trans("Product");
  1027. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  1028. }
  1029. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1030. 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
  1031. }
  1032. }
  1033. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1034. /**
  1035. * Load into cache cache_types_fees, array of types of fees
  1036. *
  1037. * @return int Nb of lines loaded, <0 if KO
  1038. */
  1039. public function load_cache_types_fees()
  1040. {
  1041. // phpcs:enable
  1042. global $langs;
  1043. $num = count($this->cache_types_fees);
  1044. if ($num > 0) {
  1045. return 0; // Cache already loaded
  1046. }
  1047. dol_syslog(__METHOD__, LOG_DEBUG);
  1048. $langs->load("trips");
  1049. $sql = "SELECT c.code, c.label";
  1050. $sql .= " FROM ".$this->db->prefix()."c_type_fees as c";
  1051. $sql .= " WHERE active > 0";
  1052. $resql = $this->db->query($sql);
  1053. if ($resql) {
  1054. $num = $this->db->num_rows($resql);
  1055. $i = 0;
  1056. while ($i < $num) {
  1057. $obj = $this->db->fetch_object($resql);
  1058. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1059. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1060. $this->cache_types_fees[$obj->code] = $label;
  1061. $i++;
  1062. }
  1063. asort($this->cache_types_fees);
  1064. return $num;
  1065. } else {
  1066. dol_print_error($this->db);
  1067. return -1;
  1068. }
  1069. }
  1070. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1071. /**
  1072. * Return list of types of notes
  1073. *
  1074. * @param string $selected Preselected type
  1075. * @param string $htmlname Name of field in form
  1076. * @param int $showempty Add an empty field
  1077. * @return void
  1078. */
  1079. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1080. {
  1081. // phpcs:enable
  1082. global $user, $langs;
  1083. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  1084. $this->load_cache_types_fees();
  1085. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  1086. if ($showempty) {
  1087. print '<option value="-1"';
  1088. if ($selected == -1) {
  1089. print ' selected';
  1090. }
  1091. print '>&nbsp;</option>';
  1092. }
  1093. foreach ($this->cache_types_fees as $key => $value) {
  1094. print '<option value="'.$key.'"';
  1095. if ($key == $selected) {
  1096. print ' selected';
  1097. }
  1098. print '>';
  1099. print $value;
  1100. print '</option>';
  1101. }
  1102. print '</select>';
  1103. if ($user->admin) {
  1104. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1105. }
  1106. }
  1107. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1108. /**
  1109. * Output html form to select a third party
  1110. *
  1111. * @param string $selected Preselected type
  1112. * @param string $htmlname Name of field in form
  1113. * @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)')
  1114. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1115. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1116. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1117. * @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')))
  1118. * @param int $limit Maximum number of elements
  1119. * @param string $morecss Add more css styles to the SELECT component
  1120. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1121. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1122. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1123. * @param array $ajaxoptions Options for ajax_autocompleter
  1124. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1125. * @param array $excludeids Exclude IDs from the select combo
  1126. * @return string HTML string with select box for thirdparty.
  1127. */
  1128. 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())
  1129. {
  1130. // phpcs:enable
  1131. global $conf, $user, $langs;
  1132. $out = '';
  1133. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1134. if (is_null($ajaxoptions)) {
  1135. $ajaxoptions = array();
  1136. }
  1137. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1138. // No immediate load of all database
  1139. $placeholder = '';
  1140. if ($selected && empty($selected_input_value)) {
  1141. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1142. $societetmp = new Societe($this->db);
  1143. $societetmp->fetch($selected);
  1144. $selected_input_value = $societetmp->name;
  1145. unset($societetmp);
  1146. }
  1147. // mode 1
  1148. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '');
  1149. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1150. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1151. if (empty($hidelabel)) {
  1152. print $langs->trans("RefOrLabel").' : ';
  1153. } elseif ($hidelabel > 1) {
  1154. $placeholder = $langs->trans("RefOrLabel");
  1155. if ($hidelabel == 2) {
  1156. $out .= img_picto($langs->trans("Search"), 'search');
  1157. }
  1158. }
  1159. $out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '').' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1160. if ($hidelabel == 3) {
  1161. $out .= img_picto($langs->trans("Search"), 'search');
  1162. }
  1163. } else {
  1164. // Immediate load of all database
  1165. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids);
  1166. }
  1167. return $out;
  1168. }
  1169. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1170. /**
  1171. * Output html form to select a third party.
  1172. * 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.
  1173. *
  1174. * @param string $selected Preselected type
  1175. * @param string $htmlname Name of field in form
  1176. * @param string $filter Optional filters criteras (example: 's.rowid NOT IN (x)', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  1177. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1178. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1179. * @param int $forcecombo Force to use standard HTML select component without beautification
  1180. * @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')))
  1181. * @param string $filterkey Filter on key value
  1182. * @param int $outputmode 0=HTML select string, 1=Array
  1183. * @param int $limit Limit number of answers
  1184. * @param string $morecss Add more css styles to the SELECT component
  1185. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1186. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1187. * @param array $excludeids Exclude IDs from the select combo
  1188. * @return string HTML string with
  1189. */
  1190. 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())
  1191. {
  1192. // phpcs:enable
  1193. global $conf, $user, $langs;
  1194. global $hookmanager;
  1195. $out = '';
  1196. $num = 0;
  1197. $outarray = array();
  1198. if ($selected === '') {
  1199. $selected = array();
  1200. } elseif (!is_array($selected)) {
  1201. $selected = array($selected);
  1202. }
  1203. // Clean $filter that may contains sql conditions so sql code
  1204. if (function_exists('testSqlAndScriptInject')) {
  1205. if (testSqlAndScriptInject($filter, 3) > 0) {
  1206. $filter = '';
  1207. }
  1208. }
  1209. // We search companies
  1210. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1211. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1212. $sql .= ", s.address, s.zip, s.town";
  1213. $sql .= ", dictp.code as country_code";
  1214. }
  1215. $sql .= " FROM ".$this->db->prefix()."societe as s";
  1216. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1217. $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as dictp ON dictp.rowid = s.fk_pays";
  1218. }
  1219. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1220. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  1221. }
  1222. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1223. if (!empty($user->socid)) {
  1224. $sql .= " AND s.rowid = ".((int) $user->socid);
  1225. }
  1226. if ($filter) {
  1227. $sql .= " AND (".$filter.")";
  1228. }
  1229. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1230. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1231. }
  1232. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1233. $sql .= " AND s.status <> 0";
  1234. }
  1235. if (!empty($excludeids)) {
  1236. $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
  1237. }
  1238. // Add where from hooks
  1239. $parameters = array();
  1240. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1241. $sql .= $hookmanager->resPrint;
  1242. // Add criteria
  1243. if ($filterkey && $filterkey != '') {
  1244. $sql .= " AND (";
  1245. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1246. // For natural search
  1247. $scrit = explode(' ', $filterkey);
  1248. $i = 0;
  1249. if (count($scrit) > 1) {
  1250. $sql .= "(";
  1251. }
  1252. foreach ($scrit as $crit) {
  1253. if ($i > 0) {
  1254. $sql .= " AND ";
  1255. }
  1256. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1257. $i++;
  1258. }
  1259. if (count($scrit) > 1) {
  1260. $sql .= ")";
  1261. }
  1262. if (!empty($conf->barcode->enabled)) {
  1263. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1264. }
  1265. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1266. $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1267. $sql .= ")";
  1268. }
  1269. $sql .= $this->db->order("nom", "ASC");
  1270. $sql .= $this->db->plimit($limit, 0);
  1271. // Build output string
  1272. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1273. $resql = $this->db->query($sql);
  1274. if ($resql) {
  1275. if (!$forcecombo) {
  1276. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1277. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1278. }
  1279. // Construct $out and $outarray
  1280. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1281. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1282. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1283. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1284. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1285. if ($showempty && !is_numeric($showempty)) {
  1286. $textifempty = $langs->trans($showempty);
  1287. } else {
  1288. $textifempty .= $langs->trans("All");
  1289. }
  1290. }
  1291. if ($showempty) {
  1292. $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
  1293. }
  1294. $num = $this->db->num_rows($resql);
  1295. $i = 0;
  1296. if ($num) {
  1297. while ($i < $num) {
  1298. $obj = $this->db->fetch_object($resql);
  1299. $label = '';
  1300. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1301. if (($obj->client) && (!empty($obj->code_client))) {
  1302. $label = $obj->code_client.' - ';
  1303. }
  1304. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1305. $label .= $obj->code_fournisseur.' - ';
  1306. }
  1307. $label .= ' '.$obj->name;
  1308. } else {
  1309. $label = $obj->name;
  1310. }
  1311. if (!empty($obj->name_alias)) {
  1312. $label .= ' ('.$obj->name_alias.')';
  1313. }
  1314. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1315. $label .= ' - '.$obj->tva_intra.'';
  1316. }
  1317. if ($showtype) {
  1318. if ($obj->client || $obj->fournisseur) {
  1319. $label .= ' (';
  1320. }
  1321. if ($obj->client == 1 || $obj->client == 3) {
  1322. $label .= $langs->trans("Customer");
  1323. }
  1324. if ($obj->client == 2 || $obj->client == 3) {
  1325. $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1326. }
  1327. if ($obj->fournisseur) {
  1328. $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1329. }
  1330. if ($obj->client || $obj->fournisseur) {
  1331. $label .= ')';
  1332. }
  1333. }
  1334. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1335. $label .= ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1336. if (!empty($obj->country_code)) {
  1337. $label .= ', '.$langs->trans('Country'.$obj->country_code);
  1338. }
  1339. }
  1340. if (empty($outputmode)) {
  1341. if (in_array($obj->rowid, $selected)) {
  1342. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1343. } else {
  1344. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1345. }
  1346. } else {
  1347. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1348. }
  1349. $i++;
  1350. if (($i % 10) == 0) {
  1351. $out .= "\n";
  1352. }
  1353. }
  1354. }
  1355. $out .= '</select>'."\n";
  1356. } else {
  1357. dol_print_error($this->db);
  1358. }
  1359. $this->result = array('nbofthirdparties'=>$num);
  1360. if ($outputmode) {
  1361. return $outarray;
  1362. }
  1363. return $out;
  1364. }
  1365. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1366. /**
  1367. * Return HTML combo list of absolute discounts
  1368. *
  1369. * @param string $selected Id remise fixe pre-selectionnee
  1370. * @param string $htmlname Nom champ formulaire
  1371. * @param string $filter Criteres optionnels de filtre
  1372. * @param int $socid Id of thirdparty
  1373. * @param int $maxvalue Max value for lines that can be selected
  1374. * @return int Return number of qualifed lines in list
  1375. */
  1376. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1377. {
  1378. // phpcs:enable
  1379. global $langs, $conf;
  1380. // On recherche les remises
  1381. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1382. $sql .= " re.description, re.fk_facture_source";
  1383. $sql .= " FROM ".$this->db->prefix()."societe_remise_except as re";
  1384. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1385. $sql .= " AND re.entity = ".$conf->entity;
  1386. if ($filter) {
  1387. $sql .= " AND ".$filter;
  1388. }
  1389. $sql .= " ORDER BY re.description ASC";
  1390. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1391. $resql = $this->db->query($sql);
  1392. if ($resql) {
  1393. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1394. $num = $this->db->num_rows($resql);
  1395. $qualifiedlines = $num;
  1396. $i = 0;
  1397. if ($num) {
  1398. print '<option value="0">&nbsp;</option>';
  1399. while ($i < $num) {
  1400. $obj = $this->db->fetch_object($resql);
  1401. $desc = dol_trunc($obj->description, 40);
  1402. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1403. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1404. }
  1405. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1406. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1407. }
  1408. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1409. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1410. }
  1411. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1412. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1413. }
  1414. $selectstring = '';
  1415. if ($selected > 0 && $selected == $obj->rowid) {
  1416. $selectstring = ' selected';
  1417. }
  1418. $disabled = '';
  1419. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1420. $qualifiedlines--;
  1421. $disabled = ' disabled';
  1422. }
  1423. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1424. $tmpfac = new Facture($this->db);
  1425. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1426. $desc = $desc.' - '.$tmpfac->ref;
  1427. }
  1428. }
  1429. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1430. $i++;
  1431. }
  1432. }
  1433. print '</select>';
  1434. return $qualifiedlines;
  1435. } else {
  1436. dol_print_error($this->db);
  1437. return -1;
  1438. }
  1439. }
  1440. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1441. /**
  1442. * Return list of all contacts (for a third party or all)
  1443. *
  1444. * @param int $socid Id ot third party or 0 for all
  1445. * @param string $selected Id contact pre-selectionne
  1446. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1447. * @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
  1448. * @param string $exclude List of contacts id to exclude
  1449. * @param string $limitto Disable answers that are not id in this array list
  1450. * @param integer $showfunction Add function into label
  1451. * @param string $morecss Add more class to class style
  1452. * @param integer $showsoc Add company into label
  1453. * @param int $forcecombo Force to use combo box
  1454. * @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')))
  1455. * @param bool $options_only Return options only (for ajax treatment)
  1456. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1457. * @param string $htmlid Html id to use instead of htmlname
  1458. * @return int <0 if KO, Nb of contact in list if OK
  1459. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1460. */
  1461. 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 = '')
  1462. {
  1463. // phpcs:enable
  1464. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1465. return $this->num;
  1466. }
  1467. /**
  1468. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1469. * This also set the number of contacts found into $this->num
  1470. *
  1471. * @since 9.0 Add afterSelectContactOptions hook
  1472. *
  1473. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1474. * @param array|int $selected Array of ID of pre-selected contact id
  1475. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1476. * @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
  1477. * @param string $exclude List of contacts id to exclude
  1478. * @param string $limitto Disable answers that are not id in this array list
  1479. * @param integer $showfunction Add function into label
  1480. * @param string $morecss Add more class to class style
  1481. * @param bool $options_only Return options only (for ajax treatment)
  1482. * @param integer $showsoc Add company into label
  1483. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1484. * @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')))
  1485. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1486. * @param string $htmlid Html id to use instead of htmlname
  1487. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1488. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1489. * @return int|string <0 if KO, HTML with select string if OK.
  1490. */
  1491. public function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0)
  1492. {
  1493. global $conf, $langs, $hookmanager, $action;
  1494. $langs->load('companies');
  1495. if (empty($htmlid)) {
  1496. $htmlid = $htmlname;
  1497. }
  1498. $num = 0;
  1499. if ($selected === '') {
  1500. $selected = array();
  1501. } elseif (!is_array($selected)) {
  1502. $selected = array($selected);
  1503. }
  1504. $out = '';
  1505. if (!is_object($hookmanager)) {
  1506. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1507. $hookmanager = new HookManager($this->db);
  1508. }
  1509. // We search third parties
  1510. $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";
  1511. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1512. $sql .= ", s.nom as company, s.town AS company_town";
  1513. }
  1514. $sql .= " FROM ".$this->db->prefix()."socpeople as sp";
  1515. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1516. $sql .= " LEFT OUTER JOIN ".$this->db->prefix()."societe as s ON s.rowid=sp.fk_soc";
  1517. }
  1518. $sql .= " WHERE sp.entity IN (".getEntity('contact').")";
  1519. if ($socid > 0 || $socid == -1) {
  1520. $sql .= " AND sp.fk_soc = ".((int) $socid);
  1521. }
  1522. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1523. $sql .= " AND sp.statut <> 0";
  1524. }
  1525. // Add where from hooks
  1526. $parameters = array();
  1527. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1528. $sql .= $hookmanager->resPrint;
  1529. $sql .= " ORDER BY sp.lastname ASC";
  1530. dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
  1531. $resql = $this->db->query($sql);
  1532. if ($resql) {
  1533. $num = $this->db->num_rows($resql);
  1534. if ($htmlname != 'none' && !$options_only) {
  1535. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1536. }
  1537. if ($showempty && ! is_numeric($showempty)) {
  1538. $textforempty = $showempty;
  1539. $out .= '<option class="optiongrey" value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>'.$textforempty.'</option>';
  1540. } else {
  1541. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && ! $multiple) {
  1542. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1543. }
  1544. if ($showempty == 2) {
  1545. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1546. }
  1547. }
  1548. $i = 0;
  1549. if ($num) {
  1550. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1551. $contactstatic = new Contact($this->db);
  1552. while ($i < $num) {
  1553. $obj = $this->db->fetch_object($resql);
  1554. // Set email (or phones) and town extended infos
  1555. $extendedInfos = '';
  1556. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1557. $extendedInfos = array();
  1558. $email = trim($obj->email);
  1559. if (!empty($email)) {
  1560. $extendedInfos[] = $email;
  1561. } else {
  1562. $phone = trim($obj->phone);
  1563. $phone_perso = trim($obj->phone_perso);
  1564. $phone_mobile = trim($obj->phone_mobile);
  1565. if (!empty($phone)) {
  1566. $extendedInfos[] = $phone;
  1567. }
  1568. if (!empty($phone_perso)) {
  1569. $extendedInfos[] = $phone_perso;
  1570. }
  1571. if (!empty($phone_mobile)) {
  1572. $extendedInfos[] = $phone_mobile;
  1573. }
  1574. }
  1575. $contact_town = trim($obj->contact_town);
  1576. $company_town = trim($obj->company_town);
  1577. if (!empty($contact_town)) {
  1578. $extendedInfos[] = $contact_town;
  1579. } elseif (!empty($company_town)) {
  1580. $extendedInfos[] = $company_town;
  1581. }
  1582. $extendedInfos = implode(' - ', $extendedInfos);
  1583. if (!empty($extendedInfos)) {
  1584. $extendedInfos = ' - '.$extendedInfos;
  1585. }
  1586. }
  1587. $contactstatic->id = $obj->rowid;
  1588. $contactstatic->lastname = $obj->lastname;
  1589. $contactstatic->firstname = $obj->firstname;
  1590. if ($obj->statut == 1) {
  1591. if ($htmlname != 'none') {
  1592. $disabled = 0;
  1593. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1594. $disabled = 1;
  1595. }
  1596. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1597. $disabled = 1;
  1598. }
  1599. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1600. $out .= '<option value="'.$obj->rowid.'"';
  1601. if ($disabled) {
  1602. $out .= ' disabled';
  1603. }
  1604. $out .= ' selected>';
  1605. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1606. if ($showfunction && $obj->poste) {
  1607. $out .= ' ('.$obj->poste.')';
  1608. }
  1609. if (($showsoc > 0) && $obj->company) {
  1610. $out .= ' - ('.$obj->company.')';
  1611. }
  1612. $out .= '</option>';
  1613. } else {
  1614. $out .= '<option value="'.$obj->rowid.'"';
  1615. if ($disabled) {
  1616. $out .= ' disabled';
  1617. }
  1618. $out .= '>';
  1619. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1620. if ($showfunction && $obj->poste) {
  1621. $out .= ' ('.$obj->poste.')';
  1622. }
  1623. if (($showsoc > 0) && $obj->company) {
  1624. $out .= ' - ('.$obj->company.')';
  1625. }
  1626. $out .= '</option>';
  1627. }
  1628. } else {
  1629. if (in_array($obj->rowid, $selected)) {
  1630. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1631. if ($showfunction && $obj->poste) {
  1632. $out .= ' ('.$obj->poste.')';
  1633. }
  1634. if (($showsoc > 0) && $obj->company) {
  1635. $out .= ' - ('.$obj->company.')';
  1636. }
  1637. }
  1638. }
  1639. }
  1640. $i++;
  1641. }
  1642. } else {
  1643. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1644. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1645. $out .= $labeltoshow;
  1646. $out .= '</option>';
  1647. }
  1648. $parameters = array(
  1649. 'socid'=>$socid,
  1650. 'htmlname'=>$htmlname,
  1651. 'resql'=>$resql,
  1652. 'out'=>&$out,
  1653. 'showfunction'=>$showfunction,
  1654. 'showsoc'=>$showsoc,
  1655. );
  1656. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1657. if ($htmlname != 'none' && !$options_only) {
  1658. $out .= '</select>';
  1659. }
  1660. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1661. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1662. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1663. }
  1664. $this->num = $num;
  1665. return $out;
  1666. } else {
  1667. dol_print_error($this->db);
  1668. return -1;
  1669. }
  1670. }
  1671. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1672. /**
  1673. * Return the HTML select list of users
  1674. *
  1675. * @param string $selected Id user preselected
  1676. * @param string $htmlname Field name in form
  1677. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1678. * @param array $exclude Array list of users id to exclude
  1679. * @param int $disabled If select list must be disabled
  1680. * @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
  1681. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1682. * @param string $force_entity '0' or Ids of environment to force
  1683. * @return void
  1684. * @deprecated Use select_dolusers instead
  1685. * @see select_dolusers()
  1686. */
  1687. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1688. {
  1689. // phpcs:enable
  1690. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1691. }
  1692. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1693. /**
  1694. * Return select list of users
  1695. *
  1696. * @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)
  1697. * @param string $htmlname Field name in form
  1698. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1699. * @param array $exclude Array list of users id to exclude
  1700. * @param int $disabled If select list must be disabled
  1701. * @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
  1702. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1703. * @param string $force_entity '0' or Ids of environment to force
  1704. * @param int $maxlength Maximum length of string into list (0=no limit)
  1705. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1706. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1707. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1708. * @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.
  1709. * @param string $morecss More css
  1710. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1711. * @param int $outputmode 0=HTML select string, 1=Array
  1712. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1713. * @return string HTML select string
  1714. * @see select_dolgroups()
  1715. */
  1716. public function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $noactive = 0, $outputmode = 0, $multiple = false)
  1717. {
  1718. // phpcs:enable
  1719. global $conf, $user, $langs, $hookmanager;
  1720. // If no preselected user defined, we take current user
  1721. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1722. $selected = $user->id;
  1723. }
  1724. if ($selected === '') {
  1725. $selected = array();
  1726. } elseif (!is_array($selected)) {
  1727. $selected = array($selected);
  1728. }
  1729. $excludeUsers = null;
  1730. $includeUsers = null;
  1731. // Permettre l'exclusion d'utilisateurs
  1732. if (is_array($exclude)) {
  1733. $excludeUsers = implode(",", $exclude);
  1734. }
  1735. // Permettre l'inclusion d'utilisateurs
  1736. if (is_array($include)) {
  1737. $includeUsers = implode(",", $include);
  1738. } elseif ($include == 'hierarchy') {
  1739. // Build list includeUsers to have only hierarchy
  1740. $includeUsers = implode(",", $user->getAllChildIds(0));
  1741. } elseif ($include == 'hierarchyme') {
  1742. // Build list includeUsers to have only hierarchy and current user
  1743. $includeUsers = implode(",", $user->getAllChildIds(1));
  1744. }
  1745. $out = '';
  1746. $outarray = array();
  1747. // Forge request to select users
  1748. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1749. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1750. $sql .= ", e.label";
  1751. }
  1752. $sql .= " FROM ".$this->db->prefix()."user as u";
  1753. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1754. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid = u.entity";
  1755. if ($force_entity) {
  1756. $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
  1757. } else {
  1758. $sql .= " WHERE u.entity IS NOT NULL";
  1759. }
  1760. } else {
  1761. if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1762. $sql .= " LEFT JOIN ".$this->db->prefix()."usergroup_user as ug";
  1763. $sql .= " ON ug.fk_user = u.rowid";
  1764. $sql .= " WHERE ug.entity = ".$conf->entity;
  1765. } else {
  1766. $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
  1767. }
  1768. }
  1769. if (!empty($user->socid)) {
  1770. $sql .= " AND u.fk_soc = ".((int) $user->socid);
  1771. }
  1772. if (is_array($exclude) && $excludeUsers) {
  1773. $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
  1774. }
  1775. if ($includeUsers) {
  1776. $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
  1777. }
  1778. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) {
  1779. $sql .= " AND u.statut <> 0";
  1780. }
  1781. if (!empty($morefilter)) {
  1782. $sql .= " ".$morefilter;
  1783. }
  1784. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1785. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1786. if (!empty($reshook)) {
  1787. $sql .= $hookmanager->resPrint;
  1788. }
  1789. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1790. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1791. } else {
  1792. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1793. }
  1794. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1795. $resql = $this->db->query($sql);
  1796. if ($resql) {
  1797. $num = $this->db->num_rows($resql);
  1798. $i = 0;
  1799. if ($num) {
  1800. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1801. $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1802. if ($show_empty && !$multiple) {
  1803. $textforempty = ' ';
  1804. if (!empty($conf->use_javascript_ajax)) {
  1805. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1806. }
  1807. if (!is_numeric($show_empty)) {
  1808. $textforempty = $show_empty;
  1809. }
  1810. $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  1811. }
  1812. if ($show_every) {
  1813. $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1814. }
  1815. $userstatic = new User($this->db);
  1816. while ($i < $num) {
  1817. $obj = $this->db->fetch_object($resql);
  1818. $userstatic->id = $obj->rowid;
  1819. $userstatic->lastname = $obj->lastname;
  1820. $userstatic->firstname = $obj->firstname;
  1821. $userstatic->photo = $obj->photo;
  1822. $userstatic->statut = $obj->status;
  1823. $userstatic->entity = $obj->entity;
  1824. $userstatic->admin = $obj->admin;
  1825. $disableline = '';
  1826. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1827. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1828. }
  1829. $labeltoshow = '';
  1830. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1831. $fullNameMode = 0;
  1832. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1833. $fullNameMode = 1; //Firstname+lastname
  1834. }
  1835. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1836. if (empty($obj->firstname) && empty($obj->lastname)) {
  1837. $labeltoshow .= $obj->login;
  1838. }
  1839. // Complete name with more info
  1840. $moreinfo = '';
  1841. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1842. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1843. }
  1844. if ($showstatus >= 0) {
  1845. if ($obj->status == 1 && $showstatus == 1) {
  1846. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1847. }
  1848. if ($obj->status == 0 && $showstatus == 1) {
  1849. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1850. }
  1851. }
  1852. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1853. if (!$obj->entity) {
  1854. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1855. } else {
  1856. if ($obj->entity != $conf->entity) {
  1857. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1858. }
  1859. }
  1860. }
  1861. $moreinfo .= ($moreinfo ? ')' : '');
  1862. if ($disableline && $disableline != '1') {
  1863. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1864. }
  1865. $labeltoshow .= $moreinfo;
  1866. $out .= '<option value="'.$obj->rowid.'"';
  1867. if ($disableline) {
  1868. $out .= ' disabled';
  1869. }
  1870. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1871. $out .= ' selected';
  1872. }
  1873. $out .= ' data-html="';
  1874. $outhtml = '';
  1875. // if (!empty($obj->photo)) {
  1876. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1877. // }
  1878. if ($showstatus >= 0 && $obj->status == 0) {
  1879. $outhtml .= '<strike class="opacitymediumxxx">';
  1880. }
  1881. $outhtml .= $labeltoshow;
  1882. if ($showstatus >= 0 && $obj->status == 0) {
  1883. $outhtml .= '</strike>';
  1884. }
  1885. $out .= dol_escape_htmltag($outhtml);
  1886. $out .= '">';
  1887. $out .= $labeltoshow;
  1888. $out .= '</option>';
  1889. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1890. $i++;
  1891. }
  1892. } else {
  1893. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1894. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1895. }
  1896. $out .= '</select>';
  1897. if ($num) {
  1898. // Enhance with select2
  1899. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1900. $out .= ajax_combobox($htmlname);
  1901. }
  1902. } else {
  1903. dol_print_error($this->db);
  1904. }
  1905. if ($outputmode) {
  1906. return $outarray;
  1907. }
  1908. return $out;
  1909. }
  1910. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1911. /**
  1912. * Return select list of users. Selected users are stored into session.
  1913. * List of users are provided into $_SESSION['assignedtouser'].
  1914. *
  1915. * @param string $action Value for $action
  1916. * @param string $htmlname Field name in form
  1917. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1918. * @param array $exclude Array list of users id to exclude
  1919. * @param int $disabled If select list must be disabled
  1920. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1921. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1922. * @param int $force_entity '0' or Ids of environment to force
  1923. * @param int $maxlength Maximum length of string into list (0=no limit)
  1924. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1925. * @param string $morefilter Add more filters into sql request
  1926. * @param int $showproperties Show properties of each attendees
  1927. * @param array $listofuserid Array with properties of each user
  1928. * @param array $listofcontactid Array with properties of each contact
  1929. * @param array $listofotherid Array with properties of each other contact
  1930. * @return string HTML select string
  1931. * @see select_dolgroups()
  1932. */
  1933. public function select_dolusers_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofuserid = array(), $listofcontactid = array(), $listofotherid = array())
  1934. {
  1935. // phpcs:enable
  1936. global $conf, $user, $langs;
  1937. $userstatic = new User($this->db);
  1938. $out = '';
  1939. $assignedtouser = array();
  1940. if (!empty($_SESSION['assignedtouser'])) {
  1941. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1942. }
  1943. $nbassignetouser = count($assignedtouser);
  1944. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1945. if ($nbassignetouser) {
  1946. $out .= '<ul class="attendees">';
  1947. }
  1948. $i = 0;
  1949. $ownerid = 0;
  1950. foreach ($assignedtouser as $key => $value) {
  1951. if ($value['id'] == $ownerid) {
  1952. continue;
  1953. }
  1954. $out .= '<li>';
  1955. $userstatic->fetch($value['id']);
  1956. $out .= $userstatic->getNomUrl(-1);
  1957. if ($i == 0) {
  1958. $ownerid = $value['id'];
  1959. $out .= ' ('.$langs->trans("Owner").')';
  1960. }
  1961. if ($nbassignetouser > 1 && $action != 'view') {
  1962. $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.'">';
  1963. }
  1964. // Show my availability
  1965. if ($showproperties) {
  1966. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  1967. $out .= '<div class="myavailability inline-block">';
  1968. $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>';
  1969. $out .= '</div>';
  1970. }
  1971. }
  1972. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1973. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1974. $out .= '</li>';
  1975. $i++;
  1976. }
  1977. if ($nbassignetouser) {
  1978. $out .= '</ul>';
  1979. }
  1980. // Method with no ajax
  1981. if ($action != 'view') {
  1982. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1983. $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
  1984. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  1985. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  1986. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  1987. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  1988. $out .= '});';
  1989. $out .= '})</script>';
  1990. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1991. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1992. $out .= '<br>';
  1993. }
  1994. return $out;
  1995. }
  1996. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1997. /**
  1998. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1999. *
  2000. * @param int $selected Preselected products
  2001. * @param string $htmlname Name of HTML select field (must be unique in page).
  2002. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2003. * @param int $limit Limit on number of returned lines
  2004. * @param int $price_level Level of price to show
  2005. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2006. * @param int $finished 2=all, 1=finished, 0=raw material
  2007. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2008. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2009. * @param array $ajaxoptions Options for ajax_autocompleter
  2010. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2011. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2012. * @param int $forcecombo Force to use combo box
  2013. * @param string $morecss Add more css on select
  2014. * @param int $hidepriceinlabel 1=Hide prices in label
  2015. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2016. * 'warehouseopen' = count products from open warehouses,
  2017. * 'warehouseclosed' = count products from closed warehouses,
  2018. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2019. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2020. * @param string $nooutput No print, return the output into a string
  2021. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2022. * @return void|string
  2023. */
  2024. public function select_produits($selected = '', $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)
  2025. {
  2026. // phpcs:enable
  2027. global $langs, $conf;
  2028. $out = '';
  2029. // check parameters
  2030. $price_level = (!empty($price_level) ? $price_level : 0);
  2031. if (is_null($ajaxoptions)) {
  2032. $ajaxoptions = array();
  2033. }
  2034. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  2035. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  2036. $filtertype = '0';
  2037. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  2038. $filtertype = '1';
  2039. }
  2040. }
  2041. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2042. $placeholder = '';
  2043. if ($selected && empty($selected_input_value)) {
  2044. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2045. $producttmpselect = new Product($this->db);
  2046. $producttmpselect->fetch($selected);
  2047. $selected_input_value = $producttmpselect->ref;
  2048. unset($producttmpselect);
  2049. }
  2050. // handle case where product or service module is disabled + no filter specified
  2051. if ($filtertype == '') {
  2052. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2053. $filtertype = 1;
  2054. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2055. $filtertype = 0;
  2056. }
  2057. }
  2058. // mode=1 means customers products
  2059. $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&status_purchase='.$status_purchase.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  2060. //Price by customer
  2061. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2062. $urloption .= '&socid='.$socid;
  2063. }
  2064. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2065. if (!empty($conf->variants->enabled) && is_array($selected_combinations)) {
  2066. // Code to automatically insert with javascript the select of attributes under the select of product
  2067. // when a parent of variant has been selected.
  2068. $out .= '
  2069. <!-- script to auto show attributes select tags if a variant was selected -->
  2070. <script>
  2071. // auto show attributes fields
  2072. selected = '.json_encode($selected_combinations).';
  2073. combvalues = {};
  2074. jQuery(document).ready(function () {
  2075. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2076. if (jQuery(this).val() == \'free\') {
  2077. jQuery(\'div#attributes_box\').empty();
  2078. }
  2079. });
  2080. jQuery("input#'.$htmlname.'").change(function () {
  2081. if (!jQuery(this).val()) {
  2082. jQuery(\'div#attributes_box\').empty();
  2083. return;
  2084. }
  2085. console.log("A change has started. We get variants fields to inject html select");
  2086. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  2087. id: jQuery(this).val()
  2088. }, function (data) {
  2089. jQuery(\'div#attributes_box\').empty();
  2090. jQuery.each(data, function (key, val) {
  2091. combvalues[val.id] = val.values;
  2092. var span = jQuery(document.createElement(\'div\')).css({
  2093. \'display\': \'table-row\'
  2094. });
  2095. span.append(
  2096. jQuery(document.createElement(\'div\')).text(val.label).css({
  2097. \'font-weight\': \'bold\',
  2098. \'display\': \'table-cell\'
  2099. })
  2100. );
  2101. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2102. \'margin-left\': \'15px\',
  2103. \'white-space\': \'pre\'
  2104. }).append(
  2105. jQuery(document.createElement(\'option\')).val(\'\')
  2106. );
  2107. jQuery.each(combvalues[val.id], function (key, val) {
  2108. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2109. if (selected[val.fk_product_attribute] == val.id) {
  2110. tag.attr(\'selected\', \'selected\');
  2111. }
  2112. html.append(tag);
  2113. });
  2114. span.append(html);
  2115. jQuery(\'div#attributes_box\').append(span);
  2116. });
  2117. })
  2118. });
  2119. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  2120. });
  2121. </script>
  2122. ';
  2123. }
  2124. if (empty($hidelabel)) {
  2125. $out .= $langs->trans("RefOrLabel").' : ';
  2126. } elseif ($hidelabel > 1) {
  2127. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  2128. if ($hidelabel == 2) {
  2129. $out .= img_picto($langs->trans("Search"), 'search');
  2130. }
  2131. }
  2132. $out .= '<input type="text" class="minwidth100'.($morecss ? ' '.$morecss : '').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  2133. if ($hidelabel == 3) {
  2134. $out .= img_picto($langs->trans("Search"), 'search');
  2135. }
  2136. } else {
  2137. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2138. }
  2139. if (empty($nooutput)) {
  2140. print $out;
  2141. } else {
  2142. return $out;
  2143. }
  2144. }
  2145. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2146. /**
  2147. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2148. *
  2149. * @param int $selected Preselected BOM id
  2150. * @param string $htmlname Name of HTML select field (must be unique in page).
  2151. * @param int $limit Limit on number of returned lines
  2152. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2153. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2154. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2155. * @param string $morecss Add more css on select
  2156. * @param string $nooutput No print, return the output into a string
  2157. * @param int $forcecombo Force to use combo box
  2158. * @return void|string
  2159. */
  2160. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 1, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0)
  2161. {
  2162. // phpcs:enable
  2163. global $conf, $user, $langs, $db;
  2164. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2165. $error = 0;
  2166. $out = '';
  2167. if (!$forcecombo) {
  2168. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2169. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2170. }
  2171. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2172. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2173. $sql.= ' FROM '.MAIN_DB_PREFIX.'bom_bom as b';
  2174. $sql.= ' WHERE b.entity IN ('.getEntity('bom').')';
  2175. if (!empty($status)) $sql.= ' AND status = '. (int) $status;
  2176. if (!empty($type)) $sql.= ' AND status = '. (int) $type;
  2177. if (!empty($limit)) $sql.= 'LIMIT '. (int) $limit;
  2178. $resql = $db->query($sql);
  2179. if ($resql) {
  2180. if ($showempty) {
  2181. $out .= '<option value="-1"';
  2182. if (empty($selected)) $out .= ' selected';
  2183. $out .= '>&nbsp;</option>';
  2184. }
  2185. while ($obj = $db->fetch_object($resql)) {
  2186. $product = new Product($db);
  2187. $res = $product->fetch($obj->fk_product);
  2188. if ($obj->rowid == $selected) $out .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.' - '. $product->label .' - '.$obj->label.'</option>';
  2189. $out .= '<option value="'.$obj->rowid.'">'.$obj->ref.' - '.$product->label .' - '. $obj->label.'</option>';
  2190. }
  2191. } else {
  2192. $error++;
  2193. dol_print_error($db);
  2194. }
  2195. if (empty($nooutput)) {
  2196. print $out;
  2197. } else {
  2198. return $out;
  2199. }
  2200. }
  2201. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2202. /**
  2203. * Return list of products for a customer.
  2204. * Called by select_produits.
  2205. *
  2206. * @param int $selected Preselected product
  2207. * @param string $htmlname Name of select html
  2208. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2209. * @param int $limit Limit on number of returned lines
  2210. * @param int $price_level Level of price to show
  2211. * @param string $filterkey Filter on product
  2212. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2213. * @param int $finished Filter on finished field: 2=No filter
  2214. * @param int $outputmode 0=HTML select string, 1=Array
  2215. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2216. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2217. * @param int $forcecombo Force to use combo box
  2218. * @param string $morecss Add more css on select
  2219. * @param int $hidepriceinlabel 1=Hide prices in label
  2220. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2221. * 'warehouseopen' = count products from open warehouses,
  2222. * 'warehouseclosed' = count products from closed warehouses,
  2223. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2224. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2225. * @return array Array of keys for json
  2226. */
  2227. 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)
  2228. {
  2229. // phpcs:enable
  2230. global $langs, $conf;
  2231. global $hookmanager;
  2232. $out = '';
  2233. $outarray = array();
  2234. // Units
  2235. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2236. $langs->load('other');
  2237. }
  2238. $warehouseStatusArray = array();
  2239. if (!empty($warehouseStatus)) {
  2240. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2241. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2242. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2243. }
  2244. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2245. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2246. }
  2247. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2248. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2249. }
  2250. }
  2251. $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";
  2252. if (count($warehouseStatusArray)) {
  2253. $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
  2254. } else {
  2255. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  2256. }
  2257. $sql = "SELECT ";
  2258. $sql .= $selectFields.$selectFieldsGrouped;
  2259. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2260. //Product category
  2261. $sql .= ", (SELECT ".$this->db->prefix()."categorie_product.fk_categorie
  2262. FROM ".$this->db->prefix()."categorie_product
  2263. WHERE ".$this->db->prefix()."categorie_product.fk_product=p.rowid
  2264. LIMIT 1
  2265. ) AS categorie_product_id ";
  2266. }
  2267. //Price by customer
  2268. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2269. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2270. $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';
  2271. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2272. }
  2273. // Units
  2274. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2275. $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";
  2276. $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';
  2277. }
  2278. // Multilang : we add translation
  2279. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2280. $sql .= ", pl.label as label_translated";
  2281. $sql .= ", pl.description as description_translated";
  2282. $selectFields .= ", label_translated";
  2283. $selectFields .= ", description_translated";
  2284. }
  2285. // Price by quantity
  2286. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2287. $sql .= ", (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid";
  2288. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2289. $sql .= " AND price_level = ".((int) $price_level);
  2290. }
  2291. $sql .= " ORDER BY date_price";
  2292. $sql .= " DESC LIMIT 1) as price_rowid";
  2293. $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
  2294. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2295. $sql .= " AND price_level = ".((int) $price_level);
  2296. }
  2297. $sql .= " ORDER BY date_price";
  2298. $sql .= " DESC LIMIT 1) as price_by_qty";
  2299. $selectFields .= ", price_rowid, price_by_qty";
  2300. }
  2301. $sql .= " FROM ".$this->db->prefix()."product as p";
  2302. if (count($warehouseStatusArray)) {
  2303. $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock as ps on ps.fk_product = p.rowid";
  2304. $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  2305. $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.
  2306. }
  2307. // include search in supplier ref
  2308. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2309. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2310. }
  2311. //Price by customer
  2312. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2313. $sql .= " LEFT JOIN ".$this->db->prefix()."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
  2314. }
  2315. // Units
  2316. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2317. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2318. }
  2319. // Multilang : we add translation
  2320. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2321. $sql .= " LEFT JOIN ".$this->db->prefix()."product_lang as pl ON pl.fk_product = p.rowid ";
  2322. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2323. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  2324. $soc = new Societe($this->db);
  2325. $result = $soc->fetch($socid);
  2326. if ($result > 0 && !empty($soc->default_lang)) {
  2327. $sql .= " AND pl.lang = '".$this->db->escape($soc->default_lang)."'";
  2328. } else {
  2329. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2330. }
  2331. } else {
  2332. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2333. }
  2334. }
  2335. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2336. $sql .= " LEFT JOIN ".$this->db->prefix()."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2337. }
  2338. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  2339. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2340. $sql .= " AND pac.rowid IS NULL";
  2341. }
  2342. if ($finished == 0) {
  2343. $sql .= " AND p.finished = ".((int) $finished);
  2344. } elseif ($finished == 1) {
  2345. $sql .= " AND p.finished = ".((int) $finished);
  2346. if ($status >= 0) {
  2347. $sql .= " AND p.tosell = ".((int) $status);
  2348. }
  2349. } elseif ($status >= 0) {
  2350. $sql .= " AND p.tosell = ".((int) $status);
  2351. }
  2352. if ($status_purchase >= 0) {
  2353. $sql .= " AND p.tobuy = ".((int) $status_purchase);
  2354. }
  2355. // Filter by product type
  2356. if (strval($filtertype) != '') {
  2357. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2358. } elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2359. $sql .= " AND p.fk_product_type = 1";
  2360. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2361. $sql .= " AND p.fk_product_type = 0";
  2362. }
  2363. // Add where from hooks
  2364. $parameters = array();
  2365. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2366. $sql .= $hookmanager->resPrint;
  2367. // Add criteria on ref/label
  2368. if ($filterkey != '') {
  2369. $sql .= ' AND (';
  2370. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2371. // For natural search
  2372. $scrit = explode(' ', $filterkey);
  2373. $i = 0;
  2374. if (count($scrit) > 1) {
  2375. $sql .= "(";
  2376. }
  2377. foreach ($scrit as $crit) {
  2378. if ($i > 0) {
  2379. $sql .= " AND ";
  2380. }
  2381. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2382. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2383. $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2384. }
  2385. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && ! empty($socid)) {
  2386. $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
  2387. }
  2388. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2389. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2390. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2391. $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2392. }
  2393. }
  2394. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2395. $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2396. }
  2397. $sql .= ")";
  2398. $i++;
  2399. }
  2400. if (count($scrit) > 1) {
  2401. $sql .= ")";
  2402. }
  2403. if (!empty($conf->barcode->enabled)) {
  2404. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2405. }
  2406. $sql .= ')';
  2407. }
  2408. if (count($warehouseStatusArray)) {
  2409. $sql .= " GROUP BY ".$selectFields;
  2410. }
  2411. //Sort by category
  2412. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2413. $sql .= " ORDER BY categorie_product_id ";
  2414. //ASC OR DESC order
  2415. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2416. } else {
  2417. $sql .= $this->db->order("p.ref");
  2418. }
  2419. $sql .= $this->db->plimit($limit, 0);
  2420. // Build output string
  2421. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2422. $result = $this->db->query($sql);
  2423. if ($result) {
  2424. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2425. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2426. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2427. $num = $this->db->num_rows($result);
  2428. $events = null;
  2429. if (!$forcecombo) {
  2430. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2431. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2432. }
  2433. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2434. $textifempty = '';
  2435. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2436. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2437. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2438. if ($showempty && !is_numeric($showempty)) {
  2439. $textifempty = $langs->trans($showempty);
  2440. } else {
  2441. $textifempty .= $langs->trans("All");
  2442. }
  2443. } else {
  2444. if ($showempty && !is_numeric($showempty)) {
  2445. $textifempty = $langs->trans($showempty);
  2446. }
  2447. }
  2448. if ($showempty) {
  2449. $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
  2450. }
  2451. $i = 0;
  2452. while ($num && $i < $num) {
  2453. $opt = '';
  2454. $optJson = array();
  2455. $objp = $this->db->fetch_object($result);
  2456. if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1) { // Price by quantity will return many prices for the same product
  2457. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2458. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2459. $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
  2460. $sql .= " ORDER BY quantity ASC";
  2461. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2462. $result2 = $this->db->query($sql);
  2463. if ($result2) {
  2464. $nb_prices = $this->db->num_rows($result2);
  2465. $j = 0;
  2466. while ($nb_prices && $j < $nb_prices) {
  2467. $objp2 = $this->db->fetch_object($result2);
  2468. $objp->price_by_qty_rowid = $objp2->rowid;
  2469. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2470. $objp->price_by_qty_quantity = $objp2->quantity;
  2471. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2472. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2473. // For backward compatibility
  2474. $objp->quantity = $objp2->quantity;
  2475. $objp->price = $objp2->price;
  2476. $objp->unitprice = $objp2->unitprice;
  2477. $objp->remise_percent = $objp2->remise_percent;
  2478. $objp->remise = $objp2->remise;
  2479. //$objp->tva_tx is not overwritten by $objp2 value
  2480. //$objp->default_vat_code is not overwritten by $objp2 value
  2481. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2482. $j++;
  2483. // Add new entry
  2484. // "key" value of json key array is used by jQuery automatically as selected value
  2485. // "label" value of json key array is used by jQuery automatically as text for combo box
  2486. $out .= $opt;
  2487. array_push($outarray, $optJson);
  2488. }
  2489. }
  2490. } else {
  2491. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2492. $price_product = new Product($this->db);
  2493. $price_product->fetch($objp->rowid, '', '', 1);
  2494. $priceparser = new PriceParser($this->db);
  2495. $price_result = $priceparser->parseProduct($price_product);
  2496. if ($price_result >= 0) {
  2497. $objp->price = $price_result;
  2498. $objp->unitprice = $price_result;
  2499. //Calculate the VAT
  2500. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2501. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2502. }
  2503. }
  2504. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2505. // Add new entry
  2506. // "key" value of json key array is used by jQuery automatically as selected value
  2507. // "label" value of json key array is used by jQuery automatically as text for combo box
  2508. $out .= $opt;
  2509. array_push($outarray, $optJson);
  2510. }
  2511. $i++;
  2512. }
  2513. $out .= '</select>';
  2514. $this->db->free($result);
  2515. if (empty($outputmode)) {
  2516. return $out;
  2517. }
  2518. return $outarray;
  2519. } else {
  2520. dol_print_error($this->db);
  2521. }
  2522. }
  2523. /**
  2524. * Function to forge the string with OPTIONs of SELECT.
  2525. * This define value for &$opt and &$optJson.
  2526. * This function is called by select_produits_list().
  2527. *
  2528. * @param resource $objp Resultset of fetch
  2529. * @param string $opt Option (var used for returned value in string option format)
  2530. * @param string $optJson Option (var used for returned value in json format)
  2531. * @param int $price_level Price level
  2532. * @param string $selected Preselected value
  2533. * @param int $hidepriceinlabel Hide price in label
  2534. * @param string $filterkey Filter key to highlight
  2535. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2536. * @return void
  2537. */
  2538. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2539. {
  2540. global $langs, $conf, $user;
  2541. $outkey = '';
  2542. $outval = '';
  2543. $outref = '';
  2544. $outlabel = '';
  2545. $outlabel_translated = '';
  2546. $outdesc = '';
  2547. $outdesc_translated = '';
  2548. $outbarcode = '';
  2549. $outorigin = '';
  2550. $outtype = '';
  2551. $outprice_ht = '';
  2552. $outprice_ttc = '';
  2553. $outpricebasetype = '';
  2554. $outtva_tx = '';
  2555. $outdefault_vat_code = '';
  2556. $outqty = 1;
  2557. $outdiscount = 0;
  2558. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2559. $label = $objp->label;
  2560. if (!empty($objp->label_translated)) {
  2561. $label = $objp->label_translated;
  2562. }
  2563. if (!empty($filterkey) && $filterkey != '') {
  2564. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2565. }
  2566. $outkey = $objp->rowid;
  2567. $outref = $objp->ref;
  2568. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2569. $outlabel = $objp->label;
  2570. $outdesc = $objp->description;
  2571. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2572. $outlabel_translated = $objp->label_translated;
  2573. $outdesc_translated = $objp->description_translated;
  2574. }
  2575. $outbarcode = $objp->barcode;
  2576. $outorigin = $objp->fk_country;
  2577. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2578. $outtype = $objp->fk_product_type;
  2579. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2580. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2581. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2582. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2583. }
  2584. // Units
  2585. $outvalUnits = '';
  2586. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2587. if (!empty($objp->unit_short)) {
  2588. $outvalUnits .= ' - '.$objp->unit_short;
  2589. }
  2590. }
  2591. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2592. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2593. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2594. $outvalUnits .= ' - '.$unitToShow;
  2595. }
  2596. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2597. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2598. $outvalUnits .= ' - '.$unitToShow;
  2599. }
  2600. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2601. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2602. $outvalUnits .= ' - '.$unitToShow;
  2603. }
  2604. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2605. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2606. $outvalUnits .= ' - '.$unitToShow;
  2607. }
  2608. }
  2609. if ($outdurationvalue && $outdurationunit) {
  2610. $da = array(
  2611. 'h' => $langs->trans('Hour'),
  2612. 'd' => $langs->trans('Day'),
  2613. 'w' => $langs->trans('Week'),
  2614. 'm' => $langs->trans('Month'),
  2615. 'y' => $langs->trans('Year')
  2616. );
  2617. if (isset($da[$outdurationunit])) {
  2618. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2619. }
  2620. }
  2621. $opt = '<option value="'.$objp->rowid.'"';
  2622. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2623. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2624. $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.'"';
  2625. }
  2626. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2627. if (!empty($user->rights->stock->lire)) {
  2628. if ($objp->stock > 0) {
  2629. $opt .= ' class="product_line_stock_ok"';
  2630. } elseif ($objp->stock <= 0) {
  2631. $opt .= ' class="product_line_stock_too_low"';
  2632. }
  2633. }
  2634. }
  2635. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2636. $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
  2637. $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
  2638. }
  2639. $opt .= '>';
  2640. $opt .= $objp->ref;
  2641. if (! empty($objp->custref)) {
  2642. $opt.= ' (' . $objp->custref . ')';
  2643. }
  2644. if ($outbarcode) {
  2645. $opt .= ' ('.$outbarcode.')';
  2646. }
  2647. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2648. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2649. $opt .= ' ('.getCountry($outorigin, 1).')';
  2650. }
  2651. $objRef = $objp->ref;
  2652. if (! empty($objp->custref)) {
  2653. $objRef .= ' (' . $objp->custref . ')';
  2654. }
  2655. if (!empty($filterkey) && $filterkey != '') {
  2656. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2657. }
  2658. $outval .= $objRef;
  2659. if ($outbarcode) {
  2660. $outval .= ' ('.$outbarcode.')';
  2661. }
  2662. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2663. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2664. $outval .= ' ('.getCountry($outorigin, 1).')';
  2665. }
  2666. // Units
  2667. $opt .= $outvalUnits;
  2668. $outval .= $outvalUnits;
  2669. $found = 0;
  2670. // Multiprice
  2671. // If we need a particular price level (from 1 to n)
  2672. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2673. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2674. $sql .= " FROM ".$this->db->prefix()."product_price";
  2675. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2676. $sql .= " AND entity IN (".getEntity('productprice').")";
  2677. $sql .= " AND price_level = ".((int) $price_level);
  2678. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2679. $sql .= " LIMIT 1";
  2680. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2681. $result2 = $this->db->query($sql);
  2682. if ($result2) {
  2683. $objp2 = $this->db->fetch_object($result2);
  2684. if ($objp2) {
  2685. $found = 1;
  2686. if ($objp2->price_base_type == 'HT') {
  2687. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2688. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2689. } else {
  2690. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2691. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2692. }
  2693. $outprice_ht = price($objp2->price);
  2694. $outprice_ttc = price($objp2->price_ttc);
  2695. $outpricebasetype = $objp2->price_base_type;
  2696. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2697. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2698. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2699. } else {
  2700. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2701. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2702. }
  2703. }
  2704. } else {
  2705. dol_print_error($this->db);
  2706. }
  2707. }
  2708. // Price by quantity
  2709. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2710. $found = 1;
  2711. $outqty = $objp->quantity;
  2712. $outdiscount = $objp->remise_percent;
  2713. if ($objp->quantity == 1) {
  2714. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2715. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2716. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2717. $outval .= $langs->transnoentities("Unit");
  2718. } else {
  2719. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2720. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2721. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2722. $outval .= $langs->transnoentities("Units");
  2723. }
  2724. $outprice_ht = price($objp->unitprice);
  2725. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2726. $outpricebasetype = $objp->price_base_type;
  2727. $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
  2728. $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
  2729. }
  2730. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2731. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2732. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2733. }
  2734. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2735. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2736. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2737. }
  2738. // Price by customer
  2739. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2740. if (!empty($objp->idprodcustprice)) {
  2741. $found = 1;
  2742. if ($objp->custprice_base_type == 'HT') {
  2743. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2744. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2745. } else {
  2746. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2747. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2748. }
  2749. $outprice_ht = price($objp->custprice);
  2750. $outprice_ttc = price($objp->custprice_ttc);
  2751. $outpricebasetype = $objp->custprice_base_type;
  2752. $outtva_tx = $objp->custtva_tx;
  2753. $outdefault_vat_code = $objp->custdefault_vat_code;
  2754. }
  2755. }
  2756. // If level no defined or multiprice not found, we used the default price
  2757. if (empty($hidepriceinlabel) && !$found) {
  2758. if ($objp->price_base_type == 'HT') {
  2759. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2760. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2761. } else {
  2762. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2763. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2764. }
  2765. $outprice_ht = price($objp->price);
  2766. $outprice_ttc = price($objp->price_ttc);
  2767. $outpricebasetype = $objp->price_base_type;
  2768. $outtva_tx = $objp->tva_tx;
  2769. $outdefault_vat_code = $objp->default_vat_code;
  2770. }
  2771. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2772. if (!empty($user->rights->stock->lire)) {
  2773. $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  2774. if ($objp->stock > 0) {
  2775. $outval .= ' - <span class="product_line_stock_ok">';
  2776. } elseif ($objp->stock <= 0) {
  2777. $outval .= ' - <span class="product_line_stock_too_low">';
  2778. }
  2779. $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
  2780. $outval .= '</span>';
  2781. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2782. $langs->load("stocks");
  2783. $tmpproduct = new Product($this->db);
  2784. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2785. $tmpproduct->load_virtual_stock();
  2786. $virtualstock = $tmpproduct->stock_theorique;
  2787. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2788. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2789. if ($virtualstock > 0) {
  2790. $outval .= '<span class="product_line_stock_ok">';
  2791. } elseif ($virtualstock <= 0) {
  2792. $outval .= '<span class="product_line_stock_too_low">';
  2793. }
  2794. $outval .= $virtualstock;
  2795. $outval .= '</span>';
  2796. unset($tmpproduct);
  2797. }
  2798. }
  2799. }
  2800. $opt .= "</option>\n";
  2801. $optJson = array(
  2802. 'key'=>$outkey,
  2803. 'value'=>$outref,
  2804. 'label'=>$outval,
  2805. 'label2'=>$outlabel,
  2806. 'desc'=>$outdesc,
  2807. 'type'=>$outtype,
  2808. 'price_ht'=>price2num($outprice_ht),
  2809. 'price_ttc'=>price2num($outprice_ttc),
  2810. 'pricebasetype'=>$outpricebasetype,
  2811. 'tva_tx'=>$outtva_tx,
  2812. 'default_vat_code'=>$outdefault_vat_code,
  2813. 'qty'=>$outqty,
  2814. 'discount'=>$outdiscount,
  2815. 'duration_value'=>$outdurationvalue,
  2816. 'duration_unit'=>$outdurationunit,
  2817. 'pbq'=>$outpbq,
  2818. 'labeltrans'=>$outlabel_translated,
  2819. 'desctrans'=>$outdesc_translated,
  2820. 'ref_customer'=>$outrefcust
  2821. );
  2822. }
  2823. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2824. /**
  2825. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2826. *
  2827. * @param int $socid Id third party
  2828. * @param string $selected Preselected product
  2829. * @param string $htmlname Name of HTML Select
  2830. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2831. * @param string $filtre For a SQL filter
  2832. * @param array $ajaxoptions Options for ajax_autocompleter
  2833. * @param int $hidelabel Hide label (0=no, 1=yes)
  2834. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2835. * @param string $morecss More CSS
  2836. * @param string $placeholder Placeholder
  2837. * @return void
  2838. */
  2839. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2840. {
  2841. // phpcs:enable
  2842. global $langs, $conf;
  2843. global $price_level, $status, $finished;
  2844. if (!isset($status)) {
  2845. $status = 1;
  2846. }
  2847. $selected_input_value = '';
  2848. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2849. if ($selected > 0) {
  2850. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2851. $producttmpselect = new Product($this->db);
  2852. $producttmpselect->fetch($selected);
  2853. $selected_input_value = $producttmpselect->ref;
  2854. unset($producttmpselect);
  2855. }
  2856. // mode=2 means suppliers products
  2857. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2858. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2859. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
  2860. } else {
  2861. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2862. }
  2863. }
  2864. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2865. /**
  2866. * Return list of suppliers products
  2867. *
  2868. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2869. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2870. * @param string $htmlname Name of HTML select
  2871. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2872. * @param string $filtre Generic filter. Data must not come from user input.
  2873. * @param string $filterkey Filter of produdts
  2874. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2875. * @param int $outputmode 0=HTML select string, 1=Array
  2876. * @param int $limit Limit of line number
  2877. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2878. * @param string $morecss Add more CSS
  2879. * @param int $showstockinlist Show stock information (slower).
  2880. * @param string $placeholder Placeholder
  2881. * @return array Array of keys for json
  2882. */
  2883. 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 = '')
  2884. {
  2885. // phpcs:enable
  2886. global $langs, $conf, $user;
  2887. global $hookmanager;
  2888. $out = '';
  2889. $outarray = array();
  2890. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2891. $langs->load('stocks');
  2892. // Units
  2893. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2894. $langs->load('other');
  2895. }
  2896. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock,";
  2897. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2898. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  2899. $sql .= " pfp.supplier_reputation";
  2900. // if we use supplier description of the products
  2901. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2902. $sql .= " ,pfp.desc_fourn as description";
  2903. } else {
  2904. $sql .= " ,p.description";
  2905. }
  2906. // Units
  2907. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2908. $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";
  2909. }
  2910. if (!empty($conf->barcode->enabled)) {
  2911. $sql .= ", pfp.barcode";
  2912. }
  2913. $sql .= " FROM ".$this->db->prefix()."product as p";
  2914. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2915. if ($socid > 0) {
  2916. $sql .= " AND pfp.fk_soc = ".((int) $socid);
  2917. }
  2918. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  2919. // Units
  2920. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2921. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2922. }
  2923. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2924. if ($statut != -1) {
  2925. $sql .= " AND p.tobuy = ".((int) $statut);
  2926. }
  2927. if (strval($filtertype) != '') {
  2928. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2929. }
  2930. if (!empty($filtre)) {
  2931. $sql .= " ".$filtre;
  2932. }
  2933. // Add where from hooks
  2934. $parameters = array();
  2935. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2936. $sql .= $hookmanager->resPrint;
  2937. // Add criteria on ref/label
  2938. if ($filterkey != '') {
  2939. $sql .= ' AND (';
  2940. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2941. // For natural search
  2942. $scrit = explode(' ', $filterkey);
  2943. $i = 0;
  2944. if (count($scrit) > 1) {
  2945. $sql .= "(";
  2946. }
  2947. foreach ($scrit as $crit) {
  2948. if ($i > 0) {
  2949. $sql .= " AND ";
  2950. }
  2951. $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)."%'";
  2952. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2953. $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2954. }
  2955. $sql .= ")";
  2956. $i++;
  2957. }
  2958. if (count($scrit) > 1) {
  2959. $sql .= ")";
  2960. }
  2961. if (!empty($conf->barcode->enabled)) {
  2962. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2963. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2964. }
  2965. $sql .= ')';
  2966. }
  2967. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2968. $sql .= $this->db->plimit($limit, 0);
  2969. // Build output string
  2970. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2971. $result = $this->db->query($sql);
  2972. if ($result) {
  2973. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2974. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2975. $num = $this->db->num_rows($result);
  2976. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2977. $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2978. if (!$selected) {
  2979. $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2980. } else {
  2981. $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2982. }
  2983. $i = 0;
  2984. while ($i < $num) {
  2985. $objp = $this->db->fetch_object($result);
  2986. $outkey = $objp->idprodfournprice; // id in table of price
  2987. if (!$outkey && $alsoproductwithnosupplierprice) {
  2988. $outkey = 'idprod_'.$objp->rowid; // id of product
  2989. }
  2990. $outref = $objp->ref;
  2991. $outval = '';
  2992. $outbarcode = $objp->barcode;
  2993. $outqty = 1;
  2994. $outdiscount = 0;
  2995. $outtype = $objp->fk_product_type;
  2996. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2997. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2998. // Units
  2999. $outvalUnits = '';
  3000. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  3001. if (!empty($objp->unit_short)) {
  3002. $outvalUnits .= ' - '.$objp->unit_short;
  3003. }
  3004. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3005. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3006. $outvalUnits .= ' - '.$unitToShow;
  3007. }
  3008. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3009. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  3010. $outvalUnits .= ' - '.$unitToShow;
  3011. }
  3012. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3013. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3014. $outvalUnits .= ' - '.$unitToShow;
  3015. }
  3016. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3017. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3018. $outvalUnits .= ' - '.$unitToShow;
  3019. }
  3020. if ($outdurationvalue && $outdurationunit) {
  3021. $da = array(
  3022. 'h' => $langs->trans('Hour'),
  3023. 'd' => $langs->trans('Day'),
  3024. 'w' => $langs->trans('Week'),
  3025. 'm' => $langs->trans('Month'),
  3026. 'y' => $langs->trans('Year')
  3027. );
  3028. if (isset($da[$outdurationunit])) {
  3029. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  3030. }
  3031. }
  3032. }
  3033. $objRef = $objp->ref;
  3034. if ($filterkey && $filterkey != '') {
  3035. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  3036. }
  3037. $objRefFourn = $objp->ref_fourn;
  3038. if ($filterkey && $filterkey != '') {
  3039. $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3040. }
  3041. $label = $objp->label;
  3042. if ($filterkey && $filterkey != '') {
  3043. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  3044. }
  3045. $optlabel = $objp->ref;
  3046. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3047. $optlabel .= ' <span class="opacitymedium">('.$objp->ref_fourn.')</span>';
  3048. }
  3049. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3050. $optlabel .= ' ('.$outbarcode.')';
  3051. }
  3052. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3053. $outvallabel = $objRef;
  3054. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3055. $outvallabel .= ' ('.$objRefFourn.')';
  3056. }
  3057. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3058. $outvallabel .= ' ('.$outbarcode.')';
  3059. }
  3060. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3061. // Units
  3062. $optlabel .= $outvalUnits;
  3063. $outvallabel .= $outvalUnits;
  3064. if (!empty($objp->idprodfournprice)) {
  3065. $outqty = $objp->quantity;
  3066. $outdiscount = $objp->remise_percent;
  3067. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3068. $prod_supplier = new ProductFournisseur($this->db);
  3069. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3070. $prod_supplier->id = $objp->fk_product;
  3071. $prod_supplier->fourn_qty = $objp->quantity;
  3072. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3073. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3074. $priceparser = new PriceParser($this->db);
  3075. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3076. if ($price_result >= 0) {
  3077. $objp->fprice = $price_result;
  3078. if ($objp->quantity >= 1) {
  3079. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3080. }
  3081. }
  3082. }
  3083. if ($objp->quantity == 1) {
  3084. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3085. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  3086. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3087. $outvallabel .= $langs->transnoentities("Unit");
  3088. } else {
  3089. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  3090. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  3091. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3092. $outvallabel .= ' '.$langs->transnoentities("Units");
  3093. }
  3094. if ($objp->quantity > 1) {
  3095. $optlabel .= " (".price($objp->unitprice * (!empty($conf->global->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
  3096. $outvallabel .= " (".price($objp->unitprice * (!empty($conf->global->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
  3097. }
  3098. if ($objp->remise_percent >= 1) {
  3099. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  3100. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  3101. }
  3102. if ($objp->duration) {
  3103. $optlabel .= " - ".$objp->duration;
  3104. $outvallabel .= " - ".$objp->duration;
  3105. }
  3106. if (!$socid) {
  3107. $optlabel .= " - ".dol_trunc($objp->name, 8);
  3108. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  3109. }
  3110. if ($objp->supplier_reputation) {
  3111. //TODO dictionary
  3112. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  3113. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  3114. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  3115. }
  3116. } else {
  3117. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3118. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3119. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3120. } else // No supplier price defined for product, even on other suppliers
  3121. {
  3122. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3123. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3124. }
  3125. }
  3126. if (!empty($conf->stock->enabled) && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3127. $novirtualstock = ($showstockinlist == 2);
  3128. if (!empty($user->rights->stock->lire)) {
  3129. $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  3130. if ($objp->stock > 0) {
  3131. $optlabel .= ' - <span class="product_line_stock_ok">';
  3132. } elseif ($objp->stock <= 0) {
  3133. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3134. }
  3135. $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
  3136. $optlabel .= '</span>';
  3137. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3138. $langs->load("stocks");
  3139. $tmpproduct = new Product($this->db);
  3140. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3141. $tmpproduct->load_virtual_stock();
  3142. $virtualstock = $tmpproduct->stock_theorique;
  3143. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  3144. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  3145. if ($virtualstock > 0) {
  3146. $optlabel .= '<span class="product_line_stock_ok">';
  3147. } elseif ($virtualstock <= 0) {
  3148. $optlabel .= '<span class="product_line_stock_too_low">';
  3149. }
  3150. $optlabel .= $virtualstock;
  3151. $optlabel .= '</span>';
  3152. unset($tmpproduct);
  3153. }
  3154. }
  3155. }
  3156. $opt = '<option value="'.$outkey.'"';
  3157. if ($selected && $selected == $objp->idprodfournprice) {
  3158. $opt .= ' selected';
  3159. }
  3160. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3161. $opt .= ' disabled';
  3162. }
  3163. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3164. $opt .= ' data-product-id="'.$objp->rowid.'" data-price-id="'.$objp->idprodfournprice.'" data-qty="'.$objp->quantity.'" data-up="'.$objp->unitprice.'" data-discount="'.$outdiscount.'"';
  3165. }
  3166. $opt .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
  3167. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  3168. $opt .= '>';
  3169. $opt .= $optlabel;
  3170. $outval .= $outvallabel;
  3171. $opt .= "</option>\n";
  3172. // Add new entry
  3173. // "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
  3174. // "label" value of json key array is used by jQuery automatically as text for combo box
  3175. $out .= $opt;
  3176. array_push(
  3177. $outarray,
  3178. array('key'=>$outkey,
  3179. 'value'=>$outref,
  3180. 'label'=>$outval,
  3181. 'qty'=>$outqty,
  3182. 'price_qty_ht'=>price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3183. 'price_unit_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3184. 'price_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3185. 'tva_tx'=>$objp->tva_tx,
  3186. 'default_vat_code'=>$objp->default_vat_code,
  3187. 'discount'=>$outdiscount,
  3188. 'type'=>$outtype,
  3189. 'duration_value'=>$outdurationvalue,
  3190. 'duration_unit'=>$outdurationunit,
  3191. 'disabled'=>(empty($objp->idprodfournprice) ? true : false),
  3192. 'description'=>$objp->description
  3193. )
  3194. );
  3195. // Exemple of var_dump $outarray
  3196. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3197. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3198. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3199. //}
  3200. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3201. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3202. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3203. $i++;
  3204. }
  3205. $out .= '</select>';
  3206. $this->db->free($result);
  3207. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  3208. $out .= ajax_combobox($htmlname);
  3209. if (empty($outputmode)) {
  3210. return $out;
  3211. }
  3212. return $outarray;
  3213. } else {
  3214. dol_print_error($this->db);
  3215. }
  3216. }
  3217. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3218. /**
  3219. * Return list of suppliers prices for a product
  3220. *
  3221. * @param int $productid Id of product
  3222. * @param string $htmlname Name of HTML field
  3223. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3224. * @return string
  3225. */
  3226. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3227. {
  3228. // phpcs:enable
  3229. global $langs, $conf;
  3230. $langs->load('stocks');
  3231. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3232. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3233. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3234. $sql .= " FROM ".$this->db->prefix()."product as p";
  3235. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3236. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  3237. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  3238. $sql .= " AND p.tobuy = 1";
  3239. $sql .= " AND s.fournisseur = 1";
  3240. $sql .= " AND p.rowid = ".((int) $productid);
  3241. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3242. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  3243. $result = $this->db->query($sql);
  3244. if ($result) {
  3245. $num = $this->db->num_rows($result);
  3246. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3247. if (!$num) {
  3248. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  3249. } else {
  3250. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3251. $form .= '<option value="0">&nbsp;</option>';
  3252. $i = 0;
  3253. while ($i < $num) {
  3254. $objp = $this->db->fetch_object($result);
  3255. $opt = '<option value="'.$objp->idprodfournprice.'"';
  3256. //if there is only one supplier, preselect it
  3257. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  3258. $opt .= ' selected';
  3259. }
  3260. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  3261. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3262. $prod_supplier = new ProductFournisseur($this->db);
  3263. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3264. $prod_supplier->id = $productid;
  3265. $prod_supplier->fourn_qty = $objp->quantity;
  3266. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3267. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3268. $priceparser = new PriceParser($this->db);
  3269. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3270. if ($price_result >= 0) {
  3271. $objp->fprice = $price_result;
  3272. if ($objp->quantity >= 1) {
  3273. $objp->unitprice = $objp->fprice / $objp->quantity;
  3274. }
  3275. }
  3276. }
  3277. if ($objp->quantity == 1) {
  3278. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3279. }
  3280. $opt .= $objp->quantity.' ';
  3281. if ($objp->quantity == 1) {
  3282. $opt .= $langs->trans("Unit");
  3283. } else {
  3284. $opt .= $langs->trans("Units");
  3285. }
  3286. if ($objp->quantity > 1) {
  3287. $opt .= " - ";
  3288. $opt .= price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit");
  3289. }
  3290. if ($objp->duration) {
  3291. $opt .= " - ".$objp->duration;
  3292. }
  3293. $opt .= "</option>\n";
  3294. $form .= $opt;
  3295. $i++;
  3296. }
  3297. }
  3298. $form .= '</select>';
  3299. $this->db->free($result);
  3300. return $form;
  3301. } else {
  3302. dol_print_error($this->db);
  3303. }
  3304. }
  3305. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3306. /**
  3307. * Return list of delivery address
  3308. *
  3309. * @param string $selected Id contact pre-selectionn
  3310. * @param int $socid Id of company
  3311. * @param string $htmlname Name of HTML field
  3312. * @param int $showempty Add an empty field
  3313. * @return integer|null
  3314. */
  3315. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3316. {
  3317. // phpcs:enable
  3318. // looking for users
  3319. $sql = "SELECT a.rowid, a.label";
  3320. $sql .= " FROM ".$this->db->prefix()."societe_address as a";
  3321. $sql .= " WHERE a.fk_soc = ".((int) $socid);
  3322. $sql .= " ORDER BY a.label ASC";
  3323. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  3324. $resql = $this->db->query($sql);
  3325. if ($resql) {
  3326. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3327. if ($showempty) {
  3328. print '<option value="0">&nbsp;</option>';
  3329. }
  3330. $num = $this->db->num_rows($resql);
  3331. $i = 0;
  3332. if ($num) {
  3333. while ($i < $num) {
  3334. $obj = $this->db->fetch_object($resql);
  3335. if ($selected && $selected == $obj->rowid) {
  3336. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  3337. } else {
  3338. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  3339. }
  3340. $i++;
  3341. }
  3342. }
  3343. print '</select>';
  3344. return $num;
  3345. } else {
  3346. dol_print_error($this->db);
  3347. }
  3348. }
  3349. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3350. /**
  3351. * Load into cache list of payment terms
  3352. *
  3353. * @return int Nb of lines loaded, <0 if KO
  3354. */
  3355. public function load_cache_conditions_paiements()
  3356. {
  3357. // phpcs:enable
  3358. global $langs;
  3359. $num = count($this->cache_conditions_paiements);
  3360. if ($num > 0) {
  3361. return 0; // Cache already loaded
  3362. }
  3363. dol_syslog(__METHOD__, LOG_DEBUG);
  3364. $sql = "SELECT rowid, code, libelle as label";
  3365. $sql .= " FROM ".$this->db->prefix().'c_payment_term';
  3366. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  3367. $sql .= " AND active > 0";
  3368. $sql .= " ORDER BY sortorder";
  3369. $resql = $this->db->query($sql);
  3370. if ($resql) {
  3371. $num = $this->db->num_rows($resql);
  3372. $i = 0;
  3373. while ($i < $num) {
  3374. $obj = $this->db->fetch_object($resql);
  3375. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3376. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3377. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3378. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3379. $i++;
  3380. }
  3381. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3382. return $num;
  3383. } else {
  3384. dol_print_error($this->db);
  3385. return -1;
  3386. }
  3387. }
  3388. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3389. /**
  3390. * Load int a cache property th elist of possible delivery delays.
  3391. *
  3392. * @return int Nb of lines loaded, <0 if KO
  3393. */
  3394. public function load_cache_availability()
  3395. {
  3396. // phpcs:enable
  3397. global $langs;
  3398. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3399. if ($num > 0) {
  3400. return 0; // Cache already loaded
  3401. }
  3402. dol_syslog(__METHOD__, LOG_DEBUG);
  3403. $langs->load('propal');
  3404. $sql = "SELECT rowid, code, label, position";
  3405. $sql .= " FROM ".$this->db->prefix().'c_availability';
  3406. $sql .= " WHERE active > 0";
  3407. $resql = $this->db->query($sql);
  3408. if ($resql) {
  3409. $num = $this->db->num_rows($resql);
  3410. $i = 0;
  3411. while ($i < $num) {
  3412. $obj = $this->db->fetch_object($resql);
  3413. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3414. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3415. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3416. $this->cache_availability[$obj->rowid]['label'] = $label;
  3417. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3418. $i++;
  3419. }
  3420. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3421. return $num;
  3422. } else {
  3423. dol_print_error($this->db);
  3424. return -1;
  3425. }
  3426. }
  3427. /**
  3428. * Retourne la liste des types de delais de livraison possibles
  3429. *
  3430. * @param int $selected Id du type de delais pre-selectionne
  3431. * @param string $htmlname Nom de la zone select
  3432. * @param string $filtertype To add a filter
  3433. * @param int $addempty Add empty entry
  3434. * @param string $morecss More CSS
  3435. * @return void
  3436. */
  3437. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3438. {
  3439. global $langs, $user;
  3440. $this->load_cache_availability();
  3441. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3442. print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3443. if ($addempty) {
  3444. print '<option value="0">&nbsp;</option>';
  3445. }
  3446. foreach ($this->cache_availability as $id => $arrayavailability) {
  3447. if ($selected == $id) {
  3448. print '<option value="'.$id.'" selected>';
  3449. } else {
  3450. print '<option value="'.$id.'">';
  3451. }
  3452. print dol_escape_htmltag($arrayavailability['label']);
  3453. print '</option>';
  3454. }
  3455. print '</select>';
  3456. if ($user->admin) {
  3457. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3458. }
  3459. print ajax_combobox($htmlname);
  3460. }
  3461. /**
  3462. * Load into cache cache_demand_reason, array of input reasons
  3463. *
  3464. * @return int Nb of lines loaded, <0 if KO
  3465. */
  3466. public function loadCacheInputReason()
  3467. {
  3468. global $langs;
  3469. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3470. if ($num > 0) {
  3471. return 0; // Cache already loaded
  3472. }
  3473. $sql = "SELECT rowid, code, label";
  3474. $sql .= " FROM ".$this->db->prefix().'c_input_reason';
  3475. $sql .= " WHERE active > 0";
  3476. $resql = $this->db->query($sql);
  3477. if ($resql) {
  3478. $num = $this->db->num_rows($resql);
  3479. $i = 0;
  3480. $tmparray = array();
  3481. while ($i < $num) {
  3482. $obj = $this->db->fetch_object($resql);
  3483. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3484. $label = ($obj->label != '-' ? $obj->label : '');
  3485. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
  3486. $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3487. }
  3488. if ($langs->trans($obj->code) != $obj->code) {
  3489. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3490. }
  3491. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3492. $tmparray[$obj->rowid]['code'] = $obj->code;
  3493. $tmparray[$obj->rowid]['label'] = $label;
  3494. $i++;
  3495. }
  3496. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3497. unset($tmparray);
  3498. return $num;
  3499. } else {
  3500. dol_print_error($this->db);
  3501. return -1;
  3502. }
  3503. }
  3504. /**
  3505. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3506. * List found into table c_input_reason loaded by loadCacheInputReason
  3507. *
  3508. * @param int $selected Id or code of type origin to select by default
  3509. * @param string $htmlname Nom de la zone select
  3510. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3511. * @param int $addempty Add an empty entry
  3512. * @param string $morecss Add more css to the HTML select component
  3513. * @param int $notooltip Do not show the tooltip for admin
  3514. * @return void
  3515. */
  3516. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3517. {
  3518. global $langs, $user;
  3519. $this->loadCacheInputReason();
  3520. print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3521. if ($addempty) {
  3522. print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3523. }
  3524. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3525. if ($arraydemandreason['code'] == $exclude) {
  3526. continue;
  3527. }
  3528. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3529. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3530. } else {
  3531. print '<option value="'.$arraydemandreason['id'].'">';
  3532. }
  3533. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3534. print $langs->trans($label);
  3535. print '</option>';
  3536. }
  3537. print '</select>';
  3538. if ($user->admin && empty($notooltip)) {
  3539. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3540. }
  3541. print ajax_combobox('select_'.$htmlname);
  3542. }
  3543. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3544. /**
  3545. * Charge dans cache la liste des types de paiements possibles
  3546. *
  3547. * @return int Nb of lines loaded, <0 if KO
  3548. */
  3549. public function load_cache_types_paiements()
  3550. {
  3551. // phpcs:enable
  3552. global $langs;
  3553. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3554. if ($num > 0) {
  3555. return $num; // Cache already loaded
  3556. }
  3557. dol_syslog(__METHOD__, LOG_DEBUG);
  3558. $this->cache_types_paiements = array();
  3559. $sql = "SELECT id, code, libelle as label, type, active";
  3560. $sql .= " FROM ".$this->db->prefix()."c_paiement";
  3561. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3562. $resql = $this->db->query($sql);
  3563. if ($resql) {
  3564. $num = $this->db->num_rows($resql);
  3565. $i = 0;
  3566. while ($i < $num) {
  3567. $obj = $this->db->fetch_object($resql);
  3568. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3569. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3570. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3571. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3572. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3573. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3574. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3575. $i++;
  3576. }
  3577. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3578. return $num;
  3579. } else {
  3580. dol_print_error($this->db);
  3581. return -1;
  3582. }
  3583. }
  3584. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3585. /**
  3586. * print list of payment modes.
  3587. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3588. * See instead to force the default value by the caller.
  3589. *
  3590. * @param int $selected Id of payment term to preselect by default
  3591. * @param string $htmlname Nom de la zone select
  3592. * @param int $filtertype Not used
  3593. * @param int $addempty Add an empty entry
  3594. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3595. * @param string $morecss Add more CSS on select tag
  3596. * @return void
  3597. */
  3598. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '')
  3599. {
  3600. // phpcs:enable
  3601. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss);
  3602. }
  3603. /**
  3604. * Return list of payment modes.
  3605. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3606. * See instead to force the default value by the caller.
  3607. *
  3608. * @param int $selected Id of payment term to preselect by default
  3609. * @param string $htmlname Nom de la zone select
  3610. * @param int $filtertype Not used
  3611. * @param int $addempty Add an empty entry
  3612. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3613. * @param string $morecss Add more CSS on select tag
  3614. * @return void
  3615. */
  3616. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '')
  3617. {
  3618. global $langs, $user, $conf;
  3619. $out = '';
  3620. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3621. $this->load_cache_conditions_paiements();
  3622. // Set default value if not already set by caller
  3623. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3624. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3625. }
  3626. $out.= '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3627. if ($addempty) {
  3628. $out.= '<option value="0">&nbsp;</option>';
  3629. }
  3630. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3631. if ($selected == $id) {
  3632. $out.= '<option value="'.$id.'" selected>';
  3633. } else {
  3634. $out.= '<option value="'.$id.'">';
  3635. }
  3636. $out.= $arrayconditions['label'];
  3637. $out.= '</option>';
  3638. }
  3639. $out.= '</select>';
  3640. if ($user->admin && empty($noinfoadmin)) {
  3641. $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3642. }
  3643. $out.= ajax_combobox($htmlname);
  3644. return $out;
  3645. }
  3646. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3647. /**
  3648. * Return list of payment methods
  3649. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3650. *
  3651. * @param string $selected Id or code or preselected payment mode
  3652. * @param string $htmlname Name of select field
  3653. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3654. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3655. * @param int $empty 1=can be empty, 0 otherwise
  3656. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3657. * @param int $maxlength Max length of label
  3658. * @param int $active Active or not, -1 = all
  3659. * @param string $morecss Add more CSS on select tag
  3660. * @param int $nooutput 1=Return string, do not send to output
  3661. * @return void
  3662. */
  3663. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3664. {
  3665. // phpcs:enable
  3666. global $langs, $user, $conf;
  3667. $out = '';
  3668. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3669. $filterarray = array();
  3670. if ($filtertype == 'CRDT') {
  3671. $filterarray = array(0, 2, 3);
  3672. } elseif ($filtertype == 'DBIT') {
  3673. $filterarray = array(1, 2, 3);
  3674. } elseif ($filtertype != '' && $filtertype != '-1') {
  3675. $filterarray = explode(',', $filtertype);
  3676. }
  3677. $this->load_cache_types_paiements();
  3678. // Set default value if not already set by caller
  3679. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3680. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3681. }
  3682. $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3683. if ($empty) {
  3684. $out .= '<option value="">&nbsp;</option>';
  3685. }
  3686. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3687. // If not good status
  3688. if ($active >= 0 && $arraytypes['active'] != $active) {
  3689. continue;
  3690. }
  3691. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3692. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3693. continue;
  3694. }
  3695. // We discard empty line if showempty is on because an empty line has already been output.
  3696. if ($empty && empty($arraytypes['code'])) {
  3697. continue;
  3698. }
  3699. if ($format == 0) {
  3700. $out .= '<option value="'.$id.'"';
  3701. } elseif ($format == 1) {
  3702. $out .= '<option value="'.$arraytypes['code'].'"';
  3703. } elseif ($format == 2) {
  3704. $out .= '<option value="'.$arraytypes['code'].'"';
  3705. } elseif ($format == 3) {
  3706. $out .= '<option value="'.$id.'"';
  3707. }
  3708. // Print attribute selected or not
  3709. if ($format == 1 || $format == 2) {
  3710. if ($selected == $arraytypes['code']) {
  3711. $out .= ' selected';
  3712. }
  3713. } else {
  3714. if ($selected == $id) {
  3715. $out .= ' selected';
  3716. }
  3717. }
  3718. $out .= '>';
  3719. if ($format == 0) {
  3720. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3721. } elseif ($format == 1) {
  3722. $value = $arraytypes['code'];
  3723. } elseif ($format == 2) {
  3724. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3725. } elseif ($format == 3) {
  3726. $value = $arraytypes['code'];
  3727. }
  3728. $out .= $value ? $value : '&nbsp;';
  3729. $out .= '</option>';
  3730. }
  3731. $out .= '</select>';
  3732. if ($user->admin && !$noadmininfo) {
  3733. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3734. }
  3735. $out .= ajax_combobox('select'.$htmlname);
  3736. if (empty($nooutput)) {
  3737. print $out;
  3738. } else {
  3739. return $out;
  3740. }
  3741. }
  3742. /**
  3743. * Selection HT or TTC
  3744. *
  3745. * @param string $selected Id pre-selectionne
  3746. * @param string $htmlname Nom de la zone select
  3747. * @param string $addjscombo Add js combo
  3748. * @return string Code of HTML select to chose tax or not
  3749. */
  3750. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3751. {
  3752. global $langs;
  3753. $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3754. $options = array(
  3755. 'HT'=>$langs->trans("HT"),
  3756. 'TTC'=>$langs->trans("TTC")
  3757. );
  3758. foreach ($options as $id => $value) {
  3759. if ($selected == $id) {
  3760. $return .= '<option value="'.$id.'" selected>'.$value;
  3761. } else {
  3762. $return .= '<option value="'.$id.'">'.$value;
  3763. }
  3764. $return .= '</option>';
  3765. }
  3766. $return .= '</select>';
  3767. if ($addjscombo) {
  3768. $return .= ajax_combobox('select_'.$htmlname);
  3769. }
  3770. return $return;
  3771. }
  3772. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3773. /**
  3774. * Load in cache list of transport mode
  3775. *
  3776. * @return int Nb of lines loaded, <0 if KO
  3777. */
  3778. public function load_cache_transport_mode()
  3779. {
  3780. // phpcs:enable
  3781. global $langs;
  3782. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  3783. if ($num > 0) {
  3784. return $num; // Cache already loaded
  3785. }
  3786. dol_syslog(__METHOD__, LOG_DEBUG);
  3787. $this->cache_transport_mode = array();
  3788. $sql = "SELECT rowid, code, label, active";
  3789. $sql .= " FROM ".$this->db->prefix()."c_transport_mode";
  3790. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3791. $resql = $this->db->query($sql);
  3792. if ($resql) {
  3793. $num = $this->db->num_rows($resql);
  3794. $i = 0;
  3795. while ($i < $num) {
  3796. $obj = $this->db->fetch_object($resql);
  3797. // If traduction exist, we use it else we take the default label
  3798. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3799. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3800. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3801. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3802. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3803. $i++;
  3804. }
  3805. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3806. return $num;
  3807. } else {
  3808. dol_print_error($this->db);
  3809. return -1;
  3810. }
  3811. }
  3812. /**
  3813. * Return list of transport mode for intracomm report
  3814. *
  3815. * @param string $selected Id of the transport mode pre-selected
  3816. * @param string $htmlname Name of the select field
  3817. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3818. * @param int $empty 1=can be empty, 0 else
  3819. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3820. * @param int $maxlength Max length of label
  3821. * @param int $active Active or not, -1 = all
  3822. * @param string $morecss Add more CSS on select tag
  3823. * @return void
  3824. */
  3825. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3826. {
  3827. global $langs, $user;
  3828. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3829. $this->load_cache_transport_mode();
  3830. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3831. if ($empty) {
  3832. print '<option value="">&nbsp;</option>';
  3833. }
  3834. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3835. // If not good status
  3836. if ($active >= 0 && $arraytypes['active'] != $active) {
  3837. continue;
  3838. }
  3839. // We discard empty line if showempty is on because an empty line has already been output.
  3840. if ($empty && empty($arraytypes['code'])) {
  3841. continue;
  3842. }
  3843. if ($format == 0) {
  3844. print '<option value="'.$id.'"';
  3845. } elseif ($format == 1) {
  3846. print '<option value="'.$arraytypes['code'].'"';
  3847. } elseif ($format == 2) {
  3848. print '<option value="'.$arraytypes['code'].'"';
  3849. } elseif ($format == 3) {
  3850. print '<option value="'.$id.'"';
  3851. }
  3852. // If text is selected, we compare with code, else with id
  3853. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  3854. print ' selected';
  3855. } elseif ($selected == $id) {
  3856. print ' selected';
  3857. }
  3858. print '>';
  3859. if ($format == 0) {
  3860. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3861. } elseif ($format == 1) {
  3862. $value = $arraytypes['code'];
  3863. } elseif ($format == 2) {
  3864. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3865. } elseif ($format == 3) {
  3866. $value = $arraytypes['code'];
  3867. }
  3868. print $value ? $value : '&nbsp;';
  3869. print '</option>';
  3870. }
  3871. print '</select>';
  3872. if ($user->admin && !$noadmininfo) {
  3873. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3874. }
  3875. }
  3876. /**
  3877. * Return a HTML select list of shipping mode
  3878. *
  3879. * @param string $selected Id shipping mode pre-selected
  3880. * @param string $htmlname Name of select zone
  3881. * @param string $filtre To filter list. This parameter must not come from input of users
  3882. * @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.
  3883. * @param string $moreattrib To add more attribute on select
  3884. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3885. * @param string $morecss More CSS
  3886. * @return void
  3887. */
  3888. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  3889. {
  3890. global $langs, $conf, $user;
  3891. $langs->load("admin");
  3892. $langs->load("deliveries");
  3893. $sql = "SELECT rowid, code, libelle as label";
  3894. $sql .= " FROM ".$this->db->prefix()."c_shipment_mode";
  3895. $sql .= " WHERE active > 0";
  3896. if ($filtre) {
  3897. $sql .= " AND ".$filtre;
  3898. }
  3899. $sql .= " ORDER BY libelle ASC";
  3900. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3901. $result = $this->db->query($sql);
  3902. if ($result) {
  3903. $num = $this->db->num_rows($result);
  3904. $i = 0;
  3905. if ($num) {
  3906. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3907. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3908. print '<option value="-1">&nbsp;</option>';
  3909. }
  3910. while ($i < $num) {
  3911. $obj = $this->db->fetch_object($result);
  3912. if ($selected == $obj->rowid) {
  3913. print '<option value="'.$obj->rowid.'" selected>';
  3914. } else {
  3915. print '<option value="'.$obj->rowid.'">';
  3916. }
  3917. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3918. print '</option>';
  3919. $i++;
  3920. }
  3921. print "</select>";
  3922. if ($user->admin && empty($noinfoadmin)) {
  3923. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3924. }
  3925. print ajax_combobox('select'.$htmlname);
  3926. } else {
  3927. print $langs->trans("NoShippingMethodDefined");
  3928. }
  3929. } else {
  3930. dol_print_error($this->db);
  3931. }
  3932. }
  3933. /**
  3934. * Display form to select shipping mode
  3935. *
  3936. * @param string $page Page
  3937. * @param int $selected Id of shipping mode
  3938. * @param string $htmlname Name of select html field
  3939. * @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.
  3940. * @return void
  3941. */
  3942. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  3943. {
  3944. global $langs;
  3945. $langs->load("deliveries");
  3946. if ($htmlname != "none") {
  3947. print '<form method="POST" action="'.$page.'">';
  3948. print '<input type="hidden" name="action" value="setshippingmethod">';
  3949. print '<input type="hidden" name="token" value="'.newToken().'">';
  3950. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3951. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3952. print '</form>';
  3953. } else {
  3954. if ($selected) {
  3955. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  3956. print $langs->trans("SendingMethod".strtoupper($code));
  3957. } else {
  3958. print "&nbsp;";
  3959. }
  3960. }
  3961. }
  3962. /**
  3963. * Creates HTML last in cycle situation invoices selector
  3964. *
  3965. * @param string $selected Preselected ID
  3966. * @param int $socid Company ID
  3967. *
  3968. * @return string HTML select
  3969. */
  3970. public function selectSituationInvoices($selected = '', $socid = 0)
  3971. {
  3972. global $langs;
  3973. $langs->load('bills');
  3974. $opt = '<option value="" selected></option>';
  3975. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  3976. $sql .= ' FROM '.$this->db->prefix().'facture';
  3977. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  3978. $sql .= ' AND situation_counter >= 1';
  3979. $sql .= ' AND fk_soc = '.(int) $socid;
  3980. $sql .= ' AND type <> 2';
  3981. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  3982. $resql = $this->db->query($sql);
  3983. if ($resql && $this->db->num_rows($resql) > 0) {
  3984. // Last seen cycle
  3985. $ref = 0;
  3986. while ($obj = $this->db->fetch_object($resql)) {
  3987. //Same cycle ?
  3988. if ($obj->situation_cycle_ref != $ref) {
  3989. // Just seen this cycle
  3990. $ref = $obj->situation_cycle_ref;
  3991. //not final ?
  3992. if ($obj->situation_final != 1) {
  3993. //Not prov?
  3994. if (substr($obj->ref, 1, 4) != 'PROV') {
  3995. if ($selected == $obj->rowid) {
  3996. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  3997. } else {
  3998. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  3999. }
  4000. }
  4001. }
  4002. }
  4003. }
  4004. } else {
  4005. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4006. }
  4007. if ($opt == '<option value ="" selected></option>') {
  4008. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  4009. }
  4010. return $opt;
  4011. }
  4012. /**
  4013. * Creates HTML units selector (code => label)
  4014. *
  4015. * @param string $selected Preselected Unit ID
  4016. * @param string $htmlname Select name
  4017. * @param int $showempty Add a nempty line
  4018. * @param string $unit_type Restrict to one given unit type
  4019. * @return string HTML select
  4020. */
  4021. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4022. {
  4023. global $langs;
  4024. $langs->load('products');
  4025. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  4026. $sql = "SELECT rowid, label, code FROM ".$this->db->prefix()."c_units";
  4027. $sql .= ' WHERE active > 0';
  4028. if (!empty($unit_type)) {
  4029. $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
  4030. }
  4031. $sql .= " ORDER BY sortorder";
  4032. $resql = $this->db->query($sql);
  4033. if ($resql && $this->db->num_rows($resql) > 0) {
  4034. if ($showempty) {
  4035. $return .= '<option value="none"></option>';
  4036. }
  4037. while ($res = $this->db->fetch_object($resql)) {
  4038. $unitLabel = $res->label;
  4039. if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
  4040. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  4041. }
  4042. if ($selected == $res->rowid) {
  4043. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  4044. } else {
  4045. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  4046. }
  4047. }
  4048. $return .= '</select>';
  4049. }
  4050. return $return;
  4051. }
  4052. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4053. /**
  4054. * Return a HTML select list of bank accounts
  4055. *
  4056. * @param string $selected Id account pre-selected
  4057. * @param string $htmlname Name of select zone
  4058. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4059. * @param string $filtre To filter list. This parameter must not come from input of users
  4060. * @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.
  4061. * @param string $moreattrib To add more attribute on select
  4062. * @param int $showcurrency Show currency in label
  4063. * @param string $morecss More CSS
  4064. * @param int $nooutput 1=Return string, do not send to output
  4065. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4066. */
  4067. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4068. {
  4069. // phpcs:enable
  4070. global $langs, $conf;
  4071. $out = '';
  4072. $langs->load("admin");
  4073. $num = 0;
  4074. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4075. $sql .= " FROM ".$this->db->prefix()."bank_account";
  4076. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  4077. if ($status != 2) {
  4078. $sql .= " AND clos = ".(int) $status;
  4079. }
  4080. if ($filtre) {
  4081. $sql .= " AND ".$filtre;
  4082. }
  4083. $sql .= " ORDER BY label";
  4084. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  4085. $result = $this->db->query($sql);
  4086. if ($result) {
  4087. $num = $this->db->num_rows($result);
  4088. $i = 0;
  4089. if ($num) {
  4090. $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4091. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4092. $out .= '<option value="-1">&nbsp;</option>';
  4093. }
  4094. while ($i < $num) {
  4095. $obj = $this->db->fetch_object($result);
  4096. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4097. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
  4098. } else {
  4099. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
  4100. }
  4101. $out .= trim($obj->label);
  4102. if ($showcurrency) {
  4103. $out .= ' ('.$obj->currency_code.')';
  4104. }
  4105. if ($status == 2 && $obj->status == 1) {
  4106. $out .= ' ('.$langs->trans("Closed").')';
  4107. }
  4108. $out .= '</option>';
  4109. $i++;
  4110. }
  4111. $out .= "</select>";
  4112. $out .= ajax_combobox('select'.$htmlname);
  4113. } else {
  4114. if ($status == 0) {
  4115. $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  4116. } else {
  4117. $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  4118. }
  4119. }
  4120. } else {
  4121. dol_print_error($this->db);
  4122. }
  4123. // Output or return
  4124. if (empty($nooutput)) {
  4125. print $out;
  4126. } else {
  4127. return $out;
  4128. }
  4129. return $num;
  4130. }
  4131. /**
  4132. * Return a HTML select list of establishment
  4133. *
  4134. * @param string $selected Id establishment pre-selected
  4135. * @param string $htmlname Name of select zone
  4136. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4137. * @param string $filtre To filter list. This parameter must not come from input of users
  4138. * @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.
  4139. * @param string $moreattrib To add more attribute on select
  4140. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4141. */
  4142. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4143. {
  4144. global $langs, $conf;
  4145. $langs->load("admin");
  4146. $num = 0;
  4147. $sql = "SELECT rowid, name, fk_country, status, entity";
  4148. $sql .= " FROM ".$this->db->prefix()."establishment";
  4149. $sql .= " WHERE 1=1";
  4150. if ($status != 2) {
  4151. $sql .= " AND status = ".(int) $status;
  4152. }
  4153. if ($filtre) {
  4154. $sql .= " AND ".$filtre;
  4155. }
  4156. $sql .= " ORDER BY name";
  4157. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  4158. $result = $this->db->query($sql);
  4159. if ($result) {
  4160. $num = $this->db->num_rows($result);
  4161. $i = 0;
  4162. if ($num) {
  4163. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4164. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4165. print '<option value="-1">&nbsp;</option>';
  4166. }
  4167. while ($i < $num) {
  4168. $obj = $this->db->fetch_object($result);
  4169. if ($selected == $obj->rowid) {
  4170. print '<option value="'.$obj->rowid.'" selected>';
  4171. } else {
  4172. print '<option value="'.$obj->rowid.'">';
  4173. }
  4174. print trim($obj->name);
  4175. if ($status == 2 && $obj->status == 1) {
  4176. print ' ('.$langs->trans("Closed").')';
  4177. }
  4178. print '</option>';
  4179. $i++;
  4180. }
  4181. print "</select>";
  4182. } else {
  4183. if ($status == 0) {
  4184. print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  4185. } else {
  4186. print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  4187. }
  4188. }
  4189. } else {
  4190. dol_print_error($this->db);
  4191. }
  4192. }
  4193. /**
  4194. * Display form to select bank account
  4195. *
  4196. * @param string $page Page
  4197. * @param int $selected Id of bank account
  4198. * @param string $htmlname Name of select html field
  4199. * @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.
  4200. * @return void
  4201. */
  4202. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4203. {
  4204. global $langs;
  4205. if ($htmlname != "none") {
  4206. print '<form method="POST" action="'.$page.'">';
  4207. print '<input type="hidden" name="action" value="setbankaccount">';
  4208. print '<input type="hidden" name="token" value="'.newToken().'">';
  4209. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4210. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4211. if ($nbaccountfound > 0) {
  4212. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4213. }
  4214. print '</form>';
  4215. } else {
  4216. $langs->load('banks');
  4217. if ($selected) {
  4218. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  4219. $bankstatic = new Account($this->db);
  4220. $result = $bankstatic->fetch($selected);
  4221. if ($result) {
  4222. print $bankstatic->getNomUrl(1);
  4223. }
  4224. } else {
  4225. print "&nbsp;";
  4226. }
  4227. }
  4228. }
  4229. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4230. /**
  4231. * Return list of categories having choosed type
  4232. *
  4233. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4234. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4235. * @param string $htmlname HTML field name
  4236. * @param int $maxlength Maximum length for labels
  4237. * @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.
  4238. * $markafterid can be an :
  4239. * - int (id of category)
  4240. * - string (categories ids seprated by comma)
  4241. * - array (list of categories ids)
  4242. * @param int $outputmode 0=HTML select string, 1=Array
  4243. * @param int $include [=0] Removed or 1=Keep only
  4244. * @param string $morecss More CSS
  4245. * @return string
  4246. * @see select_categories()
  4247. */
  4248. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4249. {
  4250. // phpcs:enable
  4251. global $conf, $langs;
  4252. $langs->load("categories");
  4253. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4254. // For backward compatibility
  4255. if (is_numeric($type)) {
  4256. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4257. }
  4258. if ($type === Categorie::TYPE_BANK_LINE) {
  4259. // TODO Move this into common category feature
  4260. $cate_arbo = array();
  4261. $sql = "SELECT c.label, c.rowid";
  4262. $sql .= " FROM ".$this->db->prefix()."bank_categ as c";
  4263. $sql .= " WHERE entity = ".$conf->entity;
  4264. $sql .= " ORDER BY c.label";
  4265. $result = $this->db->query($sql);
  4266. if ($result) {
  4267. $num = $this->db->num_rows($result);
  4268. $i = 0;
  4269. while ($i < $num) {
  4270. $objp = $this->db->fetch_object($result);
  4271. if ($objp) {
  4272. $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  4273. }
  4274. $i++;
  4275. }
  4276. $this->db->free($result);
  4277. } else {
  4278. dol_print_error($this->db);
  4279. }
  4280. } else {
  4281. $cat = new Categorie($this->db);
  4282. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4283. }
  4284. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  4285. $outarray = array();
  4286. if (is_array($cate_arbo)) {
  4287. if (!count($cate_arbo)) {
  4288. $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  4289. } else {
  4290. $output .= '<option value="-1">&nbsp;</option>';
  4291. foreach ($cate_arbo as $key => $value) {
  4292. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4293. $add = 'selected ';
  4294. } else {
  4295. $add = '';
  4296. }
  4297. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  4298. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4299. }
  4300. }
  4301. }
  4302. $output .= '</select>';
  4303. $output .= "\n";
  4304. if ($outputmode) {
  4305. return $outarray;
  4306. }
  4307. return $output;
  4308. }
  4309. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4310. /**
  4311. * Show a confirmation HTML form or AJAX popup
  4312. *
  4313. * @param string $page Url of page to call if confirmation is OK
  4314. * @param string $title Title
  4315. * @param string $question Question
  4316. * @param string $action Action
  4317. * @param array $formquestion An array with forms complementary inputs
  4318. * @param string $selectedchoice "" or "no" or "yes"
  4319. * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx
  4320. * @param int $height Force height of box
  4321. * @param int $width Force width of box
  4322. * @return void
  4323. * @deprecated
  4324. * @see formconfirm()
  4325. */
  4326. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4327. {
  4328. // phpcs:enable
  4329. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4330. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4331. }
  4332. /**
  4333. * Show a confirmation HTML form or AJAX popup.
  4334. * Easiest way to use this is with useajax=1.
  4335. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4336. * just after calling this method. For example:
  4337. * print '<script type="text/javascript">'."\n";
  4338. * print 'jQuery(document).ready(function() {'."\n";
  4339. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4340. * print '});'."\n";
  4341. * print '</script>'."\n";
  4342. *
  4343. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4344. * @param string $title Title
  4345. * @param string $question Question
  4346. * @param string $action Action
  4347. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>))
  4348. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', 'other' or 'onecolumn'...
  4349. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  4350. * @param int|string $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4351. * @param int|string $height Force height of box (0 = auto)
  4352. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4353. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4354. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4355. */
  4356. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0)
  4357. {
  4358. global $langs, $conf;
  4359. $more = '<!-- formconfirm before calling page='.dol_escape_htmltag($page).' -->';
  4360. $formconfirm = '';
  4361. $inputok = array();
  4362. $inputko = array();
  4363. // Clean parameters
  4364. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4365. if ($conf->browser->layout == 'phone') {
  4366. $width = '95%';
  4367. }
  4368. // Set height automatically if not defined
  4369. if (empty($height)) {
  4370. $height = 220;
  4371. if (is_array($formquestion) && count($formquestion) > 2) {
  4372. $height += ((count($formquestion) - 2) * 24);
  4373. }
  4374. }
  4375. if (is_array($formquestion) && !empty($formquestion)) {
  4376. // First add hidden fields and value
  4377. foreach ($formquestion as $key => $input) {
  4378. if (is_array($input) && !empty($input)) {
  4379. if ($input['type'] == 'hidden') {
  4380. $more .= '<input type="hidden" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  4381. }
  4382. }
  4383. }
  4384. // Now add questions
  4385. $moreonecolumn = '';
  4386. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  4387. foreach ($formquestion as $key => $input) {
  4388. if (is_array($input) && !empty($input)) {
  4389. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
  4390. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4391. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4392. if ($input['type'] == 'text') {
  4393. $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="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4394. } elseif ($input['type'] == 'password') {
  4395. $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="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4396. } elseif ($input['type'] == 'textarea') {
  4397. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4398. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4399. $more .= $input['value'];
  4400. $more .= '</textarea>';
  4401. $more .= '</div></div>'."\n";*/
  4402. $moreonecolumn .= '<div class="margintoponly">';
  4403. $moreonecolumn .= $input['label'].'<br>';
  4404. $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
  4405. $moreonecolumn .= $input['value'];
  4406. $moreonecolumn .= '</textarea>';
  4407. $moreonecolumn .= '</div>';
  4408. } elseif ($input['type'] == 'select') {
  4409. if (empty($morecss)) {
  4410. $morecss = 'minwidth100';
  4411. }
  4412. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4413. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4414. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4415. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4416. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4417. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4418. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4419. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4420. if (!empty($input['label'])) {
  4421. $more .= $input['label'].'</div><div class="tagtd left">';
  4422. }
  4423. $more .= $this->selectarray($input['name'], $input['values'], $input['default'], $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4424. $more .= '</div></div>'."\n";
  4425. } elseif ($input['type'] == 'checkbox') {
  4426. $more .= '<div class="tagtr">';
  4427. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  4428. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
  4429. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4430. $more .= ' checked';
  4431. }
  4432. if (is_bool($input['value']) && $input['value']) {
  4433. $more .= ' checked';
  4434. }
  4435. if (isset($input['disabled'])) {
  4436. $more .= ' disabled';
  4437. }
  4438. $more .= ' /></div>';
  4439. $more .= '</div>'."\n";
  4440. } elseif ($input['type'] == 'radio') {
  4441. $i = 0;
  4442. foreach ($input['values'] as $selkey => $selval) {
  4443. $more .= '<div class="tagtr">';
  4444. if ($i == 0) {
  4445. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4446. } else {
  4447. $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  4448. }
  4449. $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;
  4450. if ($input['disabled']) {
  4451. $more .= ' disabled';
  4452. }
  4453. if (isset($input['default']) && $input['default'] === $selkey) {
  4454. $more .= ' checked="checked"';
  4455. }
  4456. $more .= ' /> ';
  4457. $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'">'.$selval.'</label>';
  4458. $more .= '</div></div>'."\n";
  4459. $i++;
  4460. }
  4461. } elseif ($input['type'] == 'date') {
  4462. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4463. $more .= '<div class="tagtd">';
  4464. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4465. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, $addnowlink);
  4466. $more .= '</div></div>'."\n";
  4467. $formquestion[] = array('name'=>$input['name'].'day');
  4468. $formquestion[] = array('name'=>$input['name'].'month');
  4469. $formquestion[] = array('name'=>$input['name'].'year');
  4470. $formquestion[] = array('name'=>$input['name'].'hour');
  4471. $formquestion[] = array('name'=>$input['name'].'min');
  4472. } elseif ($input['type'] == 'other') {
  4473. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4474. if (!empty($input['label'])) {
  4475. $more .= $input['label'].'</div><div class="tagtd">';
  4476. }
  4477. $more .= $input['value'];
  4478. $more .= '</div></div>'."\n";
  4479. } elseif ($input['type'] == 'onecolumn') {
  4480. $moreonecolumn .= '<div class="margintoponly">';
  4481. $moreonecolumn .= $input['value'];
  4482. $moreonecolumn .= '</div>'."\n";
  4483. } elseif ($input['type'] == 'hidden') {
  4484. // Do nothing more, already added by a previous loop
  4485. } elseif ($input['type'] == 'separator') {
  4486. $more .= '<br>';
  4487. } else {
  4488. $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
  4489. }
  4490. }
  4491. }
  4492. $more .= '</div>'."\n";
  4493. $more .= $moreonecolumn;
  4494. }
  4495. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4496. // 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
  4497. // See page product/card.php for example
  4498. if (!empty($conf->dol_use_jmobile)) {
  4499. $useajax = 0;
  4500. }
  4501. if (empty($conf->use_javascript_ajax)) {
  4502. $useajax = 0;
  4503. }
  4504. if ($useajax) {
  4505. $autoOpen = true;
  4506. $dialogconfirm = 'dialog-confirm';
  4507. $button = '';
  4508. if (!is_numeric($useajax)) {
  4509. $button = $useajax;
  4510. $useajax = 1;
  4511. $autoOpen = false;
  4512. $dialogconfirm .= '-'.$button;
  4513. }
  4514. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.$action.'&confirm=yes';
  4515. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'confirm=no' : '');
  4516. // Add input fields into list of fields to read during submit (inputok and inputko)
  4517. if (is_array($formquestion)) {
  4518. foreach ($formquestion as $key => $input) {
  4519. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4520. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4521. if (is_array($input) && isset($input['name'])) {
  4522. if (strpos($input['name'], ',') > 0) {
  4523. $inputok = array_merge($inputok, explode(',', $input['name']));
  4524. } else {
  4525. array_push($inputok, $input['name']);
  4526. }
  4527. }
  4528. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4529. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4530. array_push($inputko, $input['name']);
  4531. }
  4532. }
  4533. }
  4534. // Show JQuery confirm box.
  4535. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  4536. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4537. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  4538. }
  4539. if (!empty($more)) {
  4540. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  4541. }
  4542. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  4543. $formconfirm .= '</div>'."\n";
  4544. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=".$page." -->\n";
  4545. $formconfirm .= '<script type="text/javascript">'."\n";
  4546. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4547. $formconfirm .= 'jQuery(document).ready(function() {
  4548. $(function() {
  4549. $( "#'.$dialogconfirm.'" ).dialog(
  4550. {
  4551. autoOpen: '.($autoOpen ? "true" : "false").',';
  4552. if ($newselectedchoice == 'no') {
  4553. $formconfirm .= '
  4554. open: function() {
  4555. $(this).parent().find("button.ui-button:eq(2)").focus();
  4556. },';
  4557. }
  4558. $formconfirm .= '
  4559. resizable: false,
  4560. height: "'.$height.'",
  4561. width: "'.$width.'",
  4562. modal: true,
  4563. closeOnEscape: false,
  4564. buttons: {
  4565. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  4566. var options = "&token='.urlencode(newToken()).'";
  4567. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  4568. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  4569. if (inputok.length>0) {
  4570. $.each(inputok, function(i, inputname) {
  4571. var more = "";
  4572. var inputvalue;
  4573. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4574. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4575. } else {
  4576. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4577. inputvalue = $("#" + inputname + more).val();
  4578. }
  4579. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4580. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4581. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4582. });
  4583. }
  4584. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  4585. if (pageyes.length > 0) { location.href = urljump; }
  4586. $(this).dialog("close");
  4587. },
  4588. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  4589. var options = "&token='.urlencode(newToken()).'";
  4590. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  4591. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  4592. if (inputko.length>0) {
  4593. $.each(inputko, function(i, inputname) {
  4594. var more = "";
  4595. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4596. var inputvalue = $("#" + inputname + more).val();
  4597. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4598. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4599. });
  4600. }
  4601. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  4602. //alert(urljump);
  4603. if (pageno.length > 0) { location.href = urljump; }
  4604. $(this).dialog("close");
  4605. }
  4606. }
  4607. }
  4608. );
  4609. var button = "'.$button.'";
  4610. if (button.length > 0) {
  4611. $( "#" + button ).click(function() {
  4612. $("#'.$dialogconfirm.'").dialog("open");
  4613. });
  4614. }
  4615. });
  4616. });
  4617. </script>';
  4618. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4619. } else {
  4620. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  4621. if (empty($disableformtag)) {
  4622. $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  4623. }
  4624. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  4625. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  4626. $formconfirm .= '<table class="valid centpercent">'."\n";
  4627. // Line title
  4628. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4629. $formconfirm .= img_picto('', 'recent').' '.$title;
  4630. $formconfirm .= '</td></tr>'."\n";
  4631. // Line text
  4632. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4633. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  4634. }
  4635. // Line form fields
  4636. if ($more) {
  4637. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
  4638. $formconfirm .= $more;
  4639. $formconfirm .= '</td></tr>'."\n";
  4640. }
  4641. // Line with question
  4642. $formconfirm .= '<tr class="valid">';
  4643. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4644. $formconfirm .= '<td class="valid center">';
  4645. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly');
  4646. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="'.$langs->trans("Validate").'">';
  4647. $formconfirm .= '</td>';
  4648. $formconfirm .= '</tr>'."\n";
  4649. $formconfirm .= '</table>'."\n";
  4650. if (empty($disableformtag)) {
  4651. $formconfirm .= "</form>\n";
  4652. }
  4653. $formconfirm .= '<br>';
  4654. if (!empty($conf->use_javascript_ajax)) {
  4655. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4656. $formconfirm .= '<script type="text/javascript">'."\n";
  4657. $formconfirm .= '
  4658. $(document).ready(function () {
  4659. $(".confirmvalidatebutton").on("click", function() {
  4660. console.log("We click on button");
  4661. $(this).attr("disabled", "disabled");
  4662. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4663. //console.log($(this).closest("form"));
  4664. $(this).closest("form").submit();
  4665. });
  4666. });
  4667. ';
  4668. $formconfirm .= '</script>'."\n";
  4669. }
  4670. $formconfirm .= "<!-- end formconfirm -->\n";
  4671. }
  4672. return $formconfirm;
  4673. }
  4674. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4675. /**
  4676. * Show a form to select a project
  4677. *
  4678. * @param int $page Page
  4679. * @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)
  4680. * @param int $selected Id pre-selected project
  4681. * @param string $htmlname Name of select field
  4682. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4683. * @param int $maxlength Max length
  4684. * @param int $forcefocus Force focus on field (works with javascript only)
  4685. * @param int $nooutput No print is done. String is returned.
  4686. * @return string Return html content
  4687. */
  4688. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  4689. {
  4690. // phpcs:enable
  4691. global $langs;
  4692. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4693. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4694. $out = '';
  4695. $formproject = new FormProjets($this->db);
  4696. $langs->load("project");
  4697. if ($htmlname != "none") {
  4698. $out .= "\n";
  4699. $out .= '<form method="post" action="'.$page.'">';
  4700. $out .= '<input type="hidden" name="action" value="classin">';
  4701. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4702. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  4703. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4704. $out .= '</form>';
  4705. } else {
  4706. $out .= '<span class="project_head_block">';
  4707. if ($selected) {
  4708. $projet = new Project($this->db);
  4709. $projet->fetch($selected);
  4710. $out .= $projet->getNomUrl(1, '', 1);
  4711. } else {
  4712. $out .= "&nbsp;";
  4713. }
  4714. $out .= '</span>';
  4715. }
  4716. if (empty($nooutput)) {
  4717. print $out;
  4718. return '';
  4719. }
  4720. return $out;
  4721. }
  4722. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4723. /**
  4724. * Show a form to select payment conditions
  4725. *
  4726. * @param int $page Page
  4727. * @param string $selected Id condition pre-selectionne
  4728. * @param string $htmlname Name of select html field
  4729. * @param int $addempty Add empty entry
  4730. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4731. * @return void
  4732. */
  4733. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '')
  4734. {
  4735. // phpcs:enable
  4736. global $langs;
  4737. if ($htmlname != "none") {
  4738. print '<form method="POST" action="'.$page.'">';
  4739. print '<input type="hidden" name="action" value="setconditions">';
  4740. print '<input type="hidden" name="token" value="'.newToken().'">';
  4741. if ($type) {
  4742. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4743. }
  4744. $this->select_conditions_paiements($selected, $htmlname, -1, $addempty, 0, '');
  4745. print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4746. print '</form>';
  4747. } else {
  4748. if ($selected) {
  4749. $this->load_cache_conditions_paiements();
  4750. if (isset($this->cache_conditions_paiements[$selected])) {
  4751. print $this->cache_conditions_paiements[$selected]['label'];
  4752. } else {
  4753. $langs->load('errors');
  4754. print $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4755. }
  4756. } else {
  4757. print "&nbsp;";
  4758. }
  4759. }
  4760. }
  4761. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4762. /**
  4763. * Show a form to select a delivery delay
  4764. *
  4765. * @param int $page Page
  4766. * @param string $selected Id condition pre-selectionne
  4767. * @param string $htmlname Name of select html field
  4768. * @param int $addempty Ajoute entree vide
  4769. * @return void
  4770. */
  4771. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4772. {
  4773. // phpcs:enable
  4774. global $langs;
  4775. if ($htmlname != "none") {
  4776. print '<form method="post" action="'.$page.'">';
  4777. print '<input type="hidden" name="action" value="setavailability">';
  4778. print '<input type="hidden" name="token" value="'.newToken().'">';
  4779. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4780. print '<input type="submit" name="modify" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4781. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="'.$langs->trans("Cancel").'">';
  4782. print '</form>';
  4783. } else {
  4784. if ($selected) {
  4785. $this->load_cache_availability();
  4786. print $this->cache_availability[$selected]['label'];
  4787. } else {
  4788. print "&nbsp;";
  4789. }
  4790. }
  4791. }
  4792. /**
  4793. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  4794. * List found into table c_input_reason loaded by loadCacheInputReason
  4795. *
  4796. * @param string $page Page
  4797. * @param string $selected Id condition pre-selectionne
  4798. * @param string $htmlname Name of select html field
  4799. * @param int $addempty Add empty entry
  4800. * @return void
  4801. */
  4802. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  4803. {
  4804. global $langs;
  4805. if ($htmlname != "none") {
  4806. print '<form method="post" action="'.$page.'">';
  4807. print '<input type="hidden" name="action" value="setdemandreason">';
  4808. print '<input type="hidden" name="token" value="'.newToken().'">';
  4809. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  4810. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4811. print '</form>';
  4812. } else {
  4813. if ($selected) {
  4814. $this->loadCacheInputReason();
  4815. foreach ($this->cache_demand_reason as $key => $val) {
  4816. if ($val['id'] == $selected) {
  4817. print $val['label'];
  4818. break;
  4819. }
  4820. }
  4821. } else {
  4822. print "&nbsp;";
  4823. }
  4824. }
  4825. }
  4826. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4827. /**
  4828. * Show a form + html select a date
  4829. *
  4830. * @param string $page Page
  4831. * @param string $selected Date preselected
  4832. * @param string $htmlname Html name of date input fields or 'none'
  4833. * @param int $displayhour Display hour selector
  4834. * @param int $displaymin Display minutes selector
  4835. * @param int $nooutput 1=No print output, return string
  4836. * @param string $type 'direct-debit' or 'bank-transfer'
  4837. * @return string
  4838. * @see selectDate()
  4839. */
  4840. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  4841. {
  4842. // phpcs:enable
  4843. global $langs;
  4844. $ret = '';
  4845. if ($htmlname != "none") {
  4846. $ret .= '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4847. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4848. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4849. if ($type) {
  4850. $ret .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4851. }
  4852. $ret .= '<table class="nobordernopadding">';
  4853. $ret .= '<tr><td>';
  4854. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4855. $ret .= '</td>';
  4856. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  4857. $ret .= '</tr></table></form>';
  4858. } else {
  4859. if ($displayhour) {
  4860. $ret .= dol_print_date($selected, 'dayhour');
  4861. } else {
  4862. $ret .= dol_print_date($selected, 'day');
  4863. }
  4864. }
  4865. if (empty($nooutput)) {
  4866. print $ret;
  4867. }
  4868. return $ret;
  4869. }
  4870. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4871. /**
  4872. * Show a select form to choose a user
  4873. *
  4874. * @param string $page Page
  4875. * @param string $selected Id of user preselected
  4876. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4877. * @param array $exclude List of users id to exclude
  4878. * @param array $include List of users id to include
  4879. * @return void
  4880. */
  4881. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4882. {
  4883. // phpcs:enable
  4884. global $langs;
  4885. if ($htmlname != "none") {
  4886. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4887. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4888. print '<input type="hidden" name="token" value="'.newToken().'">';
  4889. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  4890. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4891. print '</form>';
  4892. } else {
  4893. if ($selected) {
  4894. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  4895. $theuser = new User($this->db);
  4896. $theuser->fetch($selected);
  4897. print $theuser->getNomUrl(1);
  4898. } else {
  4899. print "&nbsp;";
  4900. }
  4901. }
  4902. }
  4903. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4904. /**
  4905. * Show form with payment mode
  4906. *
  4907. * @param string $page Page
  4908. * @param int $selected Id mode pre-selectionne
  4909. * @param string $htmlname Name of select html field
  4910. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  4911. * @param int $active Active or not, -1 = all
  4912. * @param int $addempty 1=Add empty entry
  4913. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4914. * @return void
  4915. */
  4916. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '')
  4917. {
  4918. // phpcs:enable
  4919. global $langs;
  4920. if ($htmlname != "none") {
  4921. print '<form method="POST" action="'.$page.'">';
  4922. print '<input type="hidden" name="action" value="setmode">';
  4923. print '<input type="hidden" name="token" value="'.newToken().'">';
  4924. if ($type) {
  4925. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4926. }
  4927. print $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  4928. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4929. print '</form>';
  4930. } else {
  4931. if ($selected) {
  4932. $this->load_cache_types_paiements();
  4933. print $this->cache_types_paiements[$selected]['label'];
  4934. } else {
  4935. print "&nbsp;";
  4936. }
  4937. }
  4938. }
  4939. /**
  4940. * Show form with transport mode
  4941. *
  4942. * @param string $page Page
  4943. * @param int $selected Id mode pre-select
  4944. * @param string $htmlname Name of select html field
  4945. * @param int $active Active or not, -1 = all
  4946. * @param int $addempty 1=Add empty entry
  4947. * @return void
  4948. */
  4949. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  4950. {
  4951. global $langs;
  4952. if ($htmlname != "none") {
  4953. print '<form method="POST" action="'.$page.'">';
  4954. print '<input type="hidden" name="action" value="settransportmode">';
  4955. print '<input type="hidden" name="token" value="'.newToken().'">';
  4956. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  4957. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4958. print '</form>';
  4959. } else {
  4960. if ($selected) {
  4961. $this->load_cache_transport_mode();
  4962. print $this->cache_transport_mode[$selected]['label'];
  4963. } else {
  4964. print "&nbsp;";
  4965. }
  4966. }
  4967. }
  4968. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4969. /**
  4970. * Show form with multicurrency code
  4971. *
  4972. * @param string $page Page
  4973. * @param string $selected code pre-selectionne
  4974. * @param string $htmlname Name of select html field
  4975. * @return void
  4976. */
  4977. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  4978. {
  4979. // phpcs:enable
  4980. global $langs;
  4981. if ($htmlname != "none") {
  4982. print '<form method="POST" action="'.$page.'">';
  4983. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  4984. print '<input type="hidden" name="token" value="'.newToken().'">';
  4985. print $this->selectMultiCurrency($selected, $htmlname, 0);
  4986. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4987. print '</form>';
  4988. } else {
  4989. dol_include_once('/core/lib/company.lib.php');
  4990. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  4991. }
  4992. }
  4993. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4994. /**
  4995. * Show form with multicurrency rate
  4996. *
  4997. * @param string $page Page
  4998. * @param double $rate Current rate
  4999. * @param string $htmlname Name of select html field
  5000. * @param string $currency Currency code to explain the rate
  5001. * @return void
  5002. */
  5003. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5004. {
  5005. // phpcs:enable
  5006. global $langs, $mysoc, $conf;
  5007. if ($htmlname != "none") {
  5008. print '<form method="POST" action="'.$page.'">';
  5009. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5010. print '<input type="hidden" name="token" value="'.newToken().'">';
  5011. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
  5012. print '<select name="calculation_mode">';
  5013. print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
  5014. print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
  5015. print '</select> ';
  5016. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5017. print '</form>';
  5018. } else {
  5019. if (!empty($rate)) {
  5020. print price($rate, 1, $langs, 1, 0);
  5021. if ($currency && $rate != 1) {
  5022. print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  5023. }
  5024. } else {
  5025. print 1;
  5026. }
  5027. }
  5028. }
  5029. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5030. /**
  5031. * Show a select box with available absolute discounts
  5032. *
  5033. * @param string $page Page URL where form is shown
  5034. * @param int $selected Value pre-selected
  5035. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5036. * @param int $socid Third party id
  5037. * @param float $amount Total amount available
  5038. * @param string $filter SQL filter on discounts
  5039. * @param int $maxvalue Max value for lines that can be selected
  5040. * @param string $more More string to add
  5041. * @param int $hidelist 1=Hide list
  5042. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5043. * @return void
  5044. */
  5045. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5046. {
  5047. // phpcs:enable
  5048. global $conf, $langs;
  5049. if ($htmlname != "none") {
  5050. print '<form method="post" action="'.$page.'">';
  5051. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5052. print '<input type="hidden" name="token" value="'.newToken().'">';
  5053. print '<div class="inline-block">';
  5054. if (!empty($discount_type)) {
  5055. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5056. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5057. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5058. } else {
  5059. $translationKey = 'HasCreditNoteFromSupplier';
  5060. }
  5061. } else {
  5062. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5063. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5064. } else {
  5065. $translationKey = 'HasCreditNoteFromSupplier';
  5066. }
  5067. }
  5068. } else {
  5069. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5070. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5071. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5072. } else {
  5073. $translationKey = 'CompanyHasCreditNote';
  5074. }
  5075. } else {
  5076. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5077. $translationKey = 'CompanyHasAbsoluteDiscount';
  5078. } else {
  5079. $translationKey = 'CompanyHasCreditNote';
  5080. }
  5081. }
  5082. }
  5083. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5084. if (empty($hidelist)) {
  5085. print ' ';
  5086. }
  5087. print '</div>';
  5088. if (empty($hidelist)) {
  5089. print '<div class="inline-block" style="padding-right: 10px">';
  5090. $newfilter = 'discount_type='.intval($discount_type);
  5091. if (!empty($discount_type)) {
  5092. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5093. } else {
  5094. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5095. }
  5096. if ($filter) {
  5097. $newfilter .= ' AND ('.$filter.')';
  5098. }
  5099. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5100. if ($nbqualifiedlines > 0) {
  5101. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  5102. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5103. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5104. }
  5105. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5106. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5107. }
  5108. print '>';
  5109. }
  5110. print '</div>';
  5111. }
  5112. if ($more) {
  5113. print '<div class="inline-block">';
  5114. print $more;
  5115. print '</div>';
  5116. }
  5117. print '</form>';
  5118. } else {
  5119. if ($selected) {
  5120. print $selected;
  5121. } else {
  5122. print "0";
  5123. }
  5124. }
  5125. }
  5126. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5127. /**
  5128. * Show forms to select a contact
  5129. *
  5130. * @param string $page Page
  5131. * @param Societe $societe Filter on third party
  5132. * @param int $selected Id contact pre-selectionne
  5133. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5134. * @return void
  5135. */
  5136. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5137. {
  5138. // phpcs:enable
  5139. global $langs, $conf;
  5140. if ($htmlname != "none") {
  5141. print '<form method="post" action="'.$page.'">';
  5142. print '<input type="hidden" name="action" value="set_contact">';
  5143. print '<input type="hidden" name="token" value="'.newToken().'">';
  5144. print '<table class="nobordernopadding">';
  5145. print '<tr><td>';
  5146. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5147. $num = $this->num;
  5148. if ($num == 0) {
  5149. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5150. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  5151. }
  5152. print '</td>';
  5153. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5154. print '</tr></table></form>';
  5155. } else {
  5156. if ($selected) {
  5157. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  5158. $contact = new Contact($this->db);
  5159. $contact->fetch($selected);
  5160. print $contact->getFullName($langs);
  5161. } else {
  5162. print "&nbsp;";
  5163. }
  5164. }
  5165. }
  5166. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5167. /**
  5168. * Output html select to select thirdparty
  5169. *
  5170. * @param string $page Page
  5171. * @param string $selected Id preselected
  5172. * @param string $htmlname Name of HTML select
  5173. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5174. * @param int $showempty Add an empty field
  5175. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5176. * @param int $forcecombo Force to use combo box
  5177. * @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')))
  5178. * @param int $nooutput No print output. Return it only.
  5179. * @param array $excludeids Exclude IDs from the select combo
  5180. * @return void|string
  5181. */
  5182. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array())
  5183. {
  5184. // phpcs:enable
  5185. global $langs;
  5186. $out = '';
  5187. if ($htmlname != "none") {
  5188. $out .= '<form method="post" action="'.$page.'">';
  5189. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5190. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5191. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5192. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5193. $out .= '</form>';
  5194. } else {
  5195. if ($selected) {
  5196. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  5197. $soc = new Societe($this->db);
  5198. $soc->fetch($selected);
  5199. $out .= $soc->getNomUrl($langs);
  5200. } else {
  5201. $out .= "&nbsp;";
  5202. }
  5203. }
  5204. if ($nooutput) {
  5205. return $out;
  5206. } else {
  5207. print $out;
  5208. }
  5209. }
  5210. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5211. /**
  5212. * Retourne la liste des devises, dans la langue de l'utilisateur
  5213. *
  5214. * @param string $selected preselected currency code
  5215. * @param string $htmlname name of HTML select list
  5216. * @deprecated
  5217. * @return void
  5218. */
  5219. public function select_currency($selected = '', $htmlname = 'currency_id')
  5220. {
  5221. // phpcs:enable
  5222. print $this->selectCurrency($selected, $htmlname);
  5223. }
  5224. /**
  5225. * Retourne la liste des devises, dans la langue de l'utilisateur
  5226. *
  5227. * @param string $selected preselected currency code
  5228. * @param string $htmlname name of HTML select list
  5229. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5230. * @return string
  5231. */
  5232. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0)
  5233. {
  5234. global $conf, $langs, $user;
  5235. $langs->loadCacheCurrencies('');
  5236. $out = '';
  5237. if ($selected == 'euro' || $selected == 'euros') {
  5238. $selected = 'EUR'; // Pour compatibilite
  5239. }
  5240. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  5241. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5242. $labeltoshow = $currency['label'];
  5243. if ($mode == 1) {
  5244. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  5245. } else {
  5246. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  5247. }
  5248. if ($selected && $selected == $code_iso) {
  5249. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5250. } else {
  5251. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5252. }
  5253. $out .= $labeltoshow;
  5254. $out .= '</option>';
  5255. }
  5256. $out .= '</select>';
  5257. if ($user->admin) {
  5258. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5259. }
  5260. // Make select dynamic
  5261. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5262. $out .= ajax_combobox($htmlname);
  5263. return $out;
  5264. }
  5265. /**
  5266. * Return array of currencies in user language
  5267. *
  5268. * @param string $selected preselected currency code
  5269. * @param string $htmlname name of HTML select list
  5270. * @param integer $useempty 1=Add empty line
  5271. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5272. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available. true = we are in currency_rate update , we don't want to see conf->currency in select
  5273. * @return string
  5274. */
  5275. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false)
  5276. {
  5277. global $conf, $langs;
  5278. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5279. $TCurrency = array();
  5280. $sql = "SELECT code FROM ".$this->db->prefix()."multicurrency";
  5281. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  5282. if ($filter) {
  5283. $sql .= " AND ".$filter;
  5284. }
  5285. $resql = $this->db->query($sql);
  5286. if ($resql) {
  5287. while ($obj = $this->db->fetch_object($resql)) {
  5288. $TCurrency[$obj->code] = $obj->code;
  5289. }
  5290. }
  5291. $out = '';
  5292. $out .= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  5293. if ($useempty) {
  5294. $out .= '<option value="">&nbsp;</option>';
  5295. }
  5296. // If company current currency not in table, we add it into list. Should always be available.
  5297. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5298. $TCurrency[$conf->currency] = $conf->currency;
  5299. }
  5300. if (count($TCurrency) > 0) {
  5301. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5302. if (isset($TCurrency[$code_iso])) {
  5303. if (!empty($selected) && $selected == $code_iso) {
  5304. $out .= '<option value="'.$code_iso.'" selected="selected">';
  5305. } else {
  5306. $out .= '<option value="'.$code_iso.'">';
  5307. }
  5308. $out .= $currency['label'];
  5309. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  5310. $out .= '</option>';
  5311. }
  5312. }
  5313. }
  5314. $out .= '</select>';
  5315. // Make select dynamic
  5316. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5317. $out .= ajax_combobox($htmlname);
  5318. return $out;
  5319. }
  5320. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5321. /**
  5322. * Load into the cache vat rates of a country
  5323. *
  5324. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5325. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5326. */
  5327. public function load_cache_vatrates($country_code)
  5328. {
  5329. // phpcs:enable
  5330. global $langs;
  5331. $num = count($this->cache_vatrates);
  5332. if ($num > 0) {
  5333. return $num; // Cache already loaded
  5334. }
  5335. dol_syslog(__METHOD__, LOG_DEBUG);
  5336. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5337. $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
  5338. $sql .= " WHERE t.fk_pays = c.rowid";
  5339. $sql .= " AND t.active > 0";
  5340. $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
  5341. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5342. $resql = $this->db->query($sql);
  5343. if ($resql) {
  5344. $num = $this->db->num_rows($resql);
  5345. if ($num) {
  5346. for ($i = 0; $i < $num; $i++) {
  5347. $obj = $this->db->fetch_object($resql);
  5348. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5349. $this->cache_vatrates[$i]['code'] = $obj->code;
  5350. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5351. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5352. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5353. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5354. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5355. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5356. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  5357. $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
  5358. $positiverates = '';
  5359. if ($obj->taux) {
  5360. $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  5361. }
  5362. if ($obj->localtax1) {
  5363. $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  5364. }
  5365. if ($obj->localtax2) {
  5366. $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  5367. }
  5368. if (empty($positiverates)) {
  5369. $positiverates = '0';
  5370. }
  5371. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5372. }
  5373. return $num;
  5374. } else {
  5375. $this->error = '<span class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</span>';
  5376. return -1;
  5377. }
  5378. } else {
  5379. $this->error = '<span class="error">'.$this->db->error().'</span>';
  5380. return -2;
  5381. }
  5382. }
  5383. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5384. /**
  5385. * Output an HTML select vat rate.
  5386. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5387. *
  5388. * @param string $htmlname Name of HTML select field
  5389. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5390. * @param Societe $societe_vendeuse Thirdparty seller
  5391. * @param Societe $societe_acheteuse Thirdparty buyer
  5392. * @param int $idprod Id product. O if unknown of NA.
  5393. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5394. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5395. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5396. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5397. * 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.
  5398. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5399. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5400. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5401. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5402. * @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
  5403. * @return string
  5404. */
  5405. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5406. {
  5407. // phpcs:enable
  5408. global $langs, $conf, $mysoc;
  5409. $langs->load('errors');
  5410. $return = '';
  5411. // Define defaultnpr, defaultttx and defaultcode
  5412. $defaultnpr = ($info_bits & 0x01);
  5413. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5414. $defaulttx = str_replace('*', '', $selectedrate);
  5415. $defaultcode = '';
  5416. $reg = array();
  5417. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5418. $defaultcode = $reg[1];
  5419. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5420. }
  5421. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5422. // Check parameters
  5423. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5424. if ($societe_vendeuse->id == $mysoc->id) {
  5425. $return .= '<span class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</span>';
  5426. } else {
  5427. $return .= '<span class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</span>';
  5428. }
  5429. return $return;
  5430. }
  5431. //var_dump($societe_acheteuse);
  5432. //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";
  5433. //exit;
  5434. // Define list of countries to use to search VAT rates to show
  5435. // First we defined code_country to use to find list
  5436. if (is_object($societe_vendeuse)) {
  5437. $code_country = "'".$societe_vendeuse->country_code."'";
  5438. } else {
  5439. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  5440. }
  5441. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5442. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5443. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5444. // We also add the buyer
  5445. if (is_numeric($type)) {
  5446. if ($type == 1) { // We know product is a service
  5447. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5448. }
  5449. } elseif (!$idprod) { // We don't know type of product
  5450. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5451. } else {
  5452. $prodstatic = new Product($this->db);
  5453. $prodstatic->fetch($idprod);
  5454. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5455. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5456. }
  5457. }
  5458. }
  5459. }
  5460. // Now we get list
  5461. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5462. if ($num > 0) {
  5463. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5464. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5465. $tmpthirdparty = new Societe($this->db);
  5466. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5467. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5468. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5469. $defaultcode = $reg[1];
  5470. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5471. }
  5472. if (empty($defaulttx)) {
  5473. $defaultnpr = 0;
  5474. }
  5475. }
  5476. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  5477. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  5478. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5479. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5480. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5481. } else {
  5482. $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  5483. }
  5484. }
  5485. // Disabled if seller is not subject to VAT
  5486. $disabled = false;
  5487. $title = '';
  5488. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5489. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5490. // of using supplier invoices (this is a very bad idea !)
  5491. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5492. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  5493. $disabled = true;
  5494. }
  5495. }
  5496. if (!$options_only) {
  5497. $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  5498. }
  5499. $selectedfound = false;
  5500. foreach ($this->cache_vatrates as $rate) {
  5501. // Keep only 0 if seller is not subject to VAT
  5502. if ($disabled && $rate['txtva'] != 0) {
  5503. continue;
  5504. }
  5505. // Define key to use into select list
  5506. $key = $rate['txtva'];
  5507. $key .= $rate['nprtva'] ? '*' : '';
  5508. if ($mode > 0 && $rate['code']) {
  5509. $key .= ' ('.$rate['code'].')';
  5510. }
  5511. if ($mode < 0) {
  5512. $key = $rate['rowid'];
  5513. }
  5514. $return .= '<option value="'.$key.'"';
  5515. if (!$selectedfound) {
  5516. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5517. if ($defaultcode == $rate['code']) {
  5518. $return .= ' selected';
  5519. $selectedfound = true;
  5520. }
  5521. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5522. $return .= ' selected';
  5523. $selectedfound = true;
  5524. }
  5525. }
  5526. $return .= '>';
  5527. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  5528. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5529. $return .= $rate['labelpositiverates'];
  5530. } else {
  5531. $return .= vatrate($rate['label']);
  5532. }
  5533. //$return.=($rate['code']?' '.$rate['code']:'');
  5534. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5535. $return .= '</option>';
  5536. }
  5537. if (!$options_only) {
  5538. $return .= '</select>';
  5539. }
  5540. } else {
  5541. $return .= $this->error;
  5542. }
  5543. $this->num = $num;
  5544. return $return;
  5545. }
  5546. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5547. /**
  5548. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5549. * Fields are preselected with :
  5550. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5551. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5552. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5553. *
  5554. * @param integer $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).
  5555. * @param string $prefix Prefix for fields name
  5556. * @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
  5557. * @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
  5558. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5559. * @param string $form_name Not used
  5560. * @param int $d 1=Show days, month, years
  5561. * @param int $addnowlink Add a link "Now"
  5562. * @param int $nooutput Do not output html string but return it
  5563. * @param int $disabled Disable input fields
  5564. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5565. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5566. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5567. * @return string|void Nothing or string if nooutput is 1
  5568. * @deprecated
  5569. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5570. */
  5571. 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 = '', $addplusone = '', $adddateof = '')
  5572. {
  5573. // phpcs:enable
  5574. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5575. if (!empty($nooutput)) {
  5576. return $retstring;
  5577. }
  5578. print $retstring;
  5579. return;
  5580. }
  5581. /**
  5582. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5583. * Fields are preselected with :
  5584. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5585. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5586. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5587. *
  5588. * @param integer $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).
  5589. * @param integer $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).
  5590. * @param string $prefix Prefix for fields name
  5591. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5592. * @param string $forcenewline Force new line between the 2 dates.
  5593. * @return string Html for selectDate
  5594. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5595. */
  5596. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5597. {
  5598. global $langs;
  5599. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5600. if ($forcenewline) {
  5601. $ret .= '<br>';
  5602. }
  5603. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5604. return $ret;
  5605. }
  5606. /**
  5607. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5608. * Fields are preselected with :
  5609. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5610. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5611. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5612. *
  5613. * @param integer $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).
  5614. * @param string $prefix Prefix for fields name
  5615. * @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
  5616. * @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
  5617. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5618. * @param string $form_name Not used
  5619. * @param int $d 1=Show days, month, years
  5620. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5621. * @param int $disabled Disable input fields
  5622. * @param int $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')
  5623. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5624. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5625. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5626. * @param int $stepminutes Specify step for minutes between 1 and 30
  5627. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5628. * @param string $placeholder Placeholder
  5629. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5630. * @return string Html for selectDate
  5631. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5632. */
  5633. 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')
  5634. {
  5635. global $conf, $langs;
  5636. if ($gm === 'auto') {
  5637. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5638. }
  5639. $retstring = '';
  5640. if ($prefix == '') {
  5641. $prefix = 're';
  5642. }
  5643. if ($h == '') {
  5644. $h = 0;
  5645. }
  5646. if ($m == '') {
  5647. $m = 0;
  5648. }
  5649. $emptydate = 0;
  5650. $emptyhours = 0;
  5651. if ($stepminutes <= 0 || $stepminutes > 30) {
  5652. $stepminutes = 1;
  5653. }
  5654. if ($empty == 1) {
  5655. $emptydate = 1;
  5656. $emptyhours = 1;
  5657. }
  5658. if ($empty == 2) {
  5659. $emptydate = 0;
  5660. $emptyhours = 1;
  5661. }
  5662. $orig_set_time = $set_time;
  5663. if ($set_time === '' && $emptydate == 0) {
  5664. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5665. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5666. $set_time = dol_now($gm);
  5667. } else {
  5668. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5669. }
  5670. }
  5671. // Analysis of the pre-selection date
  5672. $reg = array();
  5673. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5674. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5675. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5676. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5677. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5678. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5679. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5680. } elseif (strval($set_time) != '' && $set_time != -1) {
  5681. // set_time est un timestamps (0 possible)
  5682. $syear = dol_print_date($set_time, "%Y", $gm);
  5683. $smonth = dol_print_date($set_time, "%m", $gm);
  5684. $sday = dol_print_date($set_time, "%d", $gm);
  5685. if ($orig_set_time != '') {
  5686. $shour = dol_print_date($set_time, "%H", $gm);
  5687. $smin = dol_print_date($set_time, "%M", $gm);
  5688. $ssec = dol_print_date($set_time, "%S", $gm);
  5689. } else {
  5690. $shour = '';
  5691. $smin = '';
  5692. $ssec = '';
  5693. }
  5694. } else {
  5695. // Date est '' ou vaut -1
  5696. $syear = '';
  5697. $smonth = '';
  5698. $sday = '';
  5699. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5700. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5701. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5702. }
  5703. if ($h == 3) {
  5704. $shour = '';
  5705. }
  5706. if ($m == 3) {
  5707. $smin = '';
  5708. }
  5709. $nowgmt = dol_now('gmt');
  5710. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5711. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5712. $usecalendar = 'combo';
  5713. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5714. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5715. }
  5716. if ($d) {
  5717. // Show date with popup
  5718. if ($usecalendar != 'combo') {
  5719. $formated_date = '';
  5720. //print "e".$set_time." t ".$conf->format_date_short;
  5721. if (strval($set_time) != '' && $set_time != -1) {
  5722. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5723. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5724. }
  5725. // Calendrier popup version eldy
  5726. if ($usecalendar == "eldy") {
  5727. // Input area to enter date manually
  5728. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5729. $retstring .= ($disabled ? ' disabled' : '');
  5730. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5731. $retstring .= '>';
  5732. // Icon calendar
  5733. $retstringbuttom = '';
  5734. if (!$disabled) {
  5735. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5736. $base = DOL_URL_ROOT.'/core/';
  5737. $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5738. $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5739. } else {
  5740. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5741. }
  5742. $retstring = $retstringbuttom.$retstring;
  5743. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5744. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5745. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5746. } elseif ($usecalendar == 'jquery') {
  5747. if (!$disabled) {
  5748. // Output javascript for datepicker
  5749. $retstring .= "<script type='text/javascript'>";
  5750. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5751. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5752. autoclose: true,
  5753. todayHighlight: true,";
  5754. if (!empty($conf->dol_use_jmobile)) {
  5755. $retstring .= "
  5756. beforeShow: function (input, datePicker) {
  5757. input.disabled = true;
  5758. },
  5759. onClose: function (dateText, datePicker) {
  5760. this.disabled = false;
  5761. },
  5762. ";
  5763. }
  5764. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  5765. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  5766. $retstring .= "
  5767. showOn: 'button', /* both has problem with autocompletion */
  5768. buttonImage: '".DOL_URL_ROOT."/theme/".dol_escape_js($conf->theme)."/img/object_calendarday.png',
  5769. buttonImageOnly: true";
  5770. }
  5771. $retstring .= "
  5772. }) });";
  5773. $retstring .= "</script>";
  5774. }
  5775. // Zone de saisie manuelle de la date
  5776. $retstring .= '<div class="nowrap inline-block divfordateinput">';
  5777. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5778. $retstring .= ($disabled ? ' disabled' : '');
  5779. $retstring .= ($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '');
  5780. $retstring .= ' onChange="dpChangeDay(\''.dol_escape_js($prefix).'\',\''.dol_escape_js($langs->trans("FormatDateShortJavaInput")).'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5781. $retstring .= '>';
  5782. // Icone calendrier
  5783. if (!$disabled) {
  5784. /* Not required. Managed by option buttonImage of jquery
  5785. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  5786. $retstring.="<script type='text/javascript'>";
  5787. $retstring.="jQuery(document).ready(function() {";
  5788. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  5789. $retstring.=" jQuery('#".$prefix."').focus();";
  5790. $retstring.=' });';
  5791. $retstring.='});';
  5792. $retstring.="</script>";*/
  5793. } else {
  5794. $retstringbutton = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5795. $retsring = $retstringbutton.$retstring;
  5796. }
  5797. $retstring .= '</div>';
  5798. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5799. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5800. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5801. } else {
  5802. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  5803. }
  5804. } else {
  5805. // Show date with combo selects
  5806. // Day
  5807. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  5808. if ($emptydate || $set_time == -1) {
  5809. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5810. }
  5811. for ($day = 1; $day <= 31; $day++) {
  5812. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  5813. }
  5814. $retstring .= "</select>";
  5815. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  5816. if ($emptydate || $set_time == -1) {
  5817. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5818. }
  5819. // Month
  5820. for ($month = 1; $month <= 12; $month++) {
  5821. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  5822. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  5823. $retstring .= "</option>";
  5824. }
  5825. $retstring .= "</select>";
  5826. // Year
  5827. if ($emptydate || $set_time == -1) {
  5828. $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.'">';
  5829. } else {
  5830. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  5831. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  5832. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  5833. }
  5834. $retstring .= "</select>\n";
  5835. }
  5836. }
  5837. }
  5838. if ($d && $h) {
  5839. $retstring .= ($h == 2 ? '<br>' : ' ');
  5840. $retstring .= '<span class="nowraponall">';
  5841. }
  5842. if ($h) {
  5843. $hourstart = 0;
  5844. $hourend = 24;
  5845. if ($openinghours != '') {
  5846. $openinghours = explode(',', $openinghours);
  5847. $hourstart = $openinghours[0];
  5848. $hourend = $openinghours[1];
  5849. if ($hourend < $hourstart) {
  5850. $hourend = $hourstart;
  5851. }
  5852. }
  5853. // Show hour
  5854. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  5855. if ($emptyhours) {
  5856. $retstring .= '<option value="-1">&nbsp;</option>';
  5857. }
  5858. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  5859. if (strlen($hour) < 2) {
  5860. $hour = "0".$hour;
  5861. }
  5862. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  5863. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  5864. $retstring .= '</option>';
  5865. }
  5866. $retstring .= '</select>';
  5867. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  5868. if ($m) {
  5869. $retstring .= ":";
  5870. }
  5871. }
  5872. if ($m) {
  5873. // Show minutes
  5874. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  5875. if ($emptyhours) {
  5876. $retstring .= '<option value="-1">&nbsp;</option>';
  5877. }
  5878. for ($min = 0; $min < 60; $min += $stepminutes) {
  5879. if (strlen($min) < 2) {
  5880. $min = "0".$min;
  5881. }
  5882. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  5883. }
  5884. $retstring .= '</select>';
  5885. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  5886. }
  5887. if ($d && $h) {
  5888. $retstring .= '</span>';
  5889. }
  5890. // Add a "Now" link
  5891. if ($conf->use_javascript_ajax && $addnowlink) {
  5892. // Script which will be inserted in the onClick of the "Now" link
  5893. $reset_scripts = "";
  5894. if ($addnowlink == 2) { // local computer time
  5895. // pad add leading 0 on numbers
  5896. $reset_scripts .= "Number.prototype.pad = function(size) {
  5897. var s = String(this);
  5898. while (s.length < (size || 2)) {s = '0' + s;}
  5899. return s;
  5900. };
  5901. var d = new Date();";
  5902. }
  5903. // Generate the date part, depending on the use or not of the javascript calendar
  5904. if ($addnowlink == 1) { // server time expressed in user time setup
  5905. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5906. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5907. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5908. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5909. } elseif ($addnowlink == 2) {
  5910. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  5911. * This break application for foreign languages.
  5912. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  5913. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  5914. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  5915. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  5916. */
  5917. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5918. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5919. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5920. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5921. }
  5922. /*if ($usecalendar == "eldy")
  5923. {
  5924. $base=DOL_URL_ROOT.'/core/';
  5925. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  5926. }
  5927. else
  5928. {
  5929. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  5930. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  5931. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  5932. }*/
  5933. // Update the hour part
  5934. if ($h) {
  5935. if ($fullday) {
  5936. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5937. }
  5938. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  5939. if ($addnowlink == 1) {
  5940. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  5941. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5942. } elseif ($addnowlink == 2) {
  5943. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  5944. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5945. }
  5946. if ($fullday) {
  5947. $reset_scripts .= ' } ';
  5948. }
  5949. }
  5950. // Update the minute part
  5951. if ($m) {
  5952. if ($fullday) {
  5953. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5954. }
  5955. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  5956. if ($addnowlink == 1) {
  5957. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  5958. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5959. } elseif ($addnowlink == 2) {
  5960. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  5961. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5962. }
  5963. if ($fullday) {
  5964. $reset_scripts .= ' } ';
  5965. }
  5966. }
  5967. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5968. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  5969. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  5970. $retstring .= $langs->trans("Now");
  5971. $retstring .= '</button> ';
  5972. }
  5973. }
  5974. // Add a "Plus one hour" link
  5975. if ($conf->use_javascript_ajax && $addplusone) {
  5976. // Script which will be inserted in the onClick of the "Add plusone" link
  5977. $reset_scripts = "";
  5978. // Generate the date part, depending on the use or not of the javascript calendar
  5979. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');';
  5980. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5981. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5982. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5983. // Update the hour part
  5984. if ($h) {
  5985. if ($fullday) {
  5986. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5987. }
  5988. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  5989. if ($fullday) {
  5990. $reset_scripts .= ' } ';
  5991. }
  5992. }
  5993. // Update the minute part
  5994. if ($m) {
  5995. if ($fullday) {
  5996. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5997. }
  5998. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  5999. if ($fullday) {
  6000. $reset_scripts .= ' } ';
  6001. }
  6002. }
  6003. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6004. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6005. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  6006. $retstring .= $langs->trans("DateStartPlusOne");
  6007. $retstring .= '</button> ';
  6008. }
  6009. }
  6010. // Add a link to set data
  6011. if ($conf->use_javascript_ajax && $adddateof) {
  6012. $tmparray = dol_getdate($adddateof);
  6013. if (empty($labeladddateof)) {
  6014. $labeladddateof = $langs->trans("DateInvoice");
  6015. }
  6016. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="console.log(\'Click on now link\'); jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'dayinputnoreduce').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$labeladddateof.'</a>';
  6017. }
  6018. return $retstring;
  6019. }
  6020. /**
  6021. * selectTypeDuration
  6022. *
  6023. * @param string $prefix Prefix
  6024. * @param string $selected Selected duration type
  6025. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6026. * @return string HTML select string
  6027. */
  6028. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6029. {
  6030. global $langs;
  6031. $TDurationTypes = array(
  6032. 'y'=>$langs->trans('Years'),
  6033. 'm'=>$langs->trans('Month'),
  6034. 'w'=>$langs->trans('Weeks'),
  6035. 'd'=>$langs->trans('Days'),
  6036. 'h'=>$langs->trans('Hours'),
  6037. 'i'=>$langs->trans('Minutes')
  6038. );
  6039. // Removed undesired duration types
  6040. foreach ($excludetypes as $value) {
  6041. unset($TDurationTypes[$value]);
  6042. }
  6043. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  6044. foreach ($TDurationTypes as $key => $typeduration) {
  6045. $retstring .= '<option value="'.$key.'"';
  6046. if ($key == $selected) {
  6047. $retstring .= " selected";
  6048. }
  6049. $retstring .= ">".$typeduration."</option>";
  6050. }
  6051. $retstring .= "</select>";
  6052. $retstring .= ajax_combobox('select_'.$prefix.'type_duration');
  6053. return $retstring;
  6054. }
  6055. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6056. /**
  6057. * Function to show a form to select a duration on a page
  6058. *
  6059. * @param string $prefix Prefix for input fields
  6060. * @param int $iSecond Default preselected duration (number of seconds or '')
  6061. * @param int $disabled Disable the combo box
  6062. * @param string $typehour If 'select' then input hour and input min is a combo,
  6063. * If 'text' input hour is in text and input min is a text,
  6064. * If 'textselect' input hour is in text and input min is a combo
  6065. * @param integer $minunderhours If 1, show minutes selection under the hours
  6066. * @param int $nooutput Do not output html string but return it
  6067. * @return string|void
  6068. */
  6069. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6070. {
  6071. // phpcs:enable
  6072. global $langs;
  6073. $retstring = '<span class="nowraponall">';
  6074. $hourSelected = 0;
  6075. $minSelected = 0;
  6076. // Hours
  6077. if ($iSecond != '') {
  6078. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6079. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6080. $minSelected = convertSecondToTime($iSecond, 'min');
  6081. }
  6082. if ($typehour == 'select') {
  6083. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  6084. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6085. $retstring .= '<option value="'.$hour.'"';
  6086. if ($hourSelected == $hour) {
  6087. $retstring .= " selected";
  6088. }
  6089. $retstring .= ">".$hour."</option>";
  6090. }
  6091. $retstring .= "</select>";
  6092. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6093. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  6094. } else {
  6095. return 'BadValueForParameterTypeHour';
  6096. }
  6097. if ($typehour != 'text') {
  6098. $retstring .= ' '.$langs->trans('HourShort');
  6099. } else {
  6100. $retstring .= '<span class="">:</span>';
  6101. }
  6102. // Minutes
  6103. if ($minunderhours) {
  6104. $retstring .= '<br>';
  6105. } else {
  6106. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6107. }
  6108. if ($typehour == 'select' || $typehour == 'textselect') {
  6109. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  6110. for ($min = 0; $min <= 55; $min = $min + 5) {
  6111. $retstring .= '<option value="'.$min.'"';
  6112. if ($minSelected == $min) {
  6113. $retstring .= ' selected';
  6114. }
  6115. $retstring .= '>'.$min.'</option>';
  6116. }
  6117. $retstring .= "</select>";
  6118. } elseif ($typehour == 'text') {
  6119. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  6120. }
  6121. if ($typehour != 'text') {
  6122. $retstring .= ' '.$langs->trans('MinuteShort');
  6123. }
  6124. $retstring.="</span>";
  6125. if (!empty($nooutput)) {
  6126. return $retstring;
  6127. }
  6128. print $retstring;
  6129. return;
  6130. }
  6131. /**
  6132. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6133. *
  6134. * @param int $selected Preselected tickets
  6135. * @param string $htmlname Name of HTML select field (must be unique in page).
  6136. * @param string $filtertype To add a filter
  6137. * @param int $limit Limit on number of returned lines
  6138. * @param int $status Ticket status
  6139. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6140. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6141. * @param array $ajaxoptions Options for ajax_autocompleter
  6142. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6143. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6144. * @param int $forcecombo Force to use combo box
  6145. * @param string $morecss Add more css on select
  6146. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6147. * @param string $nooutput No print, return the output into a string
  6148. * @return void|string
  6149. */
  6150. 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)
  6151. {
  6152. global $langs, $conf;
  6153. $out = '';
  6154. // check parameters
  6155. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6156. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6157. $placeholder = '';
  6158. if ($selected && empty($selected_input_value)) {
  6159. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6160. $tickettmpselect = new Ticket($this->db);
  6161. $tickettmpselect->fetch($selected);
  6162. $selected_input_value = $tickettmpselect->ref;
  6163. unset($tickettmpselect);
  6164. }
  6165. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6166. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6167. elseif ($hidelabel > 1) {
  6168. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6169. if ($hidelabel == 2) {
  6170. $out .= img_picto($langs->trans("Search"), 'search');
  6171. }
  6172. }
  6173. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6174. if ($hidelabel == 3) {
  6175. $out .= img_picto($langs->trans("Search"), 'search');
  6176. }
  6177. } else {
  6178. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6179. }
  6180. if (empty($nooutput)) print $out;
  6181. else return $out;
  6182. }
  6183. /**
  6184. * Return list of tickets.
  6185. * Called by selectTickets.
  6186. *
  6187. * @param int $selected Preselected ticket
  6188. * @param string $htmlname Name of select html
  6189. * @param string $filtertype Filter on ticket type
  6190. * @param int $limit Limit on number of returned lines
  6191. * @param string $filterkey Filter on ticket ref or subject
  6192. * @param int $status Ticket status
  6193. * @param int $outputmode 0=HTML select string, 1=Array
  6194. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6195. * @param int $forcecombo Force to use combo box
  6196. * @param string $morecss Add more css on select
  6197. * @return array Array of keys for json
  6198. */
  6199. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6200. {
  6201. global $langs, $conf;
  6202. $out = '';
  6203. $outarray = array();
  6204. $selectFields = " p.rowid, p.ref, p.message";
  6205. $sql = "SELECT ";
  6206. $sql .= $selectFields;
  6207. $sql .= " FROM ".$this->db->prefix()."ticket as p";
  6208. $sql .= ' WHERE p.entity IN ('.getEntity('ticket').')';
  6209. // Add criteria on ref/label
  6210. if ($filterkey != '') {
  6211. $sql .= ' AND (';
  6212. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6213. // For natural search
  6214. $scrit = explode(' ', $filterkey);
  6215. $i = 0;
  6216. if (count($scrit) > 1) $sql .= "(";
  6217. foreach ($scrit as $crit) {
  6218. if ($i > 0) $sql .= " AND ";
  6219. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.subject LIKE '".$this->db->escape($prefix.$crit)."%'";
  6220. $sql .= ")";
  6221. $i++;
  6222. }
  6223. if (count($scrit) > 1) $sql .= ")";
  6224. $sql .= ')';
  6225. }
  6226. $sql .= $this->db->plimit($limit, 0);
  6227. // Build output string
  6228. dol_syslog(get_class($this)."::selectTicketsList search tickets", LOG_DEBUG);
  6229. $result = $this->db->query($sql);
  6230. if ($result) {
  6231. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6232. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  6233. $num = $this->db->num_rows($result);
  6234. $events = null;
  6235. if (!$forcecombo) {
  6236. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6237. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6238. }
  6239. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6240. $textifempty = '';
  6241. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6242. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6243. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6244. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6245. else $textifempty .= $langs->trans("All");
  6246. } else {
  6247. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6248. }
  6249. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6250. $i = 0;
  6251. while ($num && $i < $num) {
  6252. $opt = '';
  6253. $optJson = array();
  6254. $objp = $this->db->fetch_object($result);
  6255. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6256. // Add new entry
  6257. // "key" value of json key array is used by jQuery automatically as selected value
  6258. // "label" value of json key array is used by jQuery automatically as text for combo box
  6259. $out .= $opt;
  6260. array_push($outarray, $optJson);
  6261. $i++;
  6262. }
  6263. $out .= '</select>';
  6264. $this->db->free($result);
  6265. if (empty($outputmode)) return $out;
  6266. return $outarray;
  6267. } else {
  6268. dol_print_error($this->db);
  6269. }
  6270. }
  6271. /**
  6272. * constructTicketListOption.
  6273. * This define value for &$opt and &$optJson.
  6274. *
  6275. * @param resource $objp Result set of fetch
  6276. * @param string $opt Option (var used for returned value in string option format)
  6277. * @param string $optJson Option (var used for returned value in json format)
  6278. * @param string $selected Preselected value
  6279. * @param string $filterkey Filter key to highlight
  6280. * @return void
  6281. */
  6282. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6283. {
  6284. $outkey = '';
  6285. $outval = '';
  6286. $outref = '';
  6287. $outlabel = '';
  6288. $outtype = '';
  6289. $label = $objp->label;
  6290. $outkey = $objp->rowid;
  6291. $outref = $objp->ref;
  6292. $outlabel = $objp->label;
  6293. $outtype = $objp->fk_product_type;
  6294. $opt = '<option value="'.$objp->rowid.'"';
  6295. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6296. $opt .= '>';
  6297. $opt .= $objp->ref;
  6298. $objRef = $objp->ref;
  6299. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6300. $outval .= $objRef;
  6301. $opt .= "</option>\n";
  6302. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtypem);
  6303. }
  6304. /**
  6305. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6306. *
  6307. * @param int $selected Preselected tickets
  6308. * @param string $htmlname Name of HTML select field (must be unique in page).
  6309. * @param string $filtertype To add a filter
  6310. * @param int $limit Limit on number of returned lines
  6311. * @param int $status Ticket status
  6312. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6313. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6314. * @param array $ajaxoptions Options for ajax_autocompleter
  6315. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6316. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6317. * @param int $forcecombo Force to use combo box
  6318. * @param string $morecss Add more css on select
  6319. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6320. * @param string $nooutput No print, return the output into a string
  6321. * @return void|string
  6322. */
  6323. 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)
  6324. {
  6325. global $langs, $conf;
  6326. $out = '';
  6327. // check parameters
  6328. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6329. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6330. $placeholder = '';
  6331. if ($selected && empty($selected_input_value)) {
  6332. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6333. $projecttmpselect = new Project($this->db);
  6334. $projecttmpselect->fetch($selected);
  6335. $selected_input_value = $projecttmpselect->ref;
  6336. unset($projecttmpselect);
  6337. }
  6338. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6339. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6340. elseif ($hidelabel > 1) {
  6341. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6342. if ($hidelabel == 2) {
  6343. $out .= img_picto($langs->trans("Search"), 'search');
  6344. }
  6345. }
  6346. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6347. if ($hidelabel == 3) {
  6348. $out .= img_picto($langs->trans("Search"), 'search');
  6349. }
  6350. } else {
  6351. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6352. }
  6353. if (empty($nooutput)) print $out;
  6354. else return $out;
  6355. }
  6356. /**
  6357. * Return list of projects.
  6358. * Called by selectProjects.
  6359. *
  6360. * @param int $selected Preselected project
  6361. * @param string $htmlname Name of select html
  6362. * @param string $filtertype Filter on project type
  6363. * @param int $limit Limit on number of returned lines
  6364. * @param string $filterkey Filter on project ref or subject
  6365. * @param int $status Ticket status
  6366. * @param int $outputmode 0=HTML select string, 1=Array
  6367. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6368. * @param int $forcecombo Force to use combo box
  6369. * @param string $morecss Add more css on select
  6370. * @return array Array of keys for json
  6371. */
  6372. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6373. {
  6374. global $langs, $conf;
  6375. $out = '';
  6376. $outarray = array();
  6377. $selectFields = " p.rowid, p.ref";
  6378. $sql = "SELECT ";
  6379. $sql .= $selectFields;
  6380. $sql .= " FROM ".$this->db->prefix()."projet as p";
  6381. $sql .= ' WHERE p.entity IN ('.getEntity('project').')';
  6382. // Add criteria on ref/label
  6383. if ($filterkey != '') {
  6384. $sql .= ' AND (';
  6385. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6386. // For natural search
  6387. $scrit = explode(' ', $filterkey);
  6388. $i = 0;
  6389. if (count($scrit) > 1) $sql .= "(";
  6390. foreach ($scrit as $crit) {
  6391. if ($i > 0) $sql .= " AND ";
  6392. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6393. $sql .= "";
  6394. $i++;
  6395. }
  6396. if (count($scrit) > 1) $sql .= ")";
  6397. $sql .= ')';
  6398. }
  6399. $sql .= $this->db->plimit($limit, 0);
  6400. // Build output string
  6401. dol_syslog(get_class($this)."::selectProjectsList search projects", LOG_DEBUG);
  6402. $result = $this->db->query($sql);
  6403. if ($result) {
  6404. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6405. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  6406. $num = $this->db->num_rows($result);
  6407. $events = null;
  6408. if (!$forcecombo) {
  6409. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6410. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6411. }
  6412. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6413. $textifempty = '';
  6414. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6415. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6416. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6417. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6418. else $textifempty .= $langs->trans("All");
  6419. } else {
  6420. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6421. }
  6422. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6423. $i = 0;
  6424. while ($num && $i < $num) {
  6425. $opt = '';
  6426. $optJson = array();
  6427. $objp = $this->db->fetch_object($result);
  6428. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6429. // Add new entry
  6430. // "key" value of json key array is used by jQuery automatically as selected value
  6431. // "label" value of json key array is used by jQuery automatically as text for combo box
  6432. $out .= $opt;
  6433. array_push($outarray, $optJson);
  6434. $i++;
  6435. }
  6436. $out .= '</select>';
  6437. $this->db->free($result);
  6438. if (empty($outputmode)) return $out;
  6439. return $outarray;
  6440. } else {
  6441. dol_print_error($this->db);
  6442. }
  6443. }
  6444. /**
  6445. * constructProjectListOption.
  6446. * This define value for &$opt and &$optJson.
  6447. *
  6448. * @param resource $objp Result set of fetch
  6449. * @param string $opt Option (var used for returned value in string option format)
  6450. * @param string $optJson Option (var used for returned value in json format)
  6451. * @param string $selected Preselected value
  6452. * @param string $filterkey Filter key to highlight
  6453. * @return void
  6454. */
  6455. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6456. {
  6457. $outkey = '';
  6458. $outval = '';
  6459. $outref = '';
  6460. $outlabel = '';
  6461. $outtype = '';
  6462. $label = $objp->label;
  6463. $outkey = $objp->rowid;
  6464. $outref = $objp->ref;
  6465. $outlabel = $objp->label;
  6466. $outtype = $objp->fk_product_type;
  6467. $opt = '<option value="'.$objp->rowid.'"';
  6468. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6469. $opt .= '>';
  6470. $opt .= $objp->ref;
  6471. $objRef = $objp->ref;
  6472. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6473. $outval .= $objRef;
  6474. $opt .= "</option>\n";
  6475. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6476. }
  6477. /**
  6478. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6479. *
  6480. * @param int $selected Preselected tickets
  6481. * @param string $htmlname Name of HTML select field (must be unique in page).
  6482. * @param string $filtertype To add a filter
  6483. * @param int $limit Limit on number of returned lines
  6484. * @param int $status Ticket status
  6485. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6486. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6487. * @param array $ajaxoptions Options for ajax_autocompleter
  6488. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6489. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6490. * @param int $forcecombo Force to use combo box
  6491. * @param string $morecss Add more css on select
  6492. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6493. * @param string $nooutput No print, return the output into a string
  6494. * @return void|string
  6495. */
  6496. 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)
  6497. {
  6498. global $langs, $conf;
  6499. $out = '';
  6500. // check parameters
  6501. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6502. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6503. $placeholder = '';
  6504. if ($selected && empty($selected_input_value)) {
  6505. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6506. $adherenttmpselect = new Member($this->db);
  6507. $adherenttmpselect->fetch($selected);
  6508. $selected_input_value = $adherenttmpselect->ref;
  6509. unset($adherenttmpselect);
  6510. }
  6511. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6512. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6513. elseif ($hidelabel > 1) {
  6514. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6515. if ($hidelabel == 2) {
  6516. $out .= img_picto($langs->trans("Search"), 'search');
  6517. }
  6518. }
  6519. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6520. if ($hidelabel == 3) {
  6521. $out .= img_picto($langs->trans("Search"), 'search');
  6522. }
  6523. } else {
  6524. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6525. }
  6526. if (empty($nooutput)) print $out;
  6527. else return $out;
  6528. }
  6529. /**
  6530. * Return list of adherents.
  6531. * Called by selectMembers.
  6532. *
  6533. * @param int $selected Preselected adherent
  6534. * @param string $htmlname Name of select html
  6535. * @param string $filtertype Filter on adherent type
  6536. * @param int $limit Limit on number of returned lines
  6537. * @param string $filterkey Filter on adherent ref or subject
  6538. * @param int $status Ticket status
  6539. * @param int $outputmode 0=HTML select string, 1=Array
  6540. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6541. * @param int $forcecombo Force to use combo box
  6542. * @param string $morecss Add more css on select
  6543. * @return array Array of keys for json
  6544. */
  6545. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6546. {
  6547. global $langs, $conf;
  6548. $out = '';
  6549. $outarray = array();
  6550. $selectFields = " p.rowid, p.ref";
  6551. $sql = "SELECT ";
  6552. $sql .= $selectFields;
  6553. $sql .= " FROM ".$this->db->prefix()."adherent as p";
  6554. $sql .= ' WHERE p.entity IN ('.getEntity('adherent').')';
  6555. // Add criteria on ref/label
  6556. if ($filterkey != '') {
  6557. $sql .= ' AND (';
  6558. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6559. // For natural search
  6560. $scrit = explode(' ', $filterkey);
  6561. $i = 0;
  6562. if (count($scrit) > 1) $sql .= "(";
  6563. foreach ($scrit as $crit) {
  6564. if ($i > 0) $sql .= " AND ";
  6565. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6566. $sql .= "";
  6567. $i++;
  6568. }
  6569. if (count($scrit) > 1) $sql .= ")";
  6570. $sql .= ')';
  6571. }
  6572. $sql .= $this->db->plimit($limit, 0);
  6573. // Build output string
  6574. dol_syslog(get_class($this)."::selectMembersList search adherents", LOG_DEBUG);
  6575. $result = $this->db->query($sql);
  6576. if ($result) {
  6577. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6578. require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
  6579. $num = $this->db->num_rows($result);
  6580. $events = null;
  6581. if (!$forcecombo) {
  6582. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6583. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6584. }
  6585. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6586. $textifempty = '';
  6587. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6588. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6589. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6590. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6591. else $textifempty .= $langs->trans("All");
  6592. } else {
  6593. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6594. }
  6595. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6596. $i = 0;
  6597. while ($num && $i < $num) {
  6598. $opt = '';
  6599. $optJson = array();
  6600. $objp = $this->db->fetch_object($result);
  6601. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6602. // Add new entry
  6603. // "key" value of json key array is used by jQuery automatically as selected value
  6604. // "label" value of json key array is used by jQuery automatically as text for combo box
  6605. $out .= $opt;
  6606. array_push($outarray, $optJson);
  6607. $i++;
  6608. }
  6609. $out .= '</select>';
  6610. $this->db->free($result);
  6611. if (empty($outputmode)) return $out;
  6612. return $outarray;
  6613. } else {
  6614. dol_print_error($this->db);
  6615. }
  6616. }
  6617. /**
  6618. * constructMemberListOption.
  6619. * This define value for &$opt and &$optJson.
  6620. *
  6621. * @param resource $objp Result set of fetch
  6622. * @param string $opt Option (var used for returned value in string option format)
  6623. * @param string $optJson Option (var used for returned value in json format)
  6624. * @param string $selected Preselected value
  6625. * @param string $filterkey Filter key to highlight
  6626. * @return void
  6627. */
  6628. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6629. {
  6630. $outkey = '';
  6631. $outval = '';
  6632. $outref = '';
  6633. $outlabel = '';
  6634. $outtype = '';
  6635. $label = $objp->label;
  6636. $outkey = $objp->rowid;
  6637. $outref = $objp->ref;
  6638. $outlabel = $objp->label;
  6639. $outtype = $objp->fk_product_type;
  6640. $opt = '<option value="'.$objp->rowid.'"';
  6641. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6642. $opt .= '>';
  6643. $opt .= $objp->ref;
  6644. $objRef = $objp->ref;
  6645. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6646. $outval .= $objRef;
  6647. $opt .= "</option>\n";
  6648. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6649. }
  6650. /**
  6651. * Generic method to select a component from a combo list.
  6652. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6653. * This is the generic method that will replace all specific existing methods.
  6654. *
  6655. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6656. * @param string $htmlname Name of HTML select component
  6657. * @param int $preselectedvalue Preselected value (ID of element)
  6658. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6659. * @param string $searchkey Search criteria
  6660. * @param string $placeholder Place holder
  6661. * @param string $morecss More CSS
  6662. * @param string $moreparams More params provided to ajax call
  6663. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6664. * @param int $disabled 1=Html component is disabled
  6665. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6666. * @return string Return HTML string
  6667. * @see selectForFormsList() select_thirdparty_list()
  6668. */
  6669. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6670. {
  6671. global $conf, $user;
  6672. $objecttmp = null;
  6673. // Example of value for $objectdec:
  6674. // Bom:bom/class/bom.class.php:0:t.status=1
  6675. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  6676. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  6677. $InfoFieldList = explode(":", $objectdesc, 4);
  6678. $vartmp = $InfoFieldList[3];
  6679. $reg = array();
  6680. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  6681. $InfoFieldList[4] = $reg[1]; // take the sort field
  6682. }
  6683. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  6684. $classname = $InfoFieldList[0];
  6685. $classpath = $InfoFieldList[1];
  6686. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6687. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6688. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6689. if (!empty($classpath)) {
  6690. dol_include_once($classpath);
  6691. if ($classname && class_exists($classname)) {
  6692. $objecttmp = new $classname($this->db);
  6693. // Make some replacement
  6694. $sharedentities = getEntity(strtolower($classname));
  6695. $objecttmp->filter = str_replace(
  6696. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6697. array($conf->entity, $sharedentities, $user->id),
  6698. $filter
  6699. );
  6700. }
  6701. }
  6702. if (!is_object($objecttmp)) {
  6703. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  6704. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  6705. }
  6706. //var_dump($objecttmp->filter);
  6707. $prefixforautocompletemode = $objecttmp->element;
  6708. if ($prefixforautocompletemode == 'societe') {
  6709. $prefixforautocompletemode = 'company';
  6710. }
  6711. if ($prefixforautocompletemode == 'product') {
  6712. $prefixforautocompletemode = 'produit';
  6713. }
  6714. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6715. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  6716. $out = '';
  6717. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6718. // No immediate load of all database
  6719. $placeholder = '';
  6720. if ($preselectedvalue && empty($selected_input_value)) {
  6721. $objecttmp->fetch($preselectedvalue);
  6722. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6723. //unset($objecttmp);
  6724. }
  6725. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  6726. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  6727. // No immediate load of all database
  6728. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&objectdesc='.urlencode($objectdesc).'&filter='.urlencode($objecttmp->filter).($sortfield ? '&sortfield='.urlencode($sortfield) : '');
  6729. // Activate the auto complete using ajax call.
  6730. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6731. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6732. $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).'"' : '') .' />';
  6733. } else {
  6734. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  6735. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield);
  6736. }
  6737. return $out;
  6738. }
  6739. /**
  6740. * Function to forge a SQL criteria
  6741. *
  6742. * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
  6743. * @return string Forged criteria. Example: "t.field like 'abc%'"
  6744. */
  6745. protected static function forgeCriteriaCallback($matches)
  6746. {
  6747. global $db;
  6748. //dol_syslog("Convert matches ".$matches[1]);
  6749. if (empty($matches[1])) {
  6750. return '';
  6751. }
  6752. $tmp = explode(':', $matches[1]);
  6753. if (count($tmp) < 3) {
  6754. return '';
  6755. }
  6756. $tmpescaped = $tmp[2];
  6757. $regbis = array();
  6758. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  6759. $tmpescaped = "'".$db->escape($regbis[1])."'";
  6760. } else {
  6761. $tmpescaped = $db->escape($tmpescaped);
  6762. }
  6763. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  6764. }
  6765. /**
  6766. * Output html form to select an object.
  6767. * Note, this function is called by selectForForms or by ajax selectobject.php
  6768. *
  6769. * @param Object $objecttmp Object to knwo the table to scan for combo.
  6770. * @param string $htmlname Name of HTML select component
  6771. * @param int $preselectedvalue Preselected value (ID of element)
  6772. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6773. * @param string $searchkey Search value
  6774. * @param string $placeholder Place holder
  6775. * @param string $morecss More CSS
  6776. * @param string $moreparams More params provided to ajax call
  6777. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6778. * @param int $outputmode 0=HTML select string, 1=Array
  6779. * @param int $disabled 1=Html component is disabled
  6780. * @param string $sortfield Sort field
  6781. * @return string|array Return HTML string
  6782. * @see selectForForms()
  6783. */
  6784. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '')
  6785. {
  6786. global $conf, $langs, $user, $hookmanager;
  6787. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  6788. $prefixforautocompletemode = $objecttmp->element;
  6789. if ($prefixforautocompletemode == 'societe') {
  6790. $prefixforautocompletemode = 'company';
  6791. }
  6792. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6793. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  6794. $tmpfieldstoshow = '';
  6795. foreach ($objecttmp->fields as $key => $val) {
  6796. if (!dol_eval($val['enabled'], 1, 1, 1, '1')) {
  6797. continue;
  6798. }
  6799. if (!empty($val['showoncombobox'])) {
  6800. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  6801. }
  6802. }
  6803. if ($tmpfieldstoshow) {
  6804. $fieldstoshow = $tmpfieldstoshow;
  6805. }
  6806. } else {
  6807. // For backward compatibility
  6808. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  6809. }
  6810. if (empty($fieldstoshow)) {
  6811. if (isset($objecttmp->fields['ref'])) {
  6812. $fieldstoshow = 't.ref';
  6813. } else {
  6814. $langs->load("errors");
  6815. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  6816. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  6817. }
  6818. }
  6819. $out = '';
  6820. $outarray = array();
  6821. $num = 0;
  6822. // Search data
  6823. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".$this->db->prefix().$objecttmp->table_element." as t";
  6824. if (isset($objecttmp->ismultientitymanaged)) {
  6825. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6826. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  6827. $sql .= " INNER JOIN ".$this->db->prefix().$tmparray[1]." as parenttable ON parenttable.rowid = t.".$tmparray[0];
  6828. }
  6829. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6830. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6831. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  6832. }
  6833. }
  6834. }
  6835. // Add where from hooks
  6836. $parameters = array();
  6837. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  6838. if (!empty($hookmanager->resPrint)) {
  6839. $sql .= $hookmanager->resPrint;
  6840. } else {
  6841. $sql .= " WHERE 1=1";
  6842. if (isset($objecttmp->ismultientitymanaged)) {
  6843. if ($objecttmp->ismultientitymanaged == 1) {
  6844. $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  6845. }
  6846. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6847. $sql .= " AND parenttable.entity = t.".$tmparray[0];
  6848. }
  6849. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  6850. if ($objecttmp->element == 'societe') {
  6851. $sql .= " AND t.rowid = ".((int) $user->socid);
  6852. } else {
  6853. $sql .= " AND t.fk_soc = ".((int) $user->socid);
  6854. }
  6855. }
  6856. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6857. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6858. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  6859. }
  6860. }
  6861. }
  6862. if ($searchkey != '') {
  6863. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  6864. }
  6865. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  6866. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  6867. {
  6868. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  6869. }*/
  6870. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  6871. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  6872. }
  6873. }
  6874. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  6875. //$sql.=$this->db->plimit($limit, 0);
  6876. //print $sql;
  6877. // Build output string
  6878. $resql = $this->db->query($sql);
  6879. if ($resql) {
  6880. // Construct $out and $outarray
  6881. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  6882. // 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
  6883. $textifempty = '&nbsp;';
  6884. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6885. if (!empty($conf->global->$confkeyforautocompletemode)) {
  6886. if ($showempty && !is_numeric($showempty)) {
  6887. $textifempty = $langs->trans($showempty);
  6888. } else {
  6889. $textifempty .= $langs->trans("All");
  6890. }
  6891. }
  6892. if ($showempty) {
  6893. $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  6894. }
  6895. $num = $this->db->num_rows($resql);
  6896. $i = 0;
  6897. if ($num) {
  6898. while ($i < $num) {
  6899. $obj = $this->db->fetch_object($resql);
  6900. $label = '';
  6901. $tmparray = explode(',', $fieldstoshow);
  6902. $oldvalueforshowoncombobox = 0;
  6903. foreach ($tmparray as $key => $val) {
  6904. $val = preg_replace('/t\./', '', $val);
  6905. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  6906. $label .= $obj->$val;
  6907. $oldvalueforshowoncombobox = $objecttmp->fields[$val]['showoncombobox'];
  6908. }
  6909. if (empty($outputmode)) {
  6910. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  6911. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  6912. } else {
  6913. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  6914. }
  6915. } else {
  6916. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  6917. }
  6918. $i++;
  6919. if (($i % 10) == 0) {
  6920. $out .= "\n";
  6921. }
  6922. }
  6923. }
  6924. $out .= '</select>'."\n";
  6925. if (!$forcecombo) {
  6926. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6927. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  6928. }
  6929. } else {
  6930. dol_print_error($this->db);
  6931. }
  6932. $this->result = array('nbofelement'=>$num);
  6933. if ($outputmode) {
  6934. return $outarray;
  6935. }
  6936. return $out;
  6937. }
  6938. /**
  6939. * Return a HTML select string, built from an array of key+value.
  6940. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  6941. *
  6942. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  6943. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  6944. * @param string|string[] $id Preselected key or preselected keys for multiselect
  6945. * @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.
  6946. * @param int $key_in_label 1 to show key into label with format "[key] value"
  6947. * @param int $value_as_key 1 to use value as key
  6948. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  6949. * @param int $translate 1=Translate and encode value
  6950. * @param int $maxlen Length maximum for labels
  6951. * @param int $disabled Html select box is disabled
  6952. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  6953. * @param string $morecss Add more class to css styles
  6954. * @param int $addjscombo Add js combo
  6955. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  6956. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  6957. * @param int $nohtmlescape No html escaping.
  6958. * @return string HTML select string.
  6959. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  6960. */
  6961. 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 = '', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  6962. {
  6963. global $conf, $langs;
  6964. // Do we want a multiselect ?
  6965. //$jsbeautify = 0;
  6966. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  6967. $jsbeautify = 1;
  6968. if ($value_as_key) {
  6969. $array = array_combine($array, $array);
  6970. }
  6971. $out = '';
  6972. if ($addjscombo < 0) {
  6973. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6974. $addjscombo = 1;
  6975. } else {
  6976. $addjscombo = 0;
  6977. }
  6978. }
  6979. // Add code for jquery to use multiselect
  6980. if ($addjscombo && $jsbeautify) {
  6981. // Enhance with select2
  6982. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6983. $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', $show_empty < 0 ? (string) $show_empty : '-1');
  6984. }
  6985. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  6986. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  6987. $out .= '>';
  6988. if ($show_empty) {
  6989. $textforempty = ' ';
  6990. if (!empty($conf->use_javascript_ajax)) {
  6991. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  6992. }
  6993. if (!is_numeric($show_empty)) {
  6994. $textforempty = $show_empty;
  6995. }
  6996. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  6997. }
  6998. if (is_array($array)) {
  6999. // Translate
  7000. if ($translate) {
  7001. foreach ($array as $key => $value) {
  7002. if (!is_array($value)) {
  7003. $array[$key] = $langs->trans($value);
  7004. } else {
  7005. $array[$key]['label'] = $langs->trans($value['label']);
  7006. }
  7007. }
  7008. }
  7009. // Sort
  7010. if ($sort == 'ASC') {
  7011. asort($array);
  7012. } elseif ($sort == 'DESC') {
  7013. arsort($array);
  7014. }
  7015. foreach ($array as $key => $tmpvalue) {
  7016. if (is_array($tmpvalue)) {
  7017. $value = $tmpvalue['label'];
  7018. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7019. $style = empty($tmpvalue['css']) ? ' class="'.$tmpvalue['css'].'"' : '';
  7020. } else {
  7021. $value = $tmpvalue;
  7022. $disabled = '';
  7023. $style = '';
  7024. }
  7025. if (!empty($disablebademail)) {
  7026. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7027. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7028. $disabled = ' disabled';
  7029. $style = ' class="warning"';
  7030. }
  7031. }
  7032. if ($key_in_label) {
  7033. if (empty($nohtmlescape)) {
  7034. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  7035. } else {
  7036. $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  7037. }
  7038. } else {
  7039. if (empty($nohtmlescape)) {
  7040. $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  7041. } else {
  7042. $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  7043. }
  7044. if ($value == '' || $value == '-') {
  7045. $selectOptionValue = '&nbsp;';
  7046. }
  7047. }
  7048. $out .= '<option value="'.$key.'"';
  7049. $out .= $style.$disabled;
  7050. if (is_array($id)) {
  7051. if (in_array($key, $id) && !$disabled) {
  7052. $out .= ' selected'; // To preselect a value
  7053. }
  7054. } else {
  7055. $id = (string) $id; // if $id = 0, then $id = '0'
  7056. if ($id != '' && $id == $key && !$disabled) {
  7057. $out .= ' selected'; // To preselect a value
  7058. }
  7059. }
  7060. if ($nohtmlescape) {
  7061. $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  7062. }
  7063. if (is_array($tmpvalue)) {
  7064. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7065. if (preg_match('/^data-/', $keyforvalue)) {
  7066. $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  7067. }
  7068. }
  7069. }
  7070. $out .= '>';
  7071. //var_dump($selectOptionValue);
  7072. $out .= $selectOptionValue;
  7073. $out .= "</option>\n";
  7074. }
  7075. }
  7076. $out .= "</select>";
  7077. return $out;
  7078. }
  7079. /**
  7080. * 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.
  7081. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7082. *
  7083. * @param string $htmlname Name of html select area
  7084. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7085. * @param string $id Preselected key
  7086. * @param string $moreparam Add more parameters onto the select tag
  7087. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7088. * @param int $disabled Html select box is disabled
  7089. * @param int $minimumInputLength Minimum Input Length
  7090. * @param string $morecss Add more class to css styles
  7091. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7092. * @param string $placeholder String to use as placeholder
  7093. * @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)
  7094. * @return string HTML select string
  7095. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7096. */
  7097. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7098. {
  7099. global $conf, $langs;
  7100. global $delayedhtmlcontent; // Will be used later outside of this function
  7101. // TODO Use an internal dolibarr component instead of select2
  7102. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7103. return '';
  7104. }
  7105. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  7106. $outdelayed = '';
  7107. if (!empty($conf->use_javascript_ajax)) {
  7108. $tmpplugin = 'select2';
  7109. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7110. <script>
  7111. $(document).ready(function () {
  7112. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  7113. $(".'.$htmlname.'").select2({
  7114. ajax: {
  7115. dir: "ltr",
  7116. url: "'.$url.'",
  7117. dataType: \'json\',
  7118. delay: 250,
  7119. data: function (params) {
  7120. return {
  7121. q: params.term, // search term
  7122. page: params.page
  7123. };
  7124. },
  7125. processResults: function (data) {
  7126. // parse the results into the format expected by Select2.
  7127. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7128. //console.log(data);
  7129. saveRemoteData = data;
  7130. /* format json result for select2 */
  7131. result = []
  7132. $.each( data, function( key, value ) {
  7133. result.push({id: key, text: value.text});
  7134. });
  7135. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7136. //console.log(result);
  7137. return {results: result, more: false}
  7138. },
  7139. cache: true
  7140. },
  7141. language: select2arrayoflanguage,
  7142. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7143. placeholder: "'.dol_escape_js($placeholder).'",
  7144. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7145. minimumInputLength: '.$minimumInputLength.',
  7146. formatResult: function(result, container, query, escapeMarkup) {
  7147. return escapeMarkup(result.text);
  7148. },
  7149. });
  7150. '.($callurlonselect ? '
  7151. /* Code to execute a GET when we select a value */
  7152. $(".'.$htmlname.'").change(function() {
  7153. var selected = $(".'.$htmlname.'").val();
  7154. console.log("We select in selectArrayAjax the entry "+selected)
  7155. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7156. $.each( saveRemoteData, function( key, value ) {
  7157. if (key == selected)
  7158. {
  7159. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7160. location.assign(value.url);
  7161. }
  7162. });
  7163. });' : '').'
  7164. });
  7165. </script>';
  7166. }
  7167. if ($acceptdelayedhtml) {
  7168. $delayedhtmlcontent .= $outdelayed;
  7169. } else {
  7170. $out .= $outdelayed;
  7171. }
  7172. return $out;
  7173. }
  7174. /**
  7175. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7176. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7177. *
  7178. * @param string $htmlname Name of html select area
  7179. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7180. * @param string $id Preselected key
  7181. * @param string $moreparam Add more parameters onto the select tag
  7182. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7183. * @param int $disabled Html select box is disabled
  7184. * @param int $minimumInputLength Minimum Input Length
  7185. * @param string $morecss Add more class to css styles
  7186. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7187. * @param string $placeholder String to use as placeholder
  7188. * @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)
  7189. * @return string HTML select string
  7190. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7191. */
  7192. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7193. {
  7194. global $conf, $langs;
  7195. global $delayedhtmlcontent; // Will be used later outside of this function
  7196. // TODO Use an internal dolibarr component instead of select2
  7197. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7198. return '';
  7199. }
  7200. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  7201. $formattedarrayresult = array();
  7202. foreach ($array as $key => $value) {
  7203. $o = new stdClass();
  7204. $o->id = $key;
  7205. $o->text = $value['text'];
  7206. $o->url = $value['url'];
  7207. $formattedarrayresult[] = $o;
  7208. }
  7209. $outdelayed = '';
  7210. if (!empty($conf->use_javascript_ajax)) {
  7211. $tmpplugin = 'select2';
  7212. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7213. <script>
  7214. $(document).ready(function () {
  7215. var data = '.json_encode($formattedarrayresult).';
  7216. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  7217. $(".'.$htmlname.'").select2({
  7218. data: data,
  7219. language: select2arrayoflanguage,
  7220. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7221. placeholder: "'.dol_escape_js($placeholder).'",
  7222. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7223. minimumInputLength: '.$minimumInputLength.',
  7224. formatResult: function(result, container, query, escapeMarkup) {
  7225. return escapeMarkup(result.text);
  7226. },
  7227. matcher: function (params, data) {
  7228. if(! data.id) return null;';
  7229. if ($callurlonselect) {
  7230. $outdelayed .= '
  7231. var urlBase = data.url;
  7232. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7233. /* console.log("params.term="+params.term); */
  7234. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7235. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7236. }
  7237. if (!$disableFiltering) {
  7238. $outdelayed .= '
  7239. if(data.text.match(new RegExp(params.term))) {
  7240. return data;
  7241. }
  7242. return null;';
  7243. } else {
  7244. $outdelayed .= '
  7245. return data;';
  7246. }
  7247. $outdelayed .= '
  7248. }
  7249. });
  7250. '.($callurlonselect ? '
  7251. /* Code to execute a GET when we select a value */
  7252. $(".'.$htmlname.'").change(function() {
  7253. var selected = $(".'.$htmlname.'").val();
  7254. console.log("We select "+selected)
  7255. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7256. $.each( saveRemoteData, function( key, value ) {
  7257. if (key == selected)
  7258. {
  7259. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7260. location.assign(value.url);
  7261. }
  7262. });
  7263. });' : '').'
  7264. });
  7265. </script>';
  7266. }
  7267. if ($acceptdelayedhtml) {
  7268. $delayedhtmlcontent .= $outdelayed;
  7269. } else {
  7270. $out .= $outdelayed;
  7271. }
  7272. return $out;
  7273. }
  7274. /**
  7275. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7276. *
  7277. * @param string $htmlname Name of select
  7278. * @param array $array Array with key+value
  7279. * @param array $selected Array with key+value preselected
  7280. * @param int $key_in_label 1 to show key like in "[key] value"
  7281. * @param int $value_as_key 1 to use value as key
  7282. * @param string $morecss Add more css style
  7283. * @param int $translate Translate and encode value
  7284. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7285. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7286. * @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.
  7287. * @param string $placeholder String to use as placeholder
  7288. * @param int $addjscombo Add js combo
  7289. * @return string HTML multiselect string
  7290. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7291. */
  7292. 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)
  7293. {
  7294. global $conf, $langs;
  7295. $out = '';
  7296. if ($addjscombo < 0) {
  7297. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7298. $addjscombo = 1;
  7299. } else {
  7300. $addjscombo = 0;
  7301. }
  7302. }
  7303. // Try also magic suggest
  7304. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  7305. if (is_array($array) && !empty($array)) {
  7306. if ($value_as_key) {
  7307. $array = array_combine($array, $array);
  7308. }
  7309. if (!empty($array)) {
  7310. foreach ($array as $key => $value) {
  7311. $newval = ($translate ? $langs->trans($value) : $value);
  7312. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  7313. $out .= '<option value="'.$key.'"';
  7314. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != '')) {
  7315. $out .= ' selected';
  7316. }
  7317. $out .= ' data-html="'.dol_escape_htmltag($newval).'"';
  7318. $out .= '>';
  7319. $out .= dol_htmlentitiesbr($newval);
  7320. $out .= '</option>'."\n";
  7321. }
  7322. }
  7323. }
  7324. $out .= '</select>'."\n";
  7325. // Add code for jquery to use multiselect
  7326. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7327. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.', addjscombo='.$addjscombo.' -->';
  7328. $out .= "\n".'<script>'."\n";
  7329. if ($addjscombo == 1) {
  7330. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7331. $out .= 'function formatResult(record, container) {'."\n";
  7332. $out .= ' if ($(record.element).attr("data-html") != undefined) return htmlEntityDecodeJs($(record.element).attr("data-html")); // If property html set, we decode html entities and use this'."\n";
  7333. $out .= ' return record.text;';
  7334. $out .= '};'."\n";
  7335. $out .= 'function formatSelection(record) {'."\n";
  7336. if ($elemtype == 'category') {
  7337. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7338. } else {
  7339. $out .= 'return record.text;';
  7340. }
  7341. $out .= '};'."\n";
  7342. $out .= '$(document).ready(function () {
  7343. $(\'#'.$htmlname.'\').'.$tmpplugin.'({';
  7344. if ($placeholder) {
  7345. $out .= '
  7346. placeholder: {
  7347. id: \'-1\',
  7348. text: \''.dol_escape_js($placeholder).'\'
  7349. },';
  7350. }
  7351. $out .= ' dir: \'ltr\',
  7352. // Specify format function for dropdown item
  7353. formatResult: formatResult,
  7354. templateResult: formatResult, /* For 4.0 */
  7355. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7356. // Specify format function for selected item
  7357. formatSelection: formatSelection,
  7358. templateSelection: formatSelection /* For 4.0 */
  7359. });
  7360. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7361. the size only if component is not hidden by default on load */
  7362. $(\'#'.$htmlname.' + .select2\').addClass(\''.$morecss.'\');
  7363. });'."\n";
  7364. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7365. // Add other js lib
  7366. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7367. // ...
  7368. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  7369. $out .= '$(document).ready(function () {
  7370. $(\'#'.$htmlname.'\').multiSelect({
  7371. containerHTML: \'<div class="multi-select-container">\',
  7372. menuHTML: \'<div class="multi-select-menu">\',
  7373. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  7374. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7375. activeClass: \'multi-select-container--open\',
  7376. noneText: \''.$placeholder.'\'
  7377. });
  7378. })';
  7379. }
  7380. $out .= '</script>';
  7381. }
  7382. return $out;
  7383. }
  7384. /**
  7385. * 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.
  7386. *
  7387. * @param string $htmlname Name of HTML field
  7388. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7389. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7390. * @return string HTML multiselect string
  7391. * @see selectarray()
  7392. */
  7393. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  7394. {
  7395. global $conf, $langs, $user, $extrafields;
  7396. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7397. return '';
  7398. }
  7399. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved selected fields to show
  7400. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7401. $tmparray = explode(',', $user->conf->$tmpvar);
  7402. foreach ($array as $key => $val) {
  7403. //var_dump($key);
  7404. //var_dump($tmparray);
  7405. if (in_array($key, $tmparray)) {
  7406. $array[$key]['checked'] = 1;
  7407. } else {
  7408. $array[$key]['checked'] = 0;
  7409. }
  7410. }
  7411. } else { // There is no list of fields already customized for user
  7412. foreach ($array as $key => $val) {
  7413. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7414. $array[$key]['checked'] = 0;
  7415. }
  7416. }
  7417. }
  7418. $listoffieldsforselection = '';
  7419. $listcheckedstring = '';
  7420. foreach ($array as $key => $val) {
  7421. /* var_dump($val);
  7422. var_dump(array_key_exists('enabled', $val));
  7423. var_dump(!$val['enabled']);*/
  7424. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7425. unset($array[$key]); // We don't want this field
  7426. continue;
  7427. }
  7428. if (!empty($val['type']) && $val['type'] == 'separate') {
  7429. // Field remains in array but we don't add it into $listoffieldsforselection
  7430. //$listoffieldsforselection .= '<li>-----</li>';
  7431. continue;
  7432. }
  7433. if ($val['label']) {
  7434. if (!empty($val['langfile']) && is_object($langs)) {
  7435. $langs->load($val['langfile']);
  7436. }
  7437. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7438. $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>';
  7439. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  7440. }
  7441. }
  7442. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  7443. <dl class="dropdown">
  7444. <dt>
  7445. <a href="#'.$htmlname.'">
  7446. '.img_picto('', 'list').'
  7447. </a>
  7448. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  7449. </dt>
  7450. <dd class="dropdowndd">
  7451. <div class="multiselectcheckbox'.$htmlname.'">
  7452. <ul class="ul'.$htmlname.'">
  7453. '.$listoffieldsforselection.'
  7454. </ul>
  7455. </div>
  7456. </dd>
  7457. </dl>
  7458. <script type="text/javascript">
  7459. jQuery(document).ready(function () {
  7460. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  7461. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7462. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7463. var title = $(this).val() + ",";
  7464. if ($(this).is(\':checked\')) {
  7465. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  7466. }
  7467. else {
  7468. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  7469. }
  7470. // Now, we submit page
  7471. //$(this).parents(\'form:first\').submit();
  7472. });
  7473. });
  7474. </script>
  7475. ';
  7476. return $out;
  7477. }
  7478. /**
  7479. * Render list of categories linked to object with id $id and type $type
  7480. *
  7481. * @param int $id Id of object
  7482. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7483. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7484. * @param int $nolink 1=Do not add html links
  7485. * @return string String with categories
  7486. */
  7487. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7488. {
  7489. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7490. $cat = new Categorie($this->db);
  7491. $categories = $cat->containing($id, $type);
  7492. if ($rendermode == 1) {
  7493. $toprint = array();
  7494. foreach ($categories as $c) {
  7495. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7496. foreach ($ways as $way) {
  7497. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  7498. }
  7499. }
  7500. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  7501. }
  7502. if ($rendermode == 0) {
  7503. $arrayselected = array();
  7504. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7505. foreach ($categories as $c) {
  7506. $arrayselected[] = $c->id;
  7507. }
  7508. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7509. }
  7510. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7511. }
  7512. /**
  7513. * Show linked object block.
  7514. *
  7515. * @param CommonObject $object Object we want to show links to
  7516. * @param string $morehtmlright More html to show on right of title
  7517. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7518. * @return int <0 if KO, >=0 if OK
  7519. */
  7520. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
  7521. {
  7522. global $conf, $langs, $hookmanager;
  7523. global $bc, $action;
  7524. $object->fetchObjectLinked();
  7525. // Bypass the default method
  7526. $hookmanager->initHooks(array('commonobject'));
  7527. $parameters = array(
  7528. 'morehtmlright' => $morehtmlright,
  7529. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7530. );
  7531. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7532. if (empty($reshook)) {
  7533. $nbofdifferenttypes = count($object->linkedObjects);
  7534. print '<!-- showLinkedObjectBlock -->';
  7535. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7536. print '<div class="div-table-responsive-no-min">';
  7537. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  7538. print '<tr class="liste_titre">';
  7539. print '<td>'.$langs->trans("Type").'</td>';
  7540. print '<td>'.$langs->trans("Ref").'</td>';
  7541. print '<td class="center"></td>';
  7542. print '<td class="center">'.$langs->trans("Date").'</td>';
  7543. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7544. print '<td class="right">'.$langs->trans("Status").'</td>';
  7545. print '<td></td>';
  7546. print '</tr>';
  7547. $nboftypesoutput = 0;
  7548. foreach ($object->linkedObjects as $objecttype => $objects) {
  7549. $tplpath = $element = $subelement = $objecttype;
  7550. // to display inport button on tpl
  7551. $showImportButton = false;
  7552. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7553. $showImportButton = true;
  7554. }
  7555. $regs = array();
  7556. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7557. $element = $regs[1];
  7558. $subelement = $regs[2];
  7559. $tplpath = $element.'/'.$subelement;
  7560. }
  7561. $tplname = 'linkedobjectblock';
  7562. // To work with non standard path
  7563. if ($objecttype == 'facture') {
  7564. $tplpath = 'compta/'.$element;
  7565. if (empty($conf->facture->enabled)) {
  7566. continue; // Do not show if module disabled
  7567. }
  7568. } elseif ($objecttype == 'facturerec') {
  7569. $tplpath = 'compta/facture';
  7570. $tplname = 'linkedobjectblockForRec';
  7571. if (empty($conf->facture->enabled)) {
  7572. continue; // Do not show if module disabled
  7573. }
  7574. } elseif ($objecttype == 'propal') {
  7575. $tplpath = 'comm/'.$element;
  7576. if (empty($conf->propal->enabled)) {
  7577. continue; // Do not show if module disabled
  7578. }
  7579. } elseif ($objecttype == 'supplier_proposal') {
  7580. if (empty($conf->supplier_proposal->enabled)) {
  7581. continue; // Do not show if module disabled
  7582. }
  7583. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  7584. $tplpath = 'expedition';
  7585. if (empty($conf->expedition->enabled)) {
  7586. continue; // Do not show if module disabled
  7587. }
  7588. } elseif ($objecttype == 'reception') {
  7589. $tplpath = 'reception';
  7590. if (empty($conf->reception->enabled)) {
  7591. continue; // Do not show if module disabled
  7592. }
  7593. } elseif ($objecttype == 'delivery') {
  7594. $tplpath = 'delivery';
  7595. if (empty($conf->expedition->enabled)) {
  7596. continue; // Do not show if module disabled
  7597. }
  7598. } elseif ($objecttype == 'mo') {
  7599. $tplpath = 'mrp/mo';
  7600. if (empty($conf->mrp->enabled)) {
  7601. continue; // Do not show if module disabled
  7602. }
  7603. } elseif ($objecttype == 'ficheinter') {
  7604. $tplpath = 'fichinter';
  7605. if (empty($conf->ficheinter->enabled)) {
  7606. continue; // Do not show if module disabled
  7607. }
  7608. } elseif ($objecttype == 'invoice_supplier') {
  7609. $tplpath = 'fourn/facture';
  7610. } elseif ($objecttype == 'order_supplier') {
  7611. $tplpath = 'fourn/commande';
  7612. } elseif ($objecttype == 'expensereport') {
  7613. $tplpath = 'expensereport';
  7614. } elseif ($objecttype == 'subscription') {
  7615. $tplpath = 'adherents';
  7616. } elseif ($objecttype == 'conferenceorbooth') {
  7617. $tplpath = 'eventorganization';
  7618. } elseif ($objecttype == 'conferenceorboothattendee') {
  7619. $tplpath = 'eventorganization';
  7620. } elseif ($objecttype == 'mo') {
  7621. $tplpath = 'mrp';
  7622. if (empty($conf->mrp->enabled)) {
  7623. continue; // Do not show if module disabled
  7624. }
  7625. }
  7626. global $linkedObjectBlock;
  7627. $linkedObjectBlock = $objects;
  7628. // Output template part (modules that overwrite templates must declare this into descriptor)
  7629. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  7630. foreach ($dirtpls as $reldir) {
  7631. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7632. global $noMoreLinkedObjectBlockAfter;
  7633. $noMoreLinkedObjectBlockAfter = 1;
  7634. }
  7635. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  7636. if ($res) {
  7637. $nboftypesoutput++;
  7638. break;
  7639. }
  7640. }
  7641. }
  7642. if (!$nboftypesoutput) {
  7643. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  7644. }
  7645. print '</table>';
  7646. if (!empty($compatibleImportElementsList)) {
  7647. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  7648. }
  7649. print '</div>';
  7650. return $nbofdifferenttypes;
  7651. }
  7652. }
  7653. /**
  7654. * Show block with links to link to other objects.
  7655. *
  7656. * @param CommonObject $object Object we want to show links to
  7657. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7658. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7659. * @return string <0 if KO, >0 if OK
  7660. */
  7661. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7662. {
  7663. global $conf, $langs, $hookmanager;
  7664. global $bc, $action;
  7665. $linktoelem = '';
  7666. $linktoelemlist = '';
  7667. $listofidcompanytoscan = '';
  7668. if (!is_object($object->thirdparty)) {
  7669. $object->fetch_thirdparty();
  7670. }
  7671. $possiblelinks = array();
  7672. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7673. $listofidcompanytoscan = $object->thirdparty->id;
  7674. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7675. $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  7676. }
  7677. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7678. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7679. $tmpproject = new Project($this->db);
  7680. $tmpproject->fetch($object->fk_project);
  7681. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7682. $listofidcompanytoscan .= ','.$tmpproject->socid;
  7683. }
  7684. unset($tmpproject);
  7685. }
  7686. $possiblelinks = array(
  7687. 'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$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').')'),
  7688. 'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$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').')'),
  7689. 'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.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').')'),
  7690. 'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total_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').')'),
  7691. 'contrat'=>array(
  7692. 'enabled'=>$conf->contrat->enabled,
  7693. 'perms'=>1,
  7694. 'label'=>'LinkToContract',
  7695. '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
  7696. 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'
  7697. ),
  7698. 'fichinter'=>array('enabled'=>!empty($conf->ficheinter->enabled) ? $conf->ficheinter->enabled : 0, 'perms'=>1, 'label'=>'LinkToIntervention', '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').')'),
  7699. 'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled, 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".$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').')'),
  7700. 'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled, 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$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').')'),
  7701. 'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled, 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$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').')'),
  7702. 'ticket'=>array('enabled'=>$conf->ticket->enabled, 'perms'=>1, 'label'=>'LinkToTicket', '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').')'),
  7703. 'mo'=>array('enabled'=>$conf->mrp->enabled, 'perms'=>1, 'label'=>'LinkToMo', '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').')')
  7704. );
  7705. }
  7706. // Can complete the possiblelink array
  7707. $hookmanager->initHooks(array('commonobject'));
  7708. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan);
  7709. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  7710. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7711. }
  7712. if (empty($reshook)) {
  7713. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7714. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  7715. }
  7716. } elseif ($reshook > 0) {
  7717. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7718. $possiblelinks = $hookmanager->resArray;
  7719. }
  7720. }
  7721. foreach ($possiblelinks as $key => $possiblelink) {
  7722. $num = 0;
  7723. if (empty($possiblelink['enabled'])) {
  7724. continue;
  7725. }
  7726. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  7727. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  7728. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7729. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  7730. print '<input type="hidden" name="id" value="' . $object->id . '">';
  7731. print '<input type="hidden" name="action" value="addlinkbyref">';
  7732. print '<input type="hidden" name="token" value="'.newToken().'">';
  7733. print '<input type="hidden" name="addlink" value="' . $key . '">';
  7734. print '<table class="noborder">';
  7735. print '<tr>';
  7736. print '<td>' . $langs->trans("Ref") . '</td>';
  7737. print '<td><input type="text" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;<input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  7738. print '</tr>';
  7739. print '</table>';
  7740. print '</form>';
  7741. }
  7742. $sql = $possiblelink['sql'];
  7743. $resqllist = $this->db->query($sql);
  7744. if ($resqllist) {
  7745. $num = $this->db->num_rows($resqllist);
  7746. $i = 0;
  7747. print '<br>';
  7748. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  7749. print '<input type="hidden" name="action" value="addlink">';
  7750. print '<input type="hidden" name="token" value="'.newToken().'">';
  7751. print '<input type="hidden" name="id" value="'.$object->id.'">';
  7752. print '<input type="hidden" name="addlink" value="'.$key.'">';
  7753. print '<table class="noborder">';
  7754. print '<tr class="liste_titre">';
  7755. print '<td class="nowrap"></td>';
  7756. print '<td class="center">'.$langs->trans("Ref").'</td>';
  7757. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  7758. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7759. print '<td class="left">'.$langs->trans("Company").'</td>';
  7760. print '</tr>';
  7761. while ($i < $num) {
  7762. $objp = $this->db->fetch_object($resqllist);
  7763. print '<tr class="oddeven">';
  7764. print '<td class="left">';
  7765. print '<input type="radio" name="idtolinkto" id="'.$key.'_'.$objp->rowid.'" value="'.$objp->rowid.'">';
  7766. print '</td>';
  7767. print '<td class="center"><label for="'.$key.'_'.$objp->rowid.'">'.$objp->ref.'</label></td>';
  7768. print '<td>'.(!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')).'</td>';
  7769. print '<td class="right">';
  7770. if ($possiblelink['label'] == 'LinkToContract') {
  7771. $form = new Form($this->db);
  7772. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' ';
  7773. }
  7774. print '<span class="amount">'.price($objp->total_ht).'</span>';
  7775. print '</td>';
  7776. print '<td>'.$objp->name.'</td>';
  7777. print '</tr>';
  7778. $i++;
  7779. }
  7780. print '</table>';
  7781. print '<div class="center">';
  7782. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="'.$langs->trans('ToLink').'">';
  7783. if (empty($conf->use_javascript_ajax)) {
  7784. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7785. } else {
  7786. print '<input type="submit"; onclick="javascript:jQuery(\'#'.$key.'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7787. }
  7788. print '</form>';
  7789. $this->db->free($resqllist);
  7790. } else {
  7791. dol_print_error($this->db);
  7792. }
  7793. print '</div>';
  7794. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  7795. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7796. $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  7797. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  7798. } else {
  7799. $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  7800. }
  7801. }
  7802. }
  7803. if ($linktoelemlist) {
  7804. $linktoelem = '
  7805. <dl class="dropdown" id="linktoobjectname">
  7806. ';
  7807. if (!empty($conf->use_javascript_ajax)) {
  7808. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>'.$langs->trans("LinkTo").'...</a></dt>';
  7809. }
  7810. $linktoelem .= '<dd>
  7811. <div class="multiselectlinkto">
  7812. <ul class="ulselectedfields">'.$linktoelemlist.'
  7813. </ul>
  7814. </div>
  7815. </dd>
  7816. </dl>';
  7817. } else {
  7818. $linktoelem = '';
  7819. }
  7820. if (!empty($conf->use_javascript_ajax)) {
  7821. print '<!-- Add js to show linkto box -->
  7822. <script>
  7823. jQuery(document).ready(function() {
  7824. jQuery(".linkto").click(function() {
  7825. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  7826. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  7827. });
  7828. });
  7829. </script>
  7830. ';
  7831. }
  7832. return $linktoelem;
  7833. }
  7834. /**
  7835. * Return an html string with a select combo box to choose yes or no
  7836. *
  7837. * @param string $htmlname Name of html select field
  7838. * @param string $value Pre-selected value
  7839. * @param int $option 0 return yes/no, 1 return 1/0
  7840. * @param bool $disabled true or false
  7841. * @param int $useempty 1=Add empty line
  7842. * @param int $addjscombo 1=Add js beautifier on combo box
  7843. * @param string $morecss More CSS
  7844. * @return string See option
  7845. */
  7846. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '')
  7847. {
  7848. global $langs;
  7849. $yes = "yes";
  7850. $no = "no";
  7851. if ($option) {
  7852. $yes = "1";
  7853. $no = "0";
  7854. }
  7855. $disabled = ($disabled ? ' disabled' : '');
  7856. $resultyesno = '<select class="flat width75'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  7857. if ($useempty) {
  7858. $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  7859. }
  7860. if (("$value" == 'yes') || ($value == 1)) {
  7861. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  7862. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  7863. } else {
  7864. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  7865. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  7866. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  7867. }
  7868. $resultyesno .= '</select>'."\n";
  7869. if ($addjscombo) {
  7870. $resultyesno .= ajax_combobox($htmlname);
  7871. }
  7872. return $resultyesno;
  7873. }
  7874. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7875. /**
  7876. * Return list of export templates
  7877. *
  7878. * @param string $selected Id modele pre-selectionne
  7879. * @param string $htmlname Name of HTML select
  7880. * @param string $type Type of searched templates
  7881. * @param int $useempty Affiche valeur vide dans liste
  7882. * @return void
  7883. */
  7884. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  7885. {
  7886. // phpcs:enable
  7887. $sql = "SELECT rowid, label";
  7888. $sql .= " FROM ".$this->db->prefix()."export_model";
  7889. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  7890. $sql .= " ORDER BY rowid";
  7891. $result = $this->db->query($sql);
  7892. if ($result) {
  7893. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  7894. if ($useempty) {
  7895. print '<option value="-1">&nbsp;</option>';
  7896. }
  7897. $num = $this->db->num_rows($result);
  7898. $i = 0;
  7899. while ($i < $num) {
  7900. $obj = $this->db->fetch_object($result);
  7901. if ($selected == $obj->rowid) {
  7902. print '<option value="'.$obj->rowid.'" selected>';
  7903. } else {
  7904. print '<option value="'.$obj->rowid.'">';
  7905. }
  7906. print $obj->label;
  7907. print '</option>';
  7908. $i++;
  7909. }
  7910. print "</select>";
  7911. } else {
  7912. dol_print_error($this->db);
  7913. }
  7914. }
  7915. /**
  7916. * Return a HTML area with the reference of object and a navigation bar for a business object
  7917. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  7918. *
  7919. * @param object $object Object to show.
  7920. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  7921. * @param string $morehtml More html content to output just before the nav bar.
  7922. * @param int $shownav Show Condition (navigation is shown if value is 1).
  7923. * @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.
  7924. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  7925. * @param string $morehtmlref More html to show after ref.
  7926. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  7927. * @param int $nodbprefix Do not include DB prefix to forge table name.
  7928. * @param string $morehtmlleft More html code to show before ref.
  7929. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  7930. * @param string $morehtmlright More html code to show after ref.
  7931. * @return string Portion HTML with ref + navigation buttons
  7932. */
  7933. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  7934. {
  7935. global $conf, $langs, $hookmanager, $extralanguages;
  7936. $ret = '';
  7937. if (empty($fieldid)) {
  7938. $fieldid = 'rowid';
  7939. }
  7940. if (empty($fieldref)) {
  7941. $fieldref = 'ref';
  7942. }
  7943. // Preparing gender's display if there is one
  7944. $addgendertxt = '';
  7945. if (property_exists($object, 'gender') && !empty($object->gender)) {
  7946. $addgendertxt = ' ';
  7947. switch ($object->gender) {
  7948. case 'man':
  7949. $addgendertxt .= '<i class="fas fa-mars"></i>';
  7950. break;
  7951. case 'woman':
  7952. $addgendertxt .= '<i class="fas fa-venus"></i>';
  7953. break;
  7954. case 'other':
  7955. $addgendertxt .= '<i class="fas fa-genderless"></i>';
  7956. break;
  7957. }
  7958. }
  7959. /*
  7960. $addadmin = '';
  7961. if (property_exists($object, 'admin')) {
  7962. if (!empty($conf->multicompany->enabled) && !empty($object->admin) && empty($object->entity)) {
  7963. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  7964. } elseif (!empty($object->admin)) {
  7965. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  7966. }
  7967. }*/
  7968. // Add where from hooks
  7969. if (is_object($hookmanager)) {
  7970. $parameters = array('showrefnav' => true);
  7971. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  7972. $object->next_prev_filter .= $hookmanager->resPrint;
  7973. }
  7974. $previous_ref = $next_ref = '';
  7975. if ($shownav) {
  7976. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  7977. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  7978. $navurl = $_SERVER["PHP_SELF"];
  7979. // Special case for project/task page
  7980. if ($paramid == 'project_ref') {
  7981. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  7982. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  7983. $paramid = 'ref';
  7984. }
  7985. }
  7986. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  7987. // accesskey is for Mac: CTRL + key for all browsers
  7988. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  7989. if ($conf->browser->name == 'chrome') {
  7990. $stringforfirstkey .= ' ALT +';
  7991. } elseif ($conf->browser->name == 'firefox') {
  7992. $stringforfirstkey .= ' ALT + SHIFT +';
  7993. } else {
  7994. $stringforfirstkey .= ' CTL +';
  7995. }
  7996. $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>';
  7997. $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>';
  7998. }
  7999. //print "xx".$previous_ref."x".$next_ref;
  8000. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8001. // Right part of banner
  8002. if ($morehtmlright) {
  8003. $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  8004. }
  8005. if ($previous_ref || $next_ref || $morehtml) {
  8006. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8007. }
  8008. if ($morehtml) {
  8009. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  8010. }
  8011. if ($shownav && ($previous_ref || $next_ref)) {
  8012. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  8013. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  8014. }
  8015. if ($previous_ref || $next_ref || $morehtml) {
  8016. $ret .= '</ul></div>';
  8017. }
  8018. $parameters = array();
  8019. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8020. if (empty($reshook)) {
  8021. $morehtmlstatus .= $hookmanager->resPrint;
  8022. } else {
  8023. $morehtmlstatus = $hookmanager->resPrint;
  8024. }
  8025. if ($morehtmlstatus) {
  8026. $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  8027. }
  8028. $parameters = array();
  8029. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8030. if (empty($reshook)) {
  8031. $morehtmlref .= $hookmanager->resPrint;
  8032. } elseif ($reshook > 0) {
  8033. $morehtmlref = $hookmanager->resPrint;
  8034. }
  8035. // Left part of banner
  8036. if ($morehtmlleft) {
  8037. if ($conf->browser->layout == 'phone') {
  8038. $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  8039. } else {
  8040. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  8041. }
  8042. }
  8043. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8044. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  8045. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8046. if ($object->element == 'societe') {
  8047. $ret .= dol_htmlentities($object->name);
  8048. // List of extra languages
  8049. $arrayoflangcode = array();
  8050. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8051. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8052. }
  8053. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8054. if (!is_object($extralanguages)) {
  8055. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  8056. $extralanguages = new ExtraLanguages($this->db);
  8057. }
  8058. $extralanguages->fetch_name_extralanguages('societe');
  8059. if (!empty($extralanguages->attributes['societe']['name'])) {
  8060. $object->fetchValuesForExtraLanguages();
  8061. $htmltext = '';
  8062. // If there is extra languages
  8063. foreach ($arrayoflangcode as $extralangcode) {
  8064. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8065. if ($object->array_languages['name'][$extralangcode]) {
  8066. $htmltext .= $object->array_languages['name'][$extralangcode];
  8067. } else {
  8068. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  8069. }
  8070. }
  8071. $ret .= '<!-- Show translations of name -->'."\n";
  8072. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8073. }
  8074. }
  8075. } elseif ($object->element == 'member') {
  8076. $ret .= $object->ref.'<br>';
  8077. $fullname = $object->getFullName($langs);
  8078. if ($object->morphy == 'mor' && $object->societe) {
  8079. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).$addgendertxt.')' : '');
  8080. } else {
  8081. $ret .= dol_htmlentities($fullname).$addgendertxt.((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  8082. }
  8083. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8084. $ret .= dol_htmlentities($object->getFullName($langs));
  8085. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8086. $ret .= $object->ref.'<br>'.$object->label;
  8087. } elseif (in_array($object->element, array('adherent_type'))) {
  8088. $ret .= $object->label;
  8089. } elseif ($object->element == 'ecm_directories') {
  8090. $ret .= '';
  8091. } elseif ($fieldref != 'none') {
  8092. $ret .= dol_htmlentities($object->$fieldref);
  8093. }
  8094. if ($morehtmlref) {
  8095. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8096. if (substr($morehtmlref, 0, 4) != '<div') {
  8097. $ret .= ' ';
  8098. }
  8099. $ret .= $morehtmlref;
  8100. }
  8101. $ret .= '</div>';
  8102. $ret .= '</div><!-- End banner content -->';
  8103. return $ret;
  8104. }
  8105. /**
  8106. * Return HTML code to output a barcode
  8107. *
  8108. * @param Object $object Object containing data to retrieve file name
  8109. * @param int $width Width of photo
  8110. * @param string $morecss More CSS on img of barcode
  8111. * @return string HTML code to output barcode
  8112. */
  8113. public function showbarcode(&$object, $width = 100, $morecss = '')
  8114. {
  8115. global $conf;
  8116. //Check if barcode is filled in the card
  8117. if (empty($object->barcode)) {
  8118. return '';
  8119. }
  8120. // Complete object if not complete
  8121. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8122. $result = $object->fetch_barcode();
  8123. //Check if fetch_barcode() failed
  8124. if ($result < 1) {
  8125. return '<!-- ErrorFetchBarcode -->';
  8126. }
  8127. }
  8128. // Barcode image
  8129. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  8130. $out = '<!-- url barcode = '.$url.' -->';
  8131. $out .= '<img src="'.$url.'"'.($morecss ? ' class="'.$morecss.'"' : '').'>';
  8132. return $out;
  8133. }
  8134. /**
  8135. * Return HTML code to output a photo
  8136. *
  8137. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8138. * @param object $object Object containing data to retrieve file name
  8139. * @param int $width Width of photo
  8140. * @param int $height Height of photo (auto if 0)
  8141. * @param int $caneditfield Add edit fields
  8142. * @param string $cssclass CSS name to use on img for photo
  8143. * @param string $imagesize 'mini', 'small' or '' (original)
  8144. * @param int $addlinktofullsize Add link to fullsize image
  8145. * @param int $cache 1=Accept to use image in cache
  8146. * @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 ''.
  8147. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8148. * @return string HTML code to output photo
  8149. */
  8150. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8151. {
  8152. global $conf, $langs;
  8153. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8154. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8155. $ret = '';
  8156. $dir = '';
  8157. $file = '';
  8158. $originalfile = '';
  8159. $altfile = '';
  8160. $email = '';
  8161. $capture = '';
  8162. if ($modulepart == 'societe') {
  8163. $dir = $conf->societe->multidir_output[$entity];
  8164. if (!empty($object->logo)) {
  8165. if (dolIsAllowedForPreview($object->logo)) {
  8166. if ((string) $imagesize == 'mini') {
  8167. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8168. } elseif ((string) $imagesize == 'small') {
  8169. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_small');
  8170. } else {
  8171. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8172. }
  8173. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8174. }
  8175. }
  8176. $email = $object->email;
  8177. } elseif ($modulepart == 'contact') {
  8178. $dir = $conf->societe->multidir_output[$entity].'/contact';
  8179. if (!empty($object->photo)) {
  8180. if (dolIsAllowedForPreview($object->photo)) {
  8181. if ((string) $imagesize == 'mini') {
  8182. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8183. } elseif ((string) $imagesize == 'small') {
  8184. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8185. } else {
  8186. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8187. }
  8188. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8189. }
  8190. }
  8191. $email = $object->email;
  8192. $capture = 'user';
  8193. } elseif ($modulepart == 'userphoto') {
  8194. $dir = $conf->user->dir_output;
  8195. if (!empty($object->photo)) {
  8196. if (dolIsAllowedForPreview($object->photo)) {
  8197. if ((string) $imagesize == 'mini') {
  8198. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8199. } elseif ((string) $imagesize == 'small') {
  8200. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8201. } else {
  8202. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8203. }
  8204. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8205. }
  8206. }
  8207. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8208. $altfile = $object->id.".jpg"; // For backward compatibility
  8209. }
  8210. $email = $object->email;
  8211. $capture = 'user';
  8212. } elseif ($modulepart == 'memberphoto') {
  8213. $dir = $conf->adherent->dir_output;
  8214. if (!empty($object->photo)) {
  8215. if (dolIsAllowedForPreview($object->photo)) {
  8216. if ((string) $imagesize == 'mini') {
  8217. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8218. } elseif ((string) $imagesize == 'small') {
  8219. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8220. } else {
  8221. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8222. }
  8223. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8224. }
  8225. }
  8226. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8227. $altfile = $object->id.".jpg"; // For backward compatibility
  8228. }
  8229. $email = $object->email;
  8230. $capture = 'user';
  8231. } else {
  8232. // Generic case to show photos
  8233. $dir = $conf->$modulepart->dir_output;
  8234. if (!empty($object->photo)) {
  8235. if (dolIsAllowedForPreview($object->photo)) {
  8236. if ((string) $imagesize == 'mini') {
  8237. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8238. } elseif ((string) $imagesize == 'small') {
  8239. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  8240. } else {
  8241. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8242. }
  8243. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8244. }
  8245. }
  8246. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8247. $altfile = $object->id.".jpg"; // For backward compatibility
  8248. }
  8249. $email = $object->email;
  8250. }
  8251. if ($forcecapture) {
  8252. $capture = $forcecapture;
  8253. }
  8254. if ($dir) {
  8255. if ($file && file_exists($dir."/".$file)) {
  8256. if ($addlinktofullsize) {
  8257. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8258. if ($urladvanced) {
  8259. $ret .= '<a href="'.$urladvanced.'">';
  8260. } else {
  8261. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8262. }
  8263. }
  8264. $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.'">';
  8265. if ($addlinktofullsize) {
  8266. $ret .= '</a>';
  8267. }
  8268. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  8269. if ($addlinktofullsize) {
  8270. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8271. if ($urladvanced) {
  8272. $ret .= '<a href="'.$urladvanced.'">';
  8273. } else {
  8274. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8275. }
  8276. }
  8277. $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.'">';
  8278. if ($addlinktofullsize) {
  8279. $ret .= '</a>';
  8280. }
  8281. } else {
  8282. $nophoto = '/public/theme/common/nophoto.png';
  8283. $defaultimg = 'identicon'; // For gravatar
  8284. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8285. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8286. $nophoto = 'company';
  8287. } else {
  8288. $nophoto = '/public/theme/common/user_anonymous.png';
  8289. if (!empty($object->gender) && $object->gender == 'man') {
  8290. $nophoto = '/public/theme/common/user_man.png';
  8291. }
  8292. if (!empty($object->gender) && $object->gender == 'woman') {
  8293. $nophoto = '/public/theme/common/user_woman.png';
  8294. }
  8295. }
  8296. }
  8297. if (!empty($conf->gravatar->enabled) && $email && empty($noexternsourceoverwrite)) {
  8298. // see https://gravatar.com/site/implement/images/php/
  8299. $ret .= '<!-- Put link to gravatar -->';
  8300. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="https://www.gravatar.com/avatar/'.md5(strtolower(trim($email))).'?s='.$width.'&d='.$defaultimg.'">'; // gravatar need md5 hash
  8301. } else {
  8302. if ($nophoto == 'company') {
  8303. $ret .= '<div class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'">'.img_picto('', 'company').'</div>';
  8304. } else {
  8305. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  8306. }
  8307. }
  8308. }
  8309. if ($caneditfield) {
  8310. if ($object->photo) {
  8311. $ret .= "<br>\n";
  8312. }
  8313. $ret .= '<table class="nobordernopadding centpercent">';
  8314. if ($object->photo) {
  8315. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">'.$langs->trans("Delete").'</label><br><br></td></tr>';
  8316. }
  8317. $ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
  8318. $ret .= '</table>';
  8319. }
  8320. } else {
  8321. dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  8322. }
  8323. return $ret;
  8324. }
  8325. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8326. /**
  8327. * Return select list of groups
  8328. *
  8329. * @param string $selected Id group preselected
  8330. * @param string $htmlname Field name in form
  8331. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8332. * @param string $exclude Array list of groups id to exclude
  8333. * @param int $disabled If select list must be disabled
  8334. * @param string $include Array list of groups id to include
  8335. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8336. * @param string $force_entity '0' or Ids of environment to force
  8337. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8338. * @param string $morecss More css to add to html component
  8339. * @return string
  8340. * @see select_dolusers()
  8341. */
  8342. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8343. {
  8344. // phpcs:enable
  8345. global $conf, $user, $langs;
  8346. // Permettre l'exclusion de groupes
  8347. if (is_array($exclude)) {
  8348. $excludeGroups = implode(",", $exclude);
  8349. }
  8350. // Permettre l'inclusion de groupes
  8351. if (is_array($include)) {
  8352. $includeGroups = implode(",", $include);
  8353. }
  8354. if (!is_array($selected)) {
  8355. $selected = array($selected);
  8356. }
  8357. $out = '';
  8358. // On recherche les groupes
  8359. $sql = "SELECT ug.rowid, ug.nom as name";
  8360. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8361. $sql .= ", e.label";
  8362. }
  8363. $sql .= " FROM ".$this->db->prefix()."usergroup as ug ";
  8364. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8365. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid=ug.entity";
  8366. if ($force_entity) {
  8367. $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  8368. } else {
  8369. $sql .= " WHERE ug.entity IS NOT NULL";
  8370. }
  8371. } else {
  8372. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  8373. }
  8374. if (is_array($exclude) && $excludeGroups) {
  8375. $sql .= " AND ug.rowid NOT IN (".$this->db->sanitize($excludeGroups).")";
  8376. }
  8377. if (is_array($include) && $includeGroups) {
  8378. $sql .= " AND ug.rowid IN (".$this->db->sanitize($includeGroups).")";
  8379. }
  8380. $sql .= " ORDER BY ug.nom ASC";
  8381. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  8382. $resql = $this->db->query($sql);
  8383. if ($resql) {
  8384. // Enhance with select2
  8385. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8386. $out .= ajax_combobox($htmlname);
  8387. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  8388. $num = $this->db->num_rows($resql);
  8389. $i = 0;
  8390. if ($num) {
  8391. if ($show_empty && !$multiple) {
  8392. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8393. }
  8394. while ($i < $num) {
  8395. $obj = $this->db->fetch_object($resql);
  8396. $disableline = 0;
  8397. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8398. $disableline = 1;
  8399. }
  8400. $out .= '<option value="'.$obj->rowid.'"';
  8401. if ($disableline) {
  8402. $out .= ' disabled';
  8403. }
  8404. if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (!is_object($selected[0]) && in_array($obj->rowid, $selected))) {
  8405. $out .= ' selected';
  8406. }
  8407. $out .= '>';
  8408. $out .= $obj->name;
  8409. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8410. $out .= " (".$obj->label.")";
  8411. }
  8412. $out .= '</option>';
  8413. $i++;
  8414. }
  8415. } else {
  8416. if ($show_empty) {
  8417. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  8418. }
  8419. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  8420. }
  8421. $out .= '</select>';
  8422. } else {
  8423. dol_print_error($this->db);
  8424. }
  8425. return $out;
  8426. }
  8427. /**
  8428. * Return HTML to show the search and clear seach button
  8429. *
  8430. * @return string
  8431. */
  8432. public function showFilterButtons()
  8433. {
  8434. $out = '<div class="nowraponall">';
  8435. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8436. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8437. $out .= '</div>';
  8438. return $out;
  8439. }
  8440. /**
  8441. * Return HTML to show the search and clear search button
  8442. *
  8443. * @param string $cssclass CSS class
  8444. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8445. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8446. * @return string
  8447. */
  8448. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8449. {
  8450. global $conf, $langs;
  8451. $out = '';
  8452. if (!empty($conf->use_javascript_ajax)) {
  8453. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  8454. }
  8455. $out .= '<script>
  8456. $(document).ready(function() {
  8457. $("#' . $cssclass.'s").click(function() {
  8458. if($(this).is(\':checked\')){
  8459. console.log("We check all '.$cssclass.' and trigger the change method");
  8460. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  8461. }
  8462. else
  8463. {
  8464. console.log("We uncheck all");
  8465. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  8466. }'."\n";
  8467. if ($calljsfunction) {
  8468. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8469. }
  8470. $out .= ' });
  8471. $(".' . $cssclass.'").change(function() {
  8472. $(this).closest("tr").toggleClass("highlight", this.checked);
  8473. });
  8474. });
  8475. </script>';
  8476. return $out;
  8477. }
  8478. /**
  8479. * Return HTML to show the search and clear seach button
  8480. *
  8481. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8482. * @param string $cssclass CSS class
  8483. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8484. * @param string $massactionname Mass action name
  8485. * @return string
  8486. */
  8487. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8488. {
  8489. $out = $this->showFilterButtons();
  8490. if ($addcheckuncheckall) {
  8491. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8492. }
  8493. return $out;
  8494. }
  8495. /**
  8496. * Return HTML to show the select of expense categories
  8497. *
  8498. * @param string $selected preselected category
  8499. * @param string $htmlname name of HTML select list
  8500. * @param integer $useempty 1=Add empty line
  8501. * @param array $excludeid id to exclude
  8502. * @param string $target htmlname of target select to bind event
  8503. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8504. * @param array $params param to give
  8505. * @param int $info_admin Show the tooltip help picto to setup list
  8506. * @return string
  8507. */
  8508. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8509. {
  8510. global $langs, $user;
  8511. $out = '';
  8512. $sql = "SELECT rowid, label FROM ".$this->db->prefix()."c_exp_tax_cat WHERE active = 1";
  8513. $sql .= " AND entity IN (0,".getEntity('exp_tax_cat').")";
  8514. if (!empty($excludeid)) {
  8515. $sql .= " AND rowid NOT IN (".$this->db->sanitize(implode(',', $excludeid)).")";
  8516. }
  8517. $sql .= " ORDER BY label";
  8518. $resql = $this->db->query($sql);
  8519. if ($resql) {
  8520. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  8521. if ($useempty) {
  8522. $out .= '<option value="0">&nbsp;</option>';
  8523. }
  8524. while ($obj = $this->db->fetch_object($resql)) {
  8525. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  8526. }
  8527. $out .= '</select>';
  8528. $out .= ajax_combobox('select_'.$htmlname);
  8529. if (!empty($htmlname) && $user->admin && $info_admin) {
  8530. $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8531. }
  8532. if (!empty($target)) {
  8533. $sql = "SELECT c.id FROM ".$this->db->prefix()."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8534. $resql = $this->db->query($sql);
  8535. if ($resql) {
  8536. if ($this->db->num_rows($resql) > 0) {
  8537. $obj = $this->db->fetch_object($resql);
  8538. $out .= '<script>
  8539. $(function() {
  8540. $("select[name='.$target.']").on("change", function() {
  8541. var current_val = $(this).val();
  8542. if (current_val == '.$obj->id.') {';
  8543. if (!empty($default_selected) || !empty($selected)) {
  8544. $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  8545. }
  8546. $out .= '
  8547. $("select[name='.$htmlname.']").change();
  8548. }
  8549. });
  8550. $("select[name='.$htmlname.']").change(function() {
  8551. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  8552. // get price of kilometer to fill the unit price
  8553. $.ajax({
  8554. method: "POST",
  8555. dataType: "json",
  8556. data: { fk_c_exp_tax_cat: $(this).val(), token: \''.currentToken().'\' },
  8557. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php?'.$params).'",
  8558. }).done(function( data, textStatus, jqXHR ) {
  8559. console.log(data);
  8560. if (typeof data.up != "undefined") {
  8561. $("input[name=value_unit]").val(data.up);
  8562. $("select[name='.$htmlname.']").attr("title", data.title);
  8563. } else {
  8564. $("input[name=value_unit]").val("");
  8565. $("select[name='.$htmlname.']").attr("title", "");
  8566. }
  8567. });
  8568. }
  8569. });
  8570. });
  8571. </script>';
  8572. }
  8573. }
  8574. }
  8575. } else {
  8576. dol_print_error($this->db);
  8577. }
  8578. return $out;
  8579. }
  8580. /**
  8581. * Return HTML to show the select ranges of expense range
  8582. *
  8583. * @param string $selected preselected category
  8584. * @param string $htmlname name of HTML select list
  8585. * @param integer $useempty 1=Add empty line
  8586. * @return string
  8587. */
  8588. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8589. {
  8590. global $conf, $langs;
  8591. $out = '';
  8592. $sql = "SELECT rowid, range_ik FROM ".$this->db->prefix()."c_exp_tax_range";
  8593. $sql .= " WHERE entity = ".$conf->entity." AND active = 1";
  8594. $resql = $this->db->query($sql);
  8595. if ($resql) {
  8596. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8597. if ($useempty) {
  8598. $out .= '<option value="0"></option>';
  8599. }
  8600. while ($obj = $this->db->fetch_object($resql)) {
  8601. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  8602. }
  8603. $out .= '</select>';
  8604. } else {
  8605. dol_print_error($this->db);
  8606. }
  8607. return $out;
  8608. }
  8609. /**
  8610. * Return HTML to show a select of expense
  8611. *
  8612. * @param string $selected preselected category
  8613. * @param string $htmlname name of HTML select list
  8614. * @param integer $useempty 1=Add empty choice
  8615. * @param integer $allchoice 1=Add all choice
  8616. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8617. * @return string
  8618. */
  8619. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8620. {
  8621. global $langs;
  8622. $out = '';
  8623. $sql = "SELECT id, code, label FROM ".$this->db->prefix()."c_type_fees";
  8624. $sql .= " WHERE active = 1";
  8625. $resql = $this->db->query($sql);
  8626. if ($resql) {
  8627. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8628. if ($useempty) {
  8629. $out .= '<option value="0"></option>';
  8630. }
  8631. if ($allchoice) {
  8632. $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  8633. }
  8634. $field = 'code';
  8635. if ($useid) {
  8636. $field = 'id';
  8637. }
  8638. while ($obj = $this->db->fetch_object($resql)) {
  8639. $key = $langs->trans($obj->code);
  8640. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  8641. }
  8642. $out .= '</select>';
  8643. } else {
  8644. dol_print_error($this->db);
  8645. }
  8646. return $out;
  8647. }
  8648. /**
  8649. * Output a combo list with invoices qualified for a third party
  8650. *
  8651. * @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)
  8652. * @param int $selected Id invoice preselected
  8653. * @param string $htmlname Name of HTML select
  8654. * @param int $maxlength Maximum length of label
  8655. * @param int $option_only Return only html options lines without the select tag
  8656. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8657. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8658. * @param int $forcefocus Force focus on field (works with javascript only)
  8659. * @param int $disabled Disabled
  8660. * @param string $morecss More css added to the select component
  8661. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  8662. * @param string $showproject 'all' = Show project info, ''=Hide project info
  8663. * @param User $usertofilter User object to use for filtering
  8664. * @return int Nbr of project if OK, <0 if KO
  8665. */
  8666. 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)
  8667. {
  8668. global $user, $conf, $langs;
  8669. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  8670. if (is_null($usertofilter)) {
  8671. $usertofilter = $user;
  8672. }
  8673. $out = '';
  8674. $hideunselectables = false;
  8675. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  8676. $hideunselectables = true;
  8677. }
  8678. if (empty($projectsListId)) {
  8679. if (empty($usertofilter->rights->projet->all->lire)) {
  8680. $projectstatic = new Project($this->db);
  8681. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  8682. }
  8683. }
  8684. // Search all projects
  8685. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  8686. p.title, p.fk_soc, p.fk_statut, p.public,";
  8687. $sql .= ' s.nom as name';
  8688. $sql .= ' FROM '.$this->db->prefix().'projet as p';
  8689. $sql .= ' LEFT JOIN '.$this->db->prefix().'societe as s ON s.rowid = p.fk_soc,';
  8690. $sql .= ' '.$this->db->prefix().'facture as f';
  8691. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  8692. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  8693. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  8694. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  8695. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  8696. $sql .= " ORDER BY p.ref, f.ref ASC";
  8697. $resql = $this->db->query($sql);
  8698. if ($resql) {
  8699. // Use select2 selector
  8700. if (!empty($conf->use_javascript_ajax)) {
  8701. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8702. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8703. $out .= $comboenhancement;
  8704. $morecss = 'minwidth200imp maxwidth500';
  8705. }
  8706. if (empty($option_only)) {
  8707. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  8708. }
  8709. if (!empty($show_empty)) {
  8710. $out .= '<option value="0" class="optiongrey">';
  8711. if (!is_numeric($show_empty)) {
  8712. $out .= $show_empty;
  8713. } else {
  8714. $out .= '&nbsp;';
  8715. }
  8716. $out .= '</option>';
  8717. }
  8718. $num = $this->db->num_rows($resql);
  8719. $i = 0;
  8720. if ($num) {
  8721. while ($i < $num) {
  8722. $obj = $this->db->fetch_object($resql);
  8723. // 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.
  8724. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  8725. // Do nothing
  8726. } else {
  8727. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  8728. $i++;
  8729. continue;
  8730. }
  8731. $labeltoshow = '';
  8732. if ($showproject == 'all') {
  8733. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  8734. if ($obj->name) {
  8735. $labeltoshow .= ' - '.$obj->name; // Soc name
  8736. }
  8737. $disabled = 0;
  8738. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  8739. $disabled = 1;
  8740. $labeltoshow .= ' - '.$langs->trans("Draft");
  8741. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  8742. if ($discard_closed == 2) {
  8743. $disabled = 1;
  8744. }
  8745. $labeltoshow .= ' - '.$langs->trans("Closed");
  8746. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  8747. $disabled = 1;
  8748. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  8749. }
  8750. }
  8751. if (!empty($selected) && $selected == $obj->rowid) {
  8752. $out .= '<option value="'.$obj->rowid.'" selected';
  8753. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8754. $out .= '>'.$labeltoshow.'</option>';
  8755. } else {
  8756. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  8757. $resultat = '';
  8758. } else {
  8759. $resultat = '<option value="'.$obj->rowid.'"';
  8760. if ($disabled) {
  8761. $resultat .= ' disabled';
  8762. }
  8763. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  8764. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  8765. $resultat .= '>';
  8766. $resultat .= $labeltoshow;
  8767. $resultat .= '</option>';
  8768. }
  8769. $out .= $resultat;
  8770. }
  8771. }
  8772. $i++;
  8773. }
  8774. }
  8775. if (empty($option_only)) {
  8776. $out .= '</select>';
  8777. }
  8778. print $out;
  8779. $this->db->free($resql);
  8780. return $num;
  8781. } else {
  8782. dol_print_error($this->db);
  8783. return -1;
  8784. }
  8785. }
  8786. /**
  8787. * Output the component to make advanced search criteries
  8788. *
  8789. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  8790. * @param array $search_component_params Array of selected search criterias
  8791. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  8792. * @param string $search_component_params_hidden String with $search_component_params criterias
  8793. * @return string HTML component for advanced search
  8794. */
  8795. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  8796. {
  8797. global $langs;
  8798. $ret = '';
  8799. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  8800. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8801. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  8802. $ret .= '<span class="fas fa-filter linkobject boxfilter pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("Filters")).'" id="idsubimgproductdistribution"></span>';
  8803. //$ret .= $langs->trans("Filters");
  8804. $ret .= '</a>';
  8805. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  8806. // Show select fields as tags.
  8807. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  8808. if ($search_component_params_hidden) {
  8809. if (!preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  8810. $search_component_params_hidden .= '('.$search_component_params_hidden.')';
  8811. }
  8812. $errormessage = '';
  8813. if (!dolCheckFilters($search_component_params_hidden, $errormessage)) {
  8814. print 'ERROR in parsing search string';
  8815. }
  8816. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  8817. //var_dump($search_component_params_hidden);
  8818. $htmltags = preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $search_component_params_hidden);
  8819. //var_dump($htmltags);
  8820. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch"><span class="tagsearchdelete select2-selection__choice__remove">x</span> '.$htmltags.'</span>';
  8821. }
  8822. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8823. //$ret .= search_component_params
  8824. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  8825. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  8826. $show_search_component_params_hidden = 1;
  8827. if ($show_search_component_params_hidden) {
  8828. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  8829. }
  8830. $ret .= "<!-- We store the full search string into this field. For example: (t.ref:like:'SO-%') and ((t.ref:like:'CO-%') or (t.ref:like:'AA%')) -->";
  8831. $ret .= '<input type="hidden" name="search_component_params_hidden" value="'.dol_escape_htmltag($search_component_params_hidden).'">';
  8832. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  8833. foreach ($arrayofcriterias as $criterias) {
  8834. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  8835. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  8836. continue;
  8837. }
  8838. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  8839. continue;
  8840. }
  8841. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  8842. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  8843. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  8844. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  8845. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  8846. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  8847. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  8848. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  8849. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  8850. } else {
  8851. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  8852. }
  8853. }
  8854. }
  8855. $ret .= '</div>';
  8856. $ret .= "<!-- Syntax of 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";
  8857. $ret .= '<input type="text" placeholder="'.$langs->trans("Search").'" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  8858. $ret .= '</div>';
  8859. $ret .= '</div>';
  8860. return $ret;
  8861. }
  8862. /**
  8863. * selectModelMail
  8864. *
  8865. * @param string $prefix Prefix
  8866. * @param string $modelType Model type
  8867. * @param int $default 1=Show also Default mail template
  8868. * @param int $addjscombo Add js combobox
  8869. * @return string HTML select string
  8870. */
  8871. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  8872. {
  8873. global $langs, $user;
  8874. $retstring = '';
  8875. $TModels = array();
  8876. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  8877. $formmail = new FormMail($this->db);
  8878. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  8879. if ($default) {
  8880. $TModels[0] = $langs->trans('DefaultMailModel');
  8881. }
  8882. if ($result > 0) {
  8883. foreach ($formmail->lines_model as $model) {
  8884. $TModels[$model->id] = $model->label;
  8885. }
  8886. }
  8887. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  8888. foreach ($TModels as $id_model => $label_model) {
  8889. $retstring .= '<option value="'.$id_model.'"';
  8890. $retstring .= ">".$label_model."</option>";
  8891. }
  8892. $retstring .= "</select>";
  8893. if ($addjscombo) {
  8894. $retstring .= ajax_combobox('select_'.$prefix.'model_mail');
  8895. }
  8896. return $retstring;
  8897. }
  8898. /**
  8899. * Output the buttons to submit a creation/edit form
  8900. *
  8901. * @param string $save_label Alternative label for save button
  8902. * @param string $cancel_label Alternative label for cancel button
  8903. * @param array $morebuttons Add additional buttons between save and cancel
  8904. * @param bool $withoutdiv Option to remove enclosing centered div
  8905. * @param string $morecss More CSS
  8906. * @return string Html code with the buttons
  8907. */
  8908. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '')
  8909. {
  8910. global $langs;
  8911. $buttons = array();
  8912. $save = array(
  8913. 'name' => 'save',
  8914. 'label_key' => $save_label,
  8915. );
  8916. if ($save_label == 'Create' || $save_label == 'Add' ) {
  8917. $save['name'] = 'add';
  8918. } elseif ($save_label == 'Modify') {
  8919. $save['name'] = 'edit';
  8920. }
  8921. $cancel = array(
  8922. 'name' => 'cancel',
  8923. 'label_key' => 'Cancel',
  8924. );
  8925. !empty($save_label) ? $buttons[] = $save : '';
  8926. if (!empty($morebuttons)) {
  8927. $buttons[] = $morebuttons;
  8928. }
  8929. !empty($cancel_label) ? $buttons[] = $cancel : '';
  8930. $retstring = $withoutdiv ? '': '<div class="center">';
  8931. foreach ($buttons as $button) {
  8932. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  8933. $retstring .= '<input type="submit" class="button button-'.$button['name'].($morecss ? ' '.$morecss : '').' '.$addclass.'" name="'.$button['name'].'" value="'.dol_escape_htmltag($langs->trans($button['label_key'])).'">';
  8934. }
  8935. $retstring .= $withoutdiv ? '': '</div>';
  8936. return $retstring;
  8937. }
  8938. }